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 /// \brief 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 Expr *CheckMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// \brief Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// \brief 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 /// \brief Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy final {
60 public:
61   struct DSAVarData final {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69                DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
72   };
73   typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74       OperatorOffsetTy;
75 
76 private:
77   struct DSAInfo final {
78     OpenMPClauseKind Attributes = OMPC_unknown;
79     /// Pointer to a reference expression and a flag which shows that the
80     /// variable is marked as lastprivate(true) or not (false).
81     llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82     DeclRefExpr *PrivateCopy = nullptr;
83   };
84   typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85   typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
86   typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87   typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
88   /// Struct that associates a component with the clause kind where they are
89   /// found.
90   struct MappedExprComponentTy {
91     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92     OpenMPClauseKind Kind = OMPC_unknown;
93   };
94   typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
95       MappedExprComponentsTy;
96   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97       CriticalsWithHintsTy;
98   typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99       DoacrossDependMapTy;
100   struct ReductionData {
101     typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
102     SourceRange ReductionRange;
103     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
104     ReductionData() = default;
105     void set(BinaryOperatorKind BO, SourceRange RR) {
106       ReductionRange = RR;
107       ReductionOp = BO;
108     }
109     void set(const Expr *RefExpr, SourceRange RR) {
110       ReductionRange = RR;
111       ReductionOp = RefExpr;
112     }
113   };
114   typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
115 
116   struct SharingMapTy final {
117     DeclSAMapTy SharingMap;
118     DeclReductionMapTy ReductionMap;
119     AlignedMapTy AlignedMap;
120     MappedExprComponentsTy MappedExprComponents;
121     LoopControlVariablesMapTy LCVMap;
122     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
123     SourceLocation DefaultAttrLoc;
124     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125     SourceLocation DefaultMapAttrLoc;
126     OpenMPDirectiveKind Directive = OMPD_unknown;
127     DeclarationNameInfo DirectiveName;
128     Scope *CurScope = nullptr;
129     SourceLocation ConstructLoc;
130     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131     /// get the data (loop counters etc.) about enclosing loop-based construct.
132     /// This data is required during codegen.
133     DoacrossDependMapTy DoacrossDepends;
134     /// \brief first argument (Expr *) contains optional argument of the
135     /// 'ordered' clause, the second one is true if the regions has 'ordered'
136     /// clause, false otherwise.
137     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
138     bool NowaitRegion = false;
139     bool CancelRegion = false;
140     unsigned AssociatedLoops = 1;
141     SourceLocation InnerTeamsRegionLoc;
142     /// Reference to the taskgroup task_reduction reference expression.
143     Expr *TaskgroupReductionRef = nullptr;
144     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
145                  Scope *CurScope, SourceLocation Loc)
146         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147           ConstructLoc(Loc) {}
148     SharingMapTy() = default;
149   };
150 
151   typedef SmallVector<SharingMapTy, 4> StackTy;
152 
153   /// \brief Stack of used declaration and their data-sharing attributes.
154   DeclSAMapTy Threadprivates;
155   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
157   /// \brief true, if check for DSA must be from parent directive, false, if
158   /// from current directive.
159   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
160   Sema &SemaRef;
161   bool ForceCapturing = false;
162   CriticalsWithHintsTy Criticals;
163 
164   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165 
166   DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
167 
168   /// \brief Checks if the variable is a local for OpenMP region.
169   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
170 
171   bool isStackEmpty() const {
172     return Stack.empty() ||
173            Stack.back().second != CurrentNonCapturingFunctionScope ||
174            Stack.back().first.empty();
175   }
176 
177 public:
178   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
179 
180   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
181   OpenMPClauseKind getClauseParsingMode() const {
182     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
183     return ClauseKindMode;
184   }
185   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
186 
187   bool isForceVarCapturing() const { return ForceCapturing; }
188   void setForceVarCapturing(bool V) { ForceCapturing = V; }
189 
190   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
191             Scope *CurScope, SourceLocation Loc) {
192     if (Stack.empty() ||
193         Stack.back().second != CurrentNonCapturingFunctionScope)
194       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
195     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
196     Stack.back().first.back().DefaultAttrLoc = Loc;
197   }
198 
199   void pop() {
200     assert(!Stack.back().first.empty() &&
201            "Data-sharing attributes stack is empty!");
202     Stack.back().first.pop_back();
203   }
204 
205   /// Start new OpenMP region stack in new non-capturing function.
206   void pushFunction() {
207     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
208     assert(!isa<CapturingScopeInfo>(CurFnScope));
209     CurrentNonCapturingFunctionScope = CurFnScope;
210   }
211   /// Pop region stack for non-capturing function.
212   void popFunction(const FunctionScopeInfo *OldFSI) {
213     if (!Stack.empty() && Stack.back().second == OldFSI) {
214       assert(Stack.back().first.empty());
215       Stack.pop_back();
216     }
217     CurrentNonCapturingFunctionScope = nullptr;
218     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
219       if (!isa<CapturingScopeInfo>(FSI)) {
220         CurrentNonCapturingFunctionScope = FSI;
221         break;
222       }
223     }
224   }
225 
226   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
227     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
228   }
229   const std::pair<OMPCriticalDirective *, llvm::APSInt>
230   getCriticalWithHint(const DeclarationNameInfo &Name) const {
231     auto I = Criticals.find(Name.getAsString());
232     if (I != Criticals.end())
233       return I->second;
234     return std::make_pair(nullptr, llvm::APSInt());
235   }
236   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
237   /// add it and return NULL; otherwise return previous occurrence's expression
238   /// for diagnostics.
239   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
240 
241   /// \brief Register specified variable as loop control variable.
242   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
243   /// \brief Check if the specified variable is a loop control variable for
244   /// current region.
245   /// \return The index of the loop control variable in the list of associated
246   /// for-loops (from outer to inner).
247   LCDeclInfo isLoopControlVariable(ValueDecl *D);
248   /// \brief Check if the specified variable is a loop control variable for
249   /// parent region.
250   /// \return The index of the loop control variable in the list of associated
251   /// for-loops (from outer to inner).
252   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
253   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
254   /// parent directive.
255   ValueDecl *getParentLoopControlVariable(unsigned I);
256 
257   /// \brief Adds explicit data sharing attribute to the specified declaration.
258   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
259               DeclRefExpr *PrivateCopy = nullptr);
260 
261   /// Adds additional information for the reduction items with the reduction id
262   /// represented as an operator.
263   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264                                  BinaryOperatorKind BOK);
265   /// Adds additional information for the reduction items with the reduction id
266   /// represented as reduction identifier.
267   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
268                                  const Expr *ReductionRef);
269   /// Returns the location and reduction operation from the innermost parent
270   /// region for the given \p D.
271   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
272                                               BinaryOperatorKind &BOK,
273                                               Expr *&TaskgroupDescriptor);
274   /// Returns the location and reduction operation from the innermost parent
275   /// region for the given \p D.
276   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
277                                               const Expr *&ReductionRef,
278                                               Expr *&TaskgroupDescriptor);
279   /// Return reduction reference expression for the current taskgroup.
280   Expr *getTaskgroupReductionRef() const {
281     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
282            "taskgroup reference expression requested for non taskgroup "
283            "directive.");
284     return Stack.back().first.back().TaskgroupReductionRef;
285   }
286   /// Checks if the given \p VD declaration is actually a taskgroup reduction
287   /// descriptor variable at the \p Level of OpenMP regions.
288   bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
289     return Stack.back().first[Level].TaskgroupReductionRef &&
290            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
291                    ->getDecl() == VD;
292   }
293 
294   /// \brief Returns data sharing attributes from top of the stack for the
295   /// specified declaration.
296   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
297   /// \brief Returns data-sharing attributes for the specified declaration.
298   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
299   /// \brief Checks if the specified variables has data-sharing attributes which
300   /// match specified \a CPred predicate in any directive which matches \a DPred
301   /// predicate.
302   DSAVarData hasDSA(ValueDecl *D,
303                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
304                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
305                     bool FromParent);
306   /// \brief Checks if the specified variables has data-sharing attributes which
307   /// match specified \a CPred predicate in any innermost directive which
308   /// matches \a DPred predicate.
309   DSAVarData
310   hasInnermostDSA(ValueDecl *D,
311                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
312                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
313                   bool FromParent);
314   /// \brief Checks if the specified variables has explicit data-sharing
315   /// attributes which match specified \a CPred predicate at the specified
316   /// OpenMP region.
317   bool hasExplicitDSA(ValueDecl *D,
318                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
319                       unsigned Level, bool NotLastprivate = false);
320 
321   /// \brief Returns true if the directive at level \Level matches in the
322   /// specified \a DPred predicate.
323   bool hasExplicitDirective(
324       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
325       unsigned Level);
326 
327   /// \brief Finds a directive which matches specified \a DPred predicate.
328   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
329                                                   const DeclarationNameInfo &,
330                                                   SourceLocation)> &DPred,
331                     bool FromParent);
332 
333   /// \brief Returns currently analyzed directive.
334   OpenMPDirectiveKind getCurrentDirective() const {
335     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
336   }
337   /// \brief Returns directive kind at specified level.
338   OpenMPDirectiveKind getDirective(unsigned Level) const {
339     assert(!isStackEmpty() && "No directive at specified level.");
340     return Stack.back().first[Level].Directive;
341   }
342   /// \brief Returns parent directive.
343   OpenMPDirectiveKind getParentDirective() const {
344     if (isStackEmpty() || Stack.back().first.size() == 1)
345       return OMPD_unknown;
346     return std::next(Stack.back().first.rbegin())->Directive;
347   }
348 
349   /// \brief Set default data sharing attribute to none.
350   void setDefaultDSANone(SourceLocation Loc) {
351     assert(!isStackEmpty());
352     Stack.back().first.back().DefaultAttr = DSA_none;
353     Stack.back().first.back().DefaultAttrLoc = Loc;
354   }
355   /// \brief Set default data sharing attribute to shared.
356   void setDefaultDSAShared(SourceLocation Loc) {
357     assert(!isStackEmpty());
358     Stack.back().first.back().DefaultAttr = DSA_shared;
359     Stack.back().first.back().DefaultAttrLoc = Loc;
360   }
361   /// Set default data mapping attribute to 'tofrom:scalar'.
362   void setDefaultDMAToFromScalar(SourceLocation Loc) {
363     assert(!isStackEmpty());
364     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
365     Stack.back().first.back().DefaultMapAttrLoc = Loc;
366   }
367 
368   DefaultDataSharingAttributes getDefaultDSA() const {
369     return isStackEmpty() ? DSA_unspecified
370                           : Stack.back().first.back().DefaultAttr;
371   }
372   SourceLocation getDefaultDSALocation() const {
373     return isStackEmpty() ? SourceLocation()
374                           : Stack.back().first.back().DefaultAttrLoc;
375   }
376   DefaultMapAttributes getDefaultDMA() const {
377     return isStackEmpty() ? DMA_unspecified
378                           : Stack.back().first.back().DefaultMapAttr;
379   }
380   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
381     return Stack.back().first[Level].DefaultMapAttr;
382   }
383   SourceLocation getDefaultDMALocation() const {
384     return isStackEmpty() ? SourceLocation()
385                           : Stack.back().first.back().DefaultMapAttrLoc;
386   }
387 
388   /// \brief Checks if the specified variable is a threadprivate.
389   bool isThreadPrivate(VarDecl *D) {
390     DSAVarData DVar = getTopDSA(D, false);
391     return isOpenMPThreadPrivate(DVar.CKind);
392   }
393 
394   /// \brief Marks current region as ordered (it has an 'ordered' clause).
395   void setOrderedRegion(bool IsOrdered, Expr *Param) {
396     assert(!isStackEmpty());
397     Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
398     Stack.back().first.back().OrderedRegion.setPointer(Param);
399   }
400   /// \brief Returns true, if parent region is ordered (has associated
401   /// 'ordered' clause), false - otherwise.
402   bool isParentOrderedRegion() const {
403     if (isStackEmpty() || Stack.back().first.size() == 1)
404       return false;
405     return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
406   }
407   /// \brief Returns optional parameter for the ordered region.
408   Expr *getParentOrderedRegionParam() const {
409     if (isStackEmpty() || Stack.back().first.size() == 1)
410       return nullptr;
411     return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
412   }
413   /// \brief Marks current region as nowait (it has a 'nowait' clause).
414   void setNowaitRegion(bool IsNowait = true) {
415     assert(!isStackEmpty());
416     Stack.back().first.back().NowaitRegion = IsNowait;
417   }
418   /// \brief Returns true, if parent region is nowait (has associated
419   /// 'nowait' clause), false - otherwise.
420   bool isParentNowaitRegion() const {
421     if (isStackEmpty() || Stack.back().first.size() == 1)
422       return false;
423     return std::next(Stack.back().first.rbegin())->NowaitRegion;
424   }
425   /// \brief Marks parent region as cancel region.
426   void setParentCancelRegion(bool Cancel = true) {
427     if (!isStackEmpty() && Stack.back().first.size() > 1) {
428       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
429       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
430     }
431   }
432   /// \brief Return true if current region has inner cancel construct.
433   bool isCancelRegion() const {
434     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
435   }
436 
437   /// \brief Set collapse value for the region.
438   void setAssociatedLoops(unsigned Val) {
439     assert(!isStackEmpty());
440     Stack.back().first.back().AssociatedLoops = Val;
441   }
442   /// \brief Return collapse value for region.
443   unsigned getAssociatedLoops() const {
444     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
445   }
446 
447   /// \brief Marks current target region as one with closely nested teams
448   /// region.
449   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
450     if (!isStackEmpty() && Stack.back().first.size() > 1) {
451       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
452           TeamsRegionLoc;
453     }
454   }
455   /// \brief Returns true, if current region has closely nested teams region.
456   bool hasInnerTeamsRegion() const {
457     return getInnerTeamsRegionLoc().isValid();
458   }
459   /// \brief Returns location of the nested teams region (if any).
460   SourceLocation getInnerTeamsRegionLoc() const {
461     return isStackEmpty() ? SourceLocation()
462                           : Stack.back().first.back().InnerTeamsRegionLoc;
463   }
464 
465   Scope *getCurScope() const {
466     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
467   }
468   Scope *getCurScope() {
469     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
470   }
471   SourceLocation getConstructLoc() {
472     return isStackEmpty() ? SourceLocation()
473                           : Stack.back().first.back().ConstructLoc;
474   }
475 
476   /// Do the check specified in \a Check to all component lists and return true
477   /// if any issue is found.
478   bool checkMappableExprComponentListsForDecl(
479       ValueDecl *VD, bool CurrentRegionOnly,
480       const llvm::function_ref<
481           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
482                OpenMPClauseKind)> &Check) {
483     if (isStackEmpty())
484       return false;
485     auto SI = Stack.back().first.rbegin();
486     auto SE = Stack.back().first.rend();
487 
488     if (SI == SE)
489       return false;
490 
491     if (CurrentRegionOnly) {
492       SE = std::next(SI);
493     } else {
494       ++SI;
495     }
496 
497     for (; SI != SE; ++SI) {
498       auto MI = SI->MappedExprComponents.find(VD);
499       if (MI != SI->MappedExprComponents.end())
500         for (auto &L : MI->second.Components)
501           if (Check(L, MI->second.Kind))
502             return true;
503     }
504     return false;
505   }
506 
507   /// Do the check specified in \a Check to all component lists at a given level
508   /// and return true if any issue is found.
509   bool checkMappableExprComponentListsForDeclAtLevel(
510       ValueDecl *VD, unsigned Level,
511       const llvm::function_ref<
512           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
513                OpenMPClauseKind)> &Check) {
514     if (isStackEmpty())
515       return false;
516 
517     auto StartI = Stack.back().first.begin();
518     auto EndI = Stack.back().first.end();
519     if (std::distance(StartI, EndI) <= (int)Level)
520       return false;
521     std::advance(StartI, Level);
522 
523     auto MI = StartI->MappedExprComponents.find(VD);
524     if (MI != StartI->MappedExprComponents.end())
525       for (auto &L : MI->second.Components)
526         if (Check(L, MI->second.Kind))
527           return true;
528     return false;
529   }
530 
531   /// Create a new mappable expression component list associated with a given
532   /// declaration and initialize it with the provided list of components.
533   void addMappableExpressionComponents(
534       ValueDecl *VD,
535       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
536       OpenMPClauseKind WhereFoundClauseKind) {
537     assert(!isStackEmpty() &&
538            "Not expecting to retrieve components from a empty stack!");
539     auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
540     // Create new entry and append the new components there.
541     MEC.Components.resize(MEC.Components.size() + 1);
542     MEC.Components.back().append(Components.begin(), Components.end());
543     MEC.Kind = WhereFoundClauseKind;
544   }
545 
546   unsigned getNestingLevel() const {
547     assert(!isStackEmpty());
548     return Stack.back().first.size() - 1;
549   }
550   void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
551     assert(!isStackEmpty() && Stack.back().first.size() > 1);
552     auto &StackElem = *std::next(Stack.back().first.rbegin());
553     assert(isOpenMPWorksharingDirective(StackElem.Directive));
554     StackElem.DoacrossDepends.insert({C, OpsOffs});
555   }
556   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
557   getDoacrossDependClauses() const {
558     assert(!isStackEmpty());
559     auto &StackElem = Stack.back().first.back();
560     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
561       auto &Ref = StackElem.DoacrossDepends;
562       return llvm::make_range(Ref.begin(), Ref.end());
563     }
564     return llvm::make_range(StackElem.DoacrossDepends.end(),
565                             StackElem.DoacrossDepends.end());
566   }
567 };
568 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
569   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
570          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
571 }
572 } // namespace
573 
574 static Expr *getExprAsWritten(Expr *E) {
575   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
576     E = ExprTemp->getSubExpr();
577 
578   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
579     E = MTE->GetTemporaryExpr();
580 
581   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
582     E = Binder->getSubExpr();
583 
584   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
585     E = ICE->getSubExprAsWritten();
586   return E->IgnoreParens();
587 }
588 
589 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
590   if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
591     if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
592       D = ME->getMemberDecl();
593   auto *VD = dyn_cast<VarDecl>(D);
594   auto *FD = dyn_cast<FieldDecl>(D);
595   if (VD != nullptr) {
596     VD = VD->getCanonicalDecl();
597     D = VD;
598   } else {
599     assert(FD);
600     FD = FD->getCanonicalDecl();
601     D = FD;
602   }
603   return D;
604 }
605 
606 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
607                                           ValueDecl *D) {
608   D = getCanonicalDecl(D);
609   auto *VD = dyn_cast<VarDecl>(D);
610   auto *FD = dyn_cast<FieldDecl>(D);
611   DSAVarData DVar;
612   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
613     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
614     // in a region but not in construct]
615     //  File-scope or namespace-scope variables referenced in called routines
616     //  in the region are shared unless they appear in a threadprivate
617     //  directive.
618     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
619       DVar.CKind = OMPC_shared;
620 
621     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
622     // in a region but not in construct]
623     //  Variables with static storage duration that are declared in called
624     //  routines in the region are shared.
625     if (VD && VD->hasGlobalStorage())
626       DVar.CKind = OMPC_shared;
627 
628     // Non-static data members are shared by default.
629     if (FD)
630       DVar.CKind = OMPC_shared;
631 
632     return DVar;
633   }
634 
635   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
636   // in a Construct, C/C++, predetermined, p.1]
637   // Variables with automatic storage duration that are declared in a scope
638   // inside the construct are private.
639   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
640       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
641     DVar.CKind = OMPC_private;
642     return DVar;
643   }
644 
645   DVar.DKind = Iter->Directive;
646   // Explicitly specified attributes and local variables with predetermined
647   // attributes.
648   if (Iter->SharingMap.count(D)) {
649     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
650     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
651     DVar.CKind = Iter->SharingMap[D].Attributes;
652     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
653     return DVar;
654   }
655 
656   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
657   // in a Construct, C/C++, implicitly determined, p.1]
658   //  In a parallel or task construct, the data-sharing attributes of these
659   //  variables are determined by the default clause, if present.
660   switch (Iter->DefaultAttr) {
661   case DSA_shared:
662     DVar.CKind = OMPC_shared;
663     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
664     return DVar;
665   case DSA_none:
666     return DVar;
667   case DSA_unspecified:
668     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
669     // in a Construct, implicitly determined, p.2]
670     //  In a parallel construct, if no default clause is present, these
671     //  variables are shared.
672     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
673     if (isOpenMPParallelDirective(DVar.DKind) ||
674         isOpenMPTeamsDirective(DVar.DKind)) {
675       DVar.CKind = OMPC_shared;
676       return DVar;
677     }
678 
679     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680     // in a Construct, implicitly determined, p.4]
681     //  In a task construct, if no default clause is present, a variable that in
682     //  the enclosing context is determined to be shared by all implicit tasks
683     //  bound to the current team is shared.
684     if (isOpenMPTaskingDirective(DVar.DKind)) {
685       DSAVarData DVarTemp;
686       auto I = Iter, E = Stack.back().first.rend();
687       do {
688         ++I;
689         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
690         // Referenced in a Construct, implicitly determined, p.6]
691         //  In a task construct, if no default clause is present, a variable
692         //  whose data-sharing attribute is not determined by the rules above is
693         //  firstprivate.
694         DVarTemp = getDSA(I, D);
695         if (DVarTemp.CKind != OMPC_shared) {
696           DVar.RefExpr = nullptr;
697           DVar.CKind = OMPC_firstprivate;
698           return DVar;
699         }
700       } while (I != E && !isParallelOrTaskRegion(I->Directive));
701       DVar.CKind =
702           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
703       return DVar;
704     }
705   }
706   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
707   // in a Construct, implicitly determined, p.3]
708   //  For constructs other than task, if no default clause is present, these
709   //  variables inherit their data-sharing attributes from the enclosing
710   //  context.
711   return getDSA(++Iter, D);
712 }
713 
714 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
715   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
716   D = getCanonicalDecl(D);
717   auto &StackElem = Stack.back().first.back();
718   auto It = StackElem.AlignedMap.find(D);
719   if (It == StackElem.AlignedMap.end()) {
720     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
721     StackElem.AlignedMap[D] = NewDE;
722     return nullptr;
723   } else {
724     assert(It->second && "Unexpected nullptr expr in the aligned map");
725     return It->second;
726   }
727   return nullptr;
728 }
729 
730 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
731   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
732   D = getCanonicalDecl(D);
733   auto &StackElem = Stack.back().first.back();
734   StackElem.LCVMap.insert(
735       {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
736 }
737 
738 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
739   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
740   D = getCanonicalDecl(D);
741   auto &StackElem = Stack.back().first.back();
742   auto It = StackElem.LCVMap.find(D);
743   if (It != StackElem.LCVMap.end())
744     return It->second;
745   return {0, nullptr};
746 }
747 
748 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
749   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
750          "Data-sharing attributes stack is empty");
751   D = getCanonicalDecl(D);
752   auto &StackElem = *std::next(Stack.back().first.rbegin());
753   auto It = StackElem.LCVMap.find(D);
754   if (It != StackElem.LCVMap.end())
755     return It->second;
756   return {0, nullptr};
757 }
758 
759 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
760   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
761          "Data-sharing attributes stack is empty");
762   auto &StackElem = *std::next(Stack.back().first.rbegin());
763   if (StackElem.LCVMap.size() < I)
764     return nullptr;
765   for (auto &Pair : StackElem.LCVMap)
766     if (Pair.second.first == I)
767       return Pair.first;
768   return nullptr;
769 }
770 
771 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
772                         DeclRefExpr *PrivateCopy) {
773   D = getCanonicalDecl(D);
774   if (A == OMPC_threadprivate) {
775     auto &Data = Threadprivates[D];
776     Data.Attributes = A;
777     Data.RefExpr.setPointer(E);
778     Data.PrivateCopy = nullptr;
779   } else {
780     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
781     auto &Data = Stack.back().first.back().SharingMap[D];
782     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
783            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
784            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
785            (isLoopControlVariable(D).first && A == OMPC_private));
786     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
787       Data.RefExpr.setInt(/*IntVal=*/true);
788       return;
789     }
790     const bool IsLastprivate =
791         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
792     Data.Attributes = A;
793     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
794     Data.PrivateCopy = PrivateCopy;
795     if (PrivateCopy) {
796       auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
797       Data.Attributes = A;
798       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
799       Data.PrivateCopy = nullptr;
800     }
801   }
802 }
803 
804 /// \brief Build a variable declaration for OpenMP loop iteration variable.
805 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
806                              StringRef Name, const AttrVec *Attrs = nullptr,
807                              DeclRefExpr *OrigRef = nullptr) {
808   DeclContext *DC = SemaRef.CurContext;
809   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
810   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
811   VarDecl *Decl =
812       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
813   if (Attrs) {
814     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
815          I != E; ++I)
816       Decl->addAttr(*I);
817   }
818   Decl->setImplicit();
819   if (OrigRef) {
820     Decl->addAttr(
821         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
822   }
823   return Decl;
824 }
825 
826 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
827                                      SourceLocation Loc,
828                                      bool RefersToCapture = false) {
829   D->setReferenced();
830   D->markUsed(S.Context);
831   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
832                              SourceLocation(), D, RefersToCapture, Loc, Ty,
833                              VK_LValue);
834 }
835 
836 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
837                                            BinaryOperatorKind BOK) {
838   D = getCanonicalDecl(D);
839   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
840   assert(
841       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
842       "Additional reduction info may be specified only for reduction items.");
843   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
844   assert(ReductionData.ReductionRange.isInvalid() &&
845          Stack.back().first.back().Directive == OMPD_taskgroup &&
846          "Additional reduction info may be specified only once for reduction "
847          "items.");
848   ReductionData.set(BOK, SR);
849   Expr *&TaskgroupReductionRef =
850       Stack.back().first.back().TaskgroupReductionRef;
851   if (!TaskgroupReductionRef) {
852     auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
853                             SemaRef.Context.VoidPtrTy, ".task_red.");
854     TaskgroupReductionRef =
855         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
856   }
857 }
858 
859 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
860                                            const Expr *ReductionRef) {
861   D = getCanonicalDecl(D);
862   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
863   assert(
864       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
865       "Additional reduction info may be specified only for reduction items.");
866   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
867   assert(ReductionData.ReductionRange.isInvalid() &&
868          Stack.back().first.back().Directive == OMPD_taskgroup &&
869          "Additional reduction info may be specified only once for reduction "
870          "items.");
871   ReductionData.set(ReductionRef, SR);
872   Expr *&TaskgroupReductionRef =
873       Stack.back().first.back().TaskgroupReductionRef;
874   if (!TaskgroupReductionRef) {
875     auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
876                             ".task_red.");
877     TaskgroupReductionRef =
878         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
879   }
880 }
881 
882 DSAStackTy::DSAVarData
883 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
884                                              BinaryOperatorKind &BOK,
885                                              Expr *&TaskgroupDescriptor) {
886   D = getCanonicalDecl(D);
887   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
888   if (Stack.back().first.empty())
889       return DSAVarData();
890   for (auto I = std::next(Stack.back().first.rbegin(), 1),
891             E = Stack.back().first.rend();
892        I != E; std::advance(I, 1)) {
893     auto &Data = I->SharingMap[D];
894     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
895       continue;
896     auto &ReductionData = I->ReductionMap[D];
897     if (!ReductionData.ReductionOp ||
898         ReductionData.ReductionOp.is<const Expr *>())
899       return DSAVarData();
900     SR = ReductionData.ReductionRange;
901     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
902     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
903                                        "expression for the descriptor is not "
904                                        "set.");
905     TaskgroupDescriptor = I->TaskgroupReductionRef;
906     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
907                       Data.PrivateCopy, I->DefaultAttrLoc);
908   }
909   return DSAVarData();
910 }
911 
912 DSAStackTy::DSAVarData
913 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
914                                              const Expr *&ReductionRef,
915                                              Expr *&TaskgroupDescriptor) {
916   D = getCanonicalDecl(D);
917   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
918   if (Stack.back().first.empty())
919       return DSAVarData();
920   for (auto I = std::next(Stack.back().first.rbegin(), 1),
921             E = Stack.back().first.rend();
922        I != E; std::advance(I, 1)) {
923     auto &Data = I->SharingMap[D];
924     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
925       continue;
926     auto &ReductionData = I->ReductionMap[D];
927     if (!ReductionData.ReductionOp ||
928         !ReductionData.ReductionOp.is<const Expr *>())
929       return DSAVarData();
930     SR = ReductionData.ReductionRange;
931     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
932     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
933                                        "expression for the descriptor is not "
934                                        "set.");
935     TaskgroupDescriptor = I->TaskgroupReductionRef;
936     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
937                       Data.PrivateCopy, I->DefaultAttrLoc);
938   }
939   return DSAVarData();
940 }
941 
942 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
943   D = D->getCanonicalDecl();
944   if (!isStackEmpty()) {
945     reverse_iterator I = Iter, E = Stack.back().first.rend();
946     Scope *TopScope = nullptr;
947     while (I != E && !isParallelOrTaskRegion(I->Directive) &&
948            !isOpenMPTargetExecutionDirective(I->Directive))
949       ++I;
950     if (I == E)
951       return false;
952     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
953     Scope *CurScope = getCurScope();
954     while (CurScope != TopScope && !CurScope->isDeclScope(D))
955       CurScope = CurScope->getParent();
956     return CurScope != TopScope;
957   }
958   return false;
959 }
960 
961 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
962   D = getCanonicalDecl(D);
963   DSAVarData DVar;
964 
965   auto *VD = dyn_cast<VarDecl>(D);
966   auto TI = Threadprivates.find(D);
967   if (TI != Threadprivates.end()) {
968     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
969     DVar.CKind = OMPC_threadprivate;
970     return DVar;
971   } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
972     DVar.RefExpr = buildDeclRefExpr(
973         SemaRef, VD, D->getType().getNonReferenceType(),
974         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
975     DVar.CKind = OMPC_threadprivate;
976     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
977     return DVar;
978   }
979   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
980   // in a Construct, C/C++, predetermined, p.1]
981   //  Variables appearing in threadprivate directives are threadprivate.
982   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
983        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
984          SemaRef.getLangOpts().OpenMPUseTLS &&
985          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
986       (VD && VD->getStorageClass() == SC_Register &&
987        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
988     DVar.RefExpr = buildDeclRefExpr(
989         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
990     DVar.CKind = OMPC_threadprivate;
991     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
992     return DVar;
993   }
994   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
995       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
996       !isLoopControlVariable(D).first) {
997     auto IterTarget =
998         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
999                      [](const SharingMapTy &Data) {
1000                        return isOpenMPTargetExecutionDirective(Data.Directive);
1001                      });
1002     if (IterTarget != Stack.back().first.rend()) {
1003       auto ParentIterTarget = std::next(IterTarget, 1);
1004       auto Iter = Stack.back().first.rbegin();
1005       while (Iter != ParentIterTarget) {
1006         if (isOpenMPLocal(VD, Iter)) {
1007           DVar.RefExpr =
1008               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1009                                D->getLocation());
1010           DVar.CKind = OMPC_threadprivate;
1011           return DVar;
1012         }
1013         std::advance(Iter, 1);
1014       }
1015       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1016         auto DSAIter = IterTarget->SharingMap.find(D);
1017         if (DSAIter != IterTarget->SharingMap.end() &&
1018             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1019           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1020           DVar.CKind = OMPC_threadprivate;
1021           return DVar;
1022         } else if (!SemaRef.IsOpenMPCapturedByRef(
1023                        D, std::distance(ParentIterTarget,
1024                                         Stack.back().first.rend()))) {
1025           DVar.RefExpr =
1026               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1027                                IterTarget->ConstructLoc);
1028           DVar.CKind = OMPC_threadprivate;
1029           return DVar;
1030         }
1031       }
1032     }
1033   }
1034 
1035   if (isStackEmpty())
1036     // Not in OpenMP execution region and top scope was already checked.
1037     return DVar;
1038 
1039   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1040   // in a Construct, C/C++, predetermined, p.4]
1041   //  Static data members are shared.
1042   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1043   // in a Construct, C/C++, predetermined, p.7]
1044   //  Variables with static storage duration that are declared in a scope
1045   //  inside the construct are shared.
1046   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
1047   if (VD && VD->isStaticDataMember()) {
1048     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1049     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1050       return DVar;
1051 
1052     DVar.CKind = OMPC_shared;
1053     return DVar;
1054   }
1055 
1056   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1057   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1058   Type = SemaRef.getASTContext().getBaseElementType(Type);
1059   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1060   // in a Construct, C/C++, predetermined, p.6]
1061   //  Variables with const qualified type having no mutable member are
1062   //  shared.
1063   CXXRecordDecl *RD =
1064       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1065   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1066     if (auto *CTD = CTSD->getSpecializedTemplate())
1067       RD = CTD->getTemplatedDecl();
1068   if (IsConstant &&
1069       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1070         RD->hasMutableFields())) {
1071     // Variables with const-qualified type having no mutable member may be
1072     // listed in a firstprivate clause, even if they are static data members.
1073     DSAVarData DVarTemp = hasDSA(
1074         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1075         MatchesAlways, FromParent);
1076     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1077       return DVarTemp;
1078 
1079     DVar.CKind = OMPC_shared;
1080     return DVar;
1081   }
1082 
1083   // Explicitly specified attributes and local variables with predetermined
1084   // attributes.
1085   auto I = Stack.back().first.rbegin();
1086   auto EndI = Stack.back().first.rend();
1087   if (FromParent && I != EndI)
1088     std::advance(I, 1);
1089   if (I->SharingMap.count(D)) {
1090     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
1091     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
1092     DVar.CKind = I->SharingMap[D].Attributes;
1093     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1094     DVar.DKind = I->Directive;
1095   }
1096 
1097   return DVar;
1098 }
1099 
1100 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1101                                                   bool FromParent) {
1102   if (isStackEmpty()) {
1103     StackTy::reverse_iterator I;
1104     return getDSA(I, D);
1105   }
1106   D = getCanonicalDecl(D);
1107   auto StartI = Stack.back().first.rbegin();
1108   auto EndI = Stack.back().first.rend();
1109   if (FromParent && StartI != EndI)
1110     std::advance(StartI, 1);
1111   return getDSA(StartI, D);
1112 }
1113 
1114 DSAStackTy::DSAVarData
1115 DSAStackTy::hasDSA(ValueDecl *D,
1116                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1117                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1118                    bool FromParent) {
1119   if (isStackEmpty())
1120     return {};
1121   D = getCanonicalDecl(D);
1122   auto I = Stack.back().first.rbegin();
1123   auto EndI = Stack.back().first.rend();
1124   if (FromParent && I != EndI)
1125     std::advance(I, 1);
1126   for (; I != EndI; std::advance(I, 1)) {
1127     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1128       continue;
1129     auto NewI = I;
1130     DSAVarData DVar = getDSA(NewI, D);
1131     if (I == NewI && CPred(DVar.CKind))
1132       return DVar;
1133   }
1134   return {};
1135 }
1136 
1137 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1138     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1139     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1140     bool FromParent) {
1141   if (isStackEmpty())
1142     return {};
1143   D = getCanonicalDecl(D);
1144   auto StartI = Stack.back().first.rbegin();
1145   auto EndI = Stack.back().first.rend();
1146   if (FromParent && StartI != EndI)
1147     std::advance(StartI, 1);
1148   if (StartI == EndI || !DPred(StartI->Directive))
1149     return {};
1150   auto NewI = StartI;
1151   DSAVarData DVar = getDSA(NewI, D);
1152   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1153 }
1154 
1155 bool DSAStackTy::hasExplicitDSA(
1156     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1157     unsigned Level, bool NotLastprivate) {
1158   if (isStackEmpty())
1159     return false;
1160   D = getCanonicalDecl(D);
1161   auto StartI = Stack.back().first.begin();
1162   auto EndI = Stack.back().first.end();
1163   if (std::distance(StartI, EndI) <= (int)Level)
1164     return false;
1165   std::advance(StartI, Level);
1166   return (StartI->SharingMap.count(D) > 0) &&
1167          StartI->SharingMap[D].RefExpr.getPointer() &&
1168          CPred(StartI->SharingMap[D].Attributes) &&
1169          (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
1170 }
1171 
1172 bool DSAStackTy::hasExplicitDirective(
1173     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1174     unsigned Level) {
1175   if (isStackEmpty())
1176     return false;
1177   auto StartI = Stack.back().first.begin();
1178   auto EndI = Stack.back().first.end();
1179   if (std::distance(StartI, EndI) <= (int)Level)
1180     return false;
1181   std::advance(StartI, Level);
1182   return DPred(StartI->Directive);
1183 }
1184 
1185 bool DSAStackTy::hasDirective(
1186     const llvm::function_ref<bool(OpenMPDirectiveKind,
1187                                   const DeclarationNameInfo &, SourceLocation)>
1188         &DPred,
1189     bool FromParent) {
1190   // We look only in the enclosing region.
1191   if (isStackEmpty())
1192     return false;
1193   auto StartI = std::next(Stack.back().first.rbegin());
1194   auto EndI = Stack.back().first.rend();
1195   if (FromParent && StartI != EndI)
1196     StartI = std::next(StartI);
1197   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1198     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1199       return true;
1200   }
1201   return false;
1202 }
1203 
1204 void Sema::InitDataSharingAttributesStack() {
1205   VarDataSharingAttributesStack = new DSAStackTy(*this);
1206 }
1207 
1208 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1209 
1210 void Sema::pushOpenMPFunctionRegion() {
1211   DSAStack->pushFunction();
1212 }
1213 
1214 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1215   DSAStack->popFunction(OldFSI);
1216 }
1217 
1218 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
1219   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1220 
1221   auto &Ctx = getASTContext();
1222   bool IsByRef = true;
1223 
1224   // Find the directive that is associated with the provided scope.
1225   D = cast<ValueDecl>(D->getCanonicalDecl());
1226   auto Ty = D->getType();
1227 
1228   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1229     // This table summarizes how a given variable should be passed to the device
1230     // given its type and the clauses where it appears. This table is based on
1231     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1232     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1233     //
1234     // =========================================================================
1235     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1236     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1237     // =========================================================================
1238     // | scl  |               |     |       |       -       |          | bycopy|
1239     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1240     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1241     // | scl  |       x       |     |       |       -       |          | byref |
1242     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1243     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1244     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1245     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1246     //
1247     // | agg  |      n.a.     |     |       |       -       |          | byref |
1248     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1249     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1250     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1251     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1252     //
1253     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1254     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1255     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1256     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1257     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1258     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1259     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1260     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1261     // =========================================================================
1262     // Legend:
1263     //  scl - scalar
1264     //  ptr - pointer
1265     //  agg - aggregate
1266     //  x - applies
1267     //  - - invalid in this combination
1268     //  [] - mapped with an array section
1269     //  byref - should be mapped by reference
1270     //  byval - should be mapped by value
1271     //  null - initialize a local variable to null on the device
1272     //
1273     // Observations:
1274     //  - All scalar declarations that show up in a map clause have to be passed
1275     //    by reference, because they may have been mapped in the enclosing data
1276     //    environment.
1277     //  - If the scalar value does not fit the size of uintptr, it has to be
1278     //    passed by reference, regardless the result in the table above.
1279     //  - For pointers mapped by value that have either an implicit map or an
1280     //    array section, the runtime library may pass the NULL value to the
1281     //    device instead of the value passed to it by the compiler.
1282 
1283     if (Ty->isReferenceType())
1284       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1285 
1286     // Locate map clauses and see if the variable being captured is referred to
1287     // in any of those clauses. Here we only care about variables, not fields,
1288     // because fields are part of aggregates.
1289     bool IsVariableUsedInMapClause = false;
1290     bool IsVariableAssociatedWithSection = false;
1291 
1292     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1293         D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
1294                 MapExprComponents,
1295             OpenMPClauseKind WhereFoundClauseKind) {
1296           // Only the map clause information influences how a variable is
1297           // captured. E.g. is_device_ptr does not require changing the default
1298           // behavior.
1299           if (WhereFoundClauseKind != OMPC_map)
1300             return false;
1301 
1302           auto EI = MapExprComponents.rbegin();
1303           auto EE = MapExprComponents.rend();
1304 
1305           assert(EI != EE && "Invalid map expression!");
1306 
1307           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1308             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1309 
1310           ++EI;
1311           if (EI == EE)
1312             return false;
1313 
1314           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1315               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1316               isa<MemberExpr>(EI->getAssociatedExpression())) {
1317             IsVariableAssociatedWithSection = true;
1318             // There is nothing more we need to know about this variable.
1319             return true;
1320           }
1321 
1322           // Keep looking for more map info.
1323           return false;
1324         });
1325 
1326     if (IsVariableUsedInMapClause) {
1327       // If variable is identified in a map clause it is always captured by
1328       // reference except if it is a pointer that is dereferenced somehow.
1329       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1330     } else {
1331       // By default, all the data that has a scalar type is mapped by copy
1332       // (except for reduction variables).
1333       IsByRef =
1334           !Ty->isScalarType() ||
1335           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1336           DSAStack->hasExplicitDSA(
1337               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1338     }
1339   }
1340 
1341   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1342     IsByRef =
1343         !DSAStack->hasExplicitDSA(
1344             D,
1345             [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1346             Level, /*NotLastprivate=*/true) &&
1347         // If the variable is artificial and must be captured by value - try to
1348         // capture by value.
1349         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1350           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1351   }
1352 
1353   // When passing data by copy, we need to make sure it fits the uintptr size
1354   // and alignment, because the runtime library only deals with uintptr types.
1355   // If it does not fit the uintptr size, we need to pass the data by reference
1356   // instead.
1357   if (!IsByRef &&
1358       (Ctx.getTypeSizeInChars(Ty) >
1359            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1360        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1361     IsByRef = true;
1362   }
1363 
1364   return IsByRef;
1365 }
1366 
1367 unsigned Sema::getOpenMPNestingLevel() const {
1368   assert(getLangOpts().OpenMP);
1369   return DSAStack->getNestingLevel();
1370 }
1371 
1372 bool Sema::isInOpenMPTargetExecutionDirective() const {
1373   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1374           !DSAStack->isClauseParsingMode()) ||
1375          DSAStack->hasDirective(
1376              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1377                 SourceLocation) -> bool {
1378                return isOpenMPTargetExecutionDirective(K);
1379              },
1380              false);
1381 }
1382 
1383 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
1384   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1385   D = getCanonicalDecl(D);
1386 
1387   // If we are attempting to capture a global variable in a directive with
1388   // 'target' we return true so that this global is also mapped to the device.
1389   //
1390   auto *VD = dyn_cast<VarDecl>(D);
1391   if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
1392     // If the declaration is enclosed in a 'declare target' directive,
1393     // then it should not be captured.
1394     //
1395     for (const auto *Var = VD->getMostRecentDecl(); Var;
1396          Var = Var->getPreviousDecl())
1397       if (Var->hasAttr<OMPDeclareTargetDeclAttr>())
1398         return nullptr;
1399     return VD;
1400   }
1401 
1402   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1403       (!DSAStack->isClauseParsingMode() ||
1404        DSAStack->getParentDirective() != OMPD_unknown)) {
1405     auto &&Info = DSAStack->isLoopControlVariable(D);
1406     if (Info.first ||
1407         (VD && VD->hasLocalStorage() &&
1408          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1409         (VD && DSAStack->isForceVarCapturing()))
1410       return VD ? VD : Info.second;
1411     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1412     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1413       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1414     DVarPrivate = DSAStack->hasDSA(
1415         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1416         DSAStack->isClauseParsingMode());
1417     if (DVarPrivate.CKind != OMPC_unknown)
1418       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1419   }
1420   return nullptr;
1421 }
1422 
1423 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1424                                         unsigned Level) const {
1425   SmallVector<OpenMPDirectiveKind, 4> Regions;
1426   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1427   FunctionScopesIndex -= Regions.size();
1428 }
1429 
1430 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1431   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1432   return DSAStack->hasExplicitDSA(
1433              D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1434              Level) ||
1435          (DSAStack->isClauseParsingMode() &&
1436           DSAStack->getClauseParsingMode() == OMPC_private) ||
1437          // Consider taskgroup reduction descriptor variable a private to avoid
1438          // possible capture in the region.
1439          (DSAStack->hasExplicitDirective(
1440               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1441               Level) &&
1442           DSAStack->isTaskgroupReductionRef(D, Level));
1443 }
1444 
1445 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1446   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1447   D = getCanonicalDecl(D);
1448   OpenMPClauseKind OMPC = OMPC_unknown;
1449   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1450     const unsigned NewLevel = I - 1;
1451     if (DSAStack->hasExplicitDSA(D,
1452                                  [&OMPC](const OpenMPClauseKind K) {
1453                                    if (isOpenMPPrivate(K)) {
1454                                      OMPC = K;
1455                                      return true;
1456                                    }
1457                                    return false;
1458                                  },
1459                                  NewLevel))
1460       break;
1461     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1462             D, NewLevel,
1463             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1464                OpenMPClauseKind) { return true; })) {
1465       OMPC = OMPC_map;
1466       break;
1467     }
1468     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1469                                        NewLevel)) {
1470       OMPC = OMPC_map;
1471       if (D->getType()->isScalarType() &&
1472           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1473               DefaultMapAttributes::DMA_tofrom_scalar)
1474         OMPC = OMPC_firstprivate;
1475       break;
1476     }
1477   }
1478   if (OMPC != OMPC_unknown)
1479     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1480 }
1481 
1482 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1483   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1484   // Return true if the current level is no longer enclosed in a target region.
1485 
1486   auto *VD = dyn_cast<VarDecl>(D);
1487   return VD && !VD->hasLocalStorage() &&
1488          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1489                                         Level);
1490 }
1491 
1492 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1493 
1494 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1495                                const DeclarationNameInfo &DirName,
1496                                Scope *CurScope, SourceLocation Loc) {
1497   DSAStack->push(DKind, DirName, CurScope, Loc);
1498   PushExpressionEvaluationContext(
1499       ExpressionEvaluationContext::PotentiallyEvaluated);
1500 }
1501 
1502 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1503   DSAStack->setClauseParsingMode(K);
1504 }
1505 
1506 void Sema::EndOpenMPClause() {
1507   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1508 }
1509 
1510 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1511   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1512   //  A variable of class type (or array thereof) that appears in a lastprivate
1513   //  clause requires an accessible, unambiguous default constructor for the
1514   //  class type, unless the list item is also specified in a firstprivate
1515   //  clause.
1516   if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1517     for (auto *C : D->clauses()) {
1518       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1519         SmallVector<Expr *, 8> PrivateCopies;
1520         for (auto *DE : Clause->varlists()) {
1521           if (DE->isValueDependent() || DE->isTypeDependent()) {
1522             PrivateCopies.push_back(nullptr);
1523             continue;
1524           }
1525           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1526           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1527           QualType Type = VD->getType().getNonReferenceType();
1528           auto DVar = DSAStack->getTopDSA(VD, false);
1529           if (DVar.CKind == OMPC_lastprivate) {
1530             // Generate helper private variable and initialize it with the
1531             // default value. The address of the original variable is replaced
1532             // by the address of the new private variable in CodeGen. This new
1533             // variable is not added to IdResolver, so the code in the OpenMP
1534             // region uses original variable for proper diagnostics.
1535             auto *VDPrivate = buildVarDecl(
1536                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1537                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1538             ActOnUninitializedDecl(VDPrivate);
1539             if (VDPrivate->isInvalidDecl())
1540               continue;
1541             PrivateCopies.push_back(buildDeclRefExpr(
1542                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1543           } else {
1544             // The variable is also a firstprivate, so initialization sequence
1545             // for private copy is generated already.
1546             PrivateCopies.push_back(nullptr);
1547           }
1548         }
1549         // Set initializers to private copies if no errors were found.
1550         if (PrivateCopies.size() == Clause->varlist_size())
1551           Clause->setPrivateCopies(PrivateCopies);
1552       }
1553     }
1554   }
1555 
1556   DSAStack->pop();
1557   DiscardCleanupsInEvaluationContext();
1558   PopExpressionEvaluationContext();
1559 }
1560 
1561 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1562                                      Expr *NumIterations, Sema &SemaRef,
1563                                      Scope *S, DSAStackTy *Stack);
1564 
1565 namespace {
1566 
1567 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1568 private:
1569   Sema &SemaRef;
1570 
1571 public:
1572   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1573   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1574     NamedDecl *ND = Candidate.getCorrectionDecl();
1575     if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1576       return VD->hasGlobalStorage() &&
1577              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1578                                    SemaRef.getCurScope());
1579     }
1580     return false;
1581   }
1582 };
1583 
1584 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1585 private:
1586   Sema &SemaRef;
1587 
1588 public:
1589   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1590   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1591     NamedDecl *ND = Candidate.getCorrectionDecl();
1592     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1593       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1594                                    SemaRef.getCurScope());
1595     }
1596     return false;
1597   }
1598 };
1599 
1600 } // namespace
1601 
1602 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1603                                          CXXScopeSpec &ScopeSpec,
1604                                          const DeclarationNameInfo &Id) {
1605   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1606   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1607 
1608   if (Lookup.isAmbiguous())
1609     return ExprError();
1610 
1611   VarDecl *VD;
1612   if (!Lookup.isSingleResult()) {
1613     if (TypoCorrection Corrected = CorrectTypo(
1614             Id, LookupOrdinaryName, CurScope, nullptr,
1615             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1616       diagnoseTypo(Corrected,
1617                    PDiag(Lookup.empty()
1618                              ? diag::err_undeclared_var_use_suggest
1619                              : diag::err_omp_expected_var_arg_suggest)
1620                        << Id.getName());
1621       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1622     } else {
1623       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1624                                        : diag::err_omp_expected_var_arg)
1625           << Id.getName();
1626       return ExprError();
1627     }
1628   } else {
1629     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1630       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1631       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1632       return ExprError();
1633     }
1634   }
1635   Lookup.suppressDiagnostics();
1636 
1637   // OpenMP [2.9.2, Syntax, C/C++]
1638   //   Variables must be file-scope, namespace-scope, or static block-scope.
1639   if (!VD->hasGlobalStorage()) {
1640     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1641         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1642     bool IsDecl =
1643         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1644     Diag(VD->getLocation(),
1645          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1646         << VD;
1647     return ExprError();
1648   }
1649 
1650   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1651   NamedDecl *ND = CanonicalVD;
1652   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1653   //   A threadprivate directive for file-scope variables must appear outside
1654   //   any definition or declaration.
1655   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1656       !getCurLexicalContext()->isTranslationUnit()) {
1657     Diag(Id.getLoc(), diag::err_omp_var_scope)
1658         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1659     bool IsDecl =
1660         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1661     Diag(VD->getLocation(),
1662          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1663         << VD;
1664     return ExprError();
1665   }
1666   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1667   //   A threadprivate directive for static class member variables must appear
1668   //   in the class definition, in the same scope in which the member
1669   //   variables are declared.
1670   if (CanonicalVD->isStaticDataMember() &&
1671       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1672     Diag(Id.getLoc(), diag::err_omp_var_scope)
1673         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1674     bool IsDecl =
1675         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1676     Diag(VD->getLocation(),
1677          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1678         << VD;
1679     return ExprError();
1680   }
1681   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1682   //   A threadprivate directive for namespace-scope variables must appear
1683   //   outside any definition or declaration other than the namespace
1684   //   definition itself.
1685   if (CanonicalVD->getDeclContext()->isNamespace() &&
1686       (!getCurLexicalContext()->isFileContext() ||
1687        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1688     Diag(Id.getLoc(), diag::err_omp_var_scope)
1689         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1690     bool IsDecl =
1691         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1692     Diag(VD->getLocation(),
1693          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1694         << VD;
1695     return ExprError();
1696   }
1697   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1698   //   A threadprivate directive for static block-scope variables must appear
1699   //   in the scope of the variable and not in a nested scope.
1700   if (CanonicalVD->isStaticLocal() && CurScope &&
1701       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1702     Diag(Id.getLoc(), diag::err_omp_var_scope)
1703         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1704     bool IsDecl =
1705         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1706     Diag(VD->getLocation(),
1707          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1708         << VD;
1709     return ExprError();
1710   }
1711 
1712   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1713   //   A threadprivate directive must lexically precede all references to any
1714   //   of the variables in its list.
1715   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1716     Diag(Id.getLoc(), diag::err_omp_var_used)
1717         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1718     return ExprError();
1719   }
1720 
1721   QualType ExprType = VD->getType().getNonReferenceType();
1722   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1723                              SourceLocation(), VD,
1724                              /*RefersToEnclosingVariableOrCapture=*/false,
1725                              Id.getLoc(), ExprType, VK_LValue);
1726 }
1727 
1728 Sema::DeclGroupPtrTy
1729 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1730                                         ArrayRef<Expr *> VarList) {
1731   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1732     CurContext->addDecl(D);
1733     return DeclGroupPtrTy::make(DeclGroupRef(D));
1734   }
1735   return nullptr;
1736 }
1737 
1738 namespace {
1739 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1740   Sema &SemaRef;
1741 
1742 public:
1743   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1744     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1745       if (VD->hasLocalStorage()) {
1746         SemaRef.Diag(E->getLocStart(),
1747                      diag::err_omp_local_var_in_threadprivate_init)
1748             << E->getSourceRange();
1749         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1750             << VD << VD->getSourceRange();
1751         return true;
1752       }
1753     }
1754     return false;
1755   }
1756   bool VisitStmt(const Stmt *S) {
1757     for (auto Child : S->children()) {
1758       if (Child && Visit(Child))
1759         return true;
1760     }
1761     return false;
1762   }
1763   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1764 };
1765 } // namespace
1766 
1767 OMPThreadPrivateDecl *
1768 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1769   SmallVector<Expr *, 8> Vars;
1770   for (auto &RefExpr : VarList) {
1771     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1772     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1773     SourceLocation ILoc = DE->getExprLoc();
1774 
1775     // Mark variable as used.
1776     VD->setReferenced();
1777     VD->markUsed(Context);
1778 
1779     QualType QType = VD->getType();
1780     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1781       // It will be analyzed later.
1782       Vars.push_back(DE);
1783       continue;
1784     }
1785 
1786     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1787     //   A threadprivate variable must not have an incomplete type.
1788     if (RequireCompleteType(ILoc, VD->getType(),
1789                             diag::err_omp_threadprivate_incomplete_type)) {
1790       continue;
1791     }
1792 
1793     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1794     //   A threadprivate variable must not have a reference type.
1795     if (VD->getType()->isReferenceType()) {
1796       Diag(ILoc, diag::err_omp_ref_type_arg)
1797           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1798       bool IsDecl =
1799           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1800       Diag(VD->getLocation(),
1801            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1802           << VD;
1803       continue;
1804     }
1805 
1806     // Check if this is a TLS variable. If TLS is not being supported, produce
1807     // the corresponding diagnostic.
1808     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1809          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1810            getLangOpts().OpenMPUseTLS &&
1811            getASTContext().getTargetInfo().isTLSSupported())) ||
1812         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1813          !VD->isLocalVarDecl())) {
1814       Diag(ILoc, diag::err_omp_var_thread_local)
1815           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1816       bool IsDecl =
1817           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1818       Diag(VD->getLocation(),
1819            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1820           << VD;
1821       continue;
1822     }
1823 
1824     // Check if initial value of threadprivate variable reference variable with
1825     // local storage (it is not supported by runtime).
1826     if (auto Init = VD->getAnyInitializer()) {
1827       LocalVarRefChecker Checker(*this);
1828       if (Checker.Visit(Init))
1829         continue;
1830     }
1831 
1832     Vars.push_back(RefExpr);
1833     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1834     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1835         Context, SourceRange(Loc, Loc)));
1836     if (auto *ML = Context.getASTMutationListener())
1837       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1838   }
1839   OMPThreadPrivateDecl *D = nullptr;
1840   if (!Vars.empty()) {
1841     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1842                                      Vars);
1843     D->setAccess(AS_public);
1844   }
1845   return D;
1846 }
1847 
1848 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1849                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1850                               bool IsLoopIterVar = false) {
1851   if (DVar.RefExpr) {
1852     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1853         << getOpenMPClauseName(DVar.CKind);
1854     return;
1855   }
1856   enum {
1857     PDSA_StaticMemberShared,
1858     PDSA_StaticLocalVarShared,
1859     PDSA_LoopIterVarPrivate,
1860     PDSA_LoopIterVarLinear,
1861     PDSA_LoopIterVarLastprivate,
1862     PDSA_ConstVarShared,
1863     PDSA_GlobalVarShared,
1864     PDSA_TaskVarFirstprivate,
1865     PDSA_LocalVarPrivate,
1866     PDSA_Implicit
1867   } Reason = PDSA_Implicit;
1868   bool ReportHint = false;
1869   auto ReportLoc = D->getLocation();
1870   auto *VD = dyn_cast<VarDecl>(D);
1871   if (IsLoopIterVar) {
1872     if (DVar.CKind == OMPC_private)
1873       Reason = PDSA_LoopIterVarPrivate;
1874     else if (DVar.CKind == OMPC_lastprivate)
1875       Reason = PDSA_LoopIterVarLastprivate;
1876     else
1877       Reason = PDSA_LoopIterVarLinear;
1878   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1879              DVar.CKind == OMPC_firstprivate) {
1880     Reason = PDSA_TaskVarFirstprivate;
1881     ReportLoc = DVar.ImplicitDSALoc;
1882   } else if (VD && VD->isStaticLocal())
1883     Reason = PDSA_StaticLocalVarShared;
1884   else if (VD && VD->isStaticDataMember())
1885     Reason = PDSA_StaticMemberShared;
1886   else if (VD && VD->isFileVarDecl())
1887     Reason = PDSA_GlobalVarShared;
1888   else if (D->getType().isConstant(SemaRef.getASTContext()))
1889     Reason = PDSA_ConstVarShared;
1890   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1891     ReportHint = true;
1892     Reason = PDSA_LocalVarPrivate;
1893   }
1894   if (Reason != PDSA_Implicit) {
1895     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1896         << Reason << ReportHint
1897         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1898   } else if (DVar.ImplicitDSALoc.isValid()) {
1899     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1900         << getOpenMPClauseName(DVar.CKind);
1901   }
1902 }
1903 
1904 namespace {
1905 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1906   DSAStackTy *Stack;
1907   Sema &SemaRef;
1908   bool ErrorFound;
1909   CapturedStmt *CS;
1910   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1911   llvm::SmallVector<Expr *, 8> ImplicitMap;
1912   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1913   llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
1914 
1915 public:
1916   void VisitDeclRefExpr(DeclRefExpr *E) {
1917     if (E->isTypeDependent() || E->isValueDependent() ||
1918         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1919       return;
1920     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1921       VD = VD->getCanonicalDecl();
1922       // Skip internally declared variables.
1923       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
1924         return;
1925 
1926       auto DVar = Stack->getTopDSA(VD, false);
1927       // Check if the variable has explicit DSA set and stop analysis if it so.
1928       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
1929         return;
1930 
1931       // Skip internally declared static variables.
1932       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1933         return;
1934 
1935       auto ELoc = E->getExprLoc();
1936       auto DKind = Stack->getCurrentDirective();
1937       // The default(none) clause requires that each variable that is referenced
1938       // in the construct, and does not have a predetermined data-sharing
1939       // attribute, must have its data-sharing attribute explicitly determined
1940       // by being listed in a data-sharing attribute clause.
1941       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1942           isParallelOrTaskRegion(DKind) &&
1943           VarsWithInheritedDSA.count(VD) == 0) {
1944         VarsWithInheritedDSA[VD] = E;
1945         return;
1946       }
1947 
1948       if (isOpenMPTargetExecutionDirective(DKind) &&
1949           !Stack->isLoopControlVariable(VD).first) {
1950         if (!Stack->checkMappableExprComponentListsForDecl(
1951                 VD, /*CurrentRegionOnly=*/true,
1952                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1953                        StackComponents,
1954                    OpenMPClauseKind) {
1955                   // Variable is used if it has been marked as an array, array
1956                   // section or the variable iself.
1957                   return StackComponents.size() == 1 ||
1958                          std::all_of(
1959                              std::next(StackComponents.rbegin()),
1960                              StackComponents.rend(),
1961                              [](const OMPClauseMappableExprCommon::
1962                                     MappableComponent &MC) {
1963                                return MC.getAssociatedDeclaration() ==
1964                                           nullptr &&
1965                                       (isa<OMPArraySectionExpr>(
1966                                            MC.getAssociatedExpression()) ||
1967                                        isa<ArraySubscriptExpr>(
1968                                            MC.getAssociatedExpression()));
1969                              });
1970                 })) {
1971           bool IsFirstprivate = false;
1972           // By default lambdas are captured as firstprivates.
1973           if (const auto *RD =
1974                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
1975             IsFirstprivate = RD->isLambda();
1976           IsFirstprivate =
1977               IsFirstprivate ||
1978               (VD->getType().getNonReferenceType()->isScalarType() &&
1979                Stack->getDefaultDMA() != DMA_tofrom_scalar);
1980           if (IsFirstprivate)
1981             ImplicitFirstprivate.emplace_back(E);
1982           else
1983             ImplicitMap.emplace_back(E);
1984           return;
1985         }
1986       }
1987 
1988       // OpenMP [2.9.3.6, Restrictions, p.2]
1989       //  A list item that appears in a reduction clause of the innermost
1990       //  enclosing worksharing or parallel construct may not be accessed in an
1991       //  explicit task.
1992       DVar = Stack->hasInnermostDSA(
1993           VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1994           [](OpenMPDirectiveKind K) -> bool {
1995             return isOpenMPParallelDirective(K) ||
1996                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1997           },
1998           /*FromParent=*/true);
1999       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2000         ErrorFound = true;
2001         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2002         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
2003         return;
2004       }
2005 
2006       // Define implicit data-sharing attributes for task.
2007       DVar = Stack->getImplicitDSA(VD, false);
2008       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2009           !Stack->isLoopControlVariable(VD).first)
2010         ImplicitFirstprivate.push_back(E);
2011     }
2012   }
2013   void VisitMemberExpr(MemberExpr *E) {
2014     if (E->isTypeDependent() || E->isValueDependent() ||
2015         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2016       return;
2017     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2018     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2019     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2020       if (!FD)
2021         return;
2022       auto DVar = Stack->getTopDSA(FD, false);
2023       // Check if the variable has explicit DSA set and stop analysis if it
2024       // so.
2025       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2026         return;
2027 
2028       if (isOpenMPTargetExecutionDirective(DKind) &&
2029           !Stack->isLoopControlVariable(FD).first &&
2030           !Stack->checkMappableExprComponentListsForDecl(
2031               FD, /*CurrentRegionOnly=*/true,
2032               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2033                      StackComponents,
2034                  OpenMPClauseKind) {
2035                 return isa<CXXThisExpr>(
2036                     cast<MemberExpr>(
2037                         StackComponents.back().getAssociatedExpression())
2038                         ->getBase()
2039                         ->IgnoreParens());
2040               })) {
2041         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2042         //  A bit-field cannot appear in a map clause.
2043         //
2044         if (FD->isBitField())
2045           return;
2046         ImplicitMap.emplace_back(E);
2047         return;
2048       }
2049 
2050       auto ELoc = E->getExprLoc();
2051       // OpenMP [2.9.3.6, Restrictions, p.2]
2052       //  A list item that appears in a reduction clause of the innermost
2053       //  enclosing worksharing or parallel construct may not be accessed in
2054       //  an  explicit task.
2055       DVar = Stack->hasInnermostDSA(
2056           FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2057           [](OpenMPDirectiveKind K) -> bool {
2058             return isOpenMPParallelDirective(K) ||
2059                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2060           },
2061           /*FromParent=*/true);
2062       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2063         ErrorFound = true;
2064         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2065         ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2066         return;
2067       }
2068 
2069       // Define implicit data-sharing attributes for task.
2070       DVar = Stack->getImplicitDSA(FD, false);
2071       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2072           !Stack->isLoopControlVariable(FD).first)
2073         ImplicitFirstprivate.push_back(E);
2074       return;
2075     }
2076     if (isOpenMPTargetExecutionDirective(DKind)) {
2077       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2078       if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2079                                         /*NoDiagnose=*/true))
2080         return;
2081       auto *VD = cast<ValueDecl>(
2082           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2083       if (!Stack->checkMappableExprComponentListsForDecl(
2084               VD, /*CurrentRegionOnly=*/true,
2085               [&CurComponents](
2086                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2087                       StackComponents,
2088                   OpenMPClauseKind) {
2089                 auto CCI = CurComponents.rbegin();
2090                 auto CCE = CurComponents.rend();
2091                 for (const auto &SC : llvm::reverse(StackComponents)) {
2092                   // Do both expressions have the same kind?
2093                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2094                       SC.getAssociatedExpression()->getStmtClass())
2095                     if (!(isa<OMPArraySectionExpr>(
2096                               SC.getAssociatedExpression()) &&
2097                           isa<ArraySubscriptExpr>(
2098                               CCI->getAssociatedExpression())))
2099                       return false;
2100 
2101                   Decl *CCD = CCI->getAssociatedDeclaration();
2102                   Decl *SCD = SC.getAssociatedDeclaration();
2103                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2104                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2105                   if (SCD != CCD)
2106                     return false;
2107                   std::advance(CCI, 1);
2108                   if (CCI == CCE)
2109                     break;
2110                 }
2111                 return true;
2112               })) {
2113         Visit(E->getBase());
2114       }
2115     } else
2116       Visit(E->getBase());
2117   }
2118   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2119     for (auto *C : S->clauses()) {
2120       // Skip analysis of arguments of implicitly defined firstprivate clause
2121       // for task|target directives.
2122       // Skip analysis of arguments of implicitly defined map clause for target
2123       // directives.
2124       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2125                  C->isImplicit())) {
2126         for (auto *CC : C->children()) {
2127           if (CC)
2128             Visit(CC);
2129         }
2130       }
2131     }
2132   }
2133   void VisitStmt(Stmt *S) {
2134     for (auto *C : S->children()) {
2135       if (C && !isa<OMPExecutableDirective>(C))
2136         Visit(C);
2137     }
2138   }
2139 
2140   bool isErrorFound() { return ErrorFound; }
2141   ArrayRef<Expr *> getImplicitFirstprivate() const {
2142     return ImplicitFirstprivate;
2143   }
2144   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2145   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
2146     return VarsWithInheritedDSA;
2147   }
2148 
2149   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2150       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2151 };
2152 } // namespace
2153 
2154 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2155   switch (DKind) {
2156   case OMPD_parallel:
2157   case OMPD_parallel_for:
2158   case OMPD_parallel_for_simd:
2159   case OMPD_parallel_sections:
2160   case OMPD_teams:
2161   case OMPD_teams_distribute:
2162   case OMPD_teams_distribute_simd: {
2163     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2164     QualType KmpInt32PtrTy =
2165         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2166     Sema::CapturedParamNameType Params[] = {
2167         std::make_pair(".global_tid.", KmpInt32PtrTy),
2168         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2169         std::make_pair(StringRef(), QualType()) // __context with shared vars
2170     };
2171     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2172                              Params);
2173     break;
2174   }
2175   case OMPD_target_teams:
2176   case OMPD_target_parallel:
2177   case OMPD_target_parallel_for:
2178   case OMPD_target_parallel_for_simd:
2179   case OMPD_target_teams_distribute:
2180   case OMPD_target_teams_distribute_simd: {
2181     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2182     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2183     FunctionProtoType::ExtProtoInfo EPI;
2184     EPI.Variadic = true;
2185     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2186     Sema::CapturedParamNameType Params[] = {
2187         std::make_pair(".global_tid.", KmpInt32Ty),
2188         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2189         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2190         std::make_pair(".copy_fn.",
2191                        Context.getPointerType(CopyFnType).withConst()),
2192         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2193         std::make_pair(StringRef(), QualType()) // __context with shared vars
2194     };
2195     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2196                              Params);
2197     // Mark this captured region as inlined, because we don't use outlined
2198     // function directly.
2199     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2200         AlwaysInlineAttr::CreateImplicit(
2201             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2202     Sema::CapturedParamNameType ParamsTarget[] = {
2203         std::make_pair(StringRef(), QualType()) // __context with shared vars
2204     };
2205     // Start a captured region for 'target' with no implicit parameters.
2206     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2207                              ParamsTarget);
2208     QualType KmpInt32PtrTy =
2209         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2210     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2211         std::make_pair(".global_tid.", KmpInt32PtrTy),
2212         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2213         std::make_pair(StringRef(), QualType()) // __context with shared vars
2214     };
2215     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2216     // the same implicit parameters.
2217     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2218                              ParamsTeamsOrParallel);
2219     break;
2220   }
2221   case OMPD_target:
2222   case OMPD_target_simd: {
2223     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2224     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2225     FunctionProtoType::ExtProtoInfo EPI;
2226     EPI.Variadic = true;
2227     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2228     Sema::CapturedParamNameType Params[] = {
2229         std::make_pair(".global_tid.", KmpInt32Ty),
2230         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2231         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2232         std::make_pair(".copy_fn.",
2233                        Context.getPointerType(CopyFnType).withConst()),
2234         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2235         std::make_pair(StringRef(), QualType()) // __context with shared vars
2236     };
2237     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2238                              Params);
2239     // Mark this captured region as inlined, because we don't use outlined
2240     // function directly.
2241     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2242         AlwaysInlineAttr::CreateImplicit(
2243             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2244     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2245                              std::make_pair(StringRef(), QualType()));
2246     break;
2247   }
2248   case OMPD_simd:
2249   case OMPD_for:
2250   case OMPD_for_simd:
2251   case OMPD_sections:
2252   case OMPD_section:
2253   case OMPD_single:
2254   case OMPD_master:
2255   case OMPD_critical:
2256   case OMPD_taskgroup:
2257   case OMPD_distribute:
2258   case OMPD_distribute_simd:
2259   case OMPD_ordered:
2260   case OMPD_atomic:
2261   case OMPD_target_data: {
2262     Sema::CapturedParamNameType Params[] = {
2263         std::make_pair(StringRef(), QualType()) // __context with shared vars
2264     };
2265     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2266                              Params);
2267     break;
2268   }
2269   case OMPD_task: {
2270     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2271     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2272     FunctionProtoType::ExtProtoInfo EPI;
2273     EPI.Variadic = true;
2274     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2275     Sema::CapturedParamNameType Params[] = {
2276         std::make_pair(".global_tid.", KmpInt32Ty),
2277         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2278         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2279         std::make_pair(".copy_fn.",
2280                        Context.getPointerType(CopyFnType).withConst()),
2281         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2282         std::make_pair(StringRef(), QualType()) // __context with shared vars
2283     };
2284     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2285                              Params);
2286     // Mark this captured region as inlined, because we don't use outlined
2287     // function directly.
2288     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2289         AlwaysInlineAttr::CreateImplicit(
2290             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2291     break;
2292   }
2293   case OMPD_taskloop:
2294   case OMPD_taskloop_simd: {
2295     QualType KmpInt32Ty =
2296         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2297     QualType KmpUInt64Ty =
2298         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2299     QualType KmpInt64Ty =
2300         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2301     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2302     FunctionProtoType::ExtProtoInfo EPI;
2303     EPI.Variadic = true;
2304     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2305     Sema::CapturedParamNameType Params[] = {
2306         std::make_pair(".global_tid.", KmpInt32Ty),
2307         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2308         std::make_pair(".privates.",
2309                        Context.VoidPtrTy.withConst().withRestrict()),
2310         std::make_pair(
2311             ".copy_fn.",
2312             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2313         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2314         std::make_pair(".lb.", KmpUInt64Ty),
2315         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2316         std::make_pair(".liter.", KmpInt32Ty),
2317         std::make_pair(".reductions.",
2318                        Context.VoidPtrTy.withConst().withRestrict()),
2319         std::make_pair(StringRef(), QualType()) // __context with shared vars
2320     };
2321     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2322                              Params);
2323     // Mark this captured region as inlined, because we don't use outlined
2324     // function directly.
2325     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2326         AlwaysInlineAttr::CreateImplicit(
2327             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2328     break;
2329   }
2330   case OMPD_distribute_parallel_for_simd:
2331   case OMPD_distribute_parallel_for: {
2332     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2333     QualType KmpInt32PtrTy =
2334         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2335     Sema::CapturedParamNameType Params[] = {
2336         std::make_pair(".global_tid.", KmpInt32PtrTy),
2337         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2338         std::make_pair(".previous.lb.", Context.getSizeType()),
2339         std::make_pair(".previous.ub.", Context.getSizeType()),
2340         std::make_pair(StringRef(), QualType()) // __context with shared vars
2341     };
2342     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2343                              Params);
2344     break;
2345   }
2346   case OMPD_target_teams_distribute_parallel_for:
2347   case OMPD_target_teams_distribute_parallel_for_simd: {
2348     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2349     QualType KmpInt32PtrTy =
2350         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2351 
2352     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2353     FunctionProtoType::ExtProtoInfo EPI;
2354     EPI.Variadic = true;
2355     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2356     Sema::CapturedParamNameType Params[] = {
2357         std::make_pair(".global_tid.", KmpInt32Ty),
2358         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2359         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2360         std::make_pair(".copy_fn.",
2361                        Context.getPointerType(CopyFnType).withConst()),
2362         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2363         std::make_pair(StringRef(), QualType()) // __context with shared vars
2364     };
2365     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2366                              Params);
2367     // Mark this captured region as inlined, because we don't use outlined
2368     // function directly.
2369     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2370         AlwaysInlineAttr::CreateImplicit(
2371             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2372     Sema::CapturedParamNameType ParamsTarget[] = {
2373         std::make_pair(StringRef(), QualType()) // __context with shared vars
2374     };
2375     // Start a captured region for 'target' with no implicit parameters.
2376     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2377                              ParamsTarget);
2378 
2379     Sema::CapturedParamNameType ParamsTeams[] = {
2380         std::make_pair(".global_tid.", KmpInt32PtrTy),
2381         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2382         std::make_pair(StringRef(), QualType()) // __context with shared vars
2383     };
2384     // Start a captured region for 'target' with no implicit parameters.
2385     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2386                              ParamsTeams);
2387 
2388     Sema::CapturedParamNameType ParamsParallel[] = {
2389         std::make_pair(".global_tid.", KmpInt32PtrTy),
2390         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2391         std::make_pair(".previous.lb.", Context.getSizeType()),
2392         std::make_pair(".previous.ub.", Context.getSizeType()),
2393         std::make_pair(StringRef(), QualType()) // __context with shared vars
2394     };
2395     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2396     // the same implicit parameters.
2397     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2398                              ParamsParallel);
2399     break;
2400   }
2401 
2402   case OMPD_teams_distribute_parallel_for:
2403   case OMPD_teams_distribute_parallel_for_simd: {
2404     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2405     QualType KmpInt32PtrTy =
2406         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2407 
2408     Sema::CapturedParamNameType ParamsTeams[] = {
2409         std::make_pair(".global_tid.", KmpInt32PtrTy),
2410         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2411         std::make_pair(StringRef(), QualType()) // __context with shared vars
2412     };
2413     // Start a captured region for 'target' with no implicit parameters.
2414     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2415                              ParamsTeams);
2416 
2417     Sema::CapturedParamNameType ParamsParallel[] = {
2418         std::make_pair(".global_tid.", KmpInt32PtrTy),
2419         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2420         std::make_pair(".previous.lb.", Context.getSizeType()),
2421         std::make_pair(".previous.ub.", Context.getSizeType()),
2422         std::make_pair(StringRef(), QualType()) // __context with shared vars
2423     };
2424     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2425     // the same implicit parameters.
2426     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2427                              ParamsParallel);
2428     break;
2429   }
2430   case OMPD_target_update:
2431   case OMPD_target_enter_data:
2432   case OMPD_target_exit_data: {
2433     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2434     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2435     FunctionProtoType::ExtProtoInfo EPI;
2436     EPI.Variadic = true;
2437     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2438     Sema::CapturedParamNameType Params[] = {
2439         std::make_pair(".global_tid.", KmpInt32Ty),
2440         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2441         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2442         std::make_pair(".copy_fn.",
2443                        Context.getPointerType(CopyFnType).withConst()),
2444         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2445         std::make_pair(StringRef(), QualType()) // __context with shared vars
2446     };
2447     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2448                              Params);
2449     // Mark this captured region as inlined, because we don't use outlined
2450     // function directly.
2451     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2452         AlwaysInlineAttr::CreateImplicit(
2453             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2454     break;
2455   }
2456   case OMPD_threadprivate:
2457   case OMPD_taskyield:
2458   case OMPD_barrier:
2459   case OMPD_taskwait:
2460   case OMPD_cancellation_point:
2461   case OMPD_cancel:
2462   case OMPD_flush:
2463   case OMPD_declare_reduction:
2464   case OMPD_declare_simd:
2465   case OMPD_declare_target:
2466   case OMPD_end_declare_target:
2467     llvm_unreachable("OpenMP Directive is not allowed");
2468   case OMPD_unknown:
2469     llvm_unreachable("Unknown OpenMP directive");
2470   }
2471 }
2472 
2473 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2474   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2475   getOpenMPCaptureRegions(CaptureRegions, DKind);
2476   return CaptureRegions.size();
2477 }
2478 
2479 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2480                                              Expr *CaptureExpr, bool WithInit,
2481                                              bool AsExpression) {
2482   assert(CaptureExpr);
2483   ASTContext &C = S.getASTContext();
2484   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2485   QualType Ty = Init->getType();
2486   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2487     if (S.getLangOpts().CPlusPlus) {
2488       Ty = C.getLValueReferenceType(Ty);
2489     } else {
2490       Ty = C.getPointerType(Ty);
2491       ExprResult Res =
2492           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2493       if (!Res.isUsable())
2494         return nullptr;
2495       Init = Res.get();
2496     }
2497     WithInit = true;
2498   }
2499   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2500                                           CaptureExpr->getLocStart());
2501   if (!WithInit)
2502     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
2503   S.CurContext->addHiddenDecl(CED);
2504   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2505   return CED;
2506 }
2507 
2508 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2509                                  bool WithInit) {
2510   OMPCapturedExprDecl *CD;
2511   if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
2512     CD = cast<OMPCapturedExprDecl>(VD);
2513   } else {
2514     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2515                           /*AsExpression=*/false);
2516   }
2517   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2518                           CaptureExpr->getExprLoc());
2519 }
2520 
2521 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2522   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2523   if (!Ref) {
2524     OMPCapturedExprDecl *CD = buildCaptureDecl(
2525         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2526         /*WithInit=*/true, /*AsExpression=*/true);
2527     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2528                            CaptureExpr->getExprLoc());
2529   }
2530   ExprResult Res = Ref;
2531   if (!S.getLangOpts().CPlusPlus &&
2532       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2533       Ref->getType()->isPointerType()) {
2534     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2535     if (!Res.isUsable())
2536       return ExprError();
2537   }
2538   return S.DefaultLvalueConversion(Res.get());
2539 }
2540 
2541 namespace {
2542 // OpenMP directives parsed in this section are represented as a
2543 // CapturedStatement with an associated statement.  If a syntax error
2544 // is detected during the parsing of the associated statement, the
2545 // compiler must abort processing and close the CapturedStatement.
2546 //
2547 // Combined directives such as 'target parallel' have more than one
2548 // nested CapturedStatements.  This RAII ensures that we unwind out
2549 // of all the nested CapturedStatements when an error is found.
2550 class CaptureRegionUnwinderRAII {
2551 private:
2552   Sema &S;
2553   bool &ErrorFound;
2554   OpenMPDirectiveKind DKind;
2555 
2556 public:
2557   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2558                             OpenMPDirectiveKind DKind)
2559       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2560   ~CaptureRegionUnwinderRAII() {
2561     if (ErrorFound) {
2562       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2563       while (--ThisCaptureLevel >= 0)
2564         S.ActOnCapturedRegionError();
2565     }
2566   }
2567 };
2568 } // namespace
2569 
2570 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2571                                       ArrayRef<OMPClause *> Clauses) {
2572   bool ErrorFound = false;
2573   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2574       *this, ErrorFound, DSAStack->getCurrentDirective());
2575   if (!S.isUsable()) {
2576     ErrorFound = true;
2577     return StmtError();
2578   }
2579 
2580   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2581   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2582   OMPOrderedClause *OC = nullptr;
2583   OMPScheduleClause *SC = nullptr;
2584   SmallVector<OMPLinearClause *, 4> LCs;
2585   SmallVector<OMPClauseWithPreInit *, 8> PICs;
2586   // This is required for proper codegen.
2587   for (auto *Clause : Clauses) {
2588     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2589         Clause->getClauseKind() == OMPC_in_reduction) {
2590       // Capture taskgroup task_reduction descriptors inside the tasking regions
2591       // with the corresponding in_reduction items.
2592       auto *IRC = cast<OMPInReductionClause>(Clause);
2593       for (auto *E : IRC->taskgroup_descriptors())
2594         if (E)
2595           MarkDeclarationsReferencedInExpr(E);
2596     }
2597     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2598         Clause->getClauseKind() == OMPC_copyprivate ||
2599         (getLangOpts().OpenMPUseTLS &&
2600          getASTContext().getTargetInfo().isTLSSupported() &&
2601          Clause->getClauseKind() == OMPC_copyin)) {
2602       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2603       // Mark all variables in private list clauses as used in inner region.
2604       for (auto *VarRef : Clause->children()) {
2605         if (auto *E = cast_or_null<Expr>(VarRef)) {
2606           MarkDeclarationsReferencedInExpr(E);
2607         }
2608       }
2609       DSAStack->setForceVarCapturing(/*V=*/false);
2610     } else if (CaptureRegions.size() > 1 ||
2611                CaptureRegions.back() != OMPD_unknown) {
2612       if (auto *C = OMPClauseWithPreInit::get(Clause))
2613         PICs.push_back(C);
2614       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2615         if (auto *E = C->getPostUpdateExpr())
2616           MarkDeclarationsReferencedInExpr(E);
2617       }
2618     }
2619     if (Clause->getClauseKind() == OMPC_schedule)
2620       SC = cast<OMPScheduleClause>(Clause);
2621     else if (Clause->getClauseKind() == OMPC_ordered)
2622       OC = cast<OMPOrderedClause>(Clause);
2623     else if (Clause->getClauseKind() == OMPC_linear)
2624       LCs.push_back(cast<OMPLinearClause>(Clause));
2625   }
2626   // OpenMP, 2.7.1 Loop Construct, Restrictions
2627   // The nonmonotonic modifier cannot be specified if an ordered clause is
2628   // specified.
2629   if (SC &&
2630       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2631        SC->getSecondScheduleModifier() ==
2632            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2633       OC) {
2634     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2635              ? SC->getFirstScheduleModifierLoc()
2636              : SC->getSecondScheduleModifierLoc(),
2637          diag::err_omp_schedule_nonmonotonic_ordered)
2638         << SourceRange(OC->getLocStart(), OC->getLocEnd());
2639     ErrorFound = true;
2640   }
2641   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2642     for (auto *C : LCs) {
2643       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2644           << SourceRange(OC->getLocStart(), OC->getLocEnd());
2645     }
2646     ErrorFound = true;
2647   }
2648   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2649       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2650       OC->getNumForLoops()) {
2651     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2652         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2653     ErrorFound = true;
2654   }
2655   if (ErrorFound) {
2656     return StmtError();
2657   }
2658   StmtResult SR = S;
2659   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2660     // Mark all variables in private list clauses as used in inner region.
2661     // Required for proper codegen of combined directives.
2662     // TODO: add processing for other clauses.
2663     if (ThisCaptureRegion != OMPD_unknown) {
2664       for (auto *C : PICs) {
2665         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2666         // Find the particular capture region for the clause if the
2667         // directive is a combined one with multiple capture regions.
2668         // If the directive is not a combined one, the capture region
2669         // associated with the clause is OMPD_unknown and is generated
2670         // only once.
2671         if (CaptureRegion == ThisCaptureRegion ||
2672             CaptureRegion == OMPD_unknown) {
2673           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2674             for (auto *D : DS->decls())
2675               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2676           }
2677         }
2678       }
2679     }
2680     SR = ActOnCapturedRegionEnd(SR.get());
2681   }
2682   return SR;
2683 }
2684 
2685 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2686                               OpenMPDirectiveKind CancelRegion,
2687                               SourceLocation StartLoc) {
2688   // CancelRegion is only needed for cancel and cancellation_point.
2689   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2690     return false;
2691 
2692   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2693       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2694     return false;
2695 
2696   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2697       << getOpenMPDirectiveName(CancelRegion);
2698   return true;
2699 }
2700 
2701 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
2702                                   OpenMPDirectiveKind CurrentRegion,
2703                                   const DeclarationNameInfo &CurrentName,
2704                                   OpenMPDirectiveKind CancelRegion,
2705                                   SourceLocation StartLoc) {
2706   if (Stack->getCurScope()) {
2707     auto ParentRegion = Stack->getParentDirective();
2708     auto OffendingRegion = ParentRegion;
2709     bool NestingProhibited = false;
2710     bool CloseNesting = true;
2711     bool OrphanSeen = false;
2712     enum {
2713       NoRecommend,
2714       ShouldBeInParallelRegion,
2715       ShouldBeInOrderedRegion,
2716       ShouldBeInTargetRegion,
2717       ShouldBeInTeamsRegion
2718     } Recommend = NoRecommend;
2719     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2720       // OpenMP [2.16, Nesting of Regions]
2721       // OpenMP constructs may not be nested inside a simd region.
2722       // OpenMP [2.8.1,simd Construct, Restrictions]
2723       // An ordered construct with the simd clause is the only OpenMP
2724       // construct that can appear in the simd region.
2725       // Allowing a SIMD construct nested in another SIMD construct is an
2726       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2727       // message.
2728       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2729                                  ? diag::err_omp_prohibited_region_simd
2730                                  : diag::warn_omp_nesting_simd);
2731       return CurrentRegion != OMPD_simd;
2732     }
2733     if (ParentRegion == OMPD_atomic) {
2734       // OpenMP [2.16, Nesting of Regions]
2735       // OpenMP constructs may not be nested inside an atomic region.
2736       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2737       return true;
2738     }
2739     if (CurrentRegion == OMPD_section) {
2740       // OpenMP [2.7.2, sections Construct, Restrictions]
2741       // Orphaned section directives are prohibited. That is, the section
2742       // directives must appear within the sections construct and must not be
2743       // encountered elsewhere in the sections region.
2744       if (ParentRegion != OMPD_sections &&
2745           ParentRegion != OMPD_parallel_sections) {
2746         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2747             << (ParentRegion != OMPD_unknown)
2748             << getOpenMPDirectiveName(ParentRegion);
2749         return true;
2750       }
2751       return false;
2752     }
2753     // Allow some constructs (except teams) to be orphaned (they could be
2754     // used in functions, called from OpenMP regions with the required
2755     // preconditions).
2756     if (ParentRegion == OMPD_unknown &&
2757         !isOpenMPNestingTeamsDirective(CurrentRegion))
2758       return false;
2759     if (CurrentRegion == OMPD_cancellation_point ||
2760         CurrentRegion == OMPD_cancel) {
2761       // OpenMP [2.16, Nesting of Regions]
2762       // A cancellation point construct for which construct-type-clause is
2763       // taskgroup must be nested inside a task construct. A cancellation
2764       // point construct for which construct-type-clause is not taskgroup must
2765       // be closely nested inside an OpenMP construct that matches the type
2766       // specified in construct-type-clause.
2767       // A cancel construct for which construct-type-clause is taskgroup must be
2768       // nested inside a task construct. A cancel construct for which
2769       // construct-type-clause is not taskgroup must be closely nested inside an
2770       // OpenMP construct that matches the type specified in
2771       // construct-type-clause.
2772       NestingProhibited =
2773           !((CancelRegion == OMPD_parallel &&
2774              (ParentRegion == OMPD_parallel ||
2775               ParentRegion == OMPD_target_parallel)) ||
2776             (CancelRegion == OMPD_for &&
2777              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2778               ParentRegion == OMPD_target_parallel_for ||
2779               ParentRegion == OMPD_distribute_parallel_for ||
2780               ParentRegion == OMPD_teams_distribute_parallel_for ||
2781               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
2782             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2783             (CancelRegion == OMPD_sections &&
2784              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2785               ParentRegion == OMPD_parallel_sections)));
2786     } else if (CurrentRegion == OMPD_master) {
2787       // OpenMP [2.16, Nesting of Regions]
2788       // A master region may not be closely nested inside a worksharing,
2789       // atomic, or explicit task region.
2790       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2791                           isOpenMPTaskingDirective(ParentRegion);
2792     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2793       // OpenMP [2.16, Nesting of Regions]
2794       // A critical region may not be nested (closely or otherwise) inside a
2795       // critical region with the same name. Note that this restriction is not
2796       // sufficient to prevent deadlock.
2797       SourceLocation PreviousCriticalLoc;
2798       bool DeadLock = Stack->hasDirective(
2799           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2800                                               const DeclarationNameInfo &DNI,
2801                                               SourceLocation Loc) -> bool {
2802             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2803               PreviousCriticalLoc = Loc;
2804               return true;
2805             } else
2806               return false;
2807           },
2808           false /* skip top directive */);
2809       if (DeadLock) {
2810         SemaRef.Diag(StartLoc,
2811                      diag::err_omp_prohibited_region_critical_same_name)
2812             << CurrentName.getName();
2813         if (PreviousCriticalLoc.isValid())
2814           SemaRef.Diag(PreviousCriticalLoc,
2815                        diag::note_omp_previous_critical_region);
2816         return true;
2817       }
2818     } else if (CurrentRegion == OMPD_barrier) {
2819       // OpenMP [2.16, Nesting of Regions]
2820       // A barrier region may not be closely nested inside a worksharing,
2821       // explicit task, critical, ordered, atomic, or master region.
2822       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2823                           isOpenMPTaskingDirective(ParentRegion) ||
2824                           ParentRegion == OMPD_master ||
2825                           ParentRegion == OMPD_critical ||
2826                           ParentRegion == OMPD_ordered;
2827     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2828                !isOpenMPParallelDirective(CurrentRegion) &&
2829                !isOpenMPTeamsDirective(CurrentRegion)) {
2830       // OpenMP [2.16, Nesting of Regions]
2831       // A worksharing region may not be closely nested inside a worksharing,
2832       // explicit task, critical, ordered, atomic, or master region.
2833       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2834                           isOpenMPTaskingDirective(ParentRegion) ||
2835                           ParentRegion == OMPD_master ||
2836                           ParentRegion == OMPD_critical ||
2837                           ParentRegion == OMPD_ordered;
2838       Recommend = ShouldBeInParallelRegion;
2839     } else if (CurrentRegion == OMPD_ordered) {
2840       // OpenMP [2.16, Nesting of Regions]
2841       // An ordered region may not be closely nested inside a critical,
2842       // atomic, or explicit task region.
2843       // An ordered region must be closely nested inside a loop region (or
2844       // parallel loop region) with an ordered clause.
2845       // OpenMP [2.8.1,simd Construct, Restrictions]
2846       // An ordered construct with the simd clause is the only OpenMP construct
2847       // that can appear in the simd region.
2848       NestingProhibited = ParentRegion == OMPD_critical ||
2849                           isOpenMPTaskingDirective(ParentRegion) ||
2850                           !(isOpenMPSimdDirective(ParentRegion) ||
2851                             Stack->isParentOrderedRegion());
2852       Recommend = ShouldBeInOrderedRegion;
2853     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2854       // OpenMP [2.16, Nesting of Regions]
2855       // If specified, a teams construct must be contained within a target
2856       // construct.
2857       NestingProhibited = ParentRegion != OMPD_target;
2858       OrphanSeen = ParentRegion == OMPD_unknown;
2859       Recommend = ShouldBeInTargetRegion;
2860     }
2861     if (!NestingProhibited &&
2862         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2863         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2864         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2865       // OpenMP [2.16, Nesting of Regions]
2866       // distribute, parallel, parallel sections, parallel workshare, and the
2867       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2868       // constructs that can be closely nested in the teams region.
2869       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2870                           !isOpenMPDistributeDirective(CurrentRegion);
2871       Recommend = ShouldBeInParallelRegion;
2872     }
2873     if (!NestingProhibited &&
2874         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2875       // OpenMP 4.5 [2.17 Nesting of Regions]
2876       // The region associated with the distribute construct must be strictly
2877       // nested inside a teams region
2878       NestingProhibited =
2879           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2880       Recommend = ShouldBeInTeamsRegion;
2881     }
2882     if (!NestingProhibited &&
2883         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2884          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2885       // OpenMP 4.5 [2.17 Nesting of Regions]
2886       // If a target, target update, target data, target enter data, or
2887       // target exit data construct is encountered during execution of a
2888       // target region, the behavior is unspecified.
2889       NestingProhibited = Stack->hasDirective(
2890           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2891                              SourceLocation) -> bool {
2892             if (isOpenMPTargetExecutionDirective(K)) {
2893               OffendingRegion = K;
2894               return true;
2895             } else
2896               return false;
2897           },
2898           false /* don't skip top directive */);
2899       CloseNesting = false;
2900     }
2901     if (NestingProhibited) {
2902       if (OrphanSeen) {
2903         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2904             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2905       } else {
2906         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2907             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2908             << Recommend << getOpenMPDirectiveName(CurrentRegion);
2909       }
2910       return true;
2911     }
2912   }
2913   return false;
2914 }
2915 
2916 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2917                            ArrayRef<OMPClause *> Clauses,
2918                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2919   bool ErrorFound = false;
2920   unsigned NamedModifiersNumber = 0;
2921   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2922       OMPD_unknown + 1);
2923   SmallVector<SourceLocation, 4> NameModifierLoc;
2924   for (const auto *C : Clauses) {
2925     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2926       // At most one if clause without a directive-name-modifier can appear on
2927       // the directive.
2928       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2929       if (FoundNameModifiers[CurNM]) {
2930         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2931             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2932             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2933         ErrorFound = true;
2934       } else if (CurNM != OMPD_unknown) {
2935         NameModifierLoc.push_back(IC->getNameModifierLoc());
2936         ++NamedModifiersNumber;
2937       }
2938       FoundNameModifiers[CurNM] = IC;
2939       if (CurNM == OMPD_unknown)
2940         continue;
2941       // Check if the specified name modifier is allowed for the current
2942       // directive.
2943       // At most one if clause with the particular directive-name-modifier can
2944       // appear on the directive.
2945       bool MatchFound = false;
2946       for (auto NM : AllowedNameModifiers) {
2947         if (CurNM == NM) {
2948           MatchFound = true;
2949           break;
2950         }
2951       }
2952       if (!MatchFound) {
2953         S.Diag(IC->getNameModifierLoc(),
2954                diag::err_omp_wrong_if_directive_name_modifier)
2955             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2956         ErrorFound = true;
2957       }
2958     }
2959   }
2960   // If any if clause on the directive includes a directive-name-modifier then
2961   // all if clauses on the directive must include a directive-name-modifier.
2962   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2963     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2964       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2965              diag::err_omp_no_more_if_clause);
2966     } else {
2967       std::string Values;
2968       std::string Sep(", ");
2969       unsigned AllowedCnt = 0;
2970       unsigned TotalAllowedNum =
2971           AllowedNameModifiers.size() - NamedModifiersNumber;
2972       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2973            ++Cnt) {
2974         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2975         if (!FoundNameModifiers[NM]) {
2976           Values += "'";
2977           Values += getOpenMPDirectiveName(NM);
2978           Values += "'";
2979           if (AllowedCnt + 2 == TotalAllowedNum)
2980             Values += " or ";
2981           else if (AllowedCnt + 1 != TotalAllowedNum)
2982             Values += Sep;
2983           ++AllowedCnt;
2984         }
2985       }
2986       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2987              diag::err_omp_unnamed_if_clause)
2988           << (TotalAllowedNum > 1) << Values;
2989     }
2990     for (auto Loc : NameModifierLoc) {
2991       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2992     }
2993     ErrorFound = true;
2994   }
2995   return ErrorFound;
2996 }
2997 
2998 StmtResult Sema::ActOnOpenMPExecutableDirective(
2999     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3000     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3001     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3002   StmtResult Res = StmtError();
3003   // First check CancelRegion which is then used in checkNestingOfRegions.
3004   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3005       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3006                             StartLoc))
3007     return StmtError();
3008 
3009   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3010   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
3011   bool ErrorFound = false;
3012   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3013   if (AStmt && !CurContext->isDependentContext()) {
3014     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3015 
3016     // Check default data sharing attributes for referenced variables.
3017     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3018     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3019     Stmt *S = AStmt;
3020     while (--ThisCaptureLevel >= 0)
3021       S = cast<CapturedStmt>(S)->getCapturedStmt();
3022     DSAChecker.Visit(S);
3023     if (DSAChecker.isErrorFound())
3024       return StmtError();
3025     // Generate list of implicitly defined firstprivate variables.
3026     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3027 
3028     SmallVector<Expr *, 4> ImplicitFirstprivates(
3029         DSAChecker.getImplicitFirstprivate().begin(),
3030         DSAChecker.getImplicitFirstprivate().end());
3031     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3032                                         DSAChecker.getImplicitMap().end());
3033     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3034     for (auto *C : Clauses) {
3035       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3036         for (auto *E : IRC->taskgroup_descriptors())
3037           if (E)
3038             ImplicitFirstprivates.emplace_back(E);
3039       }
3040     }
3041     if (!ImplicitFirstprivates.empty()) {
3042       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3043               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3044               SourceLocation())) {
3045         ClausesWithImplicit.push_back(Implicit);
3046         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3047                      ImplicitFirstprivates.size();
3048       } else
3049         ErrorFound = true;
3050     }
3051     if (!ImplicitMaps.empty()) {
3052       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3053               OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3054               SourceLocation(), SourceLocation(), ImplicitMaps,
3055               SourceLocation(), SourceLocation(), SourceLocation())) {
3056         ClausesWithImplicit.emplace_back(Implicit);
3057         ErrorFound |=
3058             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3059       } else
3060         ErrorFound = true;
3061     }
3062   }
3063 
3064   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3065   switch (Kind) {
3066   case OMPD_parallel:
3067     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3068                                        EndLoc);
3069     AllowedNameModifiers.push_back(OMPD_parallel);
3070     break;
3071   case OMPD_simd:
3072     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3073                                    VarsWithInheritedDSA);
3074     break;
3075   case OMPD_for:
3076     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3077                                   VarsWithInheritedDSA);
3078     break;
3079   case OMPD_for_simd:
3080     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3081                                       EndLoc, VarsWithInheritedDSA);
3082     break;
3083   case OMPD_sections:
3084     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3085                                        EndLoc);
3086     break;
3087   case OMPD_section:
3088     assert(ClausesWithImplicit.empty() &&
3089            "No clauses are allowed for 'omp section' directive");
3090     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3091     break;
3092   case OMPD_single:
3093     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3094                                      EndLoc);
3095     break;
3096   case OMPD_master:
3097     assert(ClausesWithImplicit.empty() &&
3098            "No clauses are allowed for 'omp master' directive");
3099     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3100     break;
3101   case OMPD_critical:
3102     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3103                                        StartLoc, EndLoc);
3104     break;
3105   case OMPD_parallel_for:
3106     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3107                                           EndLoc, VarsWithInheritedDSA);
3108     AllowedNameModifiers.push_back(OMPD_parallel);
3109     break;
3110   case OMPD_parallel_for_simd:
3111     Res = ActOnOpenMPParallelForSimdDirective(
3112         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3113     AllowedNameModifiers.push_back(OMPD_parallel);
3114     break;
3115   case OMPD_parallel_sections:
3116     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3117                                                StartLoc, EndLoc);
3118     AllowedNameModifiers.push_back(OMPD_parallel);
3119     break;
3120   case OMPD_task:
3121     Res =
3122         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3123     AllowedNameModifiers.push_back(OMPD_task);
3124     break;
3125   case OMPD_taskyield:
3126     assert(ClausesWithImplicit.empty() &&
3127            "No clauses are allowed for 'omp taskyield' directive");
3128     assert(AStmt == nullptr &&
3129            "No associated statement allowed for 'omp taskyield' directive");
3130     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3131     break;
3132   case OMPD_barrier:
3133     assert(ClausesWithImplicit.empty() &&
3134            "No clauses are allowed for 'omp barrier' directive");
3135     assert(AStmt == nullptr &&
3136            "No associated statement allowed for 'omp barrier' directive");
3137     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3138     break;
3139   case OMPD_taskwait:
3140     assert(ClausesWithImplicit.empty() &&
3141            "No clauses are allowed for 'omp taskwait' directive");
3142     assert(AStmt == nullptr &&
3143            "No associated statement allowed for 'omp taskwait' directive");
3144     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3145     break;
3146   case OMPD_taskgroup:
3147     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3148                                         EndLoc);
3149     break;
3150   case OMPD_flush:
3151     assert(AStmt == nullptr &&
3152            "No associated statement allowed for 'omp flush' directive");
3153     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3154     break;
3155   case OMPD_ordered:
3156     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3157                                       EndLoc);
3158     break;
3159   case OMPD_atomic:
3160     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3161                                      EndLoc);
3162     break;
3163   case OMPD_teams:
3164     Res =
3165         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3166     break;
3167   case OMPD_target:
3168     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3169                                      EndLoc);
3170     AllowedNameModifiers.push_back(OMPD_target);
3171     break;
3172   case OMPD_target_parallel:
3173     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3174                                              StartLoc, EndLoc);
3175     AllowedNameModifiers.push_back(OMPD_target);
3176     AllowedNameModifiers.push_back(OMPD_parallel);
3177     break;
3178   case OMPD_target_parallel_for:
3179     Res = ActOnOpenMPTargetParallelForDirective(
3180         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3181     AllowedNameModifiers.push_back(OMPD_target);
3182     AllowedNameModifiers.push_back(OMPD_parallel);
3183     break;
3184   case OMPD_cancellation_point:
3185     assert(ClausesWithImplicit.empty() &&
3186            "No clauses are allowed for 'omp cancellation point' directive");
3187     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3188                                "cancellation point' directive");
3189     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3190     break;
3191   case OMPD_cancel:
3192     assert(AStmt == nullptr &&
3193            "No associated statement allowed for 'omp cancel' directive");
3194     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3195                                      CancelRegion);
3196     AllowedNameModifiers.push_back(OMPD_cancel);
3197     break;
3198   case OMPD_target_data:
3199     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3200                                          EndLoc);
3201     AllowedNameModifiers.push_back(OMPD_target_data);
3202     break;
3203   case OMPD_target_enter_data:
3204     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3205                                               EndLoc, AStmt);
3206     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3207     break;
3208   case OMPD_target_exit_data:
3209     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3210                                              EndLoc, AStmt);
3211     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3212     break;
3213   case OMPD_taskloop:
3214     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3215                                        EndLoc, VarsWithInheritedDSA);
3216     AllowedNameModifiers.push_back(OMPD_taskloop);
3217     break;
3218   case OMPD_taskloop_simd:
3219     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3220                                            EndLoc, VarsWithInheritedDSA);
3221     AllowedNameModifiers.push_back(OMPD_taskloop);
3222     break;
3223   case OMPD_distribute:
3224     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3225                                          EndLoc, VarsWithInheritedDSA);
3226     break;
3227   case OMPD_target_update:
3228     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3229                                            EndLoc, AStmt);
3230     AllowedNameModifiers.push_back(OMPD_target_update);
3231     break;
3232   case OMPD_distribute_parallel_for:
3233     Res = ActOnOpenMPDistributeParallelForDirective(
3234         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3235     AllowedNameModifiers.push_back(OMPD_parallel);
3236     break;
3237   case OMPD_distribute_parallel_for_simd:
3238     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3239         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3240     AllowedNameModifiers.push_back(OMPD_parallel);
3241     break;
3242   case OMPD_distribute_simd:
3243     Res = ActOnOpenMPDistributeSimdDirective(
3244         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3245     break;
3246   case OMPD_target_parallel_for_simd:
3247     Res = ActOnOpenMPTargetParallelForSimdDirective(
3248         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3249     AllowedNameModifiers.push_back(OMPD_target);
3250     AllowedNameModifiers.push_back(OMPD_parallel);
3251     break;
3252   case OMPD_target_simd:
3253     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3254                                          EndLoc, VarsWithInheritedDSA);
3255     AllowedNameModifiers.push_back(OMPD_target);
3256     break;
3257   case OMPD_teams_distribute:
3258     Res = ActOnOpenMPTeamsDistributeDirective(
3259         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3260     break;
3261   case OMPD_teams_distribute_simd:
3262     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3263         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3264     break;
3265   case OMPD_teams_distribute_parallel_for_simd:
3266     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3267         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3268     AllowedNameModifiers.push_back(OMPD_parallel);
3269     break;
3270   case OMPD_teams_distribute_parallel_for:
3271     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3272         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3273     AllowedNameModifiers.push_back(OMPD_parallel);
3274     break;
3275   case OMPD_target_teams:
3276     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3277                                           EndLoc);
3278     AllowedNameModifiers.push_back(OMPD_target);
3279     break;
3280   case OMPD_target_teams_distribute:
3281     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3282         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3283     AllowedNameModifiers.push_back(OMPD_target);
3284     break;
3285   case OMPD_target_teams_distribute_parallel_for:
3286     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3287         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3288     AllowedNameModifiers.push_back(OMPD_target);
3289     AllowedNameModifiers.push_back(OMPD_parallel);
3290     break;
3291   case OMPD_target_teams_distribute_parallel_for_simd:
3292     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3293         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3294     AllowedNameModifiers.push_back(OMPD_target);
3295     AllowedNameModifiers.push_back(OMPD_parallel);
3296     break;
3297   case OMPD_target_teams_distribute_simd:
3298     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3299         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3300     AllowedNameModifiers.push_back(OMPD_target);
3301     break;
3302   case OMPD_declare_target:
3303   case OMPD_end_declare_target:
3304   case OMPD_threadprivate:
3305   case OMPD_declare_reduction:
3306   case OMPD_declare_simd:
3307     llvm_unreachable("OpenMP Directive is not allowed");
3308   case OMPD_unknown:
3309     llvm_unreachable("Unknown OpenMP directive");
3310   }
3311 
3312   for (auto P : VarsWithInheritedDSA) {
3313     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3314         << P.first << P.second->getSourceRange();
3315   }
3316   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3317 
3318   if (!AllowedNameModifiers.empty())
3319     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3320                  ErrorFound;
3321 
3322   if (ErrorFound)
3323     return StmtError();
3324   return Res;
3325 }
3326 
3327 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3328     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3329     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3330     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3331     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3332   assert(Aligneds.size() == Alignments.size());
3333   assert(Linears.size() == LinModifiers.size());
3334   assert(Linears.size() == Steps.size());
3335   if (!DG || DG.get().isNull())
3336     return DeclGroupPtrTy();
3337 
3338   if (!DG.get().isSingleDecl()) {
3339     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3340     return DG;
3341   }
3342   auto *ADecl = DG.get().getSingleDecl();
3343   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3344     ADecl = FTD->getTemplatedDecl();
3345 
3346   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3347   if (!FD) {
3348     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3349     return DeclGroupPtrTy();
3350   }
3351 
3352   // OpenMP [2.8.2, declare simd construct, Description]
3353   // The parameter of the simdlen clause must be a constant positive integer
3354   // expression.
3355   ExprResult SL;
3356   if (Simdlen)
3357     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3358   // OpenMP [2.8.2, declare simd construct, Description]
3359   // The special this pointer can be used as if was one of the arguments to the
3360   // function in any of the linear, aligned, or uniform clauses.
3361   // The uniform clause declares one or more arguments to have an invariant
3362   // value for all concurrent invocations of the function in the execution of a
3363   // single SIMD loop.
3364   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3365   Expr *UniformedLinearThis = nullptr;
3366   for (auto *E : Uniforms) {
3367     E = E->IgnoreParenImpCasts();
3368     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3369       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3370         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3371             FD->getParamDecl(PVD->getFunctionScopeIndex())
3372                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3373           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
3374           continue;
3375         }
3376     if (isa<CXXThisExpr>(E)) {
3377       UniformedLinearThis = E;
3378       continue;
3379     }
3380     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3381         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3382   }
3383   // OpenMP [2.8.2, declare simd construct, Description]
3384   // The aligned clause declares that the object to which each list item points
3385   // is aligned to the number of bytes expressed in the optional parameter of
3386   // the aligned clause.
3387   // The special this pointer can be used as if was one of the arguments to the
3388   // function in any of the linear, aligned, or uniform clauses.
3389   // The type of list items appearing in the aligned clause must be array,
3390   // pointer, reference to array, or reference to pointer.
3391   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3392   Expr *AlignedThis = nullptr;
3393   for (auto *E : Aligneds) {
3394     E = E->IgnoreParenImpCasts();
3395     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3396       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3397         auto *CanonPVD = PVD->getCanonicalDecl();
3398         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3399             FD->getParamDecl(PVD->getFunctionScopeIndex())
3400                     ->getCanonicalDecl() == CanonPVD) {
3401           // OpenMP  [2.8.1, simd construct, Restrictions]
3402           // A list-item cannot appear in more than one aligned clause.
3403           if (AlignedArgs.count(CanonPVD) > 0) {
3404             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3405                 << 1 << E->getSourceRange();
3406             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3407                  diag::note_omp_explicit_dsa)
3408                 << getOpenMPClauseName(OMPC_aligned);
3409             continue;
3410           }
3411           AlignedArgs[CanonPVD] = E;
3412           QualType QTy = PVD->getType()
3413                              .getNonReferenceType()
3414                              .getUnqualifiedType()
3415                              .getCanonicalType();
3416           const Type *Ty = QTy.getTypePtrOrNull();
3417           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3418             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3419                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3420             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3421           }
3422           continue;
3423         }
3424       }
3425     if (isa<CXXThisExpr>(E)) {
3426       if (AlignedThis) {
3427         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3428             << 2 << E->getSourceRange();
3429         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3430             << getOpenMPClauseName(OMPC_aligned);
3431       }
3432       AlignedThis = E;
3433       continue;
3434     }
3435     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3436         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3437   }
3438   // The optional parameter of the aligned clause, alignment, must be a constant
3439   // positive integer expression. If no optional parameter is specified,
3440   // implementation-defined default alignments for SIMD instructions on the
3441   // target platforms are assumed.
3442   SmallVector<Expr *, 4> NewAligns;
3443   for (auto *E : Alignments) {
3444     ExprResult Align;
3445     if (E)
3446       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3447     NewAligns.push_back(Align.get());
3448   }
3449   // OpenMP [2.8.2, declare simd construct, Description]
3450   // The linear clause declares one or more list items to be private to a SIMD
3451   // lane and to have a linear relationship with respect to the iteration space
3452   // of a loop.
3453   // The special this pointer can be used as if was one of the arguments to the
3454   // function in any of the linear, aligned, or uniform clauses.
3455   // When a linear-step expression is specified in a linear clause it must be
3456   // either a constant integer expression or an integer-typed parameter that is
3457   // specified in a uniform clause on the directive.
3458   llvm::DenseMap<Decl *, Expr *> LinearArgs;
3459   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3460   auto MI = LinModifiers.begin();
3461   for (auto *E : Linears) {
3462     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3463     ++MI;
3464     E = E->IgnoreParenImpCasts();
3465     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3466       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3467         auto *CanonPVD = PVD->getCanonicalDecl();
3468         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3469             FD->getParamDecl(PVD->getFunctionScopeIndex())
3470                     ->getCanonicalDecl() == CanonPVD) {
3471           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3472           // A list-item cannot appear in more than one linear clause.
3473           if (LinearArgs.count(CanonPVD) > 0) {
3474             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3475                 << getOpenMPClauseName(OMPC_linear)
3476                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3477             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3478                  diag::note_omp_explicit_dsa)
3479                 << getOpenMPClauseName(OMPC_linear);
3480             continue;
3481           }
3482           // Each argument can appear in at most one uniform or linear clause.
3483           if (UniformedArgs.count(CanonPVD) > 0) {
3484             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3485                 << getOpenMPClauseName(OMPC_linear)
3486                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3487             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3488                  diag::note_omp_explicit_dsa)
3489                 << getOpenMPClauseName(OMPC_uniform);
3490             continue;
3491           }
3492           LinearArgs[CanonPVD] = E;
3493           if (E->isValueDependent() || E->isTypeDependent() ||
3494               E->isInstantiationDependent() ||
3495               E->containsUnexpandedParameterPack())
3496             continue;
3497           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3498                                       PVD->getOriginalType());
3499           continue;
3500         }
3501       }
3502     if (isa<CXXThisExpr>(E)) {
3503       if (UniformedLinearThis) {
3504         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3505             << getOpenMPClauseName(OMPC_linear)
3506             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3507             << E->getSourceRange();
3508         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3509             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3510                                                    : OMPC_linear);
3511         continue;
3512       }
3513       UniformedLinearThis = E;
3514       if (E->isValueDependent() || E->isTypeDependent() ||
3515           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3516         continue;
3517       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3518                                   E->getType());
3519       continue;
3520     }
3521     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3522         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3523   }
3524   Expr *Step = nullptr;
3525   Expr *NewStep = nullptr;
3526   SmallVector<Expr *, 4> NewSteps;
3527   for (auto *E : Steps) {
3528     // Skip the same step expression, it was checked already.
3529     if (Step == E || !E) {
3530       NewSteps.push_back(E ? NewStep : nullptr);
3531       continue;
3532     }
3533     Step = E;
3534     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3535       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3536         auto *CanonPVD = PVD->getCanonicalDecl();
3537         if (UniformedArgs.count(CanonPVD) == 0) {
3538           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3539               << Step->getSourceRange();
3540         } else if (E->isValueDependent() || E->isTypeDependent() ||
3541                    E->isInstantiationDependent() ||
3542                    E->containsUnexpandedParameterPack() ||
3543                    CanonPVD->getType()->hasIntegerRepresentation())
3544           NewSteps.push_back(Step);
3545         else {
3546           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3547               << Step->getSourceRange();
3548         }
3549         continue;
3550       }
3551     NewStep = Step;
3552     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3553         !Step->isInstantiationDependent() &&
3554         !Step->containsUnexpandedParameterPack()) {
3555       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3556                     .get();
3557       if (NewStep)
3558         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3559     }
3560     NewSteps.push_back(NewStep);
3561   }
3562   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3563       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3564       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3565       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3566       const_cast<Expr **>(Linears.data()), Linears.size(),
3567       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3568       NewSteps.data(), NewSteps.size(), SR);
3569   ADecl->addAttr(NewAttr);
3570   return ConvertDeclToDeclGroup(ADecl);
3571 }
3572 
3573 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3574                                               Stmt *AStmt,
3575                                               SourceLocation StartLoc,
3576                                               SourceLocation EndLoc) {
3577   if (!AStmt)
3578     return StmtError();
3579 
3580   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3581   // 1.2.2 OpenMP Language Terminology
3582   // Structured block - An executable statement with a single entry at the
3583   // top and a single exit at the bottom.
3584   // The point of exit cannot be a branch out of the structured block.
3585   // longjmp() and throw() must not violate the entry/exit criteria.
3586   CS->getCapturedDecl()->setNothrow();
3587 
3588   setFunctionHasBranchProtectedScope();
3589 
3590   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3591                                       DSAStack->isCancelRegion());
3592 }
3593 
3594 namespace {
3595 /// \brief Helper class for checking canonical form of the OpenMP loops and
3596 /// extracting iteration space of each loop in the loop nest, that will be used
3597 /// for IR generation.
3598 class OpenMPIterationSpaceChecker {
3599   /// \brief Reference to Sema.
3600   Sema &SemaRef;
3601   /// \brief A location for diagnostics (when there is no some better location).
3602   SourceLocation DefaultLoc;
3603   /// \brief A location for diagnostics (when increment is not compatible).
3604   SourceLocation ConditionLoc;
3605   /// \brief A source location for referring to loop init later.
3606   SourceRange InitSrcRange;
3607   /// \brief A source location for referring to condition later.
3608   SourceRange ConditionSrcRange;
3609   /// \brief A source location for referring to increment later.
3610   SourceRange IncrementSrcRange;
3611   /// \brief Loop variable.
3612   ValueDecl *LCDecl = nullptr;
3613   /// \brief Reference to loop variable.
3614   Expr *LCRef = nullptr;
3615   /// \brief Lower bound (initializer for the var).
3616   Expr *LB = nullptr;
3617   /// \brief Upper bound.
3618   Expr *UB = nullptr;
3619   /// \brief Loop step (increment).
3620   Expr *Step = nullptr;
3621   /// \brief This flag is true when condition is one of:
3622   ///   Var <  UB
3623   ///   Var <= UB
3624   ///   UB  >  Var
3625   ///   UB  >= Var
3626   bool TestIsLessOp = false;
3627   /// \brief This flag is true when condition is strict ( < or > ).
3628   bool TestIsStrictOp = false;
3629   /// \brief This flag is true when step is subtracted on each iteration.
3630   bool SubtractStep = false;
3631 
3632 public:
3633   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3634       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3635   /// \brief Check init-expr for canonical loop form and save loop counter
3636   /// variable - #Var and its initialization value - #LB.
3637   bool CheckInit(Stmt *S, bool EmitDiags = true);
3638   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3639   /// for less/greater and for strict/non-strict comparison.
3640   bool CheckCond(Expr *S);
3641   /// \brief Check incr-expr for canonical loop form and return true if it
3642   /// does not conform, otherwise save loop step (#Step).
3643   bool CheckInc(Expr *S);
3644   /// \brief Return the loop counter variable.
3645   ValueDecl *GetLoopDecl() const { return LCDecl; }
3646   /// \brief Return the reference expression to loop counter variable.
3647   Expr *GetLoopDeclRefExpr() const { return LCRef; }
3648   /// \brief Source range of the loop init.
3649   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3650   /// \brief Source range of the loop condition.
3651   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3652   /// \brief Source range of the loop increment.
3653   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3654   /// \brief True if the step should be subtracted.
3655   bool ShouldSubtractStep() const { return SubtractStep; }
3656   /// \brief Build the expression to calculate the number of iterations.
3657   Expr *
3658   BuildNumIterations(Scope *S, const bool LimitedType,
3659                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3660   /// \brief Build the precondition expression for the loops.
3661   Expr *BuildPreCond(Scope *S, Expr *Cond,
3662                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3663   /// \brief Build reference expression to the counter be used for codegen.
3664   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3665                                DSAStackTy &DSA) const;
3666   /// \brief Build reference expression to the private counter be used for
3667   /// codegen.
3668   Expr *BuildPrivateCounterVar() const;
3669   /// \brief Build initialization of the counter be used for codegen.
3670   Expr *BuildCounterInit() const;
3671   /// \brief Build step of the counter be used for codegen.
3672   Expr *BuildCounterStep() const;
3673   /// \brief Return true if any expression is dependent.
3674   bool Dependent() const;
3675 
3676 private:
3677   /// \brief Check the right-hand side of an assignment in the increment
3678   /// expression.
3679   bool CheckIncRHS(Expr *RHS);
3680   /// \brief Helper to set loop counter variable and its initializer.
3681   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3682   /// \brief Helper to set upper bound.
3683   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3684              SourceLocation SL);
3685   /// \brief Helper to set loop increment.
3686   bool SetStep(Expr *NewStep, bool Subtract);
3687 };
3688 
3689 bool OpenMPIterationSpaceChecker::Dependent() const {
3690   if (!LCDecl) {
3691     assert(!LB && !UB && !Step);
3692     return false;
3693   }
3694   return LCDecl->getType()->isDependentType() ||
3695          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3696          (Step && Step->isValueDependent());
3697 }
3698 
3699 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3700                                                  Expr *NewLCRefExpr,
3701                                                  Expr *NewLB) {
3702   // State consistency checking to ensure correct usage.
3703   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3704          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3705   if (!NewLCDecl || !NewLB)
3706     return true;
3707   LCDecl = getCanonicalDecl(NewLCDecl);
3708   LCRef = NewLCRefExpr;
3709   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3710     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3711       if ((Ctor->isCopyOrMoveConstructor() ||
3712            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3713           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3714         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3715   LB = NewLB;
3716   return false;
3717 }
3718 
3719 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3720                                         SourceRange SR, SourceLocation SL) {
3721   // State consistency checking to ensure correct usage.
3722   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3723          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3724   if (!NewUB)
3725     return true;
3726   UB = NewUB;
3727   TestIsLessOp = LessOp;
3728   TestIsStrictOp = StrictOp;
3729   ConditionSrcRange = SR;
3730   ConditionLoc = SL;
3731   return false;
3732 }
3733 
3734 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3735   // State consistency checking to ensure correct usage.
3736   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3737   if (!NewStep)
3738     return true;
3739   if (!NewStep->isValueDependent()) {
3740     // Check that the step is integer expression.
3741     SourceLocation StepLoc = NewStep->getLocStart();
3742     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3743         StepLoc, getExprAsWritten(NewStep));
3744     if (Val.isInvalid())
3745       return true;
3746     NewStep = Val.get();
3747 
3748     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3749     //  If test-expr is of form var relational-op b and relational-op is < or
3750     //  <= then incr-expr must cause var to increase on each iteration of the
3751     //  loop. If test-expr is of form var relational-op b and relational-op is
3752     //  > or >= then incr-expr must cause var to decrease on each iteration of
3753     //  the loop.
3754     //  If test-expr is of form b relational-op var and relational-op is < or
3755     //  <= then incr-expr must cause var to decrease on each iteration of the
3756     //  loop. If test-expr is of form b relational-op var and relational-op is
3757     //  > or >= then incr-expr must cause var to increase on each iteration of
3758     //  the loop.
3759     llvm::APSInt Result;
3760     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3761     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3762     bool IsConstNeg =
3763         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3764     bool IsConstPos =
3765         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3766     bool IsConstZero = IsConstant && !Result.getBoolValue();
3767     if (UB && (IsConstZero ||
3768                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3769                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3770       SemaRef.Diag(NewStep->getExprLoc(),
3771                    diag::err_omp_loop_incr_not_compatible)
3772           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3773       SemaRef.Diag(ConditionLoc,
3774                    diag::note_omp_loop_cond_requres_compatible_incr)
3775           << TestIsLessOp << ConditionSrcRange;
3776       return true;
3777     }
3778     if (TestIsLessOp == Subtract) {
3779       NewStep =
3780           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3781               .get();
3782       Subtract = !Subtract;
3783     }
3784   }
3785 
3786   Step = NewStep;
3787   SubtractStep = Subtract;
3788   return false;
3789 }
3790 
3791 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3792   // Check init-expr for canonical loop form and save loop counter
3793   // variable - #Var and its initialization value - #LB.
3794   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3795   //   var = lb
3796   //   integer-type var = lb
3797   //   random-access-iterator-type var = lb
3798   //   pointer-type var = lb
3799   //
3800   if (!S) {
3801     if (EmitDiags) {
3802       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3803     }
3804     return true;
3805   }
3806   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3807     if (!ExprTemp->cleanupsHaveSideEffects())
3808       S = ExprTemp->getSubExpr();
3809 
3810   InitSrcRange = S->getSourceRange();
3811   if (Expr *E = dyn_cast<Expr>(S))
3812     S = E->IgnoreParens();
3813   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3814     if (BO->getOpcode() == BO_Assign) {
3815       auto *LHS = BO->getLHS()->IgnoreParens();
3816       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3817         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3818           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3819             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3820         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3821       }
3822       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3823         if (ME->isArrow() &&
3824             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3825           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3826       }
3827     }
3828   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3829     if (DS->isSingleDecl()) {
3830       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3831         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3832           // Accept non-canonical init form here but emit ext. warning.
3833           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3834             SemaRef.Diag(S->getLocStart(),
3835                          diag::ext_omp_loop_not_canonical_init)
3836                 << S->getSourceRange();
3837           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3838         }
3839       }
3840     }
3841   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3842     if (CE->getOperator() == OO_Equal) {
3843       auto *LHS = CE->getArg(0);
3844       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3845         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3846           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3847             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3848         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3849       }
3850       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3851         if (ME->isArrow() &&
3852             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3853           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3854       }
3855     }
3856   }
3857 
3858   if (Dependent() || SemaRef.CurContext->isDependentContext())
3859     return false;
3860   if (EmitDiags) {
3861     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3862         << S->getSourceRange();
3863   }
3864   return true;
3865 }
3866 
3867 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3868 /// variable (which may be the loop variable) if possible.
3869 static const ValueDecl *GetInitLCDecl(Expr *E) {
3870   if (!E)
3871     return nullptr;
3872   E = getExprAsWritten(E);
3873   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3874     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3875       if ((Ctor->isCopyOrMoveConstructor() ||
3876            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3877           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3878         E = CE->getArg(0)->IgnoreParenImpCasts();
3879   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3880     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3881       return getCanonicalDecl(VD);
3882   }
3883   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3884     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3885       return getCanonicalDecl(ME->getMemberDecl());
3886   return nullptr;
3887 }
3888 
3889 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3890   // Check test-expr for canonical form, save upper-bound UB, flags for
3891   // less/greater and for strict/non-strict comparison.
3892   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3893   //   var relational-op b
3894   //   b relational-op var
3895   //
3896   if (!S) {
3897     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3898     return true;
3899   }
3900   S = getExprAsWritten(S);
3901   SourceLocation CondLoc = S->getLocStart();
3902   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3903     if (BO->isRelationalOp()) {
3904       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3905         return SetUB(BO->getRHS(),
3906                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3907                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3908                      BO->getSourceRange(), BO->getOperatorLoc());
3909       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3910         return SetUB(BO->getLHS(),
3911                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3912                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3913                      BO->getSourceRange(), BO->getOperatorLoc());
3914     }
3915   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3916     if (CE->getNumArgs() == 2) {
3917       auto Op = CE->getOperator();
3918       switch (Op) {
3919       case OO_Greater:
3920       case OO_GreaterEqual:
3921       case OO_Less:
3922       case OO_LessEqual:
3923         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3924           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3925                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3926                        CE->getOperatorLoc());
3927         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3928           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3929                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3930                        CE->getOperatorLoc());
3931         break;
3932       default:
3933         break;
3934       }
3935     }
3936   }
3937   if (Dependent() || SemaRef.CurContext->isDependentContext())
3938     return false;
3939   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3940       << S->getSourceRange() << LCDecl;
3941   return true;
3942 }
3943 
3944 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3945   // RHS of canonical loop form increment can be:
3946   //   var + incr
3947   //   incr + var
3948   //   var - incr
3949   //
3950   RHS = RHS->IgnoreParenImpCasts();
3951   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3952     if (BO->isAdditiveOp()) {
3953       bool IsAdd = BO->getOpcode() == BO_Add;
3954       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3955         return SetStep(BO->getRHS(), !IsAdd);
3956       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3957         return SetStep(BO->getLHS(), false);
3958     }
3959   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3960     bool IsAdd = CE->getOperator() == OO_Plus;
3961     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3962       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3963         return SetStep(CE->getArg(1), !IsAdd);
3964       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3965         return SetStep(CE->getArg(0), false);
3966     }
3967   }
3968   if (Dependent() || SemaRef.CurContext->isDependentContext())
3969     return false;
3970   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3971       << RHS->getSourceRange() << LCDecl;
3972   return true;
3973 }
3974 
3975 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3976   // Check incr-expr for canonical loop form and return true if it
3977   // does not conform.
3978   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3979   //   ++var
3980   //   var++
3981   //   --var
3982   //   var--
3983   //   var += incr
3984   //   var -= incr
3985   //   var = var + incr
3986   //   var = incr + var
3987   //   var = var - incr
3988   //
3989   if (!S) {
3990     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3991     return true;
3992   }
3993   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3994     if (!ExprTemp->cleanupsHaveSideEffects())
3995       S = ExprTemp->getSubExpr();
3996 
3997   IncrementSrcRange = S->getSourceRange();
3998   S = S->IgnoreParens();
3999   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4000     if (UO->isIncrementDecrementOp() &&
4001         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
4002       return SetStep(SemaRef
4003                          .ActOnIntegerConstant(UO->getLocStart(),
4004                                                (UO->isDecrementOp() ? -1 : 1))
4005                          .get(),
4006                      false);
4007   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4008     switch (BO->getOpcode()) {
4009     case BO_AddAssign:
4010     case BO_SubAssign:
4011       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
4012         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4013       break;
4014     case BO_Assign:
4015       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
4016         return CheckIncRHS(BO->getRHS());
4017       break;
4018     default:
4019       break;
4020     }
4021   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4022     switch (CE->getOperator()) {
4023     case OO_PlusPlus:
4024     case OO_MinusMinus:
4025       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4026         return SetStep(SemaRef
4027                            .ActOnIntegerConstant(
4028                                CE->getLocStart(),
4029                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4030                            .get(),
4031                        false);
4032       break;
4033     case OO_PlusEqual:
4034     case OO_MinusEqual:
4035       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4036         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4037       break;
4038     case OO_Equal:
4039       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4040         return CheckIncRHS(CE->getArg(1));
4041       break;
4042     default:
4043       break;
4044     }
4045   }
4046   if (Dependent() || SemaRef.CurContext->isDependentContext())
4047     return false;
4048   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
4049       << S->getSourceRange() << LCDecl;
4050   return true;
4051 }
4052 
4053 static ExprResult
4054 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4055                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4056   if (SemaRef.CurContext->isDependentContext())
4057     return ExprResult(Capture);
4058   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4059     return SemaRef.PerformImplicitConversion(
4060         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4061         /*AllowExplicit=*/true);
4062   auto I = Captures.find(Capture);
4063   if (I != Captures.end())
4064     return buildCapture(SemaRef, Capture, I->second);
4065   DeclRefExpr *Ref = nullptr;
4066   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4067   Captures[Capture] = Ref;
4068   return Res;
4069 }
4070 
4071 /// \brief Build the expression to calculate the number of iterations.
4072 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4073     Scope *S, const bool LimitedType,
4074     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4075   ExprResult Diff;
4076   auto VarType = LCDecl->getType().getNonReferenceType();
4077   if (VarType->isIntegerType() || VarType->isPointerType() ||
4078       SemaRef.getLangOpts().CPlusPlus) {
4079     // Upper - Lower
4080     auto *UBExpr = TestIsLessOp ? UB : LB;
4081     auto *LBExpr = TestIsLessOp ? LB : UB;
4082     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4083     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4084     if (!Upper || !Lower)
4085       return nullptr;
4086 
4087     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4088 
4089     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4090       // BuildBinOp already emitted error, this one is to point user to upper
4091       // and lower bound, and to tell what is passed to 'operator-'.
4092       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4093           << Upper->getSourceRange() << Lower->getSourceRange();
4094       return nullptr;
4095     }
4096   }
4097 
4098   if (!Diff.isUsable())
4099     return nullptr;
4100 
4101   // Upper - Lower [- 1]
4102   if (TestIsStrictOp)
4103     Diff = SemaRef.BuildBinOp(
4104         S, DefaultLoc, BO_Sub, Diff.get(),
4105         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4106   if (!Diff.isUsable())
4107     return nullptr;
4108 
4109   // Upper - Lower [- 1] + Step
4110   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4111   if (!NewStep.isUsable())
4112     return nullptr;
4113   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4114   if (!Diff.isUsable())
4115     return nullptr;
4116 
4117   // Parentheses (for dumping/debugging purposes only).
4118   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4119   if (!Diff.isUsable())
4120     return nullptr;
4121 
4122   // (Upper - Lower [- 1] + Step) / Step
4123   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4124   if (!Diff.isUsable())
4125     return nullptr;
4126 
4127   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4128   QualType Type = Diff.get()->getType();
4129   auto &C = SemaRef.Context;
4130   bool UseVarType = VarType->hasIntegerRepresentation() &&
4131                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4132   if (!Type->isIntegerType() || UseVarType) {
4133     unsigned NewSize =
4134         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4135     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4136                                : Type->hasSignedIntegerRepresentation();
4137     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4138     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4139       Diff = SemaRef.PerformImplicitConversion(
4140           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4141       if (!Diff.isUsable())
4142         return nullptr;
4143     }
4144   }
4145   if (LimitedType) {
4146     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4147     if (NewSize != C.getTypeSize(Type)) {
4148       if (NewSize < C.getTypeSize(Type)) {
4149         assert(NewSize == 64 && "incorrect loop var size");
4150         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4151             << InitSrcRange << ConditionSrcRange;
4152       }
4153       QualType NewType = C.getIntTypeForBitwidth(
4154           NewSize, Type->hasSignedIntegerRepresentation() ||
4155                        C.getTypeSize(Type) < NewSize);
4156       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4157         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4158                                                  Sema::AA_Converting, true);
4159         if (!Diff.isUsable())
4160           return nullptr;
4161       }
4162     }
4163   }
4164 
4165   return Diff.get();
4166 }
4167 
4168 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4169     Scope *S, Expr *Cond,
4170     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4171   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4172   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4173   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4174 
4175   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4176   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4177   if (!NewLB.isUsable() || !NewUB.isUsable())
4178     return nullptr;
4179 
4180   auto CondExpr = SemaRef.BuildBinOp(
4181       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4182                                   : (TestIsStrictOp ? BO_GT : BO_GE),
4183       NewLB.get(), NewUB.get());
4184   if (CondExpr.isUsable()) {
4185     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4186                                                 SemaRef.Context.BoolTy))
4187       CondExpr = SemaRef.PerformImplicitConversion(
4188           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4189           /*AllowExplicit=*/true);
4190   }
4191   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4192   // Otherwise use original loop conditon and evaluate it in runtime.
4193   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4194 }
4195 
4196 /// \brief Build reference expression to the counter be used for codegen.
4197 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
4198     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
4199   auto *VD = dyn_cast<VarDecl>(LCDecl);
4200   if (!VD) {
4201     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4202     auto *Ref = buildDeclRefExpr(
4203         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4204     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4205     // If the loop control decl is explicitly marked as private, do not mark it
4206     // as captured again.
4207     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4208       Captures.insert(std::make_pair(LCRef, Ref));
4209     return Ref;
4210   }
4211   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4212                           DefaultLoc);
4213 }
4214 
4215 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
4216   if (LCDecl && !LCDecl->isInvalidDecl()) {
4217     auto Type = LCDecl->getType().getNonReferenceType();
4218     auto *PrivateVar = buildVarDecl(
4219         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4220         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4221         isa<VarDecl>(LCDecl)
4222             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4223             : nullptr);
4224     if (PrivateVar->isInvalidDecl())
4225       return nullptr;
4226     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4227   }
4228   return nullptr;
4229 }
4230 
4231 /// \brief Build initialization of the counter to be used for codegen.
4232 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4233 
4234 /// \brief Build step of the counter be used for codegen.
4235 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4236 
4237 /// \brief Iteration space of a single for loop.
4238 struct LoopIterationSpace final {
4239   /// \brief Condition of the loop.
4240   Expr *PreCond = nullptr;
4241   /// \brief This expression calculates the number of iterations in the loop.
4242   /// It is always possible to calculate it before starting the loop.
4243   Expr *NumIterations = nullptr;
4244   /// \brief The loop counter variable.
4245   Expr *CounterVar = nullptr;
4246   /// \brief Private loop counter variable.
4247   Expr *PrivateCounterVar = nullptr;
4248   /// \brief This is initializer for the initial value of #CounterVar.
4249   Expr *CounterInit = nullptr;
4250   /// \brief This is step for the #CounterVar used to generate its update:
4251   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4252   Expr *CounterStep = nullptr;
4253   /// \brief Should step be subtracted?
4254   bool Subtract = false;
4255   /// \brief Source range of the loop init.
4256   SourceRange InitSrcRange;
4257   /// \brief Source range of the loop condition.
4258   SourceRange CondSrcRange;
4259   /// \brief Source range of the loop increment.
4260   SourceRange IncSrcRange;
4261 };
4262 
4263 } // namespace
4264 
4265 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4266   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4267   assert(Init && "Expected loop in canonical form.");
4268   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4269   if (AssociatedLoops > 0 &&
4270       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4271     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4272     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4273       if (auto *D = ISC.GetLoopDecl()) {
4274         auto *VD = dyn_cast<VarDecl>(D);
4275         if (!VD) {
4276           if (auto *Private = IsOpenMPCapturedDecl(D))
4277             VD = Private;
4278           else {
4279             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4280                                      /*WithInit=*/false);
4281             VD = cast<VarDecl>(Ref->getDecl());
4282           }
4283         }
4284         DSAStack->addLoopControlVariable(D, VD);
4285       }
4286     }
4287     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4288   }
4289 }
4290 
4291 /// \brief Called on a for stmt to check and extract its iteration space
4292 /// for further processing (such as collapsing).
4293 static bool CheckOpenMPIterationSpace(
4294     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4295     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4296     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4297     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4298     LoopIterationSpace &ResultIterSpace,
4299     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4300   // OpenMP [2.6, Canonical Loop Form]
4301   //   for (init-expr; test-expr; incr-expr) structured-block
4302   auto *For = dyn_cast_or_null<ForStmt>(S);
4303   if (!For) {
4304     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4305         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4306         << getOpenMPDirectiveName(DKind) << NestedLoopCount
4307         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4308     if (NestedLoopCount > 1) {
4309       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4310         SemaRef.Diag(DSA.getConstructLoc(),
4311                      diag::note_omp_collapse_ordered_expr)
4312             << 2 << CollapseLoopCountExpr->getSourceRange()
4313             << OrderedLoopCountExpr->getSourceRange();
4314       else if (CollapseLoopCountExpr)
4315         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4316                      diag::note_omp_collapse_ordered_expr)
4317             << 0 << CollapseLoopCountExpr->getSourceRange();
4318       else
4319         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4320                      diag::note_omp_collapse_ordered_expr)
4321             << 1 << OrderedLoopCountExpr->getSourceRange();
4322     }
4323     return true;
4324   }
4325   assert(For->getBody());
4326 
4327   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4328 
4329   // Check init.
4330   auto Init = For->getInit();
4331   if (ISC.CheckInit(Init))
4332     return true;
4333 
4334   bool HasErrors = false;
4335 
4336   // Check loop variable's type.
4337   if (auto *LCDecl = ISC.GetLoopDecl()) {
4338     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
4339 
4340     // OpenMP [2.6, Canonical Loop Form]
4341     // Var is one of the following:
4342     //   A variable of signed or unsigned integer type.
4343     //   For C++, a variable of a random access iterator type.
4344     //   For C, a variable of a pointer type.
4345     auto VarType = LCDecl->getType().getNonReferenceType();
4346     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4347         !VarType->isPointerType() &&
4348         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4349       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4350           << SemaRef.getLangOpts().CPlusPlus;
4351       HasErrors = true;
4352     }
4353 
4354     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4355     // a Construct
4356     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4357     // parallel for construct is (are) private.
4358     // The loop iteration variable in the associated for-loop of a simd
4359     // construct with just one associated for-loop is linear with a
4360     // constant-linear-step that is the increment of the associated for-loop.
4361     // Exclude loop var from the list of variables with implicitly defined data
4362     // sharing attributes.
4363     VarsWithImplicitDSA.erase(LCDecl);
4364 
4365     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4366     // in a Construct, C/C++].
4367     // The loop iteration variable in the associated for-loop of a simd
4368     // construct with just one associated for-loop may be listed in a linear
4369     // clause with a constant-linear-step that is the increment of the
4370     // associated for-loop.
4371     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4372     // parallel for construct may be listed in a private or lastprivate clause.
4373     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4374     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4375     // declared in the loop and it is predetermined as a private.
4376     auto PredeterminedCKind =
4377         isOpenMPSimdDirective(DKind)
4378             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4379             : OMPC_private;
4380     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4381           DVar.CKind != PredeterminedCKind) ||
4382          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4383            isOpenMPDistributeDirective(DKind)) &&
4384           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4385           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4386         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4387       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4388           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4389           << getOpenMPClauseName(PredeterminedCKind);
4390       if (DVar.RefExpr == nullptr)
4391         DVar.CKind = PredeterminedCKind;
4392       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4393       HasErrors = true;
4394     } else if (LoopDeclRefExpr != nullptr) {
4395       // Make the loop iteration variable private (for worksharing constructs),
4396       // linear (for simd directives with the only one associated loop) or
4397       // lastprivate (for simd directives with several collapsed or ordered
4398       // loops).
4399       if (DVar.CKind == OMPC_unknown)
4400         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4401                           [](OpenMPDirectiveKind) -> bool { return true; },
4402                           /*FromParent=*/false);
4403       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4404     }
4405 
4406     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4407 
4408     // Check test-expr.
4409     HasErrors |= ISC.CheckCond(For->getCond());
4410 
4411     // Check incr-expr.
4412     HasErrors |= ISC.CheckInc(For->getInc());
4413   }
4414 
4415   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4416     return HasErrors;
4417 
4418   // Build the loop's iteration space representation.
4419   ResultIterSpace.PreCond =
4420       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4421   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4422       DSA.getCurScope(),
4423       (isOpenMPWorksharingDirective(DKind) ||
4424        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4425       Captures);
4426   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
4427   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4428   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4429   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4430   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4431   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4432   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4433   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4434 
4435   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4436                 ResultIterSpace.NumIterations == nullptr ||
4437                 ResultIterSpace.CounterVar == nullptr ||
4438                 ResultIterSpace.PrivateCounterVar == nullptr ||
4439                 ResultIterSpace.CounterInit == nullptr ||
4440                 ResultIterSpace.CounterStep == nullptr);
4441 
4442   return HasErrors;
4443 }
4444 
4445 /// \brief Build 'VarRef = Start.
4446 static ExprResult
4447 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4448                  ExprResult Start,
4449                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4450   // Build 'VarRef = Start.
4451   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4452   if (!NewStart.isUsable())
4453     return ExprError();
4454   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4455                                    VarRef.get()->getType())) {
4456     NewStart = SemaRef.PerformImplicitConversion(
4457         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4458         /*AllowExplicit=*/true);
4459     if (!NewStart.isUsable())
4460       return ExprError();
4461   }
4462 
4463   auto Init =
4464       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4465   return Init;
4466 }
4467 
4468 /// \brief Build 'VarRef = Start + Iter * Step'.
4469 static ExprResult
4470 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4471                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
4472                    ExprResult Step, bool Subtract,
4473                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4474   // Add parentheses (for debugging purposes only).
4475   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4476   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4477       !Step.isUsable())
4478     return ExprError();
4479 
4480   ExprResult NewStep = Step;
4481   if (Captures)
4482     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4483   if (NewStep.isInvalid())
4484     return ExprError();
4485   ExprResult Update =
4486       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4487   if (!Update.isUsable())
4488     return ExprError();
4489 
4490   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4491   // 'VarRef = Start (+|-) Iter * Step'.
4492   ExprResult NewStart = Start;
4493   if (Captures)
4494     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4495   if (NewStart.isInvalid())
4496     return ExprError();
4497 
4498   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4499   ExprResult SavedUpdate = Update;
4500   ExprResult UpdateVal;
4501   if (VarRef.get()->getType()->isOverloadableType() ||
4502       NewStart.get()->getType()->isOverloadableType() ||
4503       Update.get()->getType()->isOverloadableType()) {
4504     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4505     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4506     Update =
4507         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4508     if (Update.isUsable()) {
4509       UpdateVal =
4510           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4511                              VarRef.get(), SavedUpdate.get());
4512       if (UpdateVal.isUsable()) {
4513         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4514                                             UpdateVal.get());
4515       }
4516     }
4517     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4518   }
4519 
4520   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4521   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4522     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4523                                 NewStart.get(), SavedUpdate.get());
4524     if (!Update.isUsable())
4525       return ExprError();
4526 
4527     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4528                                      VarRef.get()->getType())) {
4529       Update = SemaRef.PerformImplicitConversion(
4530           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4531       if (!Update.isUsable())
4532         return ExprError();
4533     }
4534 
4535     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4536   }
4537   return Update;
4538 }
4539 
4540 /// \brief Convert integer expression \a E to make it have at least \a Bits
4541 /// bits.
4542 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4543   if (E == nullptr)
4544     return ExprError();
4545   auto &C = SemaRef.Context;
4546   QualType OldType = E->getType();
4547   unsigned HasBits = C.getTypeSize(OldType);
4548   if (HasBits >= Bits)
4549     return ExprResult(E);
4550   // OK to convert to signed, because new type has more bits than old.
4551   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4552   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4553                                            true);
4554 }
4555 
4556 /// \brief Check if the given expression \a E is a constant integer that fits
4557 /// into \a Bits bits.
4558 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4559   if (E == nullptr)
4560     return false;
4561   llvm::APSInt Result;
4562   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4563     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4564   return false;
4565 }
4566 
4567 /// Build preinits statement for the given declarations.
4568 static Stmt *buildPreInits(ASTContext &Context,
4569                            MutableArrayRef<Decl *> PreInits) {
4570   if (!PreInits.empty()) {
4571     return new (Context) DeclStmt(
4572         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4573         SourceLocation(), SourceLocation());
4574   }
4575   return nullptr;
4576 }
4577 
4578 /// Build preinits statement for the given declarations.
4579 static Stmt *
4580 buildPreInits(ASTContext &Context,
4581               const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4582   if (!Captures.empty()) {
4583     SmallVector<Decl *, 16> PreInits;
4584     for (auto &Pair : Captures)
4585       PreInits.push_back(Pair.second->getDecl());
4586     return buildPreInits(Context, PreInits);
4587   }
4588   return nullptr;
4589 }
4590 
4591 /// Build postupdate expression for the given list of postupdates expressions.
4592 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4593   Expr *PostUpdate = nullptr;
4594   if (!PostUpdates.empty()) {
4595     for (auto *E : PostUpdates) {
4596       Expr *ConvE = S.BuildCStyleCastExpr(
4597                          E->getExprLoc(),
4598                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4599                          E->getExprLoc(), E)
4600                         .get();
4601       PostUpdate = PostUpdate
4602                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4603                                               PostUpdate, ConvE)
4604                              .get()
4605                        : ConvE;
4606     }
4607   }
4608   return PostUpdate;
4609 }
4610 
4611 /// \brief Called on a for stmt to check itself and nested loops (if any).
4612 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4613 /// number of collapsed loops otherwise.
4614 static unsigned
4615 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4616                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4617                 DSAStackTy &DSA,
4618                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4619                 OMPLoopDirective::HelperExprs &Built) {
4620   unsigned NestedLoopCount = 1;
4621   if (CollapseLoopCountExpr) {
4622     // Found 'collapse' clause - calculate collapse number.
4623     llvm::APSInt Result;
4624     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4625       NestedLoopCount = Result.getLimitedValue();
4626   }
4627   if (OrderedLoopCountExpr) {
4628     // Found 'ordered' clause - calculate collapse number.
4629     llvm::APSInt Result;
4630     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4631       if (Result.getLimitedValue() < NestedLoopCount) {
4632         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4633                      diag::err_omp_wrong_ordered_loop_count)
4634             << OrderedLoopCountExpr->getSourceRange();
4635         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4636                      diag::note_collapse_loop_count)
4637             << CollapseLoopCountExpr->getSourceRange();
4638       }
4639       NestedLoopCount = Result.getLimitedValue();
4640     }
4641   }
4642   // This is helper routine for loop directives (e.g., 'for', 'simd',
4643   // 'for simd', etc.).
4644   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4645   SmallVector<LoopIterationSpace, 4> IterSpaces;
4646   IterSpaces.resize(NestedLoopCount);
4647   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4648   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4649     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4650                                   NestedLoopCount, CollapseLoopCountExpr,
4651                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4652                                   IterSpaces[Cnt], Captures))
4653       return 0;
4654     // Move on to the next nested for loop, or to the loop body.
4655     // OpenMP [2.8.1, simd construct, Restrictions]
4656     // All loops associated with the construct must be perfectly nested; that
4657     // is, there must be no intervening code nor any OpenMP directive between
4658     // any two loops.
4659     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4660   }
4661 
4662   Built.clear(/* size */ NestedLoopCount);
4663 
4664   if (SemaRef.CurContext->isDependentContext())
4665     return NestedLoopCount;
4666 
4667   // An example of what is generated for the following code:
4668   //
4669   //   #pragma omp simd collapse(2) ordered(2)
4670   //   for (i = 0; i < NI; ++i)
4671   //     for (k = 0; k < NK; ++k)
4672   //       for (j = J0; j < NJ; j+=2) {
4673   //         <loop body>
4674   //       }
4675   //
4676   // We generate the code below.
4677   // Note: the loop body may be outlined in CodeGen.
4678   // Note: some counters may be C++ classes, operator- is used to find number of
4679   // iterations and operator+= to calculate counter value.
4680   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4681   // or i64 is currently supported).
4682   //
4683   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4684   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4685   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4686   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4687   //     // similar updates for vars in clauses (e.g. 'linear')
4688   //     <loop body (using local i and j)>
4689   //   }
4690   //   i = NI; // assign final values of counters
4691   //   j = NJ;
4692   //
4693 
4694   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4695   // the iteration counts of the collapsed for loops.
4696   // Precondition tests if there is at least one iteration (all conditions are
4697   // true).
4698   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4699   auto N0 = IterSpaces[0].NumIterations;
4700   ExprResult LastIteration32 = WidenIterationCount(
4701       32 /* Bits */, SemaRef
4702                          .PerformImplicitConversion(
4703                              N0->IgnoreImpCasts(), N0->getType(),
4704                              Sema::AA_Converting, /*AllowExplicit=*/true)
4705                          .get(),
4706       SemaRef);
4707   ExprResult LastIteration64 = WidenIterationCount(
4708       64 /* Bits */, SemaRef
4709                          .PerformImplicitConversion(
4710                              N0->IgnoreImpCasts(), N0->getType(),
4711                              Sema::AA_Converting, /*AllowExplicit=*/true)
4712                          .get(),
4713       SemaRef);
4714 
4715   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4716     return NestedLoopCount;
4717 
4718   auto &C = SemaRef.Context;
4719   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4720 
4721   Scope *CurScope = DSA.getCurScope();
4722   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4723     if (PreCond.isUsable()) {
4724       PreCond =
4725           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4726                              PreCond.get(), IterSpaces[Cnt].PreCond);
4727     }
4728     auto N = IterSpaces[Cnt].NumIterations;
4729     SourceLocation Loc = N->getExprLoc();
4730     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4731     if (LastIteration32.isUsable())
4732       LastIteration32 = SemaRef.BuildBinOp(
4733           CurScope, Loc, BO_Mul, LastIteration32.get(),
4734           SemaRef
4735               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4736                                          Sema::AA_Converting,
4737                                          /*AllowExplicit=*/true)
4738               .get());
4739     if (LastIteration64.isUsable())
4740       LastIteration64 = SemaRef.BuildBinOp(
4741           CurScope, Loc, BO_Mul, LastIteration64.get(),
4742           SemaRef
4743               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4744                                          Sema::AA_Converting,
4745                                          /*AllowExplicit=*/true)
4746               .get());
4747   }
4748 
4749   // Choose either the 32-bit or 64-bit version.
4750   ExprResult LastIteration = LastIteration64;
4751   if (LastIteration32.isUsable() &&
4752       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4753       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4754        FitsInto(
4755            32 /* Bits */,
4756            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4757            LastIteration64.get(), SemaRef)))
4758     LastIteration = LastIteration32;
4759   QualType VType = LastIteration.get()->getType();
4760   QualType RealVType = VType;
4761   QualType StrideVType = VType;
4762   if (isOpenMPTaskLoopDirective(DKind)) {
4763     VType =
4764         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4765     StrideVType =
4766         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4767   }
4768 
4769   if (!LastIteration.isUsable())
4770     return 0;
4771 
4772   // Save the number of iterations.
4773   ExprResult NumIterations = LastIteration;
4774   {
4775     LastIteration = SemaRef.BuildBinOp(
4776         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4777         LastIteration.get(),
4778         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4779     if (!LastIteration.isUsable())
4780       return 0;
4781   }
4782 
4783   // Calculate the last iteration number beforehand instead of doing this on
4784   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4785   llvm::APSInt Result;
4786   bool IsConstant =
4787       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4788   ExprResult CalcLastIteration;
4789   if (!IsConstant) {
4790     ExprResult SaveRef =
4791         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4792     LastIteration = SaveRef;
4793 
4794     // Prepare SaveRef + 1.
4795     NumIterations = SemaRef.BuildBinOp(
4796         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4797         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4798     if (!NumIterations.isUsable())
4799       return 0;
4800   }
4801 
4802   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4803 
4804   // Build variables passed into runtime, necessary for worksharing directives.
4805   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4806   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4807       isOpenMPDistributeDirective(DKind)) {
4808     // Lower bound variable, initialized with zero.
4809     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4810     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4811     SemaRef.AddInitializerToDecl(LBDecl,
4812                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4813                                  /*DirectInit*/ false);
4814 
4815     // Upper bound variable, initialized with last iteration number.
4816     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4817     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4818     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4819                                  /*DirectInit*/ false);
4820 
4821     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4822     // This will be used to implement clause 'lastprivate'.
4823     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4824     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4825     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4826     SemaRef.AddInitializerToDecl(ILDecl,
4827                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4828                                  /*DirectInit*/ false);
4829 
4830     // Stride variable returned by runtime (we initialize it to 1 by default).
4831     VarDecl *STDecl =
4832         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4833     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4834     SemaRef.AddInitializerToDecl(STDecl,
4835                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4836                                  /*DirectInit*/ false);
4837 
4838     // Build expression: UB = min(UB, LastIteration)
4839     // It is necessary for CodeGen of directives with static scheduling.
4840     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4841                                                 UB.get(), LastIteration.get());
4842     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4843         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4844     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4845                              CondOp.get());
4846     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4847 
4848     // If we have a combined directive that combines 'distribute', 'for' or
4849     // 'simd' we need to be able to access the bounds of the schedule of the
4850     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4851     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4852     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4853 
4854       // Lower bound variable, initialized with zero.
4855       VarDecl *CombLBDecl =
4856           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4857       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4858       SemaRef.AddInitializerToDecl(
4859           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4860           /*DirectInit*/ false);
4861 
4862       // Upper bound variable, initialized with last iteration number.
4863       VarDecl *CombUBDecl =
4864           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4865       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4866       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4867                                    /*DirectInit*/ false);
4868 
4869       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4870           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4871       ExprResult CombCondOp =
4872           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4873                                      LastIteration.get(), CombUB.get());
4874       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4875                                    CombCondOp.get());
4876       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4877 
4878       auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4879       // We expect to have at least 2 more parameters than the 'parallel'
4880       // directive does - the lower and upper bounds of the previous schedule.
4881       assert(CD->getNumParams() >= 4 &&
4882              "Unexpected number of parameters in loop combined directive");
4883 
4884       // Set the proper type for the bounds given what we learned from the
4885       // enclosed loops.
4886       auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4887       auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4888 
4889       // Previous lower and upper bounds are obtained from the region
4890       // parameters.
4891       PrevLB =
4892           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4893       PrevUB =
4894           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4895     }
4896   }
4897 
4898   // Build the iteration variable and its initialization before loop.
4899   ExprResult IV;
4900   ExprResult Init, CombInit;
4901   {
4902     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4903     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4904     Expr *RHS =
4905         (isOpenMPWorksharingDirective(DKind) ||
4906          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4907             ? LB.get()
4908             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4909     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4910     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4911 
4912     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4913       Expr *CombRHS =
4914           (isOpenMPWorksharingDirective(DKind) ||
4915            isOpenMPTaskLoopDirective(DKind) ||
4916            isOpenMPDistributeDirective(DKind))
4917               ? CombLB.get()
4918               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4919       CombInit =
4920           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4921       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4922     }
4923   }
4924 
4925   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4926   SourceLocation CondLoc = AStmt->getLocStart();
4927   ExprResult Cond =
4928       (isOpenMPWorksharingDirective(DKind) ||
4929        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4930           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4931           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4932                                NumIterations.get());
4933   ExprResult CombCond;
4934   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4935     CombCond =
4936         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4937   }
4938   // Loop increment (IV = IV + 1)
4939   SourceLocation IncLoc = AStmt->getLocStart();
4940   ExprResult Inc =
4941       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4942                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4943   if (!Inc.isUsable())
4944     return 0;
4945   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4946   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4947   if (!Inc.isUsable())
4948     return 0;
4949 
4950   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4951   // Used for directives with static scheduling.
4952   // In combined construct, add combined version that use CombLB and CombUB
4953   // base variables for the update
4954   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
4955   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4956       isOpenMPDistributeDirective(DKind)) {
4957     // LB + ST
4958     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4959     if (!NextLB.isUsable())
4960       return 0;
4961     // LB = LB + ST
4962     NextLB =
4963         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4964     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4965     if (!NextLB.isUsable())
4966       return 0;
4967     // UB + ST
4968     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4969     if (!NextUB.isUsable())
4970       return 0;
4971     // UB = UB + ST
4972     NextUB =
4973         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4974     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4975     if (!NextUB.isUsable())
4976       return 0;
4977     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4978       CombNextLB =
4979           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4980       if (!NextLB.isUsable())
4981         return 0;
4982       // LB = LB + ST
4983       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4984                                       CombNextLB.get());
4985       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4986       if (!CombNextLB.isUsable())
4987         return 0;
4988       // UB + ST
4989       CombNextUB =
4990           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4991       if (!CombNextUB.isUsable())
4992         return 0;
4993       // UB = UB + ST
4994       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4995                                       CombNextUB.get());
4996       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4997       if (!CombNextUB.isUsable())
4998         return 0;
4999     }
5000   }
5001 
5002   // Create increment expression for distribute loop when combined in a same
5003   // directive with for as IV = IV + ST; ensure upper bound expression based
5004   // on PrevUB instead of NumIterations - used to implement 'for' when found
5005   // in combination with 'distribute', like in 'distribute parallel for'
5006   SourceLocation DistIncLoc = AStmt->getLocStart();
5007   ExprResult DistCond, DistInc, PrevEUB;
5008   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5009     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5010     assert(DistCond.isUsable() && "distribute cond expr was not built");
5011 
5012     DistInc =
5013         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5014     assert(DistInc.isUsable() && "distribute inc expr was not built");
5015     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5016                                  DistInc.get());
5017     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5018     assert(DistInc.isUsable() && "distribute inc expr was not built");
5019 
5020     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5021     // construct
5022     SourceLocation DistEUBLoc = AStmt->getLocStart();
5023     ExprResult IsUBGreater =
5024         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5025     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5026         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5027     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5028                                  CondOp.get());
5029     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5030   }
5031 
5032   // Build updates and final values of the loop counters.
5033   bool HasErrors = false;
5034   Built.Counters.resize(NestedLoopCount);
5035   Built.Inits.resize(NestedLoopCount);
5036   Built.Updates.resize(NestedLoopCount);
5037   Built.Finals.resize(NestedLoopCount);
5038   SmallVector<Expr *, 4> LoopMultipliers;
5039   {
5040     ExprResult Div;
5041     // Go from inner nested loop to outer.
5042     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5043       LoopIterationSpace &IS = IterSpaces[Cnt];
5044       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5045       // Build: Iter = (IV / Div) % IS.NumIters
5046       // where Div is product of previous iterations' IS.NumIters.
5047       ExprResult Iter;
5048       if (Div.isUsable()) {
5049         Iter =
5050             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5051       } else {
5052         Iter = IV;
5053         assert((Cnt == (int)NestedLoopCount - 1) &&
5054                "unusable div expected on first iteration only");
5055       }
5056 
5057       if (Cnt != 0 && Iter.isUsable())
5058         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5059                                   IS.NumIterations);
5060       if (!Iter.isUsable()) {
5061         HasErrors = true;
5062         break;
5063       }
5064 
5065       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5066       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5067       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5068                                           IS.CounterVar->getExprLoc(),
5069                                           /*RefersToCapture=*/true);
5070       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5071                                          IS.CounterInit, Captures);
5072       if (!Init.isUsable()) {
5073         HasErrors = true;
5074         break;
5075       }
5076       ExprResult Update = BuildCounterUpdate(
5077           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5078           IS.CounterStep, IS.Subtract, &Captures);
5079       if (!Update.isUsable()) {
5080         HasErrors = true;
5081         break;
5082       }
5083 
5084       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5085       ExprResult Final = BuildCounterUpdate(
5086           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5087           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5088       if (!Final.isUsable()) {
5089         HasErrors = true;
5090         break;
5091       }
5092 
5093       // Build Div for the next iteration: Div <- Div * IS.NumIters
5094       if (Cnt != 0) {
5095         if (Div.isUnset())
5096           Div = IS.NumIterations;
5097         else
5098           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5099                                    IS.NumIterations);
5100 
5101         // Add parentheses (for debugging purposes only).
5102         if (Div.isUsable())
5103           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5104         if (!Div.isUsable()) {
5105           HasErrors = true;
5106           break;
5107         }
5108         LoopMultipliers.push_back(Div.get());
5109       }
5110       if (!Update.isUsable() || !Final.isUsable()) {
5111         HasErrors = true;
5112         break;
5113       }
5114       // Save results
5115       Built.Counters[Cnt] = IS.CounterVar;
5116       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5117       Built.Inits[Cnt] = Init.get();
5118       Built.Updates[Cnt] = Update.get();
5119       Built.Finals[Cnt] = Final.get();
5120     }
5121   }
5122 
5123   if (HasErrors)
5124     return 0;
5125 
5126   // Save results
5127   Built.IterationVarRef = IV.get();
5128   Built.LastIteration = LastIteration.get();
5129   Built.NumIterations = NumIterations.get();
5130   Built.CalcLastIteration =
5131       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
5132   Built.PreCond = PreCond.get();
5133   Built.PreInits = buildPreInits(C, Captures);
5134   Built.Cond = Cond.get();
5135   Built.Init = Init.get();
5136   Built.Inc = Inc.get();
5137   Built.LB = LB.get();
5138   Built.UB = UB.get();
5139   Built.IL = IL.get();
5140   Built.ST = ST.get();
5141   Built.EUB = EUB.get();
5142   Built.NLB = NextLB.get();
5143   Built.NUB = NextUB.get();
5144   Built.PrevLB = PrevLB.get();
5145   Built.PrevUB = PrevUB.get();
5146   Built.DistInc = DistInc.get();
5147   Built.PrevEUB = PrevEUB.get();
5148   Built.DistCombinedFields.LB = CombLB.get();
5149   Built.DistCombinedFields.UB = CombUB.get();
5150   Built.DistCombinedFields.EUB = CombEUB.get();
5151   Built.DistCombinedFields.Init = CombInit.get();
5152   Built.DistCombinedFields.Cond = CombCond.get();
5153   Built.DistCombinedFields.NLB = CombNextLB.get();
5154   Built.DistCombinedFields.NUB = CombNextUB.get();
5155 
5156   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5157   // Fill data for doacross depend clauses.
5158   for (auto Pair : DSA.getDoacrossDependClauses()) {
5159     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5160       Pair.first->setCounterValue(CounterVal);
5161     else {
5162       if (NestedLoopCount != Pair.second.size() ||
5163           NestedLoopCount != LoopMultipliers.size() + 1) {
5164         // Erroneous case - clause has some problems.
5165         Pair.first->setCounterValue(CounterVal);
5166         continue;
5167       }
5168       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5169       auto I = Pair.second.rbegin();
5170       auto IS = IterSpaces.rbegin();
5171       auto ILM = LoopMultipliers.rbegin();
5172       Expr *UpCounterVal = CounterVal;
5173       Expr *Multiplier = nullptr;
5174       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5175         if (I->first) {
5176           assert(IS->CounterStep);
5177           Expr *NormalizedOffset =
5178               SemaRef
5179                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5180                               I->first, IS->CounterStep)
5181                   .get();
5182           if (Multiplier) {
5183             NormalizedOffset =
5184                 SemaRef
5185                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5186                                 NormalizedOffset, Multiplier)
5187                     .get();
5188           }
5189           assert(I->second == OO_Plus || I->second == OO_Minus);
5190           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
5191           UpCounterVal = SemaRef
5192                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5193                                          UpCounterVal, NormalizedOffset)
5194                              .get();
5195         }
5196         Multiplier = *ILM;
5197         ++I;
5198         ++IS;
5199         ++ILM;
5200       }
5201       Pair.first->setCounterValue(UpCounterVal);
5202     }
5203   }
5204 
5205   return NestedLoopCount;
5206 }
5207 
5208 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5209   auto CollapseClauses =
5210       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5211   if (CollapseClauses.begin() != CollapseClauses.end())
5212     return (*CollapseClauses.begin())->getNumForLoops();
5213   return nullptr;
5214 }
5215 
5216 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5217   auto OrderedClauses =
5218       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5219   if (OrderedClauses.begin() != OrderedClauses.end())
5220     return (*OrderedClauses.begin())->getNumForLoops();
5221   return nullptr;
5222 }
5223 
5224 static bool checkSimdlenSafelenSpecified(Sema &S,
5225                                          const ArrayRef<OMPClause *> Clauses) {
5226   OMPSafelenClause *Safelen = nullptr;
5227   OMPSimdlenClause *Simdlen = nullptr;
5228 
5229   for (auto *Clause : Clauses) {
5230     if (Clause->getClauseKind() == OMPC_safelen)
5231       Safelen = cast<OMPSafelenClause>(Clause);
5232     else if (Clause->getClauseKind() == OMPC_simdlen)
5233       Simdlen = cast<OMPSimdlenClause>(Clause);
5234     if (Safelen && Simdlen)
5235       break;
5236   }
5237 
5238   if (Simdlen && Safelen) {
5239     llvm::APSInt SimdlenRes, SafelenRes;
5240     auto SimdlenLength = Simdlen->getSimdlen();
5241     auto SafelenLength = Safelen->getSafelen();
5242     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5243         SimdlenLength->isInstantiationDependent() ||
5244         SimdlenLength->containsUnexpandedParameterPack())
5245       return false;
5246     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5247         SafelenLength->isInstantiationDependent() ||
5248         SafelenLength->containsUnexpandedParameterPack())
5249       return false;
5250     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5251     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5252     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5253     // If both simdlen and safelen clauses are specified, the value of the
5254     // simdlen parameter must be less than or equal to the value of the safelen
5255     // parameter.
5256     if (SimdlenRes > SafelenRes) {
5257       S.Diag(SimdlenLength->getExprLoc(),
5258              diag::err_omp_wrong_simdlen_safelen_values)
5259           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5260       return true;
5261     }
5262   }
5263   return false;
5264 }
5265 
5266 StmtResult Sema::ActOnOpenMPSimdDirective(
5267     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5268     SourceLocation EndLoc,
5269     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5270   if (!AStmt)
5271     return StmtError();
5272 
5273   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5274   OMPLoopDirective::HelperExprs B;
5275   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5276   // define the nested loops number.
5277   unsigned NestedLoopCount = CheckOpenMPLoop(
5278       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5279       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5280   if (NestedLoopCount == 0)
5281     return StmtError();
5282 
5283   assert((CurContext->isDependentContext() || B.builtAll()) &&
5284          "omp simd loop exprs were not built");
5285 
5286   if (!CurContext->isDependentContext()) {
5287     // Finalize the clauses that need pre-built expressions for CodeGen.
5288     for (auto C : Clauses) {
5289       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5290         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5291                                      B.NumIterations, *this, CurScope,
5292                                      DSAStack))
5293           return StmtError();
5294     }
5295   }
5296 
5297   if (checkSimdlenSafelenSpecified(*this, Clauses))
5298     return StmtError();
5299 
5300   setFunctionHasBranchProtectedScope();
5301   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5302                                   Clauses, AStmt, B);
5303 }
5304 
5305 StmtResult Sema::ActOnOpenMPForDirective(
5306     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5307     SourceLocation EndLoc,
5308     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5309   if (!AStmt)
5310     return StmtError();
5311 
5312   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5313   OMPLoopDirective::HelperExprs B;
5314   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5315   // define the nested loops number.
5316   unsigned NestedLoopCount = CheckOpenMPLoop(
5317       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5318       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5319   if (NestedLoopCount == 0)
5320     return StmtError();
5321 
5322   assert((CurContext->isDependentContext() || B.builtAll()) &&
5323          "omp for loop exprs were not built");
5324 
5325   if (!CurContext->isDependentContext()) {
5326     // Finalize the clauses that need pre-built expressions for CodeGen.
5327     for (auto C : Clauses) {
5328       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5329         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5330                                      B.NumIterations, *this, CurScope,
5331                                      DSAStack))
5332           return StmtError();
5333     }
5334   }
5335 
5336   setFunctionHasBranchProtectedScope();
5337   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5338                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5339 }
5340 
5341 StmtResult Sema::ActOnOpenMPForSimdDirective(
5342     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5343     SourceLocation EndLoc,
5344     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5345   if (!AStmt)
5346     return StmtError();
5347 
5348   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5349   OMPLoopDirective::HelperExprs B;
5350   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5351   // define the nested loops number.
5352   unsigned NestedLoopCount =
5353       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5354                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5355                       VarsWithImplicitDSA, B);
5356   if (NestedLoopCount == 0)
5357     return StmtError();
5358 
5359   assert((CurContext->isDependentContext() || B.builtAll()) &&
5360          "omp for simd loop exprs were not built");
5361 
5362   if (!CurContext->isDependentContext()) {
5363     // Finalize the clauses that need pre-built expressions for CodeGen.
5364     for (auto C : Clauses) {
5365       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5366         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5367                                      B.NumIterations, *this, CurScope,
5368                                      DSAStack))
5369           return StmtError();
5370     }
5371   }
5372 
5373   if (checkSimdlenSafelenSpecified(*this, Clauses))
5374     return StmtError();
5375 
5376   setFunctionHasBranchProtectedScope();
5377   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5378                                      Clauses, AStmt, B);
5379 }
5380 
5381 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5382                                               Stmt *AStmt,
5383                                               SourceLocation StartLoc,
5384                                               SourceLocation EndLoc) {
5385   if (!AStmt)
5386     return StmtError();
5387 
5388   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5389   auto BaseStmt = AStmt;
5390   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5391     BaseStmt = CS->getCapturedStmt();
5392   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5393     auto S = C->children();
5394     if (S.begin() == S.end())
5395       return StmtError();
5396     // All associated statements must be '#pragma omp section' except for
5397     // the first one.
5398     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5399       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5400         if (SectionStmt)
5401           Diag(SectionStmt->getLocStart(),
5402                diag::err_omp_sections_substmt_not_section);
5403         return StmtError();
5404       }
5405       cast<OMPSectionDirective>(SectionStmt)
5406           ->setHasCancel(DSAStack->isCancelRegion());
5407     }
5408   } else {
5409     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5410     return StmtError();
5411   }
5412 
5413   setFunctionHasBranchProtectedScope();
5414 
5415   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5416                                       DSAStack->isCancelRegion());
5417 }
5418 
5419 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5420                                              SourceLocation StartLoc,
5421                                              SourceLocation EndLoc) {
5422   if (!AStmt)
5423     return StmtError();
5424 
5425   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5426 
5427   setFunctionHasBranchProtectedScope();
5428   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5429 
5430   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5431                                      DSAStack->isCancelRegion());
5432 }
5433 
5434 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5435                                             Stmt *AStmt,
5436                                             SourceLocation StartLoc,
5437                                             SourceLocation EndLoc) {
5438   if (!AStmt)
5439     return StmtError();
5440 
5441   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5442 
5443   setFunctionHasBranchProtectedScope();
5444 
5445   // OpenMP [2.7.3, single Construct, Restrictions]
5446   // The copyprivate clause must not be used with the nowait clause.
5447   OMPClause *Nowait = nullptr;
5448   OMPClause *Copyprivate = nullptr;
5449   for (auto *Clause : Clauses) {
5450     if (Clause->getClauseKind() == OMPC_nowait)
5451       Nowait = Clause;
5452     else if (Clause->getClauseKind() == OMPC_copyprivate)
5453       Copyprivate = Clause;
5454     if (Copyprivate && Nowait) {
5455       Diag(Copyprivate->getLocStart(),
5456            diag::err_omp_single_copyprivate_with_nowait);
5457       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5458       return StmtError();
5459     }
5460   }
5461 
5462   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5463 }
5464 
5465 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5466                                             SourceLocation StartLoc,
5467                                             SourceLocation EndLoc) {
5468   if (!AStmt)
5469     return StmtError();
5470 
5471   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5472 
5473   setFunctionHasBranchProtectedScope();
5474 
5475   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5476 }
5477 
5478 StmtResult Sema::ActOnOpenMPCriticalDirective(
5479     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5480     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5481   if (!AStmt)
5482     return StmtError();
5483 
5484   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5485 
5486   bool ErrorFound = false;
5487   llvm::APSInt Hint;
5488   SourceLocation HintLoc;
5489   bool DependentHint = false;
5490   for (auto *C : Clauses) {
5491     if (C->getClauseKind() == OMPC_hint) {
5492       if (!DirName.getName()) {
5493         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5494         ErrorFound = true;
5495       }
5496       Expr *E = cast<OMPHintClause>(C)->getHint();
5497       if (E->isTypeDependent() || E->isValueDependent() ||
5498           E->isInstantiationDependent())
5499         DependentHint = true;
5500       else {
5501         Hint = E->EvaluateKnownConstInt(Context);
5502         HintLoc = C->getLocStart();
5503       }
5504     }
5505   }
5506   if (ErrorFound)
5507     return StmtError();
5508   auto Pair = DSAStack->getCriticalWithHint(DirName);
5509   if (Pair.first && DirName.getName() && !DependentHint) {
5510     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5511       Diag(StartLoc, diag::err_omp_critical_with_hint);
5512       if (HintLoc.isValid()) {
5513         Diag(HintLoc, diag::note_omp_critical_hint_here)
5514             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5515       } else
5516         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5517       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5518         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5519             << 1
5520             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5521                    /*Radix=*/10, /*Signed=*/false);
5522       } else
5523         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5524     }
5525   }
5526 
5527   setFunctionHasBranchProtectedScope();
5528 
5529   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5530                                            Clauses, AStmt);
5531   if (!Pair.first && DirName.getName() && !DependentHint)
5532     DSAStack->addCriticalWithHint(Dir, Hint);
5533   return Dir;
5534 }
5535 
5536 StmtResult Sema::ActOnOpenMPParallelForDirective(
5537     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5538     SourceLocation EndLoc,
5539     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5540   if (!AStmt)
5541     return StmtError();
5542 
5543   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5544   // 1.2.2 OpenMP Language Terminology
5545   // Structured block - An executable statement with a single entry at the
5546   // top and a single exit at the bottom.
5547   // The point of exit cannot be a branch out of the structured block.
5548   // longjmp() and throw() must not violate the entry/exit criteria.
5549   CS->getCapturedDecl()->setNothrow();
5550 
5551   OMPLoopDirective::HelperExprs B;
5552   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5553   // define the nested loops number.
5554   unsigned NestedLoopCount =
5555       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5556                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5557                       VarsWithImplicitDSA, B);
5558   if (NestedLoopCount == 0)
5559     return StmtError();
5560 
5561   assert((CurContext->isDependentContext() || B.builtAll()) &&
5562          "omp parallel for loop exprs were not built");
5563 
5564   if (!CurContext->isDependentContext()) {
5565     // Finalize the clauses that need pre-built expressions for CodeGen.
5566     for (auto C : Clauses) {
5567       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5568         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5569                                      B.NumIterations, *this, CurScope,
5570                                      DSAStack))
5571           return StmtError();
5572     }
5573   }
5574 
5575   setFunctionHasBranchProtectedScope();
5576   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5577                                          NestedLoopCount, Clauses, AStmt, B,
5578                                          DSAStack->isCancelRegion());
5579 }
5580 
5581 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5582     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5583     SourceLocation EndLoc,
5584     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5585   if (!AStmt)
5586     return StmtError();
5587 
5588   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5589   // 1.2.2 OpenMP Language Terminology
5590   // Structured block - An executable statement with a single entry at the
5591   // top and a single exit at the bottom.
5592   // The point of exit cannot be a branch out of the structured block.
5593   // longjmp() and throw() must not violate the entry/exit criteria.
5594   CS->getCapturedDecl()->setNothrow();
5595 
5596   OMPLoopDirective::HelperExprs B;
5597   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5598   // define the nested loops number.
5599   unsigned NestedLoopCount =
5600       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5601                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5602                       VarsWithImplicitDSA, B);
5603   if (NestedLoopCount == 0)
5604     return StmtError();
5605 
5606   if (!CurContext->isDependentContext()) {
5607     // Finalize the clauses that need pre-built expressions for CodeGen.
5608     for (auto C : Clauses) {
5609       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5610         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5611                                      B.NumIterations, *this, CurScope,
5612                                      DSAStack))
5613           return StmtError();
5614     }
5615   }
5616 
5617   if (checkSimdlenSafelenSpecified(*this, Clauses))
5618     return StmtError();
5619 
5620   setFunctionHasBranchProtectedScope();
5621   return OMPParallelForSimdDirective::Create(
5622       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5623 }
5624 
5625 StmtResult
5626 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5627                                            Stmt *AStmt, SourceLocation StartLoc,
5628                                            SourceLocation EndLoc) {
5629   if (!AStmt)
5630     return StmtError();
5631 
5632   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5633   auto BaseStmt = AStmt;
5634   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5635     BaseStmt = CS->getCapturedStmt();
5636   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5637     auto S = C->children();
5638     if (S.begin() == S.end())
5639       return StmtError();
5640     // All associated statements must be '#pragma omp section' except for
5641     // the first one.
5642     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5643       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5644         if (SectionStmt)
5645           Diag(SectionStmt->getLocStart(),
5646                diag::err_omp_parallel_sections_substmt_not_section);
5647         return StmtError();
5648       }
5649       cast<OMPSectionDirective>(SectionStmt)
5650           ->setHasCancel(DSAStack->isCancelRegion());
5651     }
5652   } else {
5653     Diag(AStmt->getLocStart(),
5654          diag::err_omp_parallel_sections_not_compound_stmt);
5655     return StmtError();
5656   }
5657 
5658   setFunctionHasBranchProtectedScope();
5659 
5660   return OMPParallelSectionsDirective::Create(
5661       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5662 }
5663 
5664 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5665                                           Stmt *AStmt, SourceLocation StartLoc,
5666                                           SourceLocation EndLoc) {
5667   if (!AStmt)
5668     return StmtError();
5669 
5670   auto *CS = cast<CapturedStmt>(AStmt);
5671   // 1.2.2 OpenMP Language Terminology
5672   // Structured block - An executable statement with a single entry at the
5673   // top and a single exit at the bottom.
5674   // The point of exit cannot be a branch out of the structured block.
5675   // longjmp() and throw() must not violate the entry/exit criteria.
5676   CS->getCapturedDecl()->setNothrow();
5677 
5678   setFunctionHasBranchProtectedScope();
5679 
5680   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5681                                   DSAStack->isCancelRegion());
5682 }
5683 
5684 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5685                                                SourceLocation EndLoc) {
5686   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5687 }
5688 
5689 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5690                                              SourceLocation EndLoc) {
5691   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5692 }
5693 
5694 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5695                                               SourceLocation EndLoc) {
5696   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5697 }
5698 
5699 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5700                                                Stmt *AStmt,
5701                                                SourceLocation StartLoc,
5702                                                SourceLocation EndLoc) {
5703   if (!AStmt)
5704     return StmtError();
5705 
5706   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5707 
5708   setFunctionHasBranchProtectedScope();
5709 
5710   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5711                                        AStmt,
5712                                        DSAStack->getTaskgroupReductionRef());
5713 }
5714 
5715 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5716                                            SourceLocation StartLoc,
5717                                            SourceLocation EndLoc) {
5718   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5719   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5720 }
5721 
5722 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5723                                              Stmt *AStmt,
5724                                              SourceLocation StartLoc,
5725                                              SourceLocation EndLoc) {
5726   OMPClause *DependFound = nullptr;
5727   OMPClause *DependSourceClause = nullptr;
5728   OMPClause *DependSinkClause = nullptr;
5729   bool ErrorFound = false;
5730   OMPThreadsClause *TC = nullptr;
5731   OMPSIMDClause *SC = nullptr;
5732   for (auto *C : Clauses) {
5733     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5734       DependFound = C;
5735       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5736         if (DependSourceClause) {
5737           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5738               << getOpenMPDirectiveName(OMPD_ordered)
5739               << getOpenMPClauseName(OMPC_depend) << 2;
5740           ErrorFound = true;
5741         } else
5742           DependSourceClause = C;
5743         if (DependSinkClause) {
5744           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5745               << 0;
5746           ErrorFound = true;
5747         }
5748       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5749         if (DependSourceClause) {
5750           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5751               << 1;
5752           ErrorFound = true;
5753         }
5754         DependSinkClause = C;
5755       }
5756     } else if (C->getClauseKind() == OMPC_threads)
5757       TC = cast<OMPThreadsClause>(C);
5758     else if (C->getClauseKind() == OMPC_simd)
5759       SC = cast<OMPSIMDClause>(C);
5760   }
5761   if (!ErrorFound && !SC &&
5762       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5763     // OpenMP [2.8.1,simd Construct, Restrictions]
5764     // An ordered construct with the simd clause is the only OpenMP construct
5765     // that can appear in the simd region.
5766     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5767     ErrorFound = true;
5768   } else if (DependFound && (TC || SC)) {
5769     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5770         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5771     ErrorFound = true;
5772   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5773     Diag(DependFound->getLocStart(),
5774          diag::err_omp_ordered_directive_without_param);
5775     ErrorFound = true;
5776   } else if (TC || Clauses.empty()) {
5777     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5778       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5779       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5780           << (TC != nullptr);
5781       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5782       ErrorFound = true;
5783     }
5784   }
5785   if ((!AStmt && !DependFound) || ErrorFound)
5786     return StmtError();
5787 
5788   if (AStmt) {
5789     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5790 
5791     setFunctionHasBranchProtectedScope();
5792   }
5793 
5794   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5795 }
5796 
5797 namespace {
5798 /// \brief Helper class for checking expression in 'omp atomic [update]'
5799 /// construct.
5800 class OpenMPAtomicUpdateChecker {
5801   /// \brief Error results for atomic update expressions.
5802   enum ExprAnalysisErrorCode {
5803     /// \brief A statement is not an expression statement.
5804     NotAnExpression,
5805     /// \brief Expression is not builtin binary or unary operation.
5806     NotABinaryOrUnaryExpression,
5807     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5808     NotAnUnaryIncDecExpression,
5809     /// \brief An expression is not of scalar type.
5810     NotAScalarType,
5811     /// \brief A binary operation is not an assignment operation.
5812     NotAnAssignmentOp,
5813     /// \brief RHS part of the binary operation is not a binary expression.
5814     NotABinaryExpression,
5815     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5816     /// expression.
5817     NotABinaryOperator,
5818     /// \brief RHS binary operation does not have reference to the updated LHS
5819     /// part.
5820     NotAnUpdateExpression,
5821     /// \brief No errors is found.
5822     NoError
5823   };
5824   /// \brief Reference to Sema.
5825   Sema &SemaRef;
5826   /// \brief A location for note diagnostics (when error is found).
5827   SourceLocation NoteLoc;
5828   /// \brief 'x' lvalue part of the source atomic expression.
5829   Expr *X;
5830   /// \brief 'expr' rvalue part of the source atomic expression.
5831   Expr *E;
5832   /// \brief Helper expression of the form
5833   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5834   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5835   Expr *UpdateExpr;
5836   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5837   /// important for non-associative operations.
5838   bool IsXLHSInRHSPart;
5839   BinaryOperatorKind Op;
5840   SourceLocation OpLoc;
5841   /// \brief true if the source expression is a postfix unary operation, false
5842   /// if it is a prefix unary operation.
5843   bool IsPostfixUpdate;
5844 
5845 public:
5846   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5847       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5848         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5849   /// \brief Check specified statement that it is suitable for 'atomic update'
5850   /// constructs and extract 'x', 'expr' and Operation from the original
5851   /// expression. If DiagId and NoteId == 0, then only check is performed
5852   /// without error notification.
5853   /// \param DiagId Diagnostic which should be emitted if error is found.
5854   /// \param NoteId Diagnostic note for the main error message.
5855   /// \return true if statement is not an update expression, false otherwise.
5856   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5857   /// \brief Return the 'x' lvalue part of the source atomic expression.
5858   Expr *getX() const { return X; }
5859   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5860   Expr *getExpr() const { return E; }
5861   /// \brief Return the update expression used in calculation of the updated
5862   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5863   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5864   Expr *getUpdateExpr() const { return UpdateExpr; }
5865   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5866   /// false otherwise.
5867   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5868 
5869   /// \brief true if the source expression is a postfix unary operation, false
5870   /// if it is a prefix unary operation.
5871   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5872 
5873 private:
5874   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5875                             unsigned NoteId = 0);
5876 };
5877 } // namespace
5878 
5879 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5880     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5881   ExprAnalysisErrorCode ErrorFound = NoError;
5882   SourceLocation ErrorLoc, NoteLoc;
5883   SourceRange ErrorRange, NoteRange;
5884   // Allowed constructs are:
5885   //  x = x binop expr;
5886   //  x = expr binop x;
5887   if (AtomicBinOp->getOpcode() == BO_Assign) {
5888     X = AtomicBinOp->getLHS();
5889     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5890             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5891       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5892           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5893           AtomicInnerBinOp->isBitwiseOp()) {
5894         Op = AtomicInnerBinOp->getOpcode();
5895         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5896         auto *LHS = AtomicInnerBinOp->getLHS();
5897         auto *RHS = AtomicInnerBinOp->getRHS();
5898         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5899         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5900                                           /*Canonical=*/true);
5901         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5902                                             /*Canonical=*/true);
5903         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5904                                             /*Canonical=*/true);
5905         if (XId == LHSId) {
5906           E = RHS;
5907           IsXLHSInRHSPart = true;
5908         } else if (XId == RHSId) {
5909           E = LHS;
5910           IsXLHSInRHSPart = false;
5911         } else {
5912           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5913           ErrorRange = AtomicInnerBinOp->getSourceRange();
5914           NoteLoc = X->getExprLoc();
5915           NoteRange = X->getSourceRange();
5916           ErrorFound = NotAnUpdateExpression;
5917         }
5918       } else {
5919         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5920         ErrorRange = AtomicInnerBinOp->getSourceRange();
5921         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5922         NoteRange = SourceRange(NoteLoc, NoteLoc);
5923         ErrorFound = NotABinaryOperator;
5924       }
5925     } else {
5926       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5927       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5928       ErrorFound = NotABinaryExpression;
5929     }
5930   } else {
5931     ErrorLoc = AtomicBinOp->getExprLoc();
5932     ErrorRange = AtomicBinOp->getSourceRange();
5933     NoteLoc = AtomicBinOp->getOperatorLoc();
5934     NoteRange = SourceRange(NoteLoc, NoteLoc);
5935     ErrorFound = NotAnAssignmentOp;
5936   }
5937   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5938     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5939     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5940     return true;
5941   } else if (SemaRef.CurContext->isDependentContext())
5942     E = X = UpdateExpr = nullptr;
5943   return ErrorFound != NoError;
5944 }
5945 
5946 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5947                                                unsigned NoteId) {
5948   ExprAnalysisErrorCode ErrorFound = NoError;
5949   SourceLocation ErrorLoc, NoteLoc;
5950   SourceRange ErrorRange, NoteRange;
5951   // Allowed constructs are:
5952   //  x++;
5953   //  x--;
5954   //  ++x;
5955   //  --x;
5956   //  x binop= expr;
5957   //  x = x binop expr;
5958   //  x = expr binop x;
5959   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5960     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5961     if (AtomicBody->getType()->isScalarType() ||
5962         AtomicBody->isInstantiationDependent()) {
5963       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5964               AtomicBody->IgnoreParenImpCasts())) {
5965         // Check for Compound Assignment Operation
5966         Op = BinaryOperator::getOpForCompoundAssignment(
5967             AtomicCompAssignOp->getOpcode());
5968         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5969         E = AtomicCompAssignOp->getRHS();
5970         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5971         IsXLHSInRHSPart = true;
5972       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5973                      AtomicBody->IgnoreParenImpCasts())) {
5974         // Check for Binary Operation
5975         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5976           return true;
5977       } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5978                      AtomicBody->IgnoreParenImpCasts())) {
5979         // Check for Unary Operation
5980         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5981           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5982           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5983           OpLoc = AtomicUnaryOp->getOperatorLoc();
5984           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5985           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5986           IsXLHSInRHSPart = true;
5987         } else {
5988           ErrorFound = NotAnUnaryIncDecExpression;
5989           ErrorLoc = AtomicUnaryOp->getExprLoc();
5990           ErrorRange = AtomicUnaryOp->getSourceRange();
5991           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5992           NoteRange = SourceRange(NoteLoc, NoteLoc);
5993         }
5994       } else if (!AtomicBody->isInstantiationDependent()) {
5995         ErrorFound = NotABinaryOrUnaryExpression;
5996         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5997         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5998       }
5999     } else {
6000       ErrorFound = NotAScalarType;
6001       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
6002       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6003     }
6004   } else {
6005     ErrorFound = NotAnExpression;
6006     NoteLoc = ErrorLoc = S->getLocStart();
6007     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6008   }
6009   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6010     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6011     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6012     return true;
6013   } else if (SemaRef.CurContext->isDependentContext())
6014     E = X = UpdateExpr = nullptr;
6015   if (ErrorFound == NoError && E && X) {
6016     // Build an update expression of form 'OpaqueValueExpr(x) binop
6017     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6018     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6019     auto *OVEX = new (SemaRef.getASTContext())
6020         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6021     auto *OVEExpr = new (SemaRef.getASTContext())
6022         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6023     auto Update =
6024         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6025                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6026     if (Update.isInvalid())
6027       return true;
6028     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6029                                                Sema::AA_Casting);
6030     if (Update.isInvalid())
6031       return true;
6032     UpdateExpr = Update.get();
6033   }
6034   return ErrorFound != NoError;
6035 }
6036 
6037 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6038                                             Stmt *AStmt,
6039                                             SourceLocation StartLoc,
6040                                             SourceLocation EndLoc) {
6041   if (!AStmt)
6042     return StmtError();
6043 
6044   auto *CS = cast<CapturedStmt>(AStmt);
6045   // 1.2.2 OpenMP Language Terminology
6046   // Structured block - An executable statement with a single entry at the
6047   // top and a single exit at the bottom.
6048   // The point of exit cannot be a branch out of the structured block.
6049   // longjmp() and throw() must not violate the entry/exit criteria.
6050   OpenMPClauseKind AtomicKind = OMPC_unknown;
6051   SourceLocation AtomicKindLoc;
6052   for (auto *C : Clauses) {
6053     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6054         C->getClauseKind() == OMPC_update ||
6055         C->getClauseKind() == OMPC_capture) {
6056       if (AtomicKind != OMPC_unknown) {
6057         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6058             << SourceRange(C->getLocStart(), C->getLocEnd());
6059         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6060             << getOpenMPClauseName(AtomicKind);
6061       } else {
6062         AtomicKind = C->getClauseKind();
6063         AtomicKindLoc = C->getLocStart();
6064       }
6065     }
6066   }
6067 
6068   auto Body = CS->getCapturedStmt();
6069   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6070     Body = EWC->getSubExpr();
6071 
6072   Expr *X = nullptr;
6073   Expr *V = nullptr;
6074   Expr *E = nullptr;
6075   Expr *UE = nullptr;
6076   bool IsXLHSInRHSPart = false;
6077   bool IsPostfixUpdate = false;
6078   // OpenMP [2.12.6, atomic Construct]
6079   // In the next expressions:
6080   // * x and v (as applicable) are both l-value expressions with scalar type.
6081   // * During the execution of an atomic region, multiple syntactic
6082   // occurrences of x must designate the same storage location.
6083   // * Neither of v and expr (as applicable) may access the storage location
6084   // designated by x.
6085   // * Neither of x and expr (as applicable) may access the storage location
6086   // designated by v.
6087   // * expr is an expression with scalar type.
6088   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6089   // * binop, binop=, ++, and -- are not overloaded operators.
6090   // * The expression x binop expr must be numerically equivalent to x binop
6091   // (expr). This requirement is satisfied if the operators in expr have
6092   // precedence greater than binop, or by using parentheses around expr or
6093   // subexpressions of expr.
6094   // * The expression expr binop x must be numerically equivalent to (expr)
6095   // binop x. This requirement is satisfied if the operators in expr have
6096   // precedence equal to or greater than binop, or by using parentheses around
6097   // expr or subexpressions of expr.
6098   // * For forms that allow multiple occurrences of x, the number of times
6099   // that x is evaluated is unspecified.
6100   if (AtomicKind == OMPC_read) {
6101     enum {
6102       NotAnExpression,
6103       NotAnAssignmentOp,
6104       NotAScalarType,
6105       NotAnLValue,
6106       NoError
6107     } ErrorFound = NoError;
6108     SourceLocation ErrorLoc, NoteLoc;
6109     SourceRange ErrorRange, NoteRange;
6110     // If clause is read:
6111     //  v = x;
6112     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6113       auto *AtomicBinOp =
6114           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6115       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6116         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6117         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6118         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6119             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6120           if (!X->isLValue() || !V->isLValue()) {
6121             auto NotLValueExpr = X->isLValue() ? V : X;
6122             ErrorFound = NotAnLValue;
6123             ErrorLoc = AtomicBinOp->getExprLoc();
6124             ErrorRange = AtomicBinOp->getSourceRange();
6125             NoteLoc = NotLValueExpr->getExprLoc();
6126             NoteRange = NotLValueExpr->getSourceRange();
6127           }
6128         } else if (!X->isInstantiationDependent() ||
6129                    !V->isInstantiationDependent()) {
6130           auto NotScalarExpr =
6131               (X->isInstantiationDependent() || X->getType()->isScalarType())
6132                   ? V
6133                   : X;
6134           ErrorFound = NotAScalarType;
6135           ErrorLoc = AtomicBinOp->getExprLoc();
6136           ErrorRange = AtomicBinOp->getSourceRange();
6137           NoteLoc = NotScalarExpr->getExprLoc();
6138           NoteRange = NotScalarExpr->getSourceRange();
6139         }
6140       } else if (!AtomicBody->isInstantiationDependent()) {
6141         ErrorFound = NotAnAssignmentOp;
6142         ErrorLoc = AtomicBody->getExprLoc();
6143         ErrorRange = AtomicBody->getSourceRange();
6144         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6145                               : AtomicBody->getExprLoc();
6146         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6147                                 : AtomicBody->getSourceRange();
6148       }
6149     } else {
6150       ErrorFound = NotAnExpression;
6151       NoteLoc = ErrorLoc = Body->getLocStart();
6152       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6153     }
6154     if (ErrorFound != NoError) {
6155       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6156           << ErrorRange;
6157       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6158                                                       << NoteRange;
6159       return StmtError();
6160     } else if (CurContext->isDependentContext())
6161       V = X = nullptr;
6162   } else if (AtomicKind == OMPC_write) {
6163     enum {
6164       NotAnExpression,
6165       NotAnAssignmentOp,
6166       NotAScalarType,
6167       NotAnLValue,
6168       NoError
6169     } ErrorFound = NoError;
6170     SourceLocation ErrorLoc, NoteLoc;
6171     SourceRange ErrorRange, NoteRange;
6172     // If clause is write:
6173     //  x = expr;
6174     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6175       auto *AtomicBinOp =
6176           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6177       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6178         X = AtomicBinOp->getLHS();
6179         E = AtomicBinOp->getRHS();
6180         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6181             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6182           if (!X->isLValue()) {
6183             ErrorFound = NotAnLValue;
6184             ErrorLoc = AtomicBinOp->getExprLoc();
6185             ErrorRange = AtomicBinOp->getSourceRange();
6186             NoteLoc = X->getExprLoc();
6187             NoteRange = X->getSourceRange();
6188           }
6189         } else if (!X->isInstantiationDependent() ||
6190                    !E->isInstantiationDependent()) {
6191           auto NotScalarExpr =
6192               (X->isInstantiationDependent() || X->getType()->isScalarType())
6193                   ? E
6194                   : X;
6195           ErrorFound = NotAScalarType;
6196           ErrorLoc = AtomicBinOp->getExprLoc();
6197           ErrorRange = AtomicBinOp->getSourceRange();
6198           NoteLoc = NotScalarExpr->getExprLoc();
6199           NoteRange = NotScalarExpr->getSourceRange();
6200         }
6201       } else if (!AtomicBody->isInstantiationDependent()) {
6202         ErrorFound = NotAnAssignmentOp;
6203         ErrorLoc = AtomicBody->getExprLoc();
6204         ErrorRange = AtomicBody->getSourceRange();
6205         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6206                               : AtomicBody->getExprLoc();
6207         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6208                                 : AtomicBody->getSourceRange();
6209       }
6210     } else {
6211       ErrorFound = NotAnExpression;
6212       NoteLoc = ErrorLoc = Body->getLocStart();
6213       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6214     }
6215     if (ErrorFound != NoError) {
6216       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6217           << ErrorRange;
6218       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6219                                                       << NoteRange;
6220       return StmtError();
6221     } else if (CurContext->isDependentContext())
6222       E = X = nullptr;
6223   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6224     // If clause is update:
6225     //  x++;
6226     //  x--;
6227     //  ++x;
6228     //  --x;
6229     //  x binop= expr;
6230     //  x = x binop expr;
6231     //  x = expr binop x;
6232     OpenMPAtomicUpdateChecker Checker(*this);
6233     if (Checker.checkStatement(
6234             Body, (AtomicKind == OMPC_update)
6235                       ? diag::err_omp_atomic_update_not_expression_statement
6236                       : diag::err_omp_atomic_not_expression_statement,
6237             diag::note_omp_atomic_update))
6238       return StmtError();
6239     if (!CurContext->isDependentContext()) {
6240       E = Checker.getExpr();
6241       X = Checker.getX();
6242       UE = Checker.getUpdateExpr();
6243       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6244     }
6245   } else if (AtomicKind == OMPC_capture) {
6246     enum {
6247       NotAnAssignmentOp,
6248       NotACompoundStatement,
6249       NotTwoSubstatements,
6250       NotASpecificExpression,
6251       NoError
6252     } ErrorFound = NoError;
6253     SourceLocation ErrorLoc, NoteLoc;
6254     SourceRange ErrorRange, NoteRange;
6255     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6256       // If clause is a capture:
6257       //  v = x++;
6258       //  v = x--;
6259       //  v = ++x;
6260       //  v = --x;
6261       //  v = x binop= expr;
6262       //  v = x = x binop expr;
6263       //  v = x = expr binop x;
6264       auto *AtomicBinOp =
6265           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6266       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6267         V = AtomicBinOp->getLHS();
6268         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6269         OpenMPAtomicUpdateChecker Checker(*this);
6270         if (Checker.checkStatement(
6271                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6272                 diag::note_omp_atomic_update))
6273           return StmtError();
6274         E = Checker.getExpr();
6275         X = Checker.getX();
6276         UE = Checker.getUpdateExpr();
6277         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6278         IsPostfixUpdate = Checker.isPostfixUpdate();
6279       } else if (!AtomicBody->isInstantiationDependent()) {
6280         ErrorLoc = AtomicBody->getExprLoc();
6281         ErrorRange = AtomicBody->getSourceRange();
6282         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6283                               : AtomicBody->getExprLoc();
6284         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6285                                 : AtomicBody->getSourceRange();
6286         ErrorFound = NotAnAssignmentOp;
6287       }
6288       if (ErrorFound != NoError) {
6289         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6290             << ErrorRange;
6291         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6292         return StmtError();
6293       } else if (CurContext->isDependentContext()) {
6294         UE = V = E = X = nullptr;
6295       }
6296     } else {
6297       // If clause is a capture:
6298       //  { v = x; x = expr; }
6299       //  { v = x; x++; }
6300       //  { v = x; x--; }
6301       //  { v = x; ++x; }
6302       //  { v = x; --x; }
6303       //  { v = x; x binop= expr; }
6304       //  { v = x; x = x binop expr; }
6305       //  { v = x; x = expr binop x; }
6306       //  { x++; v = x; }
6307       //  { x--; v = x; }
6308       //  { ++x; v = x; }
6309       //  { --x; v = x; }
6310       //  { x binop= expr; v = x; }
6311       //  { x = x binop expr; v = x; }
6312       //  { x = expr binop x; v = x; }
6313       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6314         // Check that this is { expr1; expr2; }
6315         if (CS->size() == 2) {
6316           auto *First = CS->body_front();
6317           auto *Second = CS->body_back();
6318           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6319             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6320           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6321             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6322           // Need to find what subexpression is 'v' and what is 'x'.
6323           OpenMPAtomicUpdateChecker Checker(*this);
6324           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6325           BinaryOperator *BinOp = nullptr;
6326           if (IsUpdateExprFound) {
6327             BinOp = dyn_cast<BinaryOperator>(First);
6328             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6329           }
6330           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6331             //  { v = x; x++; }
6332             //  { v = x; x--; }
6333             //  { v = x; ++x; }
6334             //  { v = x; --x; }
6335             //  { v = x; x binop= expr; }
6336             //  { v = x; x = x binop expr; }
6337             //  { v = x; x = expr binop x; }
6338             // Check that the first expression has form v = x.
6339             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6340             llvm::FoldingSetNodeID XId, PossibleXId;
6341             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6342             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6343             IsUpdateExprFound = XId == PossibleXId;
6344             if (IsUpdateExprFound) {
6345               V = BinOp->getLHS();
6346               X = Checker.getX();
6347               E = Checker.getExpr();
6348               UE = Checker.getUpdateExpr();
6349               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6350               IsPostfixUpdate = true;
6351             }
6352           }
6353           if (!IsUpdateExprFound) {
6354             IsUpdateExprFound = !Checker.checkStatement(First);
6355             BinOp = nullptr;
6356             if (IsUpdateExprFound) {
6357               BinOp = dyn_cast<BinaryOperator>(Second);
6358               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6359             }
6360             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6361               //  { x++; v = x; }
6362               //  { x--; v = x; }
6363               //  { ++x; v = x; }
6364               //  { --x; v = x; }
6365               //  { x binop= expr; v = x; }
6366               //  { x = x binop expr; v = x; }
6367               //  { x = expr binop x; v = x; }
6368               // Check that the second expression has form v = x.
6369               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6370               llvm::FoldingSetNodeID XId, PossibleXId;
6371               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6372               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6373               IsUpdateExprFound = XId == PossibleXId;
6374               if (IsUpdateExprFound) {
6375                 V = BinOp->getLHS();
6376                 X = Checker.getX();
6377                 E = Checker.getExpr();
6378                 UE = Checker.getUpdateExpr();
6379                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6380                 IsPostfixUpdate = false;
6381               }
6382             }
6383           }
6384           if (!IsUpdateExprFound) {
6385             //  { v = x; x = expr; }
6386             auto *FirstExpr = dyn_cast<Expr>(First);
6387             auto *SecondExpr = dyn_cast<Expr>(Second);
6388             if (!FirstExpr || !SecondExpr ||
6389                 !(FirstExpr->isInstantiationDependent() ||
6390                   SecondExpr->isInstantiationDependent())) {
6391               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6392               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6393                 ErrorFound = NotAnAssignmentOp;
6394                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6395                                                 : First->getLocStart();
6396                 NoteRange = ErrorRange = FirstBinOp
6397                                              ? FirstBinOp->getSourceRange()
6398                                              : SourceRange(ErrorLoc, ErrorLoc);
6399               } else {
6400                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6401                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6402                   ErrorFound = NotAnAssignmentOp;
6403                   NoteLoc = ErrorLoc = SecondBinOp
6404                                            ? SecondBinOp->getOperatorLoc()
6405                                            : Second->getLocStart();
6406                   NoteRange = ErrorRange =
6407                       SecondBinOp ? SecondBinOp->getSourceRange()
6408                                   : SourceRange(ErrorLoc, ErrorLoc);
6409                 } else {
6410                   auto *PossibleXRHSInFirst =
6411                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6412                   auto *PossibleXLHSInSecond =
6413                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6414                   llvm::FoldingSetNodeID X1Id, X2Id;
6415                   PossibleXRHSInFirst->Profile(X1Id, Context,
6416                                                /*Canonical=*/true);
6417                   PossibleXLHSInSecond->Profile(X2Id, Context,
6418                                                 /*Canonical=*/true);
6419                   IsUpdateExprFound = X1Id == X2Id;
6420                   if (IsUpdateExprFound) {
6421                     V = FirstBinOp->getLHS();
6422                     X = SecondBinOp->getLHS();
6423                     E = SecondBinOp->getRHS();
6424                     UE = nullptr;
6425                     IsXLHSInRHSPart = false;
6426                     IsPostfixUpdate = true;
6427                   } else {
6428                     ErrorFound = NotASpecificExpression;
6429                     ErrorLoc = FirstBinOp->getExprLoc();
6430                     ErrorRange = FirstBinOp->getSourceRange();
6431                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6432                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6433                   }
6434                 }
6435               }
6436             }
6437           }
6438         } else {
6439           NoteLoc = ErrorLoc = Body->getLocStart();
6440           NoteRange = ErrorRange =
6441               SourceRange(Body->getLocStart(), Body->getLocStart());
6442           ErrorFound = NotTwoSubstatements;
6443         }
6444       } else {
6445         NoteLoc = ErrorLoc = Body->getLocStart();
6446         NoteRange = ErrorRange =
6447             SourceRange(Body->getLocStart(), Body->getLocStart());
6448         ErrorFound = NotACompoundStatement;
6449       }
6450       if (ErrorFound != NoError) {
6451         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6452             << ErrorRange;
6453         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6454         return StmtError();
6455       } else if (CurContext->isDependentContext()) {
6456         UE = V = E = X = nullptr;
6457       }
6458     }
6459   }
6460 
6461   setFunctionHasBranchProtectedScope();
6462 
6463   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6464                                     X, V, E, UE, IsXLHSInRHSPart,
6465                                     IsPostfixUpdate);
6466 }
6467 
6468 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6469                                             Stmt *AStmt,
6470                                             SourceLocation StartLoc,
6471                                             SourceLocation EndLoc) {
6472   if (!AStmt)
6473     return StmtError();
6474 
6475   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6476   // 1.2.2 OpenMP Language Terminology
6477   // Structured block - An executable statement with a single entry at the
6478   // top and a single exit at the bottom.
6479   // The point of exit cannot be a branch out of the structured block.
6480   // longjmp() and throw() must not violate the entry/exit criteria.
6481   CS->getCapturedDecl()->setNothrow();
6482   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6483        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6484     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6485     // 1.2.2 OpenMP Language Terminology
6486     // Structured block - An executable statement with a single entry at the
6487     // top and a single exit at the bottom.
6488     // The point of exit cannot be a branch out of the structured block.
6489     // longjmp() and throw() must not violate the entry/exit criteria.
6490     CS->getCapturedDecl()->setNothrow();
6491   }
6492 
6493   // OpenMP [2.16, Nesting of Regions]
6494   // If specified, a teams construct must be contained within a target
6495   // construct. That target construct must contain no statements or directives
6496   // outside of the teams construct.
6497   if (DSAStack->hasInnerTeamsRegion()) {
6498     Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
6499     bool OMPTeamsFound = true;
6500     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6501       auto I = CS->body_begin();
6502       while (I != CS->body_end()) {
6503         auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6504         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6505           OMPTeamsFound = false;
6506           break;
6507         }
6508         ++I;
6509       }
6510       assert(I != CS->body_end() && "Not found statement");
6511       S = *I;
6512     } else {
6513       auto *OED = dyn_cast<OMPExecutableDirective>(S);
6514       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6515     }
6516     if (!OMPTeamsFound) {
6517       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6518       Diag(DSAStack->getInnerTeamsRegionLoc(),
6519            diag::note_omp_nested_teams_construct_here);
6520       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6521           << isa<OMPExecutableDirective>(S);
6522       return StmtError();
6523     }
6524   }
6525 
6526   setFunctionHasBranchProtectedScope();
6527 
6528   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6529 }
6530 
6531 StmtResult
6532 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6533                                          Stmt *AStmt, SourceLocation StartLoc,
6534                                          SourceLocation EndLoc) {
6535   if (!AStmt)
6536     return StmtError();
6537 
6538   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6539   // 1.2.2 OpenMP Language Terminology
6540   // Structured block - An executable statement with a single entry at the
6541   // top and a single exit at the bottom.
6542   // The point of exit cannot be a branch out of the structured block.
6543   // longjmp() and throw() must not violate the entry/exit criteria.
6544   CS->getCapturedDecl()->setNothrow();
6545   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6546        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6547     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6548     // 1.2.2 OpenMP Language Terminology
6549     // Structured block - An executable statement with a single entry at the
6550     // top and a single exit at the bottom.
6551     // The point of exit cannot be a branch out of the structured block.
6552     // longjmp() and throw() must not violate the entry/exit criteria.
6553     CS->getCapturedDecl()->setNothrow();
6554   }
6555 
6556   setFunctionHasBranchProtectedScope();
6557 
6558   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6559                                             AStmt);
6560 }
6561 
6562 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6563     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6564     SourceLocation EndLoc,
6565     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6566   if (!AStmt)
6567     return StmtError();
6568 
6569   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6570   // 1.2.2 OpenMP Language Terminology
6571   // Structured block - An executable statement with a single entry at the
6572   // top and a single exit at the bottom.
6573   // The point of exit cannot be a branch out of the structured block.
6574   // longjmp() and throw() must not violate the entry/exit criteria.
6575   CS->getCapturedDecl()->setNothrow();
6576   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6577        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6578     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6579     // 1.2.2 OpenMP Language Terminology
6580     // Structured block - An executable statement with a single entry at the
6581     // top and a single exit at the bottom.
6582     // The point of exit cannot be a branch out of the structured block.
6583     // longjmp() and throw() must not violate the entry/exit criteria.
6584     CS->getCapturedDecl()->setNothrow();
6585   }
6586 
6587   OMPLoopDirective::HelperExprs B;
6588   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6589   // define the nested loops number.
6590   unsigned NestedLoopCount =
6591       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6592                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
6593                       VarsWithImplicitDSA, B);
6594   if (NestedLoopCount == 0)
6595     return StmtError();
6596 
6597   assert((CurContext->isDependentContext() || B.builtAll()) &&
6598          "omp target parallel for loop exprs were not built");
6599 
6600   if (!CurContext->isDependentContext()) {
6601     // Finalize the clauses that need pre-built expressions for CodeGen.
6602     for (auto C : Clauses) {
6603       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6604         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6605                                      B.NumIterations, *this, CurScope,
6606                                      DSAStack))
6607           return StmtError();
6608     }
6609   }
6610 
6611   setFunctionHasBranchProtectedScope();
6612   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6613                                                NestedLoopCount, Clauses, AStmt,
6614                                                B, DSAStack->isCancelRegion());
6615 }
6616 
6617 /// Check for existence of a map clause in the list of clauses.
6618 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6619                        const OpenMPClauseKind K) {
6620   return llvm::any_of(
6621       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6622 }
6623 
6624 template <typename... Params>
6625 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6626                        const Params... ClauseTypes) {
6627   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6628 }
6629 
6630 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6631                                                 Stmt *AStmt,
6632                                                 SourceLocation StartLoc,
6633                                                 SourceLocation EndLoc) {
6634   if (!AStmt)
6635     return StmtError();
6636 
6637   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6638 
6639   // OpenMP [2.10.1, Restrictions, p. 97]
6640   // At least one map clause must appear on the directive.
6641   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6642     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6643         << "'map' or 'use_device_ptr'"
6644         << getOpenMPDirectiveName(OMPD_target_data);
6645     return StmtError();
6646   }
6647 
6648   setFunctionHasBranchProtectedScope();
6649 
6650   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6651                                         AStmt);
6652 }
6653 
6654 StmtResult
6655 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6656                                           SourceLocation StartLoc,
6657                                           SourceLocation EndLoc, Stmt *AStmt) {
6658   if (!AStmt)
6659     return StmtError();
6660 
6661   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6662   // 1.2.2 OpenMP Language Terminology
6663   // Structured block - An executable statement with a single entry at the
6664   // top and a single exit at the bottom.
6665   // The point of exit cannot be a branch out of the structured block.
6666   // longjmp() and throw() must not violate the entry/exit criteria.
6667   CS->getCapturedDecl()->setNothrow();
6668   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6669        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6670     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6671     // 1.2.2 OpenMP Language Terminology
6672     // Structured block - An executable statement with a single entry at the
6673     // top and a single exit at the bottom.
6674     // The point of exit cannot be a branch out of the structured block.
6675     // longjmp() and throw() must not violate the entry/exit criteria.
6676     CS->getCapturedDecl()->setNothrow();
6677   }
6678 
6679   // OpenMP [2.10.2, Restrictions, p. 99]
6680   // At least one map clause must appear on the directive.
6681   if (!hasClauses(Clauses, OMPC_map)) {
6682     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6683         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
6684     return StmtError();
6685   }
6686 
6687   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6688                                              AStmt);
6689 }
6690 
6691 StmtResult
6692 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6693                                          SourceLocation StartLoc,
6694                                          SourceLocation EndLoc, Stmt *AStmt) {
6695   if (!AStmt)
6696     return StmtError();
6697 
6698   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6699   // 1.2.2 OpenMP Language Terminology
6700   // Structured block - An executable statement with a single entry at the
6701   // top and a single exit at the bottom.
6702   // The point of exit cannot be a branch out of the structured block.
6703   // longjmp() and throw() must not violate the entry/exit criteria.
6704   CS->getCapturedDecl()->setNothrow();
6705   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6706        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6707     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6708     // 1.2.2 OpenMP Language Terminology
6709     // Structured block - An executable statement with a single entry at the
6710     // top and a single exit at the bottom.
6711     // The point of exit cannot be a branch out of the structured block.
6712     // longjmp() and throw() must not violate the entry/exit criteria.
6713     CS->getCapturedDecl()->setNothrow();
6714   }
6715 
6716   // OpenMP [2.10.3, Restrictions, p. 102]
6717   // At least one map clause must appear on the directive.
6718   if (!hasClauses(Clauses, OMPC_map)) {
6719     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6720         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
6721     return StmtError();
6722   }
6723 
6724   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6725                                             AStmt);
6726 }
6727 
6728 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6729                                                   SourceLocation StartLoc,
6730                                                   SourceLocation EndLoc,
6731                                                   Stmt *AStmt) {
6732   if (!AStmt)
6733     return StmtError();
6734 
6735   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6736   // 1.2.2 OpenMP Language Terminology
6737   // Structured block - An executable statement with a single entry at the
6738   // top and a single exit at the bottom.
6739   // The point of exit cannot be a branch out of the structured block.
6740   // longjmp() and throw() must not violate the entry/exit criteria.
6741   CS->getCapturedDecl()->setNothrow();
6742   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6743        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6744     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6745     // 1.2.2 OpenMP Language Terminology
6746     // Structured block - An executable statement with a single entry at the
6747     // top and a single exit at the bottom.
6748     // The point of exit cannot be a branch out of the structured block.
6749     // longjmp() and throw() must not violate the entry/exit criteria.
6750     CS->getCapturedDecl()->setNothrow();
6751   }
6752 
6753   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
6754     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6755     return StmtError();
6756   }
6757   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6758                                           AStmt);
6759 }
6760 
6761 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6762                                            Stmt *AStmt, SourceLocation StartLoc,
6763                                            SourceLocation EndLoc) {
6764   if (!AStmt)
6765     return StmtError();
6766 
6767   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6768   // 1.2.2 OpenMP Language Terminology
6769   // Structured block - An executable statement with a single entry at the
6770   // top and a single exit at the bottom.
6771   // The point of exit cannot be a branch out of the structured block.
6772   // longjmp() and throw() must not violate the entry/exit criteria.
6773   CS->getCapturedDecl()->setNothrow();
6774 
6775   setFunctionHasBranchProtectedScope();
6776 
6777   DSAStack->setParentTeamsRegionLoc(StartLoc);
6778 
6779   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6780 }
6781 
6782 StmtResult
6783 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6784                                             SourceLocation EndLoc,
6785                                             OpenMPDirectiveKind CancelRegion) {
6786   if (DSAStack->isParentNowaitRegion()) {
6787     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6788     return StmtError();
6789   }
6790   if (DSAStack->isParentOrderedRegion()) {
6791     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6792     return StmtError();
6793   }
6794   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6795                                                CancelRegion);
6796 }
6797 
6798 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6799                                             SourceLocation StartLoc,
6800                                             SourceLocation EndLoc,
6801                                             OpenMPDirectiveKind CancelRegion) {
6802   if (DSAStack->isParentNowaitRegion()) {
6803     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6804     return StmtError();
6805   }
6806   if (DSAStack->isParentOrderedRegion()) {
6807     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6808     return StmtError();
6809   }
6810   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6811   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6812                                     CancelRegion);
6813 }
6814 
6815 static bool checkGrainsizeNumTasksClauses(Sema &S,
6816                                           ArrayRef<OMPClause *> Clauses) {
6817   OMPClause *PrevClause = nullptr;
6818   bool ErrorFound = false;
6819   for (auto *C : Clauses) {
6820     if (C->getClauseKind() == OMPC_grainsize ||
6821         C->getClauseKind() == OMPC_num_tasks) {
6822       if (!PrevClause)
6823         PrevClause = C;
6824       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6825         S.Diag(C->getLocStart(),
6826                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6827             << getOpenMPClauseName(C->getClauseKind())
6828             << getOpenMPClauseName(PrevClause->getClauseKind());
6829         S.Diag(PrevClause->getLocStart(),
6830                diag::note_omp_previous_grainsize_num_tasks)
6831             << getOpenMPClauseName(PrevClause->getClauseKind());
6832         ErrorFound = true;
6833       }
6834     }
6835   }
6836   return ErrorFound;
6837 }
6838 
6839 static bool checkReductionClauseWithNogroup(Sema &S,
6840                                             ArrayRef<OMPClause *> Clauses) {
6841   OMPClause *ReductionClause = nullptr;
6842   OMPClause *NogroupClause = nullptr;
6843   for (auto *C : Clauses) {
6844     if (C->getClauseKind() == OMPC_reduction) {
6845       ReductionClause = C;
6846       if (NogroupClause)
6847         break;
6848       continue;
6849     }
6850     if (C->getClauseKind() == OMPC_nogroup) {
6851       NogroupClause = C;
6852       if (ReductionClause)
6853         break;
6854       continue;
6855     }
6856   }
6857   if (ReductionClause && NogroupClause) {
6858     S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6859         << SourceRange(NogroupClause->getLocStart(),
6860                        NogroupClause->getLocEnd());
6861     return true;
6862   }
6863   return false;
6864 }
6865 
6866 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6867     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6868     SourceLocation EndLoc,
6869     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6870   if (!AStmt)
6871     return StmtError();
6872 
6873   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6874   OMPLoopDirective::HelperExprs B;
6875   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6876   // define the nested loops number.
6877   unsigned NestedLoopCount =
6878       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6879                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6880                       VarsWithImplicitDSA, B);
6881   if (NestedLoopCount == 0)
6882     return StmtError();
6883 
6884   assert((CurContext->isDependentContext() || B.builtAll()) &&
6885          "omp for loop exprs were not built");
6886 
6887   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6888   // The grainsize clause and num_tasks clause are mutually exclusive and may
6889   // not appear on the same taskloop directive.
6890   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6891     return StmtError();
6892   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6893   // If a reduction clause is present on the taskloop directive, the nogroup
6894   // clause must not be specified.
6895   if (checkReductionClauseWithNogroup(*this, Clauses))
6896     return StmtError();
6897 
6898   setFunctionHasBranchProtectedScope();
6899   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6900                                       NestedLoopCount, Clauses, AStmt, B);
6901 }
6902 
6903 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6904     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6905     SourceLocation EndLoc,
6906     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6907   if (!AStmt)
6908     return StmtError();
6909 
6910   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6911   OMPLoopDirective::HelperExprs B;
6912   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6913   // define the nested loops number.
6914   unsigned NestedLoopCount =
6915       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6916                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6917                       VarsWithImplicitDSA, B);
6918   if (NestedLoopCount == 0)
6919     return StmtError();
6920 
6921   assert((CurContext->isDependentContext() || B.builtAll()) &&
6922          "omp for loop exprs were not built");
6923 
6924   if (!CurContext->isDependentContext()) {
6925     // Finalize the clauses that need pre-built expressions for CodeGen.
6926     for (auto C : Clauses) {
6927       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6928         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6929                                      B.NumIterations, *this, CurScope,
6930                                      DSAStack))
6931           return StmtError();
6932     }
6933   }
6934 
6935   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6936   // The grainsize clause and num_tasks clause are mutually exclusive and may
6937   // not appear on the same taskloop directive.
6938   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6939     return StmtError();
6940   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6941   // If a reduction clause is present on the taskloop directive, the nogroup
6942   // clause must not be specified.
6943   if (checkReductionClauseWithNogroup(*this, Clauses))
6944     return StmtError();
6945   if (checkSimdlenSafelenSpecified(*this, Clauses))
6946     return StmtError();
6947 
6948   setFunctionHasBranchProtectedScope();
6949   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6950                                           NestedLoopCount, Clauses, AStmt, B);
6951 }
6952 
6953 StmtResult Sema::ActOnOpenMPDistributeDirective(
6954     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6955     SourceLocation EndLoc,
6956     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6957   if (!AStmt)
6958     return StmtError();
6959 
6960   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6961   OMPLoopDirective::HelperExprs B;
6962   // In presence of clause 'collapse' with number of loops, it will
6963   // define the nested loops number.
6964   unsigned NestedLoopCount =
6965       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6966                       nullptr /*ordered not a clause on distribute*/, AStmt,
6967                       *this, *DSAStack, VarsWithImplicitDSA, B);
6968   if (NestedLoopCount == 0)
6969     return StmtError();
6970 
6971   assert((CurContext->isDependentContext() || B.builtAll()) &&
6972          "omp for loop exprs were not built");
6973 
6974   setFunctionHasBranchProtectedScope();
6975   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6976                                         NestedLoopCount, Clauses, AStmt, B);
6977 }
6978 
6979 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6980     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6981     SourceLocation EndLoc,
6982     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6983   if (!AStmt)
6984     return StmtError();
6985 
6986   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6987   // 1.2.2 OpenMP Language Terminology
6988   // Structured block - An executable statement with a single entry at the
6989   // top and a single exit at the bottom.
6990   // The point of exit cannot be a branch out of the structured block.
6991   // longjmp() and throw() must not violate the entry/exit criteria.
6992   CS->getCapturedDecl()->setNothrow();
6993   for (int ThisCaptureLevel =
6994            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6995        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6996     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6997     // 1.2.2 OpenMP Language Terminology
6998     // Structured block - An executable statement with a single entry at the
6999     // top and a single exit at the bottom.
7000     // The point of exit cannot be a branch out of the structured block.
7001     // longjmp() and throw() must not violate the entry/exit criteria.
7002     CS->getCapturedDecl()->setNothrow();
7003   }
7004 
7005   OMPLoopDirective::HelperExprs B;
7006   // In presence of clause 'collapse' with number of loops, it will
7007   // define the nested loops number.
7008   unsigned NestedLoopCount = CheckOpenMPLoop(
7009       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7010       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7011       VarsWithImplicitDSA, B);
7012   if (NestedLoopCount == 0)
7013     return StmtError();
7014 
7015   assert((CurContext->isDependentContext() || B.builtAll()) &&
7016          "omp for loop exprs were not built");
7017 
7018   setFunctionHasBranchProtectedScope();
7019   return OMPDistributeParallelForDirective::Create(
7020       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7021       DSAStack->isCancelRegion());
7022 }
7023 
7024 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7025     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7026     SourceLocation EndLoc,
7027     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7028   if (!AStmt)
7029     return StmtError();
7030 
7031   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7032   // 1.2.2 OpenMP Language Terminology
7033   // Structured block - An executable statement with a single entry at the
7034   // top and a single exit at the bottom.
7035   // The point of exit cannot be a branch out of the structured block.
7036   // longjmp() and throw() must not violate the entry/exit criteria.
7037   CS->getCapturedDecl()->setNothrow();
7038   for (int ThisCaptureLevel =
7039            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
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   OMPLoopDirective::HelperExprs B;
7051   // In presence of clause 'collapse' with number of loops, it will
7052   // define the nested loops number.
7053   unsigned NestedLoopCount = CheckOpenMPLoop(
7054       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7055       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7056       VarsWithImplicitDSA, B);
7057   if (NestedLoopCount == 0)
7058     return StmtError();
7059 
7060   assert((CurContext->isDependentContext() || B.builtAll()) &&
7061          "omp for loop exprs were not built");
7062 
7063   if (!CurContext->isDependentContext()) {
7064     // Finalize the clauses that need pre-built expressions for CodeGen.
7065     for (auto C : Clauses) {
7066       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7067         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7068                                      B.NumIterations, *this, CurScope,
7069                                      DSAStack))
7070           return StmtError();
7071     }
7072   }
7073 
7074   if (checkSimdlenSafelenSpecified(*this, Clauses))
7075     return StmtError();
7076 
7077   setFunctionHasBranchProtectedScope();
7078   return OMPDistributeParallelForSimdDirective::Create(
7079       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7080 }
7081 
7082 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7083     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7084     SourceLocation EndLoc,
7085     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7086   if (!AStmt)
7087     return StmtError();
7088 
7089   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7090   // 1.2.2 OpenMP Language Terminology
7091   // Structured block - An executable statement with a single entry at the
7092   // top and a single exit at the bottom.
7093   // The point of exit cannot be a branch out of the structured block.
7094   // longjmp() and throw() must not violate the entry/exit criteria.
7095   CS->getCapturedDecl()->setNothrow();
7096   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7097        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7098     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7099     // 1.2.2 OpenMP Language Terminology
7100     // Structured block - An executable statement with a single entry at the
7101     // top and a single exit at the bottom.
7102     // The point of exit cannot be a branch out of the structured block.
7103     // longjmp() and throw() must not violate the entry/exit criteria.
7104     CS->getCapturedDecl()->setNothrow();
7105   }
7106 
7107   OMPLoopDirective::HelperExprs B;
7108   // In presence of clause 'collapse' with number of loops, it will
7109   // define the nested loops number.
7110   unsigned NestedLoopCount =
7111       CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7112                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7113                       *DSAStack, VarsWithImplicitDSA, B);
7114   if (NestedLoopCount == 0)
7115     return StmtError();
7116 
7117   assert((CurContext->isDependentContext() || B.builtAll()) &&
7118          "omp for loop exprs were not built");
7119 
7120   if (!CurContext->isDependentContext()) {
7121     // Finalize the clauses that need pre-built expressions for CodeGen.
7122     for (auto C : Clauses) {
7123       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7124         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7125                                      B.NumIterations, *this, CurScope,
7126                                      DSAStack))
7127           return StmtError();
7128     }
7129   }
7130 
7131   if (checkSimdlenSafelenSpecified(*this, Clauses))
7132     return StmtError();
7133 
7134   setFunctionHasBranchProtectedScope();
7135   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7136                                             NestedLoopCount, Clauses, AStmt, B);
7137 }
7138 
7139 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7140     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7141     SourceLocation EndLoc,
7142     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7143   if (!AStmt)
7144     return StmtError();
7145 
7146   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7147   // 1.2.2 OpenMP Language Terminology
7148   // Structured block - An executable statement with a single entry at the
7149   // top and a single exit at the bottom.
7150   // The point of exit cannot be a branch out of the structured block.
7151   // longjmp() and throw() must not violate the entry/exit criteria.
7152   CS->getCapturedDecl()->setNothrow();
7153   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7154        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7155     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7156     // 1.2.2 OpenMP Language Terminology
7157     // Structured block - An executable statement with a single entry at the
7158     // top and a single exit at the bottom.
7159     // The point of exit cannot be a branch out of the structured block.
7160     // longjmp() and throw() must not violate the entry/exit criteria.
7161     CS->getCapturedDecl()->setNothrow();
7162   }
7163 
7164   OMPLoopDirective::HelperExprs B;
7165   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7166   // define the nested loops number.
7167   unsigned NestedLoopCount = CheckOpenMPLoop(
7168       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7169       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7170       VarsWithImplicitDSA, B);
7171   if (NestedLoopCount == 0)
7172     return StmtError();
7173 
7174   assert((CurContext->isDependentContext() || B.builtAll()) &&
7175          "omp target parallel for simd loop exprs were not built");
7176 
7177   if (!CurContext->isDependentContext()) {
7178     // Finalize the clauses that need pre-built expressions for CodeGen.
7179     for (auto C : Clauses) {
7180       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7181         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7182                                      B.NumIterations, *this, CurScope,
7183                                      DSAStack))
7184           return StmtError();
7185     }
7186   }
7187   if (checkSimdlenSafelenSpecified(*this, Clauses))
7188     return StmtError();
7189 
7190   setFunctionHasBranchProtectedScope();
7191   return OMPTargetParallelForSimdDirective::Create(
7192       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7193 }
7194 
7195 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7196     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7197     SourceLocation EndLoc,
7198     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7199   if (!AStmt)
7200     return StmtError();
7201 
7202   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7203   // 1.2.2 OpenMP Language Terminology
7204   // Structured block - An executable statement with a single entry at the
7205   // top and a single exit at the bottom.
7206   // The point of exit cannot be a branch out of the structured block.
7207   // longjmp() and throw() must not violate the entry/exit criteria.
7208   CS->getCapturedDecl()->setNothrow();
7209   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7210        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7211     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7212     // 1.2.2 OpenMP Language Terminology
7213     // Structured block - An executable statement with a single entry at the
7214     // top and a single exit at the bottom.
7215     // The point of exit cannot be a branch out of the structured block.
7216     // longjmp() and throw() must not violate the entry/exit criteria.
7217     CS->getCapturedDecl()->setNothrow();
7218   }
7219 
7220   OMPLoopDirective::HelperExprs B;
7221   // In presence of clause 'collapse' with number of loops, it will define the
7222   // nested loops number.
7223   unsigned NestedLoopCount =
7224       CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7225                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7226                       VarsWithImplicitDSA, B);
7227   if (NestedLoopCount == 0)
7228     return StmtError();
7229 
7230   assert((CurContext->isDependentContext() || B.builtAll()) &&
7231          "omp target simd loop exprs were not built");
7232 
7233   if (!CurContext->isDependentContext()) {
7234     // Finalize the clauses that need pre-built expressions for CodeGen.
7235     for (auto C : Clauses) {
7236       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7237         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7238                                      B.NumIterations, *this, CurScope,
7239                                      DSAStack))
7240           return StmtError();
7241     }
7242   }
7243 
7244   if (checkSimdlenSafelenSpecified(*this, Clauses))
7245     return StmtError();
7246 
7247   setFunctionHasBranchProtectedScope();
7248   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7249                                         NestedLoopCount, Clauses, AStmt, B);
7250 }
7251 
7252 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7253     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7254     SourceLocation EndLoc,
7255     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7256   if (!AStmt)
7257     return StmtError();
7258 
7259   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7260   // 1.2.2 OpenMP Language Terminology
7261   // Structured block - An executable statement with a single entry at the
7262   // top and a single exit at the bottom.
7263   // The point of exit cannot be a branch out of the structured block.
7264   // longjmp() and throw() must not violate the entry/exit criteria.
7265   CS->getCapturedDecl()->setNothrow();
7266   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7267        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7268     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7269     // 1.2.2 OpenMP Language Terminology
7270     // Structured block - An executable statement with a single entry at the
7271     // top and a single exit at the bottom.
7272     // The point of exit cannot be a branch out of the structured block.
7273     // longjmp() and throw() must not violate the entry/exit criteria.
7274     CS->getCapturedDecl()->setNothrow();
7275   }
7276 
7277   OMPLoopDirective::HelperExprs B;
7278   // In presence of clause 'collapse' with number of loops, it will
7279   // define the nested loops number.
7280   unsigned NestedLoopCount =
7281       CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7282                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7283                       *DSAStack, VarsWithImplicitDSA, B);
7284   if (NestedLoopCount == 0)
7285     return StmtError();
7286 
7287   assert((CurContext->isDependentContext() || B.builtAll()) &&
7288          "omp teams distribute loop exprs were not built");
7289 
7290   setFunctionHasBranchProtectedScope();
7291 
7292   DSAStack->setParentTeamsRegionLoc(StartLoc);
7293 
7294   return OMPTeamsDistributeDirective::Create(
7295       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7296 }
7297 
7298 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7299     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7300     SourceLocation EndLoc,
7301     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7302   if (!AStmt)
7303     return StmtError();
7304 
7305   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7306   // 1.2.2 OpenMP Language Terminology
7307   // Structured block - An executable statement with a single entry at the
7308   // top and a single exit at the bottom.
7309   // The point of exit cannot be a branch out of the structured block.
7310   // longjmp() and throw() must not violate the entry/exit criteria.
7311   CS->getCapturedDecl()->setNothrow();
7312   for (int ThisCaptureLevel =
7313            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7314        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7315     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7316     // 1.2.2 OpenMP Language Terminology
7317     // Structured block - An executable statement with a single entry at the
7318     // top and a single exit at the bottom.
7319     // The point of exit cannot be a branch out of the structured block.
7320     // longjmp() and throw() must not violate the entry/exit criteria.
7321     CS->getCapturedDecl()->setNothrow();
7322   }
7323 
7324 
7325   OMPLoopDirective::HelperExprs B;
7326   // In presence of clause 'collapse' with number of loops, it will
7327   // define the nested loops number.
7328   unsigned NestedLoopCount = CheckOpenMPLoop(
7329       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7330       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7331       VarsWithImplicitDSA, B);
7332 
7333   if (NestedLoopCount == 0)
7334     return StmtError();
7335 
7336   assert((CurContext->isDependentContext() || B.builtAll()) &&
7337          "omp teams distribute simd loop exprs were not built");
7338 
7339   if (!CurContext->isDependentContext()) {
7340     // Finalize the clauses that need pre-built expressions for CodeGen.
7341     for (auto C : Clauses) {
7342       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7343         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7344                                      B.NumIterations, *this, CurScope,
7345                                      DSAStack))
7346           return StmtError();
7347     }
7348   }
7349 
7350   if (checkSimdlenSafelenSpecified(*this, Clauses))
7351     return StmtError();
7352 
7353   setFunctionHasBranchProtectedScope();
7354 
7355   DSAStack->setParentTeamsRegionLoc(StartLoc);
7356 
7357   return OMPTeamsDistributeSimdDirective::Create(
7358       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7359 }
7360 
7361 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7362     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7363     SourceLocation EndLoc,
7364     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7365   if (!AStmt)
7366     return StmtError();
7367 
7368   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7369   // 1.2.2 OpenMP Language Terminology
7370   // Structured block - An executable statement with a single entry at the
7371   // top and a single exit at the bottom.
7372   // The point of exit cannot be a branch out of the structured block.
7373   // longjmp() and throw() must not violate the entry/exit criteria.
7374   CS->getCapturedDecl()->setNothrow();
7375 
7376   for (int ThisCaptureLevel =
7377            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7378        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7379     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7380     // 1.2.2 OpenMP Language Terminology
7381     // Structured block - An executable statement with a single entry at the
7382     // top and a single exit at the bottom.
7383     // The point of exit cannot be a branch out of the structured block.
7384     // longjmp() and throw() must not violate the entry/exit criteria.
7385     CS->getCapturedDecl()->setNothrow();
7386   }
7387 
7388   OMPLoopDirective::HelperExprs B;
7389   // In presence of clause 'collapse' with number of loops, it will
7390   // define the nested loops number.
7391   auto NestedLoopCount = CheckOpenMPLoop(
7392       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7393       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7394       VarsWithImplicitDSA, B);
7395 
7396   if (NestedLoopCount == 0)
7397     return StmtError();
7398 
7399   assert((CurContext->isDependentContext() || B.builtAll()) &&
7400          "omp for loop exprs were not built");
7401 
7402   if (!CurContext->isDependentContext()) {
7403     // Finalize the clauses that need pre-built expressions for CodeGen.
7404     for (auto C : Clauses) {
7405       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7406         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7407                                      B.NumIterations, *this, CurScope,
7408                                      DSAStack))
7409           return StmtError();
7410     }
7411   }
7412 
7413   if (checkSimdlenSafelenSpecified(*this, Clauses))
7414     return StmtError();
7415 
7416   setFunctionHasBranchProtectedScope();
7417 
7418   DSAStack->setParentTeamsRegionLoc(StartLoc);
7419 
7420   return OMPTeamsDistributeParallelForSimdDirective::Create(
7421       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7422 }
7423 
7424 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7425     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7426     SourceLocation EndLoc,
7427     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7428   if (!AStmt)
7429     return StmtError();
7430 
7431   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7432   // 1.2.2 OpenMP Language Terminology
7433   // Structured block - An executable statement with a single entry at the
7434   // top and a single exit at the bottom.
7435   // The point of exit cannot be a branch out of the structured block.
7436   // longjmp() and throw() must not violate the entry/exit criteria.
7437   CS->getCapturedDecl()->setNothrow();
7438 
7439   for (int ThisCaptureLevel =
7440            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7441        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7442     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7443     // 1.2.2 OpenMP Language Terminology
7444     // Structured block - An executable statement with a single entry at the
7445     // top and a single exit at the bottom.
7446     // The point of exit cannot be a branch out of the structured block.
7447     // longjmp() and throw() must not violate the entry/exit criteria.
7448     CS->getCapturedDecl()->setNothrow();
7449   }
7450 
7451   OMPLoopDirective::HelperExprs B;
7452   // In presence of clause 'collapse' with number of loops, it will
7453   // define the nested loops number.
7454   unsigned NestedLoopCount = CheckOpenMPLoop(
7455       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7456       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7457       VarsWithImplicitDSA, B);
7458 
7459   if (NestedLoopCount == 0)
7460     return StmtError();
7461 
7462   assert((CurContext->isDependentContext() || B.builtAll()) &&
7463          "omp for loop exprs were not built");
7464 
7465   setFunctionHasBranchProtectedScope();
7466 
7467   DSAStack->setParentTeamsRegionLoc(StartLoc);
7468 
7469   return OMPTeamsDistributeParallelForDirective::Create(
7470       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7471       DSAStack->isCancelRegion());
7472 }
7473 
7474 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7475                                                  Stmt *AStmt,
7476                                                  SourceLocation StartLoc,
7477                                                  SourceLocation EndLoc) {
7478   if (!AStmt)
7479     return StmtError();
7480 
7481   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7482   // 1.2.2 OpenMP Language Terminology
7483   // Structured block - An executable statement with a single entry at the
7484   // top and a single exit at the bottom.
7485   // The point of exit cannot be a branch out of the structured block.
7486   // longjmp() and throw() must not violate the entry/exit criteria.
7487   CS->getCapturedDecl()->setNothrow();
7488 
7489   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7490        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7491     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7492     // 1.2.2 OpenMP Language Terminology
7493     // Structured block - An executable statement with a single entry at the
7494     // top and a single exit at the bottom.
7495     // The point of exit cannot be a branch out of the structured block.
7496     // longjmp() and throw() must not violate the entry/exit criteria.
7497     CS->getCapturedDecl()->setNothrow();
7498   }
7499   setFunctionHasBranchProtectedScope();
7500 
7501   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7502                                          AStmt);
7503 }
7504 
7505 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7506     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7507     SourceLocation EndLoc,
7508     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7509   if (!AStmt)
7510     return StmtError();
7511 
7512   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7513   // 1.2.2 OpenMP Language Terminology
7514   // Structured block - An executable statement with a single entry at the
7515   // top and a single exit at the bottom.
7516   // The point of exit cannot be a branch out of the structured block.
7517   // longjmp() and throw() must not violate the entry/exit criteria.
7518   CS->getCapturedDecl()->setNothrow();
7519   for (int ThisCaptureLevel =
7520            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7521        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7522     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7523     // 1.2.2 OpenMP Language Terminology
7524     // Structured block - An executable statement with a single entry at the
7525     // top and a single exit at the bottom.
7526     // The point of exit cannot be a branch out of the structured block.
7527     // longjmp() and throw() must not violate the entry/exit criteria.
7528     CS->getCapturedDecl()->setNothrow();
7529   }
7530 
7531   OMPLoopDirective::HelperExprs B;
7532   // In presence of clause 'collapse' with number of loops, it will
7533   // define the nested loops number.
7534   auto NestedLoopCount = CheckOpenMPLoop(
7535       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7536       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7537       VarsWithImplicitDSA, B);
7538   if (NestedLoopCount == 0)
7539     return StmtError();
7540 
7541   assert((CurContext->isDependentContext() || B.builtAll()) &&
7542          "omp target teams distribute loop exprs were not built");
7543 
7544   setFunctionHasBranchProtectedScope();
7545   return OMPTargetTeamsDistributeDirective::Create(
7546       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7547 }
7548 
7549 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7550     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7551     SourceLocation EndLoc,
7552     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7553   if (!AStmt)
7554     return StmtError();
7555 
7556   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7557   // 1.2.2 OpenMP Language Terminology
7558   // Structured block - An executable statement with a single entry at the
7559   // top and a single exit at the bottom.
7560   // The point of exit cannot be a branch out of the structured block.
7561   // longjmp() and throw() must not violate the entry/exit criteria.
7562   CS->getCapturedDecl()->setNothrow();
7563   for (int ThisCaptureLevel =
7564            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7565        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7566     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7567     // 1.2.2 OpenMP Language Terminology
7568     // Structured block - An executable statement with a single entry at the
7569     // top and a single exit at the bottom.
7570     // The point of exit cannot be a branch out of the structured block.
7571     // longjmp() and throw() must not violate the entry/exit criteria.
7572     CS->getCapturedDecl()->setNothrow();
7573   }
7574 
7575   OMPLoopDirective::HelperExprs B;
7576   // In presence of clause 'collapse' with number of loops, it will
7577   // define the nested loops number.
7578   auto NestedLoopCount = CheckOpenMPLoop(
7579       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7580       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7581       VarsWithImplicitDSA, B);
7582   if (NestedLoopCount == 0)
7583     return StmtError();
7584 
7585   assert((CurContext->isDependentContext() || B.builtAll()) &&
7586          "omp target teams distribute parallel for loop exprs were not built");
7587 
7588   if (!CurContext->isDependentContext()) {
7589     // Finalize the clauses that need pre-built expressions for CodeGen.
7590     for (auto C : Clauses) {
7591       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7592         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7593                                      B.NumIterations, *this, CurScope,
7594                                      DSAStack))
7595           return StmtError();
7596     }
7597   }
7598 
7599   setFunctionHasBranchProtectedScope();
7600   return OMPTargetTeamsDistributeParallelForDirective::Create(
7601       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7602       DSAStack->isCancelRegion());
7603 }
7604 
7605 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7606     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7607     SourceLocation EndLoc,
7608     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7609   if (!AStmt)
7610     return StmtError();
7611 
7612   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7613   // 1.2.2 OpenMP Language Terminology
7614   // Structured block - An executable statement with a single entry at the
7615   // top and a single exit at the bottom.
7616   // The point of exit cannot be a branch out of the structured block.
7617   // longjmp() and throw() must not violate the entry/exit criteria.
7618   CS->getCapturedDecl()->setNothrow();
7619   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7620            OMPD_target_teams_distribute_parallel_for_simd);
7621        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7622     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7623     // 1.2.2 OpenMP Language Terminology
7624     // Structured block - An executable statement with a single entry at the
7625     // top and a single exit at the bottom.
7626     // The point of exit cannot be a branch out of the structured block.
7627     // longjmp() and throw() must not violate the entry/exit criteria.
7628     CS->getCapturedDecl()->setNothrow();
7629   }
7630 
7631   OMPLoopDirective::HelperExprs B;
7632   // In presence of clause 'collapse' with number of loops, it will
7633   // define the nested loops number.
7634   auto NestedLoopCount =
7635       CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7636                       getCollapseNumberExpr(Clauses),
7637                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7638                       *DSAStack, VarsWithImplicitDSA, B);
7639   if (NestedLoopCount == 0)
7640     return StmtError();
7641 
7642   assert((CurContext->isDependentContext() || B.builtAll()) &&
7643          "omp target teams distribute parallel for simd loop exprs were not "
7644          "built");
7645 
7646   if (!CurContext->isDependentContext()) {
7647     // Finalize the clauses that need pre-built expressions for CodeGen.
7648     for (auto C : Clauses) {
7649       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7650         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7651                                      B.NumIterations, *this, CurScope,
7652                                      DSAStack))
7653           return StmtError();
7654     }
7655   }
7656 
7657   if (checkSimdlenSafelenSpecified(*this, Clauses))
7658     return StmtError();
7659 
7660   setFunctionHasBranchProtectedScope();
7661   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7662       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7663 }
7664 
7665 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7666     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7667     SourceLocation EndLoc,
7668     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7669   if (!AStmt)
7670     return StmtError();
7671 
7672   auto *CS = cast<CapturedStmt>(AStmt);
7673   // 1.2.2 OpenMP Language Terminology
7674   // Structured block - An executable statement with a single entry at the
7675   // top and a single exit at the bottom.
7676   // The point of exit cannot be a branch out of the structured block.
7677   // longjmp() and throw() must not violate the entry/exit criteria.
7678   CS->getCapturedDecl()->setNothrow();
7679   for (int ThisCaptureLevel =
7680            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7681        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7682     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7683     // 1.2.2 OpenMP Language Terminology
7684     // Structured block - An executable statement with a single entry at the
7685     // top and a single exit at the bottom.
7686     // The point of exit cannot be a branch out of the structured block.
7687     // longjmp() and throw() must not violate the entry/exit criteria.
7688     CS->getCapturedDecl()->setNothrow();
7689   }
7690 
7691   OMPLoopDirective::HelperExprs B;
7692   // In presence of clause 'collapse' with number of loops, it will
7693   // define the nested loops number.
7694   auto NestedLoopCount = CheckOpenMPLoop(
7695       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7696       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7697       VarsWithImplicitDSA, B);
7698   if (NestedLoopCount == 0)
7699     return StmtError();
7700 
7701   assert((CurContext->isDependentContext() || B.builtAll()) &&
7702          "omp target teams distribute simd loop exprs were not built");
7703 
7704   if (!CurContext->isDependentContext()) {
7705     // Finalize the clauses that need pre-built expressions for CodeGen.
7706     for (auto C : Clauses) {
7707       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7708         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7709                                      B.NumIterations, *this, CurScope,
7710                                      DSAStack))
7711           return StmtError();
7712     }
7713   }
7714 
7715   if (checkSimdlenSafelenSpecified(*this, Clauses))
7716     return StmtError();
7717 
7718   setFunctionHasBranchProtectedScope();
7719   return OMPTargetTeamsDistributeSimdDirective::Create(
7720       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7721 }
7722 
7723 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
7724                                              SourceLocation StartLoc,
7725                                              SourceLocation LParenLoc,
7726                                              SourceLocation EndLoc) {
7727   OMPClause *Res = nullptr;
7728   switch (Kind) {
7729   case OMPC_final:
7730     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7731     break;
7732   case OMPC_num_threads:
7733     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7734     break;
7735   case OMPC_safelen:
7736     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7737     break;
7738   case OMPC_simdlen:
7739     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7740     break;
7741   case OMPC_collapse:
7742     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7743     break;
7744   case OMPC_ordered:
7745     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7746     break;
7747   case OMPC_device:
7748     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7749     break;
7750   case OMPC_num_teams:
7751     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7752     break;
7753   case OMPC_thread_limit:
7754     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7755     break;
7756   case OMPC_priority:
7757     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7758     break;
7759   case OMPC_grainsize:
7760     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7761     break;
7762   case OMPC_num_tasks:
7763     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7764     break;
7765   case OMPC_hint:
7766     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7767     break;
7768   case OMPC_if:
7769   case OMPC_default:
7770   case OMPC_proc_bind:
7771   case OMPC_schedule:
7772   case OMPC_private:
7773   case OMPC_firstprivate:
7774   case OMPC_lastprivate:
7775   case OMPC_shared:
7776   case OMPC_reduction:
7777   case OMPC_task_reduction:
7778   case OMPC_in_reduction:
7779   case OMPC_linear:
7780   case OMPC_aligned:
7781   case OMPC_copyin:
7782   case OMPC_copyprivate:
7783   case OMPC_nowait:
7784   case OMPC_untied:
7785   case OMPC_mergeable:
7786   case OMPC_threadprivate:
7787   case OMPC_flush:
7788   case OMPC_read:
7789   case OMPC_write:
7790   case OMPC_update:
7791   case OMPC_capture:
7792   case OMPC_seq_cst:
7793   case OMPC_depend:
7794   case OMPC_threads:
7795   case OMPC_simd:
7796   case OMPC_map:
7797   case OMPC_nogroup:
7798   case OMPC_dist_schedule:
7799   case OMPC_defaultmap:
7800   case OMPC_unknown:
7801   case OMPC_uniform:
7802   case OMPC_to:
7803   case OMPC_from:
7804   case OMPC_use_device_ptr:
7805   case OMPC_is_device_ptr:
7806     llvm_unreachable("Clause is not allowed.");
7807   }
7808   return Res;
7809 }
7810 
7811 // An OpenMP directive such as 'target parallel' has two captured regions:
7812 // for the 'target' and 'parallel' respectively.  This function returns
7813 // the region in which to capture expressions associated with a clause.
7814 // A return value of OMPD_unknown signifies that the expression should not
7815 // be captured.
7816 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7817     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7818     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
7819   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7820   switch (CKind) {
7821   case OMPC_if:
7822     switch (DKind) {
7823     case OMPD_target_parallel:
7824     case OMPD_target_parallel_for:
7825     case OMPD_target_parallel_for_simd:
7826       // If this clause applies to the nested 'parallel' region, capture within
7827       // the 'target' region, otherwise do not capture.
7828       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7829         CaptureRegion = OMPD_target;
7830       break;
7831     case OMPD_target_teams_distribute_parallel_for:
7832     case OMPD_target_teams_distribute_parallel_for_simd:
7833       // If this clause applies to the nested 'parallel' region, capture within
7834       // the 'teams' region, otherwise do not capture.
7835       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7836         CaptureRegion = OMPD_teams;
7837       break;
7838     case OMPD_teams_distribute_parallel_for:
7839     case OMPD_teams_distribute_parallel_for_simd:
7840       CaptureRegion = OMPD_teams;
7841       break;
7842     case OMPD_target_update:
7843     case OMPD_target_enter_data:
7844     case OMPD_target_exit_data:
7845       CaptureRegion = OMPD_task;
7846       break;
7847     case OMPD_cancel:
7848     case OMPD_parallel:
7849     case OMPD_parallel_sections:
7850     case OMPD_parallel_for:
7851     case OMPD_parallel_for_simd:
7852     case OMPD_target:
7853     case OMPD_target_simd:
7854     case OMPD_target_teams:
7855     case OMPD_target_teams_distribute:
7856     case OMPD_target_teams_distribute_simd:
7857     case OMPD_distribute_parallel_for:
7858     case OMPD_distribute_parallel_for_simd:
7859     case OMPD_task:
7860     case OMPD_taskloop:
7861     case OMPD_taskloop_simd:
7862     case OMPD_target_data:
7863       // Do not capture if-clause expressions.
7864       break;
7865     case OMPD_threadprivate:
7866     case OMPD_taskyield:
7867     case OMPD_barrier:
7868     case OMPD_taskwait:
7869     case OMPD_cancellation_point:
7870     case OMPD_flush:
7871     case OMPD_declare_reduction:
7872     case OMPD_declare_simd:
7873     case OMPD_declare_target:
7874     case OMPD_end_declare_target:
7875     case OMPD_teams:
7876     case OMPD_simd:
7877     case OMPD_for:
7878     case OMPD_for_simd:
7879     case OMPD_sections:
7880     case OMPD_section:
7881     case OMPD_single:
7882     case OMPD_master:
7883     case OMPD_critical:
7884     case OMPD_taskgroup:
7885     case OMPD_distribute:
7886     case OMPD_ordered:
7887     case OMPD_atomic:
7888     case OMPD_distribute_simd:
7889     case OMPD_teams_distribute:
7890     case OMPD_teams_distribute_simd:
7891       llvm_unreachable("Unexpected OpenMP directive with if-clause");
7892     case OMPD_unknown:
7893       llvm_unreachable("Unknown OpenMP directive");
7894     }
7895     break;
7896   case OMPC_num_threads:
7897     switch (DKind) {
7898     case OMPD_target_parallel:
7899     case OMPD_target_parallel_for:
7900     case OMPD_target_parallel_for_simd:
7901       CaptureRegion = OMPD_target;
7902       break;
7903     case OMPD_teams_distribute_parallel_for:
7904     case OMPD_teams_distribute_parallel_for_simd:
7905     case OMPD_target_teams_distribute_parallel_for:
7906     case OMPD_target_teams_distribute_parallel_for_simd:
7907       CaptureRegion = OMPD_teams;
7908       break;
7909     case OMPD_parallel:
7910     case OMPD_parallel_sections:
7911     case OMPD_parallel_for:
7912     case OMPD_parallel_for_simd:
7913     case OMPD_distribute_parallel_for:
7914     case OMPD_distribute_parallel_for_simd:
7915       // Do not capture num_threads-clause expressions.
7916       break;
7917     case OMPD_target_data:
7918     case OMPD_target_enter_data:
7919     case OMPD_target_exit_data:
7920     case OMPD_target_update:
7921     case OMPD_target:
7922     case OMPD_target_simd:
7923     case OMPD_target_teams:
7924     case OMPD_target_teams_distribute:
7925     case OMPD_target_teams_distribute_simd:
7926     case OMPD_cancel:
7927     case OMPD_task:
7928     case OMPD_taskloop:
7929     case OMPD_taskloop_simd:
7930     case OMPD_threadprivate:
7931     case OMPD_taskyield:
7932     case OMPD_barrier:
7933     case OMPD_taskwait:
7934     case OMPD_cancellation_point:
7935     case OMPD_flush:
7936     case OMPD_declare_reduction:
7937     case OMPD_declare_simd:
7938     case OMPD_declare_target:
7939     case OMPD_end_declare_target:
7940     case OMPD_teams:
7941     case OMPD_simd:
7942     case OMPD_for:
7943     case OMPD_for_simd:
7944     case OMPD_sections:
7945     case OMPD_section:
7946     case OMPD_single:
7947     case OMPD_master:
7948     case OMPD_critical:
7949     case OMPD_taskgroup:
7950     case OMPD_distribute:
7951     case OMPD_ordered:
7952     case OMPD_atomic:
7953     case OMPD_distribute_simd:
7954     case OMPD_teams_distribute:
7955     case OMPD_teams_distribute_simd:
7956       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7957     case OMPD_unknown:
7958       llvm_unreachable("Unknown OpenMP directive");
7959     }
7960     break;
7961   case OMPC_num_teams:
7962     switch (DKind) {
7963     case OMPD_target_teams:
7964     case OMPD_target_teams_distribute:
7965     case OMPD_target_teams_distribute_simd:
7966     case OMPD_target_teams_distribute_parallel_for:
7967     case OMPD_target_teams_distribute_parallel_for_simd:
7968       CaptureRegion = OMPD_target;
7969       break;
7970     case OMPD_teams_distribute_parallel_for:
7971     case OMPD_teams_distribute_parallel_for_simd:
7972     case OMPD_teams:
7973     case OMPD_teams_distribute:
7974     case OMPD_teams_distribute_simd:
7975       // Do not capture num_teams-clause expressions.
7976       break;
7977     case OMPD_distribute_parallel_for:
7978     case OMPD_distribute_parallel_for_simd:
7979     case OMPD_task:
7980     case OMPD_taskloop:
7981     case OMPD_taskloop_simd:
7982     case OMPD_target_data:
7983     case OMPD_target_enter_data:
7984     case OMPD_target_exit_data:
7985     case OMPD_target_update:
7986     case OMPD_cancel:
7987     case OMPD_parallel:
7988     case OMPD_parallel_sections:
7989     case OMPD_parallel_for:
7990     case OMPD_parallel_for_simd:
7991     case OMPD_target:
7992     case OMPD_target_simd:
7993     case OMPD_target_parallel:
7994     case OMPD_target_parallel_for:
7995     case OMPD_target_parallel_for_simd:
7996     case OMPD_threadprivate:
7997     case OMPD_taskyield:
7998     case OMPD_barrier:
7999     case OMPD_taskwait:
8000     case OMPD_cancellation_point:
8001     case OMPD_flush:
8002     case OMPD_declare_reduction:
8003     case OMPD_declare_simd:
8004     case OMPD_declare_target:
8005     case OMPD_end_declare_target:
8006     case OMPD_simd:
8007     case OMPD_for:
8008     case OMPD_for_simd:
8009     case OMPD_sections:
8010     case OMPD_section:
8011     case OMPD_single:
8012     case OMPD_master:
8013     case OMPD_critical:
8014     case OMPD_taskgroup:
8015     case OMPD_distribute:
8016     case OMPD_ordered:
8017     case OMPD_atomic:
8018     case OMPD_distribute_simd:
8019       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8020     case OMPD_unknown:
8021       llvm_unreachable("Unknown OpenMP directive");
8022     }
8023     break;
8024   case OMPC_thread_limit:
8025     switch (DKind) {
8026     case OMPD_target_teams:
8027     case OMPD_target_teams_distribute:
8028     case OMPD_target_teams_distribute_simd:
8029     case OMPD_target_teams_distribute_parallel_for:
8030     case OMPD_target_teams_distribute_parallel_for_simd:
8031       CaptureRegion = OMPD_target;
8032       break;
8033     case OMPD_teams_distribute_parallel_for:
8034     case OMPD_teams_distribute_parallel_for_simd:
8035     case OMPD_teams:
8036     case OMPD_teams_distribute:
8037     case OMPD_teams_distribute_simd:
8038       // Do not capture thread_limit-clause expressions.
8039       break;
8040     case OMPD_distribute_parallel_for:
8041     case OMPD_distribute_parallel_for_simd:
8042     case OMPD_task:
8043     case OMPD_taskloop:
8044     case OMPD_taskloop_simd:
8045     case OMPD_target_data:
8046     case OMPD_target_enter_data:
8047     case OMPD_target_exit_data:
8048     case OMPD_target_update:
8049     case OMPD_cancel:
8050     case OMPD_parallel:
8051     case OMPD_parallel_sections:
8052     case OMPD_parallel_for:
8053     case OMPD_parallel_for_simd:
8054     case OMPD_target:
8055     case OMPD_target_simd:
8056     case OMPD_target_parallel:
8057     case OMPD_target_parallel_for:
8058     case OMPD_target_parallel_for_simd:
8059     case OMPD_threadprivate:
8060     case OMPD_taskyield:
8061     case OMPD_barrier:
8062     case OMPD_taskwait:
8063     case OMPD_cancellation_point:
8064     case OMPD_flush:
8065     case OMPD_declare_reduction:
8066     case OMPD_declare_simd:
8067     case OMPD_declare_target:
8068     case OMPD_end_declare_target:
8069     case OMPD_simd:
8070     case OMPD_for:
8071     case OMPD_for_simd:
8072     case OMPD_sections:
8073     case OMPD_section:
8074     case OMPD_single:
8075     case OMPD_master:
8076     case OMPD_critical:
8077     case OMPD_taskgroup:
8078     case OMPD_distribute:
8079     case OMPD_ordered:
8080     case OMPD_atomic:
8081     case OMPD_distribute_simd:
8082       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8083     case OMPD_unknown:
8084       llvm_unreachable("Unknown OpenMP directive");
8085     }
8086     break;
8087   case OMPC_schedule:
8088     switch (DKind) {
8089     case OMPD_parallel_for:
8090     case OMPD_parallel_for_simd:
8091     case OMPD_distribute_parallel_for:
8092     case OMPD_distribute_parallel_for_simd:
8093     case OMPD_teams_distribute_parallel_for:
8094     case OMPD_teams_distribute_parallel_for_simd:
8095     case OMPD_target_parallel_for:
8096     case OMPD_target_parallel_for_simd:
8097     case OMPD_target_teams_distribute_parallel_for:
8098     case OMPD_target_teams_distribute_parallel_for_simd:
8099       CaptureRegion = OMPD_parallel;
8100       break;
8101     case OMPD_for:
8102     case OMPD_for_simd:
8103       // Do not capture schedule-clause expressions.
8104       break;
8105     case OMPD_task:
8106     case OMPD_taskloop:
8107     case OMPD_taskloop_simd:
8108     case OMPD_target_data:
8109     case OMPD_target_enter_data:
8110     case OMPD_target_exit_data:
8111     case OMPD_target_update:
8112     case OMPD_teams:
8113     case OMPD_teams_distribute:
8114     case OMPD_teams_distribute_simd:
8115     case OMPD_target_teams_distribute:
8116     case OMPD_target_teams_distribute_simd:
8117     case OMPD_target:
8118     case OMPD_target_simd:
8119     case OMPD_target_parallel:
8120     case OMPD_cancel:
8121     case OMPD_parallel:
8122     case OMPD_parallel_sections:
8123     case OMPD_threadprivate:
8124     case OMPD_taskyield:
8125     case OMPD_barrier:
8126     case OMPD_taskwait:
8127     case OMPD_cancellation_point:
8128     case OMPD_flush:
8129     case OMPD_declare_reduction:
8130     case OMPD_declare_simd:
8131     case OMPD_declare_target:
8132     case OMPD_end_declare_target:
8133     case OMPD_simd:
8134     case OMPD_sections:
8135     case OMPD_section:
8136     case OMPD_single:
8137     case OMPD_master:
8138     case OMPD_critical:
8139     case OMPD_taskgroup:
8140     case OMPD_distribute:
8141     case OMPD_ordered:
8142     case OMPD_atomic:
8143     case OMPD_distribute_simd:
8144     case OMPD_target_teams:
8145       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8146     case OMPD_unknown:
8147       llvm_unreachable("Unknown OpenMP directive");
8148     }
8149     break;
8150   case OMPC_dist_schedule:
8151     switch (DKind) {
8152     case OMPD_teams_distribute_parallel_for:
8153     case OMPD_teams_distribute_parallel_for_simd:
8154     case OMPD_teams_distribute:
8155     case OMPD_teams_distribute_simd:
8156     case OMPD_target_teams_distribute_parallel_for:
8157     case OMPD_target_teams_distribute_parallel_for_simd:
8158     case OMPD_target_teams_distribute:
8159     case OMPD_target_teams_distribute_simd:
8160       CaptureRegion = OMPD_teams;
8161       break;
8162     case OMPD_distribute_parallel_for:
8163     case OMPD_distribute_parallel_for_simd:
8164     case OMPD_distribute:
8165     case OMPD_distribute_simd:
8166       // Do not capture thread_limit-clause expressions.
8167       break;
8168     case OMPD_parallel_for:
8169     case OMPD_parallel_for_simd:
8170     case OMPD_target_parallel_for_simd:
8171     case OMPD_target_parallel_for:
8172     case OMPD_task:
8173     case OMPD_taskloop:
8174     case OMPD_taskloop_simd:
8175     case OMPD_target_data:
8176     case OMPD_target_enter_data:
8177     case OMPD_target_exit_data:
8178     case OMPD_target_update:
8179     case OMPD_teams:
8180     case OMPD_target:
8181     case OMPD_target_simd:
8182     case OMPD_target_parallel:
8183     case OMPD_cancel:
8184     case OMPD_parallel:
8185     case OMPD_parallel_sections:
8186     case OMPD_threadprivate:
8187     case OMPD_taskyield:
8188     case OMPD_barrier:
8189     case OMPD_taskwait:
8190     case OMPD_cancellation_point:
8191     case OMPD_flush:
8192     case OMPD_declare_reduction:
8193     case OMPD_declare_simd:
8194     case OMPD_declare_target:
8195     case OMPD_end_declare_target:
8196     case OMPD_simd:
8197     case OMPD_for:
8198     case OMPD_for_simd:
8199     case OMPD_sections:
8200     case OMPD_section:
8201     case OMPD_single:
8202     case OMPD_master:
8203     case OMPD_critical:
8204     case OMPD_taskgroup:
8205     case OMPD_ordered:
8206     case OMPD_atomic:
8207     case OMPD_target_teams:
8208       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8209     case OMPD_unknown:
8210       llvm_unreachable("Unknown OpenMP directive");
8211     }
8212     break;
8213   case OMPC_device:
8214     switch (DKind) {
8215     case OMPD_target_update:
8216     case OMPD_target_enter_data:
8217     case OMPD_target_exit_data:
8218     case OMPD_target:
8219     case OMPD_target_simd:
8220     case OMPD_target_teams:
8221     case OMPD_target_parallel:
8222     case OMPD_target_teams_distribute:
8223     case OMPD_target_teams_distribute_simd:
8224     case OMPD_target_parallel_for:
8225     case OMPD_target_parallel_for_simd:
8226     case OMPD_target_teams_distribute_parallel_for:
8227     case OMPD_target_teams_distribute_parallel_for_simd:
8228       CaptureRegion = OMPD_task;
8229       break;
8230     case OMPD_target_data:
8231       // Do not capture device-clause expressions.
8232       break;
8233     case OMPD_teams_distribute_parallel_for:
8234     case OMPD_teams_distribute_parallel_for_simd:
8235     case OMPD_teams:
8236     case OMPD_teams_distribute:
8237     case OMPD_teams_distribute_simd:
8238     case OMPD_distribute_parallel_for:
8239     case OMPD_distribute_parallel_for_simd:
8240     case OMPD_task:
8241     case OMPD_taskloop:
8242     case OMPD_taskloop_simd:
8243     case OMPD_cancel:
8244     case OMPD_parallel:
8245     case OMPD_parallel_sections:
8246     case OMPD_parallel_for:
8247     case OMPD_parallel_for_simd:
8248     case OMPD_threadprivate:
8249     case OMPD_taskyield:
8250     case OMPD_barrier:
8251     case OMPD_taskwait:
8252     case OMPD_cancellation_point:
8253     case OMPD_flush:
8254     case OMPD_declare_reduction:
8255     case OMPD_declare_simd:
8256     case OMPD_declare_target:
8257     case OMPD_end_declare_target:
8258     case OMPD_simd:
8259     case OMPD_for:
8260     case OMPD_for_simd:
8261     case OMPD_sections:
8262     case OMPD_section:
8263     case OMPD_single:
8264     case OMPD_master:
8265     case OMPD_critical:
8266     case OMPD_taskgroup:
8267     case OMPD_distribute:
8268     case OMPD_ordered:
8269     case OMPD_atomic:
8270     case OMPD_distribute_simd:
8271       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8272     case OMPD_unknown:
8273       llvm_unreachable("Unknown OpenMP directive");
8274     }
8275     break;
8276   case OMPC_firstprivate:
8277   case OMPC_lastprivate:
8278   case OMPC_reduction:
8279   case OMPC_task_reduction:
8280   case OMPC_in_reduction:
8281   case OMPC_linear:
8282   case OMPC_default:
8283   case OMPC_proc_bind:
8284   case OMPC_final:
8285   case OMPC_safelen:
8286   case OMPC_simdlen:
8287   case OMPC_collapse:
8288   case OMPC_private:
8289   case OMPC_shared:
8290   case OMPC_aligned:
8291   case OMPC_copyin:
8292   case OMPC_copyprivate:
8293   case OMPC_ordered:
8294   case OMPC_nowait:
8295   case OMPC_untied:
8296   case OMPC_mergeable:
8297   case OMPC_threadprivate:
8298   case OMPC_flush:
8299   case OMPC_read:
8300   case OMPC_write:
8301   case OMPC_update:
8302   case OMPC_capture:
8303   case OMPC_seq_cst:
8304   case OMPC_depend:
8305   case OMPC_threads:
8306   case OMPC_simd:
8307   case OMPC_map:
8308   case OMPC_priority:
8309   case OMPC_grainsize:
8310   case OMPC_nogroup:
8311   case OMPC_num_tasks:
8312   case OMPC_hint:
8313   case OMPC_defaultmap:
8314   case OMPC_unknown:
8315   case OMPC_uniform:
8316   case OMPC_to:
8317   case OMPC_from:
8318   case OMPC_use_device_ptr:
8319   case OMPC_is_device_ptr:
8320     llvm_unreachable("Unexpected OpenMP clause.");
8321   }
8322   return CaptureRegion;
8323 }
8324 
8325 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8326                                      Expr *Condition, SourceLocation StartLoc,
8327                                      SourceLocation LParenLoc,
8328                                      SourceLocation NameModifierLoc,
8329                                      SourceLocation ColonLoc,
8330                                      SourceLocation EndLoc) {
8331   Expr *ValExpr = Condition;
8332   Stmt *HelperValStmt = nullptr;
8333   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8334   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8335       !Condition->isInstantiationDependent() &&
8336       !Condition->containsUnexpandedParameterPack()) {
8337     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8338     if (Val.isInvalid())
8339       return nullptr;
8340 
8341     ValExpr = Val.get();
8342 
8343     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8344     CaptureRegion =
8345         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8346     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8347       ValExpr = MakeFullExpr(ValExpr).get();
8348       llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8349       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8350       HelperValStmt = buildPreInits(Context, Captures);
8351     }
8352   }
8353 
8354   return new (Context)
8355       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8356                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8357 }
8358 
8359 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8360                                         SourceLocation StartLoc,
8361                                         SourceLocation LParenLoc,
8362                                         SourceLocation EndLoc) {
8363   Expr *ValExpr = Condition;
8364   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8365       !Condition->isInstantiationDependent() &&
8366       !Condition->containsUnexpandedParameterPack()) {
8367     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8368     if (Val.isInvalid())
8369       return nullptr;
8370 
8371     ValExpr = MakeFullExpr(Val.get()).get();
8372   }
8373 
8374   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8375 }
8376 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8377                                                         Expr *Op) {
8378   if (!Op)
8379     return ExprError();
8380 
8381   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8382   public:
8383     IntConvertDiagnoser()
8384         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8385     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8386                                          QualType T) override {
8387       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8388     }
8389     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8390                                              QualType T) override {
8391       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8392     }
8393     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8394                                                QualType T,
8395                                                QualType ConvTy) override {
8396       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8397     }
8398     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8399                                            QualType ConvTy) override {
8400       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8401              << ConvTy->isEnumeralType() << ConvTy;
8402     }
8403     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8404                                             QualType T) override {
8405       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8406     }
8407     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8408                                         QualType ConvTy) override {
8409       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8410              << ConvTy->isEnumeralType() << ConvTy;
8411     }
8412     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8413                                              QualType) override {
8414       llvm_unreachable("conversion functions are permitted");
8415     }
8416   } ConvertDiagnoser;
8417   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8418 }
8419 
8420 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8421                                       OpenMPClauseKind CKind,
8422                                       bool StrictlyPositive) {
8423   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8424       !ValExpr->isInstantiationDependent()) {
8425     SourceLocation Loc = ValExpr->getExprLoc();
8426     ExprResult Value =
8427         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8428     if (Value.isInvalid())
8429       return false;
8430 
8431     ValExpr = Value.get();
8432     // The expression must evaluate to a non-negative integer value.
8433     llvm::APSInt Result;
8434     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8435         Result.isSigned() &&
8436         !((!StrictlyPositive && Result.isNonNegative()) ||
8437           (StrictlyPositive && Result.isStrictlyPositive()))) {
8438       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8439           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8440           << ValExpr->getSourceRange();
8441       return false;
8442     }
8443   }
8444   return true;
8445 }
8446 
8447 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8448                                              SourceLocation StartLoc,
8449                                              SourceLocation LParenLoc,
8450                                              SourceLocation EndLoc) {
8451   Expr *ValExpr = NumThreads;
8452   Stmt *HelperValStmt = nullptr;
8453 
8454   // OpenMP [2.5, Restrictions]
8455   //  The num_threads expression must evaluate to a positive integer value.
8456   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8457                                  /*StrictlyPositive=*/true))
8458     return nullptr;
8459 
8460   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8461   OpenMPDirectiveKind CaptureRegion =
8462       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8463   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8464     ValExpr = MakeFullExpr(ValExpr).get();
8465     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8466     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8467     HelperValStmt = buildPreInits(Context, Captures);
8468   }
8469 
8470   return new (Context) OMPNumThreadsClause(
8471       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8472 }
8473 
8474 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8475                                                        OpenMPClauseKind CKind,
8476                                                        bool StrictlyPositive) {
8477   if (!E)
8478     return ExprError();
8479   if (E->isValueDependent() || E->isTypeDependent() ||
8480       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8481     return E;
8482   llvm::APSInt Result;
8483   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8484   if (ICE.isInvalid())
8485     return ExprError();
8486   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8487       (!StrictlyPositive && !Result.isNonNegative())) {
8488     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8489         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8490         << E->getSourceRange();
8491     return ExprError();
8492   }
8493   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8494     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8495         << E->getSourceRange();
8496     return ExprError();
8497   }
8498   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8499     DSAStack->setAssociatedLoops(Result.getExtValue());
8500   else if (CKind == OMPC_ordered)
8501     DSAStack->setAssociatedLoops(Result.getExtValue());
8502   return ICE;
8503 }
8504 
8505 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8506                                           SourceLocation LParenLoc,
8507                                           SourceLocation EndLoc) {
8508   // OpenMP [2.8.1, simd construct, Description]
8509   // The parameter of the safelen clause must be a constant
8510   // positive integer expression.
8511   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8512   if (Safelen.isInvalid())
8513     return nullptr;
8514   return new (Context)
8515       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8516 }
8517 
8518 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8519                                           SourceLocation LParenLoc,
8520                                           SourceLocation EndLoc) {
8521   // OpenMP [2.8.1, simd construct, Description]
8522   // The parameter of the simdlen clause must be a constant
8523   // positive integer expression.
8524   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8525   if (Simdlen.isInvalid())
8526     return nullptr;
8527   return new (Context)
8528       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8529 }
8530 
8531 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8532                                            SourceLocation StartLoc,
8533                                            SourceLocation LParenLoc,
8534                                            SourceLocation EndLoc) {
8535   // OpenMP [2.7.1, loop construct, Description]
8536   // OpenMP [2.8.1, simd construct, Description]
8537   // OpenMP [2.9.6, distribute construct, Description]
8538   // The parameter of the collapse clause must be a constant
8539   // positive integer expression.
8540   ExprResult NumForLoopsResult =
8541       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8542   if (NumForLoopsResult.isInvalid())
8543     return nullptr;
8544   return new (Context)
8545       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
8546 }
8547 
8548 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8549                                           SourceLocation EndLoc,
8550                                           SourceLocation LParenLoc,
8551                                           Expr *NumForLoops) {
8552   // OpenMP [2.7.1, loop construct, Description]
8553   // OpenMP [2.8.1, simd construct, Description]
8554   // OpenMP [2.9.6, distribute construct, Description]
8555   // The parameter of the ordered clause must be a constant
8556   // positive integer expression if any.
8557   if (NumForLoops && LParenLoc.isValid()) {
8558     ExprResult NumForLoopsResult =
8559         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8560     if (NumForLoopsResult.isInvalid())
8561       return nullptr;
8562     NumForLoops = NumForLoopsResult.get();
8563   } else
8564     NumForLoops = nullptr;
8565   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
8566   return new (Context)
8567       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8568 }
8569 
8570 OMPClause *Sema::ActOnOpenMPSimpleClause(
8571     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8572     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8573   OMPClause *Res = nullptr;
8574   switch (Kind) {
8575   case OMPC_default:
8576     Res =
8577         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8578                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
8579     break;
8580   case OMPC_proc_bind:
8581     Res = ActOnOpenMPProcBindClause(
8582         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8583         LParenLoc, EndLoc);
8584     break;
8585   case OMPC_if:
8586   case OMPC_final:
8587   case OMPC_num_threads:
8588   case OMPC_safelen:
8589   case OMPC_simdlen:
8590   case OMPC_collapse:
8591   case OMPC_schedule:
8592   case OMPC_private:
8593   case OMPC_firstprivate:
8594   case OMPC_lastprivate:
8595   case OMPC_shared:
8596   case OMPC_reduction:
8597   case OMPC_task_reduction:
8598   case OMPC_in_reduction:
8599   case OMPC_linear:
8600   case OMPC_aligned:
8601   case OMPC_copyin:
8602   case OMPC_copyprivate:
8603   case OMPC_ordered:
8604   case OMPC_nowait:
8605   case OMPC_untied:
8606   case OMPC_mergeable:
8607   case OMPC_threadprivate:
8608   case OMPC_flush:
8609   case OMPC_read:
8610   case OMPC_write:
8611   case OMPC_update:
8612   case OMPC_capture:
8613   case OMPC_seq_cst:
8614   case OMPC_depend:
8615   case OMPC_device:
8616   case OMPC_threads:
8617   case OMPC_simd:
8618   case OMPC_map:
8619   case OMPC_num_teams:
8620   case OMPC_thread_limit:
8621   case OMPC_priority:
8622   case OMPC_grainsize:
8623   case OMPC_nogroup:
8624   case OMPC_num_tasks:
8625   case OMPC_hint:
8626   case OMPC_dist_schedule:
8627   case OMPC_defaultmap:
8628   case OMPC_unknown:
8629   case OMPC_uniform:
8630   case OMPC_to:
8631   case OMPC_from:
8632   case OMPC_use_device_ptr:
8633   case OMPC_is_device_ptr:
8634     llvm_unreachable("Clause is not allowed.");
8635   }
8636   return Res;
8637 }
8638 
8639 static std::string
8640 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8641                         ArrayRef<unsigned> Exclude = llvm::None) {
8642   std::string Values;
8643   unsigned Bound = Last >= 2 ? Last - 2 : 0;
8644   unsigned Skipped = Exclude.size();
8645   auto S = Exclude.begin(), E = Exclude.end();
8646   for (unsigned i = First; i < Last; ++i) {
8647     if (std::find(S, E, i) != E) {
8648       --Skipped;
8649       continue;
8650     }
8651     Values += "'";
8652     Values += getOpenMPSimpleClauseTypeName(K, i);
8653     Values += "'";
8654     if (i == Bound - Skipped)
8655       Values += " or ";
8656     else if (i != Bound + 1 - Skipped)
8657       Values += ", ";
8658   }
8659   return Values;
8660 }
8661 
8662 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8663                                           SourceLocation KindKwLoc,
8664                                           SourceLocation StartLoc,
8665                                           SourceLocation LParenLoc,
8666                                           SourceLocation EndLoc) {
8667   if (Kind == OMPC_DEFAULT_unknown) {
8668     static_assert(OMPC_DEFAULT_unknown > 0,
8669                   "OMPC_DEFAULT_unknown not greater than 0");
8670     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8671         << getListOfPossibleValues(OMPC_default, /*First=*/0,
8672                                    /*Last=*/OMPC_DEFAULT_unknown)
8673         << getOpenMPClauseName(OMPC_default);
8674     return nullptr;
8675   }
8676   switch (Kind) {
8677   case OMPC_DEFAULT_none:
8678     DSAStack->setDefaultDSANone(KindKwLoc);
8679     break;
8680   case OMPC_DEFAULT_shared:
8681     DSAStack->setDefaultDSAShared(KindKwLoc);
8682     break;
8683   case OMPC_DEFAULT_unknown:
8684     llvm_unreachable("Clause kind is not allowed.");
8685     break;
8686   }
8687   return new (Context)
8688       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8689 }
8690 
8691 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8692                                            SourceLocation KindKwLoc,
8693                                            SourceLocation StartLoc,
8694                                            SourceLocation LParenLoc,
8695                                            SourceLocation EndLoc) {
8696   if (Kind == OMPC_PROC_BIND_unknown) {
8697     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8698         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8699                                    /*Last=*/OMPC_PROC_BIND_unknown)
8700         << getOpenMPClauseName(OMPC_proc_bind);
8701     return nullptr;
8702   }
8703   return new (Context)
8704       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8705 }
8706 
8707 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
8708     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
8709     SourceLocation StartLoc, SourceLocation LParenLoc,
8710     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
8711     SourceLocation EndLoc) {
8712   OMPClause *Res = nullptr;
8713   switch (Kind) {
8714   case OMPC_schedule:
8715     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8716     assert(Argument.size() == NumberOfElements &&
8717            ArgumentLoc.size() == NumberOfElements);
8718     Res = ActOnOpenMPScheduleClause(
8719         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8720         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8721         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8722         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8723         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
8724     break;
8725   case OMPC_if:
8726     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8727     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8728                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8729                               DelimLoc, EndLoc);
8730     break;
8731   case OMPC_dist_schedule:
8732     Res = ActOnOpenMPDistScheduleClause(
8733         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8734         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8735     break;
8736   case OMPC_defaultmap:
8737     enum { Modifier, DefaultmapKind };
8738     Res = ActOnOpenMPDefaultmapClause(
8739         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8740         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
8741         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8742         EndLoc);
8743     break;
8744   case OMPC_final:
8745   case OMPC_num_threads:
8746   case OMPC_safelen:
8747   case OMPC_simdlen:
8748   case OMPC_collapse:
8749   case OMPC_default:
8750   case OMPC_proc_bind:
8751   case OMPC_private:
8752   case OMPC_firstprivate:
8753   case OMPC_lastprivate:
8754   case OMPC_shared:
8755   case OMPC_reduction:
8756   case OMPC_task_reduction:
8757   case OMPC_in_reduction:
8758   case OMPC_linear:
8759   case OMPC_aligned:
8760   case OMPC_copyin:
8761   case OMPC_copyprivate:
8762   case OMPC_ordered:
8763   case OMPC_nowait:
8764   case OMPC_untied:
8765   case OMPC_mergeable:
8766   case OMPC_threadprivate:
8767   case OMPC_flush:
8768   case OMPC_read:
8769   case OMPC_write:
8770   case OMPC_update:
8771   case OMPC_capture:
8772   case OMPC_seq_cst:
8773   case OMPC_depend:
8774   case OMPC_device:
8775   case OMPC_threads:
8776   case OMPC_simd:
8777   case OMPC_map:
8778   case OMPC_num_teams:
8779   case OMPC_thread_limit:
8780   case OMPC_priority:
8781   case OMPC_grainsize:
8782   case OMPC_nogroup:
8783   case OMPC_num_tasks:
8784   case OMPC_hint:
8785   case OMPC_unknown:
8786   case OMPC_uniform:
8787   case OMPC_to:
8788   case OMPC_from:
8789   case OMPC_use_device_ptr:
8790   case OMPC_is_device_ptr:
8791     llvm_unreachable("Clause is not allowed.");
8792   }
8793   return Res;
8794 }
8795 
8796 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8797                                    OpenMPScheduleClauseModifier M2,
8798                                    SourceLocation M1Loc, SourceLocation M2Loc) {
8799   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8800     SmallVector<unsigned, 2> Excluded;
8801     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8802       Excluded.push_back(M2);
8803     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8804       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8805     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8806       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8807     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8808         << getListOfPossibleValues(OMPC_schedule,
8809                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8810                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8811                                    Excluded)
8812         << getOpenMPClauseName(OMPC_schedule);
8813     return true;
8814   }
8815   return false;
8816 }
8817 
8818 OMPClause *Sema::ActOnOpenMPScheduleClause(
8819     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8820     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8821     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8822     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8823   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8824       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8825     return nullptr;
8826   // OpenMP, 2.7.1, Loop Construct, Restrictions
8827   // Either the monotonic modifier or the nonmonotonic modifier can be specified
8828   // but not both.
8829   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8830       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8831        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8832       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8833        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8834     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8835         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8836         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8837     return nullptr;
8838   }
8839   if (Kind == OMPC_SCHEDULE_unknown) {
8840     std::string Values;
8841     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8842       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8843       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8844                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8845                                        Exclude);
8846     } else {
8847       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8848                                        /*Last=*/OMPC_SCHEDULE_unknown);
8849     }
8850     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8851         << Values << getOpenMPClauseName(OMPC_schedule);
8852     return nullptr;
8853   }
8854   // OpenMP, 2.7.1, Loop Construct, Restrictions
8855   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8856   // schedule(guided).
8857   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8858        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8859       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8860     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8861          diag::err_omp_schedule_nonmonotonic_static);
8862     return nullptr;
8863   }
8864   Expr *ValExpr = ChunkSize;
8865   Stmt *HelperValStmt = nullptr;
8866   if (ChunkSize) {
8867     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8868         !ChunkSize->isInstantiationDependent() &&
8869         !ChunkSize->containsUnexpandedParameterPack()) {
8870       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8871       ExprResult Val =
8872           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8873       if (Val.isInvalid())
8874         return nullptr;
8875 
8876       ValExpr = Val.get();
8877 
8878       // OpenMP [2.7.1, Restrictions]
8879       //  chunk_size must be a loop invariant integer expression with a positive
8880       //  value.
8881       llvm::APSInt Result;
8882       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8883         if (Result.isSigned() && !Result.isStrictlyPositive()) {
8884           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
8885               << "schedule" << 1 << ChunkSize->getSourceRange();
8886           return nullptr;
8887         }
8888       } else if (getOpenMPCaptureRegionForClause(
8889                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
8890                      OMPD_unknown &&
8891                  !CurContext->isDependentContext()) {
8892         ValExpr = MakeFullExpr(ValExpr).get();
8893         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8894         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8895         HelperValStmt = buildPreInits(Context, Captures);
8896       }
8897     }
8898   }
8899 
8900   return new (Context)
8901       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
8902                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
8903 }
8904 
8905 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8906                                    SourceLocation StartLoc,
8907                                    SourceLocation EndLoc) {
8908   OMPClause *Res = nullptr;
8909   switch (Kind) {
8910   case OMPC_ordered:
8911     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8912     break;
8913   case OMPC_nowait:
8914     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8915     break;
8916   case OMPC_untied:
8917     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8918     break;
8919   case OMPC_mergeable:
8920     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8921     break;
8922   case OMPC_read:
8923     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8924     break;
8925   case OMPC_write:
8926     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8927     break;
8928   case OMPC_update:
8929     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8930     break;
8931   case OMPC_capture:
8932     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8933     break;
8934   case OMPC_seq_cst:
8935     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8936     break;
8937   case OMPC_threads:
8938     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8939     break;
8940   case OMPC_simd:
8941     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8942     break;
8943   case OMPC_nogroup:
8944     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8945     break;
8946   case OMPC_if:
8947   case OMPC_final:
8948   case OMPC_num_threads:
8949   case OMPC_safelen:
8950   case OMPC_simdlen:
8951   case OMPC_collapse:
8952   case OMPC_schedule:
8953   case OMPC_private:
8954   case OMPC_firstprivate:
8955   case OMPC_lastprivate:
8956   case OMPC_shared:
8957   case OMPC_reduction:
8958   case OMPC_task_reduction:
8959   case OMPC_in_reduction:
8960   case OMPC_linear:
8961   case OMPC_aligned:
8962   case OMPC_copyin:
8963   case OMPC_copyprivate:
8964   case OMPC_default:
8965   case OMPC_proc_bind:
8966   case OMPC_threadprivate:
8967   case OMPC_flush:
8968   case OMPC_depend:
8969   case OMPC_device:
8970   case OMPC_map:
8971   case OMPC_num_teams:
8972   case OMPC_thread_limit:
8973   case OMPC_priority:
8974   case OMPC_grainsize:
8975   case OMPC_num_tasks:
8976   case OMPC_hint:
8977   case OMPC_dist_schedule:
8978   case OMPC_defaultmap:
8979   case OMPC_unknown:
8980   case OMPC_uniform:
8981   case OMPC_to:
8982   case OMPC_from:
8983   case OMPC_use_device_ptr:
8984   case OMPC_is_device_ptr:
8985     llvm_unreachable("Clause is not allowed.");
8986   }
8987   return Res;
8988 }
8989 
8990 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8991                                          SourceLocation EndLoc) {
8992   DSAStack->setNowaitRegion();
8993   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8994 }
8995 
8996 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8997                                          SourceLocation EndLoc) {
8998   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8999 }
9000 
9001 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9002                                             SourceLocation EndLoc) {
9003   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9004 }
9005 
9006 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9007                                        SourceLocation EndLoc) {
9008   return new (Context) OMPReadClause(StartLoc, EndLoc);
9009 }
9010 
9011 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9012                                         SourceLocation EndLoc) {
9013   return new (Context) OMPWriteClause(StartLoc, EndLoc);
9014 }
9015 
9016 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9017                                          SourceLocation EndLoc) {
9018   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9019 }
9020 
9021 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9022                                           SourceLocation EndLoc) {
9023   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9024 }
9025 
9026 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9027                                          SourceLocation EndLoc) {
9028   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9029 }
9030 
9031 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9032                                           SourceLocation EndLoc) {
9033   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9034 }
9035 
9036 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9037                                        SourceLocation EndLoc) {
9038   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9039 }
9040 
9041 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9042                                           SourceLocation EndLoc) {
9043   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9044 }
9045 
9046 OMPClause *Sema::ActOnOpenMPVarListClause(
9047     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9048     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9049     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
9050     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9051     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9052     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9053     SourceLocation DepLinMapLoc) {
9054   OMPClause *Res = nullptr;
9055   switch (Kind) {
9056   case OMPC_private:
9057     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9058     break;
9059   case OMPC_firstprivate:
9060     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9061     break;
9062   case OMPC_lastprivate:
9063     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9064     break;
9065   case OMPC_shared:
9066     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9067     break;
9068   case OMPC_reduction:
9069     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9070                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9071     break;
9072   case OMPC_task_reduction:
9073     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9074                                          EndLoc, ReductionIdScopeSpec,
9075                                          ReductionId);
9076     break;
9077   case OMPC_in_reduction:
9078     Res =
9079         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9080                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9081     break;
9082   case OMPC_linear:
9083     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
9084                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
9085     break;
9086   case OMPC_aligned:
9087     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9088                                    ColonLoc, EndLoc);
9089     break;
9090   case OMPC_copyin:
9091     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9092     break;
9093   case OMPC_copyprivate:
9094     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9095     break;
9096   case OMPC_flush:
9097     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9098     break;
9099   case OMPC_depend:
9100     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9101                                   StartLoc, LParenLoc, EndLoc);
9102     break;
9103   case OMPC_map:
9104     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9105                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
9106                                LParenLoc, EndLoc);
9107     break;
9108   case OMPC_to:
9109     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9110     break;
9111   case OMPC_from:
9112     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9113     break;
9114   case OMPC_use_device_ptr:
9115     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9116     break;
9117   case OMPC_is_device_ptr:
9118     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9119     break;
9120   case OMPC_if:
9121   case OMPC_final:
9122   case OMPC_num_threads:
9123   case OMPC_safelen:
9124   case OMPC_simdlen:
9125   case OMPC_collapse:
9126   case OMPC_default:
9127   case OMPC_proc_bind:
9128   case OMPC_schedule:
9129   case OMPC_ordered:
9130   case OMPC_nowait:
9131   case OMPC_untied:
9132   case OMPC_mergeable:
9133   case OMPC_threadprivate:
9134   case OMPC_read:
9135   case OMPC_write:
9136   case OMPC_update:
9137   case OMPC_capture:
9138   case OMPC_seq_cst:
9139   case OMPC_device:
9140   case OMPC_threads:
9141   case OMPC_simd:
9142   case OMPC_num_teams:
9143   case OMPC_thread_limit:
9144   case OMPC_priority:
9145   case OMPC_grainsize:
9146   case OMPC_nogroup:
9147   case OMPC_num_tasks:
9148   case OMPC_hint:
9149   case OMPC_dist_schedule:
9150   case OMPC_defaultmap:
9151   case OMPC_unknown:
9152   case OMPC_uniform:
9153     llvm_unreachable("Clause is not allowed.");
9154   }
9155   return Res;
9156 }
9157 
9158 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9159                                        ExprObjectKind OK, SourceLocation Loc) {
9160   ExprResult Res = BuildDeclRefExpr(
9161       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9162   if (!Res.isUsable())
9163     return ExprError();
9164   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9165     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9166     if (!Res.isUsable())
9167       return ExprError();
9168   }
9169   if (VK != VK_LValue && Res.get()->isGLValue()) {
9170     Res = DefaultLvalueConversion(Res.get());
9171     if (!Res.isUsable())
9172       return ExprError();
9173   }
9174   return Res;
9175 }
9176 
9177 static std::pair<ValueDecl *, bool>
9178 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9179                SourceRange &ERange, bool AllowArraySection = false) {
9180   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9181       RefExpr->containsUnexpandedParameterPack())
9182     return std::make_pair(nullptr, true);
9183 
9184   // OpenMP [3.1, C/C++]
9185   //  A list item is a variable name.
9186   // OpenMP  [2.9.3.3, Restrictions, p.1]
9187   //  A variable that is part of another variable (as an array or
9188   //  structure element) cannot appear in a private clause.
9189   RefExpr = RefExpr->IgnoreParens();
9190   enum {
9191     NoArrayExpr = -1,
9192     ArraySubscript = 0,
9193     OMPArraySection = 1
9194   } IsArrayExpr = NoArrayExpr;
9195   if (AllowArraySection) {
9196     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9197       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9198       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9199         Base = TempASE->getBase()->IgnoreParenImpCasts();
9200       RefExpr = Base;
9201       IsArrayExpr = ArraySubscript;
9202     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9203       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9204       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9205         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9206       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9207         Base = TempASE->getBase()->IgnoreParenImpCasts();
9208       RefExpr = Base;
9209       IsArrayExpr = OMPArraySection;
9210     }
9211   }
9212   ELoc = RefExpr->getExprLoc();
9213   ERange = RefExpr->getSourceRange();
9214   RefExpr = RefExpr->IgnoreParenImpCasts();
9215   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9216   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9217   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9218       (S.getCurrentThisType().isNull() || !ME ||
9219        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9220        !isa<FieldDecl>(ME->getMemberDecl()))) {
9221     if (IsArrayExpr != NoArrayExpr)
9222       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9223                                                          << ERange;
9224     else {
9225       S.Diag(ELoc,
9226              AllowArraySection
9227                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9228                  : diag::err_omp_expected_var_name_member_expr)
9229           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9230     }
9231     return std::make_pair(nullptr, false);
9232   }
9233   return std::make_pair(
9234       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9235 }
9236 
9237 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9238                                           SourceLocation StartLoc,
9239                                           SourceLocation LParenLoc,
9240                                           SourceLocation EndLoc) {
9241   SmallVector<Expr *, 8> Vars;
9242   SmallVector<Expr *, 8> PrivateCopies;
9243   for (auto &RefExpr : VarList) {
9244     assert(RefExpr && "NULL expr in OpenMP private clause.");
9245     SourceLocation ELoc;
9246     SourceRange ERange;
9247     Expr *SimpleRefExpr = RefExpr;
9248     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9249     if (Res.second) {
9250       // It will be analyzed later.
9251       Vars.push_back(RefExpr);
9252       PrivateCopies.push_back(nullptr);
9253     }
9254     ValueDecl *D = Res.first;
9255     if (!D)
9256       continue;
9257 
9258     QualType Type = D->getType();
9259     auto *VD = dyn_cast<VarDecl>(D);
9260 
9261     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9262     //  A variable that appears in a private clause must not have an incomplete
9263     //  type or a reference type.
9264     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9265       continue;
9266     Type = Type.getNonReferenceType();
9267 
9268     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9269     // in a Construct]
9270     //  Variables with the predetermined data-sharing attributes may not be
9271     //  listed in data-sharing attributes clauses, except for the cases
9272     //  listed below. For these exceptions only, listing a predetermined
9273     //  variable in a data-sharing attribute clause is allowed and overrides
9274     //  the variable's predetermined data-sharing attributes.
9275     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9276     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9277       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9278                                           << getOpenMPClauseName(OMPC_private);
9279       ReportOriginalDSA(*this, DSAStack, D, DVar);
9280       continue;
9281     }
9282 
9283     auto CurrDir = DSAStack->getCurrentDirective();
9284     // Variably modified types are not supported for tasks.
9285     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9286         isOpenMPTaskingDirective(CurrDir)) {
9287       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9288           << getOpenMPClauseName(OMPC_private) << Type
9289           << getOpenMPDirectiveName(CurrDir);
9290       bool IsDecl =
9291           !VD ||
9292           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9293       Diag(D->getLocation(),
9294            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9295           << D;
9296       continue;
9297     }
9298 
9299     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9300     // A list item cannot appear in both a map clause and a data-sharing
9301     // attribute clause on the same construct
9302     if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
9303         CurrDir == OMPD_target_teams ||
9304         CurrDir == OMPD_target_teams_distribute ||
9305         CurrDir == OMPD_target_teams_distribute_parallel_for ||
9306         CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
9307         CurrDir == OMPD_target_teams_distribute_simd ||
9308         CurrDir == OMPD_target_parallel_for_simd ||
9309         CurrDir == OMPD_target_parallel_for) {
9310       OpenMPClauseKind ConflictKind;
9311       if (DSAStack->checkMappableExprComponentListsForDecl(
9312               VD, /*CurrentRegionOnly=*/true,
9313               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9314                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9315                 ConflictKind = WhereFoundClauseKind;
9316                 return true;
9317               })) {
9318         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9319             << getOpenMPClauseName(OMPC_private)
9320             << getOpenMPClauseName(ConflictKind)
9321             << getOpenMPDirectiveName(CurrDir);
9322         ReportOriginalDSA(*this, DSAStack, D, DVar);
9323         continue;
9324       }
9325     }
9326 
9327     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9328     //  A variable of class type (or array thereof) that appears in a private
9329     //  clause requires an accessible, unambiguous default constructor for the
9330     //  class type.
9331     // Generate helper private variable and initialize it with the default
9332     // value. The address of the original variable is replaced by the address of
9333     // the new private variable in CodeGen. This new variable is not added to
9334     // IdResolver, so the code in the OpenMP region uses original variable for
9335     // proper diagnostics.
9336     Type = Type.getUnqualifiedType();
9337     auto VDPrivate =
9338         buildVarDecl(*this, ELoc, Type, D->getName(),
9339                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9340                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9341     ActOnUninitializedDecl(VDPrivate);
9342     if (VDPrivate->isInvalidDecl())
9343       continue;
9344     auto VDPrivateRefExpr = buildDeclRefExpr(
9345         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9346 
9347     DeclRefExpr *Ref = nullptr;
9348     if (!VD && !CurContext->isDependentContext())
9349       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9350     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9351     Vars.push_back((VD || CurContext->isDependentContext())
9352                        ? RefExpr->IgnoreParens()
9353                        : Ref);
9354     PrivateCopies.push_back(VDPrivateRefExpr);
9355   }
9356 
9357   if (Vars.empty())
9358     return nullptr;
9359 
9360   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9361                                   PrivateCopies);
9362 }
9363 
9364 namespace {
9365 class DiagsUninitializedSeveretyRAII {
9366 private:
9367   DiagnosticsEngine &Diags;
9368   SourceLocation SavedLoc;
9369   bool IsIgnored;
9370 
9371 public:
9372   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9373                                  bool IsIgnored)
9374       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9375     if (!IsIgnored) {
9376       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9377                         /*Map*/ diag::Severity::Ignored, Loc);
9378     }
9379   }
9380   ~DiagsUninitializedSeveretyRAII() {
9381     if (!IsIgnored)
9382       Diags.popMappings(SavedLoc);
9383   }
9384 };
9385 }
9386 
9387 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9388                                                SourceLocation StartLoc,
9389                                                SourceLocation LParenLoc,
9390                                                SourceLocation EndLoc) {
9391   SmallVector<Expr *, 8> Vars;
9392   SmallVector<Expr *, 8> PrivateCopies;
9393   SmallVector<Expr *, 8> Inits;
9394   SmallVector<Decl *, 4> ExprCaptures;
9395   bool IsImplicitClause =
9396       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9397   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9398 
9399   for (auto &RefExpr : VarList) {
9400     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9401     SourceLocation ELoc;
9402     SourceRange ERange;
9403     Expr *SimpleRefExpr = RefExpr;
9404     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9405     if (Res.second) {
9406       // It will be analyzed later.
9407       Vars.push_back(RefExpr);
9408       PrivateCopies.push_back(nullptr);
9409       Inits.push_back(nullptr);
9410     }
9411     ValueDecl *D = Res.first;
9412     if (!D)
9413       continue;
9414 
9415     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9416     QualType Type = D->getType();
9417     auto *VD = dyn_cast<VarDecl>(D);
9418 
9419     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9420     //  A variable that appears in a private clause must not have an incomplete
9421     //  type or a reference type.
9422     if (RequireCompleteType(ELoc, Type,
9423                             diag::err_omp_firstprivate_incomplete_type))
9424       continue;
9425     Type = Type.getNonReferenceType();
9426 
9427     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9428     //  A variable of class type (or array thereof) that appears in a private
9429     //  clause requires an accessible, unambiguous copy constructor for the
9430     //  class type.
9431     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9432 
9433     // If an implicit firstprivate variable found it was checked already.
9434     DSAStackTy::DSAVarData TopDVar;
9435     if (!IsImplicitClause) {
9436       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9437       TopDVar = DVar;
9438       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9439       bool IsConstant = ElemType.isConstant(Context);
9440       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9441       //  A list item that specifies a given variable may not appear in more
9442       // than one clause on the same directive, except that a variable may be
9443       //  specified in both firstprivate and lastprivate clauses.
9444       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9445       // A list item may appear in a firstprivate or lastprivate clause but not
9446       // both.
9447       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9448           (isOpenMPDistributeDirective(CurrDir) ||
9449            DVar.CKind != OMPC_lastprivate) &&
9450           DVar.RefExpr) {
9451         Diag(ELoc, diag::err_omp_wrong_dsa)
9452             << getOpenMPClauseName(DVar.CKind)
9453             << getOpenMPClauseName(OMPC_firstprivate);
9454         ReportOriginalDSA(*this, DSAStack, D, DVar);
9455         continue;
9456       }
9457 
9458       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9459       // in a Construct]
9460       //  Variables with the predetermined data-sharing attributes may not be
9461       //  listed in data-sharing attributes clauses, except for the cases
9462       //  listed below. For these exceptions only, listing a predetermined
9463       //  variable in a data-sharing attribute clause is allowed and overrides
9464       //  the variable's predetermined data-sharing attributes.
9465       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9466       // in a Construct, C/C++, p.2]
9467       //  Variables with const-qualified type having no mutable member may be
9468       //  listed in a firstprivate clause, even if they are static data members.
9469       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9470           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9471         Diag(ELoc, diag::err_omp_wrong_dsa)
9472             << getOpenMPClauseName(DVar.CKind)
9473             << getOpenMPClauseName(OMPC_firstprivate);
9474         ReportOriginalDSA(*this, DSAStack, D, DVar);
9475         continue;
9476       }
9477 
9478       // OpenMP [2.9.3.4, Restrictions, p.2]
9479       //  A list item that is private within a parallel region must not appear
9480       //  in a firstprivate clause on a worksharing construct if any of the
9481       //  worksharing regions arising from the worksharing construct ever bind
9482       //  to any of the parallel regions arising from the parallel construct.
9483       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9484       // A list item that is private within a teams region must not appear in a
9485       // firstprivate clause on a distribute construct if any of the distribute
9486       // regions arising from the distribute construct ever bind to any of the
9487       // teams regions arising from the teams construct.
9488       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9489       // A list item that appears in a reduction clause of a teams construct
9490       // must not appear in a firstprivate clause on a distribute construct if
9491       // any of the distribute regions arising from the distribute construct
9492       // ever bind to any of the teams regions arising from the teams construct.
9493       if ((isOpenMPWorksharingDirective(CurrDir) ||
9494            isOpenMPDistributeDirective(CurrDir)) &&
9495           !isOpenMPParallelDirective(CurrDir) &&
9496           !isOpenMPTeamsDirective(CurrDir)) {
9497         DVar = DSAStack->getImplicitDSA(D, true);
9498         if (DVar.CKind != OMPC_shared &&
9499             (isOpenMPParallelDirective(DVar.DKind) ||
9500              isOpenMPTeamsDirective(DVar.DKind) ||
9501              DVar.DKind == OMPD_unknown)) {
9502           Diag(ELoc, diag::err_omp_required_access)
9503               << getOpenMPClauseName(OMPC_firstprivate)
9504               << getOpenMPClauseName(OMPC_shared);
9505           ReportOriginalDSA(*this, DSAStack, D, DVar);
9506           continue;
9507         }
9508       }
9509       // OpenMP [2.9.3.4, Restrictions, p.3]
9510       //  A list item that appears in a reduction clause of a parallel construct
9511       //  must not appear in a firstprivate clause on a worksharing or task
9512       //  construct if any of the worksharing or task regions arising from the
9513       //  worksharing or task construct ever bind to any of the parallel regions
9514       //  arising from the parallel construct.
9515       // OpenMP [2.9.3.4, Restrictions, p.4]
9516       //  A list item that appears in a reduction clause in worksharing
9517       //  construct must not appear in a firstprivate clause in a task construct
9518       //  encountered during execution of any of the worksharing regions arising
9519       //  from the worksharing construct.
9520       if (isOpenMPTaskingDirective(CurrDir)) {
9521         DVar = DSAStack->hasInnermostDSA(
9522             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9523             [](OpenMPDirectiveKind K) -> bool {
9524               return isOpenMPParallelDirective(K) ||
9525                      isOpenMPWorksharingDirective(K) ||
9526                      isOpenMPTeamsDirective(K);
9527             },
9528             /*FromParent=*/true);
9529         if (DVar.CKind == OMPC_reduction &&
9530             (isOpenMPParallelDirective(DVar.DKind) ||
9531              isOpenMPWorksharingDirective(DVar.DKind) ||
9532              isOpenMPTeamsDirective(DVar.DKind))) {
9533           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9534               << getOpenMPDirectiveName(DVar.DKind);
9535           ReportOriginalDSA(*this, DSAStack, D, DVar);
9536           continue;
9537         }
9538       }
9539 
9540       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9541       // A list item cannot appear in both a map clause and a data-sharing
9542       // attribute clause on the same construct
9543       if (isOpenMPTargetExecutionDirective(CurrDir)) {
9544         OpenMPClauseKind ConflictKind;
9545         if (DSAStack->checkMappableExprComponentListsForDecl(
9546                 VD, /*CurrentRegionOnly=*/true,
9547                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9548                     OpenMPClauseKind WhereFoundClauseKind) -> bool {
9549                   ConflictKind = WhereFoundClauseKind;
9550                   return true;
9551                 })) {
9552           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9553               << getOpenMPClauseName(OMPC_firstprivate)
9554               << getOpenMPClauseName(ConflictKind)
9555               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9556           ReportOriginalDSA(*this, DSAStack, D, DVar);
9557           continue;
9558         }
9559       }
9560     }
9561 
9562     // Variably modified types are not supported for tasks.
9563     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9564         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
9565       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9566           << getOpenMPClauseName(OMPC_firstprivate) << Type
9567           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9568       bool IsDecl =
9569           !VD ||
9570           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9571       Diag(D->getLocation(),
9572            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9573           << D;
9574       continue;
9575     }
9576 
9577     Type = Type.getUnqualifiedType();
9578     auto VDPrivate =
9579         buildVarDecl(*this, ELoc, Type, D->getName(),
9580                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9581                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9582     // Generate helper private variable and initialize it with the value of the
9583     // original variable. The address of the original variable is replaced by
9584     // the address of the new private variable in the CodeGen. This new variable
9585     // is not added to IdResolver, so the code in the OpenMP region uses
9586     // original variable for proper diagnostics and variable capturing.
9587     Expr *VDInitRefExpr = nullptr;
9588     // For arrays generate initializer for single element and replace it by the
9589     // original array element in CodeGen.
9590     if (Type->isArrayType()) {
9591       auto VDInit =
9592           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
9593       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
9594       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
9595       ElemType = ElemType.getUnqualifiedType();
9596       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
9597                                       ".firstprivate.temp");
9598       InitializedEntity Entity =
9599           InitializedEntity::InitializeVariable(VDInitTemp);
9600       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9601 
9602       InitializationSequence InitSeq(*this, Entity, Kind, Init);
9603       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9604       if (Result.isInvalid())
9605         VDPrivate->setInvalidDecl();
9606       else
9607         VDPrivate->setInit(Result.getAs<Expr>());
9608       // Remove temp variable declaration.
9609       Context.Deallocate(VDInitTemp);
9610     } else {
9611       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9612                                   ".firstprivate.temp");
9613       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9614                                        RefExpr->getExprLoc());
9615       AddInitializerToDecl(VDPrivate,
9616                            DefaultLvalueConversion(VDInitRefExpr).get(),
9617                            /*DirectInit=*/false);
9618     }
9619     if (VDPrivate->isInvalidDecl()) {
9620       if (IsImplicitClause) {
9621         Diag(RefExpr->getExprLoc(),
9622              diag::note_omp_task_predetermined_firstprivate_here);
9623       }
9624       continue;
9625     }
9626     CurContext->addDecl(VDPrivate);
9627     auto VDPrivateRefExpr = buildDeclRefExpr(
9628         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9629         RefExpr->getExprLoc());
9630     DeclRefExpr *Ref = nullptr;
9631     if (!VD && !CurContext->isDependentContext()) {
9632       if (TopDVar.CKind == OMPC_lastprivate)
9633         Ref = TopDVar.PrivateCopy;
9634       else {
9635         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9636         if (!IsOpenMPCapturedDecl(D))
9637           ExprCaptures.push_back(Ref->getDecl());
9638       }
9639     }
9640     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
9641     Vars.push_back((VD || CurContext->isDependentContext())
9642                        ? RefExpr->IgnoreParens()
9643                        : Ref);
9644     PrivateCopies.push_back(VDPrivateRefExpr);
9645     Inits.push_back(VDInitRefExpr);
9646   }
9647 
9648   if (Vars.empty())
9649     return nullptr;
9650 
9651   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9652                                        Vars, PrivateCopies, Inits,
9653                                        buildPreInits(Context, ExprCaptures));
9654 }
9655 
9656 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9657                                               SourceLocation StartLoc,
9658                                               SourceLocation LParenLoc,
9659                                               SourceLocation EndLoc) {
9660   SmallVector<Expr *, 8> Vars;
9661   SmallVector<Expr *, 8> SrcExprs;
9662   SmallVector<Expr *, 8> DstExprs;
9663   SmallVector<Expr *, 8> AssignmentOps;
9664   SmallVector<Decl *, 4> ExprCaptures;
9665   SmallVector<Expr *, 4> ExprPostUpdates;
9666   for (auto &RefExpr : VarList) {
9667     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9668     SourceLocation ELoc;
9669     SourceRange ERange;
9670     Expr *SimpleRefExpr = RefExpr;
9671     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9672     if (Res.second) {
9673       // It will be analyzed later.
9674       Vars.push_back(RefExpr);
9675       SrcExprs.push_back(nullptr);
9676       DstExprs.push_back(nullptr);
9677       AssignmentOps.push_back(nullptr);
9678     }
9679     ValueDecl *D = Res.first;
9680     if (!D)
9681       continue;
9682 
9683     QualType Type = D->getType();
9684     auto *VD = dyn_cast<VarDecl>(D);
9685 
9686     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9687     //  A variable that appears in a lastprivate clause must not have an
9688     //  incomplete type or a reference type.
9689     if (RequireCompleteType(ELoc, Type,
9690                             diag::err_omp_lastprivate_incomplete_type))
9691       continue;
9692     Type = Type.getNonReferenceType();
9693 
9694     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9695     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9696     // in a Construct]
9697     //  Variables with the predetermined data-sharing attributes may not be
9698     //  listed in data-sharing attributes clauses, except for the cases
9699     //  listed below.
9700     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9701     // A list item may appear in a firstprivate or lastprivate clause but not
9702     // both.
9703     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9704     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
9705         (isOpenMPDistributeDirective(CurrDir) ||
9706          DVar.CKind != OMPC_firstprivate) &&
9707         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9708       Diag(ELoc, diag::err_omp_wrong_dsa)
9709           << getOpenMPClauseName(DVar.CKind)
9710           << getOpenMPClauseName(OMPC_lastprivate);
9711       ReportOriginalDSA(*this, DSAStack, D, DVar);
9712       continue;
9713     }
9714 
9715     // OpenMP [2.14.3.5, Restrictions, p.2]
9716     // A list item that is private within a parallel region, or that appears in
9717     // the reduction clause of a parallel construct, must not appear in a
9718     // lastprivate clause on a worksharing construct if any of the corresponding
9719     // worksharing regions ever binds to any of the corresponding parallel
9720     // regions.
9721     DSAStackTy::DSAVarData TopDVar = DVar;
9722     if (isOpenMPWorksharingDirective(CurrDir) &&
9723         !isOpenMPParallelDirective(CurrDir) &&
9724         !isOpenMPTeamsDirective(CurrDir)) {
9725       DVar = DSAStack->getImplicitDSA(D, true);
9726       if (DVar.CKind != OMPC_shared) {
9727         Diag(ELoc, diag::err_omp_required_access)
9728             << getOpenMPClauseName(OMPC_lastprivate)
9729             << getOpenMPClauseName(OMPC_shared);
9730         ReportOriginalDSA(*this, DSAStack, D, DVar);
9731         continue;
9732       }
9733     }
9734 
9735     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
9736     //  A variable of class type (or array thereof) that appears in a
9737     //  lastprivate clause requires an accessible, unambiguous default
9738     //  constructor for the class type, unless the list item is also specified
9739     //  in a firstprivate clause.
9740     //  A variable of class type (or array thereof) that appears in a
9741     //  lastprivate clause requires an accessible, unambiguous copy assignment
9742     //  operator for the class type.
9743     Type = Context.getBaseElementType(Type).getNonReferenceType();
9744     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
9745                                Type.getUnqualifiedType(), ".lastprivate.src",
9746                                D->hasAttrs() ? &D->getAttrs() : nullptr);
9747     auto *PseudoSrcExpr =
9748         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
9749     auto *DstVD =
9750         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
9751                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9752     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9753     // For arrays generate assignment operation for single element and replace
9754     // it by the original array element in CodeGen.
9755     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
9756                                    PseudoDstExpr, PseudoSrcExpr);
9757     if (AssignmentOp.isInvalid())
9758       continue;
9759     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9760                                        /*DiscardedValue=*/true);
9761     if (AssignmentOp.isInvalid())
9762       continue;
9763 
9764     DeclRefExpr *Ref = nullptr;
9765     if (!VD && !CurContext->isDependentContext()) {
9766       if (TopDVar.CKind == OMPC_firstprivate)
9767         Ref = TopDVar.PrivateCopy;
9768       else {
9769         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9770         if (!IsOpenMPCapturedDecl(D))
9771           ExprCaptures.push_back(Ref->getDecl());
9772       }
9773       if (TopDVar.CKind == OMPC_firstprivate ||
9774           (!IsOpenMPCapturedDecl(D) &&
9775            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
9776         ExprResult RefRes = DefaultLvalueConversion(Ref);
9777         if (!RefRes.isUsable())
9778           continue;
9779         ExprResult PostUpdateRes =
9780             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9781                        RefRes.get());
9782         if (!PostUpdateRes.isUsable())
9783           continue;
9784         ExprPostUpdates.push_back(
9785             IgnoredValueConversions(PostUpdateRes.get()).get());
9786       }
9787     }
9788     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
9789     Vars.push_back((VD || CurContext->isDependentContext())
9790                        ? RefExpr->IgnoreParens()
9791                        : Ref);
9792     SrcExprs.push_back(PseudoSrcExpr);
9793     DstExprs.push_back(PseudoDstExpr);
9794     AssignmentOps.push_back(AssignmentOp.get());
9795   }
9796 
9797   if (Vars.empty())
9798     return nullptr;
9799 
9800   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9801                                       Vars, SrcExprs, DstExprs, AssignmentOps,
9802                                       buildPreInits(Context, ExprCaptures),
9803                                       buildPostUpdate(*this, ExprPostUpdates));
9804 }
9805 
9806 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9807                                          SourceLocation StartLoc,
9808                                          SourceLocation LParenLoc,
9809                                          SourceLocation EndLoc) {
9810   SmallVector<Expr *, 8> Vars;
9811   for (auto &RefExpr : VarList) {
9812     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9813     SourceLocation ELoc;
9814     SourceRange ERange;
9815     Expr *SimpleRefExpr = RefExpr;
9816     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9817     if (Res.second) {
9818       // It will be analyzed later.
9819       Vars.push_back(RefExpr);
9820     }
9821     ValueDecl *D = Res.first;
9822     if (!D)
9823       continue;
9824 
9825     auto *VD = dyn_cast<VarDecl>(D);
9826     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9827     // in a Construct]
9828     //  Variables with the predetermined data-sharing attributes may not be
9829     //  listed in data-sharing attributes clauses, except for the cases
9830     //  listed below. For these exceptions only, listing a predetermined
9831     //  variable in a data-sharing attribute clause is allowed and overrides
9832     //  the variable's predetermined data-sharing attributes.
9833     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9834     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9835         DVar.RefExpr) {
9836       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9837                                           << getOpenMPClauseName(OMPC_shared);
9838       ReportOriginalDSA(*this, DSAStack, D, DVar);
9839       continue;
9840     }
9841 
9842     DeclRefExpr *Ref = nullptr;
9843     if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
9844       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9845     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
9846     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9847                        ? RefExpr->IgnoreParens()
9848                        : Ref);
9849   }
9850 
9851   if (Vars.empty())
9852     return nullptr;
9853 
9854   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9855 }
9856 
9857 namespace {
9858 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9859   DSAStackTy *Stack;
9860 
9861 public:
9862   bool VisitDeclRefExpr(DeclRefExpr *E) {
9863     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
9864       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
9865       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9866         return false;
9867       if (DVar.CKind != OMPC_unknown)
9868         return true;
9869       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9870           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
9871           /*FromParent=*/true);
9872       if (DVarPrivate.CKind != OMPC_unknown)
9873         return true;
9874       return false;
9875     }
9876     return false;
9877   }
9878   bool VisitStmt(Stmt *S) {
9879     for (auto Child : S->children()) {
9880       if (Child && Visit(Child))
9881         return true;
9882     }
9883     return false;
9884   }
9885   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
9886 };
9887 } // namespace
9888 
9889 namespace {
9890 // Transform MemberExpression for specified FieldDecl of current class to
9891 // DeclRefExpr to specified OMPCapturedExprDecl.
9892 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9893   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9894   ValueDecl *Field;
9895   DeclRefExpr *CapturedExpr;
9896 
9897 public:
9898   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9899       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9900 
9901   ExprResult TransformMemberExpr(MemberExpr *E) {
9902     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9903         E->getMemberDecl() == Field) {
9904       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
9905       return CapturedExpr;
9906     }
9907     return BaseTransform::TransformMemberExpr(E);
9908   }
9909   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9910 };
9911 } // namespace
9912 
9913 template <typename T>
9914 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9915                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
9916   for (auto &Set : Lookups) {
9917     for (auto *D : Set) {
9918       if (auto Res = Gen(cast<ValueDecl>(D)))
9919         return Res;
9920     }
9921   }
9922   return T();
9923 }
9924 
9925 static ExprResult
9926 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9927                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9928                          const DeclarationNameInfo &ReductionId, QualType Ty,
9929                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9930   if (ReductionIdScopeSpec.isInvalid())
9931     return ExprError();
9932   SmallVector<UnresolvedSet<8>, 4> Lookups;
9933   if (S) {
9934     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9935     Lookup.suppressDiagnostics();
9936     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9937       auto *D = Lookup.getRepresentativeDecl();
9938       do {
9939         S = S->getParent();
9940       } while (S && !S->isDeclScope(D));
9941       if (S)
9942         S = S->getParent();
9943       Lookups.push_back(UnresolvedSet<8>());
9944       Lookups.back().append(Lookup.begin(), Lookup.end());
9945       Lookup.clear();
9946     }
9947   } else if (auto *ULE =
9948                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9949     Lookups.push_back(UnresolvedSet<8>());
9950     Decl *PrevD = nullptr;
9951     for (auto *D : ULE->decls()) {
9952       if (D == PrevD)
9953         Lookups.push_back(UnresolvedSet<8>());
9954       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9955         Lookups.back().addDecl(DRD);
9956       PrevD = D;
9957     }
9958   }
9959   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9960       Ty->isInstantiationDependentType() ||
9961       Ty->containsUnexpandedParameterPack() ||
9962       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9963         return !D->isInvalidDecl() &&
9964                (D->getType()->isDependentType() ||
9965                 D->getType()->isInstantiationDependentType() ||
9966                 D->getType()->containsUnexpandedParameterPack());
9967       })) {
9968     UnresolvedSet<8> ResSet;
9969     for (auto &Set : Lookups) {
9970       ResSet.append(Set.begin(), Set.end());
9971       // The last item marks the end of all declarations at the specified scope.
9972       ResSet.addDecl(Set[Set.size() - 1]);
9973     }
9974     return UnresolvedLookupExpr::Create(
9975         SemaRef.Context, /*NamingClass=*/nullptr,
9976         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9977         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9978   }
9979   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9980           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9981             if (!D->isInvalidDecl() &&
9982                 SemaRef.Context.hasSameType(D->getType(), Ty))
9983               return D;
9984             return nullptr;
9985           }))
9986     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9987   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9988           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9989             if (!D->isInvalidDecl() &&
9990                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9991                 !Ty.isMoreQualifiedThan(D->getType()))
9992               return D;
9993             return nullptr;
9994           })) {
9995     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9996                        /*DetectVirtual=*/false);
9997     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9998       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9999               VD->getType().getUnqualifiedType()))) {
10000         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10001                                          /*DiagID=*/0) !=
10002             Sema::AR_inaccessible) {
10003           SemaRef.BuildBasePathArray(Paths, BasePath);
10004           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10005         }
10006       }
10007     }
10008   }
10009   if (ReductionIdScopeSpec.isSet()) {
10010     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10011     return ExprError();
10012   }
10013   return ExprEmpty();
10014 }
10015 
10016 namespace {
10017 /// Data for the reduction-based clauses.
10018 struct ReductionData {
10019   /// List of original reduction items.
10020   SmallVector<Expr *, 8> Vars;
10021   /// List of private copies of the reduction items.
10022   SmallVector<Expr *, 8> Privates;
10023   /// LHS expressions for the reduction_op expressions.
10024   SmallVector<Expr *, 8> LHSs;
10025   /// RHS expressions for the reduction_op expressions.
10026   SmallVector<Expr *, 8> RHSs;
10027   /// Reduction operation expression.
10028   SmallVector<Expr *, 8> ReductionOps;
10029   /// Taskgroup descriptors for the corresponding reduction items in
10030   /// in_reduction clauses.
10031   SmallVector<Expr *, 8> TaskgroupDescriptors;
10032   /// List of captures for clause.
10033   SmallVector<Decl *, 4> ExprCaptures;
10034   /// List of postupdate expressions.
10035   SmallVector<Expr *, 4> ExprPostUpdates;
10036   ReductionData() = delete;
10037   /// Reserves required memory for the reduction data.
10038   ReductionData(unsigned Size) {
10039     Vars.reserve(Size);
10040     Privates.reserve(Size);
10041     LHSs.reserve(Size);
10042     RHSs.reserve(Size);
10043     ReductionOps.reserve(Size);
10044     TaskgroupDescriptors.reserve(Size);
10045     ExprCaptures.reserve(Size);
10046     ExprPostUpdates.reserve(Size);
10047   }
10048   /// Stores reduction item and reduction operation only (required for dependent
10049   /// reduction item).
10050   void push(Expr *Item, Expr *ReductionOp) {
10051     Vars.emplace_back(Item);
10052     Privates.emplace_back(nullptr);
10053     LHSs.emplace_back(nullptr);
10054     RHSs.emplace_back(nullptr);
10055     ReductionOps.emplace_back(ReductionOp);
10056     TaskgroupDescriptors.emplace_back(nullptr);
10057   }
10058   /// Stores reduction data.
10059   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10060             Expr *TaskgroupDescriptor) {
10061     Vars.emplace_back(Item);
10062     Privates.emplace_back(Private);
10063     LHSs.emplace_back(LHS);
10064     RHSs.emplace_back(RHS);
10065     ReductionOps.emplace_back(ReductionOp);
10066     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
10067   }
10068 };
10069 } // namespace
10070 
10071 static bool CheckOMPArraySectionConstantForReduction(
10072     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10073     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10074   const Expr *Length = OASE->getLength();
10075   if (Length == nullptr) {
10076     // For array sections of the form [1:] or [:], we would need to analyze
10077     // the lower bound...
10078     if (OASE->getColonLoc().isValid())
10079       return false;
10080 
10081     // This is an array subscript which has implicit length 1!
10082     SingleElement = true;
10083     ArraySizes.push_back(llvm::APSInt::get(1));
10084   } else {
10085     llvm::APSInt ConstantLengthValue;
10086     if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10087       return false;
10088 
10089     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10090     ArraySizes.push_back(ConstantLengthValue);
10091   }
10092 
10093   // Get the base of this array section and walk up from there.
10094   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10095 
10096   // We require length = 1 for all array sections except the right-most to
10097   // guarantee that the memory region is contiguous and has no holes in it.
10098   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10099     Length = TempOASE->getLength();
10100     if (Length == nullptr) {
10101       // For array sections of the form [1:] or [:], we would need to analyze
10102       // the lower bound...
10103       if (OASE->getColonLoc().isValid())
10104         return false;
10105 
10106       // This is an array subscript which has implicit length 1!
10107       ArraySizes.push_back(llvm::APSInt::get(1));
10108     } else {
10109       llvm::APSInt ConstantLengthValue;
10110       if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10111           ConstantLengthValue.getSExtValue() != 1)
10112         return false;
10113 
10114       ArraySizes.push_back(ConstantLengthValue);
10115     }
10116     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10117   }
10118 
10119   // If we have a single element, we don't need to add the implicit lengths.
10120   if (!SingleElement) {
10121     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10122       // Has implicit length 1!
10123       ArraySizes.push_back(llvm::APSInt::get(1));
10124       Base = TempASE->getBase()->IgnoreParenImpCasts();
10125     }
10126   }
10127 
10128   // This array section can be privatized as a single value or as a constant
10129   // sized array.
10130   return true;
10131 }
10132 
10133 static bool ActOnOMPReductionKindClause(
10134     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10135     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10136     SourceLocation ColonLoc, SourceLocation EndLoc,
10137     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10138     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10139   auto DN = ReductionId.getName();
10140   auto OOK = DN.getCXXOverloadedOperator();
10141   BinaryOperatorKind BOK = BO_Comma;
10142 
10143   ASTContext &Context = S.Context;
10144   // OpenMP [2.14.3.6, reduction clause]
10145   // C
10146   // reduction-identifier is either an identifier or one of the following
10147   // operators: +, -, *,  &, |, ^, && and ||
10148   // C++
10149   // reduction-identifier is either an id-expression or one of the following
10150   // operators: +, -, *, &, |, ^, && and ||
10151   switch (OOK) {
10152   case OO_Plus:
10153   case OO_Minus:
10154     BOK = BO_Add;
10155     break;
10156   case OO_Star:
10157     BOK = BO_Mul;
10158     break;
10159   case OO_Amp:
10160     BOK = BO_And;
10161     break;
10162   case OO_Pipe:
10163     BOK = BO_Or;
10164     break;
10165   case OO_Caret:
10166     BOK = BO_Xor;
10167     break;
10168   case OO_AmpAmp:
10169     BOK = BO_LAnd;
10170     break;
10171   case OO_PipePipe:
10172     BOK = BO_LOr;
10173     break;
10174   case OO_New:
10175   case OO_Delete:
10176   case OO_Array_New:
10177   case OO_Array_Delete:
10178   case OO_Slash:
10179   case OO_Percent:
10180   case OO_Tilde:
10181   case OO_Exclaim:
10182   case OO_Equal:
10183   case OO_Less:
10184   case OO_Greater:
10185   case OO_LessEqual:
10186   case OO_GreaterEqual:
10187   case OO_PlusEqual:
10188   case OO_MinusEqual:
10189   case OO_StarEqual:
10190   case OO_SlashEqual:
10191   case OO_PercentEqual:
10192   case OO_CaretEqual:
10193   case OO_AmpEqual:
10194   case OO_PipeEqual:
10195   case OO_LessLess:
10196   case OO_GreaterGreater:
10197   case OO_LessLessEqual:
10198   case OO_GreaterGreaterEqual:
10199   case OO_EqualEqual:
10200   case OO_ExclaimEqual:
10201   case OO_Spaceship:
10202   case OO_PlusPlus:
10203   case OO_MinusMinus:
10204   case OO_Comma:
10205   case OO_ArrowStar:
10206   case OO_Arrow:
10207   case OO_Call:
10208   case OO_Subscript:
10209   case OO_Conditional:
10210   case OO_Coawait:
10211   case NUM_OVERLOADED_OPERATORS:
10212     llvm_unreachable("Unexpected reduction identifier");
10213   case OO_None:
10214     if (auto *II = DN.getAsIdentifierInfo()) {
10215       if (II->isStr("max"))
10216         BOK = BO_GT;
10217       else if (II->isStr("min"))
10218         BOK = BO_LT;
10219     }
10220     break;
10221   }
10222   SourceRange ReductionIdRange;
10223   if (ReductionIdScopeSpec.isValid())
10224     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10225   else
10226     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10227   ReductionIdRange.setEnd(ReductionId.getEndLoc());
10228 
10229   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10230   bool FirstIter = true;
10231   for (auto RefExpr : VarList) {
10232     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
10233     // OpenMP [2.1, C/C++]
10234     //  A list item is a variable or array section, subject to the restrictions
10235     //  specified in Section 2.4 on page 42 and in each of the sections
10236     // describing clauses and directives for which a list appears.
10237     // OpenMP  [2.14.3.3, Restrictions, p.1]
10238     //  A variable that is part of another variable (as an array or
10239     //  structure element) cannot appear in a private clause.
10240     if (!FirstIter && IR != ER)
10241       ++IR;
10242     FirstIter = false;
10243     SourceLocation ELoc;
10244     SourceRange ERange;
10245     Expr *SimpleRefExpr = RefExpr;
10246     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10247                               /*AllowArraySection=*/true);
10248     if (Res.second) {
10249       // Try to find 'declare reduction' corresponding construct before using
10250       // builtin/overloaded operators.
10251       QualType Type = Context.DependentTy;
10252       CXXCastPath BasePath;
10253       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10254           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10255           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10256       Expr *ReductionOp = nullptr;
10257       if (S.CurContext->isDependentContext() &&
10258           (DeclareReductionRef.isUnset() ||
10259            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10260         ReductionOp = DeclareReductionRef.get();
10261       // It will be analyzed later.
10262       RD.push(RefExpr, ReductionOp);
10263     }
10264     ValueDecl *D = Res.first;
10265     if (!D)
10266       continue;
10267 
10268     Expr *TaskgroupDescriptor = nullptr;
10269     QualType Type;
10270     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10271     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10272     if (ASE)
10273       Type = ASE->getType().getNonReferenceType();
10274     else if (OASE) {
10275       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10276       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10277         Type = ATy->getElementType();
10278       else
10279         Type = BaseType->getPointeeType();
10280       Type = Type.getNonReferenceType();
10281     } else
10282       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10283     auto *VD = dyn_cast<VarDecl>(D);
10284 
10285     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10286     //  A variable that appears in a private clause must not have an incomplete
10287     //  type or a reference type.
10288     if (S.RequireCompleteType(ELoc, Type,
10289                               diag::err_omp_reduction_incomplete_type))
10290       continue;
10291     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10292     // A list item that appears in a reduction clause must not be
10293     // const-qualified.
10294     if (Type.getNonReferenceType().isConstant(Context)) {
10295       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10296       if (!ASE && !OASE) {
10297         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10298                                  VarDecl::DeclarationOnly;
10299         S.Diag(D->getLocation(),
10300                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10301             << D;
10302       }
10303       continue;
10304     }
10305     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10306     //  If a list-item is a reference type then it must bind to the same object
10307     //  for all threads of the team.
10308     if (!ASE && !OASE && VD) {
10309       VarDecl *VDDef = VD->getDefinition();
10310       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10311         DSARefChecker Check(Stack);
10312         if (Check.Visit(VDDef->getInit())) {
10313           S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10314               << getOpenMPClauseName(ClauseKind) << ERange;
10315           S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10316           continue;
10317         }
10318       }
10319     }
10320 
10321     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10322     // in a Construct]
10323     //  Variables with the predetermined data-sharing attributes may not be
10324     //  listed in data-sharing attributes clauses, except for the cases
10325     //  listed below. For these exceptions only, listing a predetermined
10326     //  variable in a data-sharing attribute clause is allowed and overrides
10327     //  the variable's predetermined data-sharing attributes.
10328     // OpenMP [2.14.3.6, Restrictions, p.3]
10329     //  Any number of reduction clauses can be specified on the directive,
10330     //  but a list item can appear only once in the reduction clauses for that
10331     //  directive.
10332     DSAStackTy::DSAVarData DVar;
10333     DVar = Stack->getTopDSA(D, false);
10334     if (DVar.CKind == OMPC_reduction) {
10335       S.Diag(ELoc, diag::err_omp_once_referenced)
10336           << getOpenMPClauseName(ClauseKind);
10337       if (DVar.RefExpr)
10338         S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10339       continue;
10340     } else if (DVar.CKind != OMPC_unknown) {
10341       S.Diag(ELoc, diag::err_omp_wrong_dsa)
10342           << getOpenMPClauseName(DVar.CKind)
10343           << getOpenMPClauseName(OMPC_reduction);
10344       ReportOriginalDSA(S, Stack, D, DVar);
10345       continue;
10346     }
10347 
10348     // OpenMP [2.14.3.6, Restrictions, p.1]
10349     //  A list item that appears in a reduction clause of a worksharing
10350     //  construct must be shared in the parallel regions to which any of the
10351     //  worksharing regions arising from the worksharing construct bind.
10352     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10353     if (isOpenMPWorksharingDirective(CurrDir) &&
10354         !isOpenMPParallelDirective(CurrDir) &&
10355         !isOpenMPTeamsDirective(CurrDir)) {
10356       DVar = Stack->getImplicitDSA(D, true);
10357       if (DVar.CKind != OMPC_shared) {
10358         S.Diag(ELoc, diag::err_omp_required_access)
10359             << getOpenMPClauseName(OMPC_reduction)
10360             << getOpenMPClauseName(OMPC_shared);
10361         ReportOriginalDSA(S, Stack, D, DVar);
10362         continue;
10363       }
10364     }
10365 
10366     // Try to find 'declare reduction' corresponding construct before using
10367     // builtin/overloaded operators.
10368     CXXCastPath BasePath;
10369     ExprResult DeclareReductionRef = buildDeclareReductionRef(
10370         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10371         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10372     if (DeclareReductionRef.isInvalid())
10373       continue;
10374     if (S.CurContext->isDependentContext() &&
10375         (DeclareReductionRef.isUnset() ||
10376          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
10377       RD.push(RefExpr, DeclareReductionRef.get());
10378       continue;
10379     }
10380     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10381       // Not allowed reduction identifier is found.
10382       S.Diag(ReductionId.getLocStart(),
10383              diag::err_omp_unknown_reduction_identifier)
10384           << Type << ReductionIdRange;
10385       continue;
10386     }
10387 
10388     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10389     // The type of a list item that appears in a reduction clause must be valid
10390     // for the reduction-identifier. For a max or min reduction in C, the type
10391     // of the list item must be an allowed arithmetic data type: char, int,
10392     // float, double, or _Bool, possibly modified with long, short, signed, or
10393     // unsigned. For a max or min reduction in C++, the type of the list item
10394     // must be an allowed arithmetic data type: char, wchar_t, int, float,
10395     // double, or bool, possibly modified with long, short, signed, or unsigned.
10396     if (DeclareReductionRef.isUnset()) {
10397       if ((BOK == BO_GT || BOK == BO_LT) &&
10398           !(Type->isScalarType() ||
10399             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10400         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
10401             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
10402         if (!ASE && !OASE) {
10403           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10404                                    VarDecl::DeclarationOnly;
10405           S.Diag(D->getLocation(),
10406                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10407               << D;
10408         }
10409         continue;
10410       }
10411       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
10412           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
10413         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10414             << getOpenMPClauseName(ClauseKind);
10415         if (!ASE && !OASE) {
10416           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10417                                    VarDecl::DeclarationOnly;
10418           S.Diag(D->getLocation(),
10419                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10420               << D;
10421         }
10422         continue;
10423       }
10424     }
10425 
10426     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
10427     auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
10428                                D->hasAttrs() ? &D->getAttrs() : nullptr);
10429     auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
10430                                D->hasAttrs() ? &D->getAttrs() : nullptr);
10431     auto PrivateTy = Type;
10432 
10433     // Try if we can determine constant lengths for all array sections and avoid
10434     // the VLA.
10435     bool ConstantLengthOASE = false;
10436     if (OASE) {
10437       bool SingleElement;
10438       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10439       ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10440           Context, OASE, SingleElement, ArraySizes);
10441 
10442       // If we don't have a single element, we must emit a constant array type.
10443       if (ConstantLengthOASE && !SingleElement) {
10444         for (auto &Size : ArraySizes) {
10445           PrivateTy = Context.getConstantArrayType(
10446               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10447         }
10448       }
10449     }
10450 
10451     if ((OASE && !ConstantLengthOASE) ||
10452         (!OASE && !ASE &&
10453          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
10454       if (!Context.getTargetInfo().isVLASupported() &&
10455           S.shouldDiagnoseTargetSupportFromOpenMP()) {
10456         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10457         S.Diag(ELoc, diag::note_vla_unsupported);
10458         continue;
10459       }
10460       // For arrays/array sections only:
10461       // Create pseudo array type for private copy. The size for this array will
10462       // be generated during codegen.
10463       // For array subscripts or single variables Private Ty is the same as Type
10464       // (type of the variable or single array element).
10465       PrivateTy = Context.getVariableArrayType(
10466           Type,
10467           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
10468           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
10469     } else if (!ASE && !OASE &&
10470                Context.getAsArrayType(D->getType().getNonReferenceType()))
10471       PrivateTy = D->getType().getNonReferenceType();
10472     // Private copy.
10473     auto *PrivateVD =
10474         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10475                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10476                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10477     // Add initializer for private variable.
10478     Expr *Init = nullptr;
10479     auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10480     auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
10481     if (DeclareReductionRef.isUsable()) {
10482       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10483       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10484       if (DRD->getInitializer()) {
10485         Init = DRDRef;
10486         RHSVD->setInit(DRDRef);
10487         RHSVD->setInitStyle(VarDecl::CallInit);
10488       }
10489     } else {
10490       switch (BOK) {
10491       case BO_Add:
10492       case BO_Xor:
10493       case BO_Or:
10494       case BO_LOr:
10495         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10496         if (Type->isScalarType() || Type->isAnyComplexType())
10497           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
10498         break;
10499       case BO_Mul:
10500       case BO_LAnd:
10501         if (Type->isScalarType() || Type->isAnyComplexType()) {
10502           // '*' and '&&' reduction ops - initializer is '1'.
10503           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
10504         }
10505         break;
10506       case BO_And: {
10507         // '&' reduction op - initializer is '~0'.
10508         QualType OrigType = Type;
10509         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10510           Type = ComplexTy->getElementType();
10511         if (Type->isRealFloatingType()) {
10512           llvm::APFloat InitValue =
10513               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10514                                              /*isIEEE=*/true);
10515           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10516                                          Type, ELoc);
10517         } else if (Type->isScalarType()) {
10518           auto Size = Context.getTypeSize(Type);
10519           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10520           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10521           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10522         }
10523         if (Init && OrigType->isAnyComplexType()) {
10524           // Init = 0xFFFF + 0xFFFFi;
10525           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
10526           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
10527         }
10528         Type = OrigType;
10529         break;
10530       }
10531       case BO_LT:
10532       case BO_GT: {
10533         // 'min' reduction op - initializer is 'Largest representable number in
10534         // the reduction list item type'.
10535         // 'max' reduction op - initializer is 'Least representable number in
10536         // the reduction list item type'.
10537         if (Type->isIntegerType() || Type->isPointerType()) {
10538           bool IsSigned = Type->hasSignedIntegerRepresentation();
10539           auto Size = Context.getTypeSize(Type);
10540           QualType IntTy =
10541               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10542           llvm::APInt InitValue =
10543               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10544                                         : llvm::APInt::getMinValue(Size)
10545                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10546                                         : llvm::APInt::getMaxValue(Size);
10547           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10548           if (Type->isPointerType()) {
10549             // Cast to pointer type.
10550             auto CastExpr = S.BuildCStyleCastExpr(
10551                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
10552             if (CastExpr.isInvalid())
10553               continue;
10554             Init = CastExpr.get();
10555           }
10556         } else if (Type->isRealFloatingType()) {
10557           llvm::APFloat InitValue = llvm::APFloat::getLargest(
10558               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10559           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10560                                          Type, ELoc);
10561         }
10562         break;
10563       }
10564       case BO_PtrMemD:
10565       case BO_PtrMemI:
10566       case BO_MulAssign:
10567       case BO_Div:
10568       case BO_Rem:
10569       case BO_Sub:
10570       case BO_Shl:
10571       case BO_Shr:
10572       case BO_LE:
10573       case BO_GE:
10574       case BO_EQ:
10575       case BO_NE:
10576       case BO_Cmp:
10577       case BO_AndAssign:
10578       case BO_XorAssign:
10579       case BO_OrAssign:
10580       case BO_Assign:
10581       case BO_AddAssign:
10582       case BO_SubAssign:
10583       case BO_DivAssign:
10584       case BO_RemAssign:
10585       case BO_ShlAssign:
10586       case BO_ShrAssign:
10587       case BO_Comma:
10588         llvm_unreachable("Unexpected reduction operation");
10589       }
10590     }
10591     if (Init && DeclareReductionRef.isUnset())
10592       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10593     else if (!Init)
10594       S.ActOnUninitializedDecl(RHSVD);
10595     if (RHSVD->isInvalidDecl())
10596       continue;
10597     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
10598       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10599           << Type << ReductionIdRange;
10600       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10601                                VarDecl::DeclarationOnly;
10602       S.Diag(D->getLocation(),
10603              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10604           << D;
10605       continue;
10606     }
10607     // Store initializer for single element in private copy. Will be used during
10608     // codegen.
10609     PrivateVD->setInit(RHSVD->getInit());
10610     PrivateVD->setInitStyle(RHSVD->getInitStyle());
10611     auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
10612     ExprResult ReductionOp;
10613     if (DeclareReductionRef.isUsable()) {
10614       QualType RedTy = DeclareReductionRef.get()->getType();
10615       QualType PtrRedTy = Context.getPointerType(RedTy);
10616       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10617       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
10618       if (!BasePath.empty()) {
10619         LHS = S.DefaultLvalueConversion(LHS.get());
10620         RHS = S.DefaultLvalueConversion(RHS.get());
10621         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10622                                        CK_UncheckedDerivedToBase, LHS.get(),
10623                                        &BasePath, LHS.get()->getValueKind());
10624         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10625                                        CK_UncheckedDerivedToBase, RHS.get(),
10626                                        &BasePath, RHS.get()->getValueKind());
10627       }
10628       FunctionProtoType::ExtProtoInfo EPI;
10629       QualType Params[] = {PtrRedTy, PtrRedTy};
10630       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10631       auto *OVE = new (Context) OpaqueValueExpr(
10632           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
10633           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
10634       Expr *Args[] = {LHS.get(), RHS.get()};
10635       ReductionOp = new (Context)
10636           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10637     } else {
10638       ReductionOp = S.BuildBinOp(
10639           Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
10640       if (ReductionOp.isUsable()) {
10641         if (BOK != BO_LT && BOK != BO_GT) {
10642           ReductionOp =
10643               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10644                            BO_Assign, LHSDRE, ReductionOp.get());
10645         } else {
10646           auto *ConditionalOp = new (Context)
10647               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10648                                   Type, VK_LValue, OK_Ordinary);
10649           ReductionOp =
10650               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10651                            BO_Assign, LHSDRE, ConditionalOp);
10652         }
10653         if (ReductionOp.isUsable())
10654           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
10655       }
10656       if (!ReductionOp.isUsable())
10657         continue;
10658     }
10659 
10660     // OpenMP [2.15.4.6, Restrictions, p.2]
10661     // A list item that appears in an in_reduction clause of a task construct
10662     // must appear in a task_reduction clause of a construct associated with a
10663     // taskgroup region that includes the participating task in its taskgroup
10664     // set. The construct associated with the innermost region that meets this
10665     // condition must specify the same reduction-identifier as the in_reduction
10666     // clause.
10667     if (ClauseKind == OMPC_in_reduction) {
10668       SourceRange ParentSR;
10669       BinaryOperatorKind ParentBOK;
10670       const Expr *ParentReductionOp;
10671       Expr *ParentBOKTD, *ParentReductionOpTD;
10672       DSAStackTy::DSAVarData ParentBOKDSA =
10673           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10674                                                   ParentBOKTD);
10675       DSAStackTy::DSAVarData ParentReductionOpDSA =
10676           Stack->getTopMostTaskgroupReductionData(
10677               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
10678       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10679       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10680       if (!IsParentBOK && !IsParentReductionOp) {
10681         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10682         continue;
10683       }
10684       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10685           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10686           IsParentReductionOp) {
10687         bool EmitError = true;
10688         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10689           llvm::FoldingSetNodeID RedId, ParentRedId;
10690           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10691           DeclareReductionRef.get()->Profile(RedId, Context,
10692                                              /*Canonical=*/true);
10693           EmitError = RedId != ParentRedId;
10694         }
10695         if (EmitError) {
10696           S.Diag(ReductionId.getLocStart(),
10697                  diag::err_omp_reduction_identifier_mismatch)
10698               << ReductionIdRange << RefExpr->getSourceRange();
10699           S.Diag(ParentSR.getBegin(),
10700                  diag::note_omp_previous_reduction_identifier)
10701               << ParentSR
10702               << (IsParentBOK ? ParentBOKDSA.RefExpr
10703                               : ParentReductionOpDSA.RefExpr)
10704                      ->getSourceRange();
10705           continue;
10706         }
10707       }
10708       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10709       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
10710     }
10711 
10712     DeclRefExpr *Ref = nullptr;
10713     Expr *VarsExpr = RefExpr->IgnoreParens();
10714     if (!VD && !S.CurContext->isDependentContext()) {
10715       if (ASE || OASE) {
10716         TransformExprToCaptures RebuildToCapture(S, D);
10717         VarsExpr =
10718             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10719         Ref = RebuildToCapture.getCapturedExpr();
10720       } else {
10721         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
10722       }
10723       if (!S.IsOpenMPCapturedDecl(D)) {
10724         RD.ExprCaptures.emplace_back(Ref->getDecl());
10725         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10726           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
10727           if (!RefRes.isUsable())
10728             continue;
10729           ExprResult PostUpdateRes =
10730               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10731                            RefRes.get());
10732           if (!PostUpdateRes.isUsable())
10733             continue;
10734           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10735               Stack->getCurrentDirective() == OMPD_taskgroup) {
10736             S.Diag(RefExpr->getExprLoc(),
10737                    diag::err_omp_reduction_non_addressable_expression)
10738                 << RefExpr->getSourceRange();
10739             continue;
10740           }
10741           RD.ExprPostUpdates.emplace_back(
10742               S.IgnoredValueConversions(PostUpdateRes.get()).get());
10743         }
10744       }
10745     }
10746     // All reduction items are still marked as reduction (to do not increase
10747     // code base size).
10748     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
10749     if (CurrDir == OMPD_taskgroup) {
10750       if (DeclareReductionRef.isUsable())
10751         Stack->addTaskgroupReductionData(D, ReductionIdRange,
10752                                          DeclareReductionRef.get());
10753       else
10754         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
10755     }
10756     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10757             TaskgroupDescriptor);
10758   }
10759   return RD.Vars.empty();
10760 }
10761 
10762 OMPClause *Sema::ActOnOpenMPReductionClause(
10763     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10764     SourceLocation ColonLoc, SourceLocation EndLoc,
10765     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10766     ArrayRef<Expr *> UnresolvedReductions) {
10767   ReductionData RD(VarList.size());
10768 
10769   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10770                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10771                                   ReductionIdScopeSpec, ReductionId,
10772                                   UnresolvedReductions, RD))
10773     return nullptr;
10774 
10775   return OMPReductionClause::Create(
10776       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10777       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10778       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10779       buildPreInits(Context, RD.ExprCaptures),
10780       buildPostUpdate(*this, RD.ExprPostUpdates));
10781 }
10782 
10783 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10784     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10785     SourceLocation ColonLoc, SourceLocation EndLoc,
10786     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10787     ArrayRef<Expr *> UnresolvedReductions) {
10788   ReductionData RD(VarList.size());
10789 
10790   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10791                                   VarList, StartLoc, LParenLoc, ColonLoc,
10792                                   EndLoc, ReductionIdScopeSpec, ReductionId,
10793                                   UnresolvedReductions, RD))
10794     return nullptr;
10795 
10796   return OMPTaskReductionClause::Create(
10797       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10798       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10799       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10800       buildPreInits(Context, RD.ExprCaptures),
10801       buildPostUpdate(*this, RD.ExprPostUpdates));
10802 }
10803 
10804 OMPClause *Sema::ActOnOpenMPInReductionClause(
10805     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10806     SourceLocation ColonLoc, SourceLocation EndLoc,
10807     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10808     ArrayRef<Expr *> UnresolvedReductions) {
10809   ReductionData RD(VarList.size());
10810 
10811   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10812                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10813                                   ReductionIdScopeSpec, ReductionId,
10814                                   UnresolvedReductions, RD))
10815     return nullptr;
10816 
10817   return OMPInReductionClause::Create(
10818       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10819       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10820       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
10821       buildPreInits(Context, RD.ExprCaptures),
10822       buildPostUpdate(*this, RD.ExprPostUpdates));
10823 }
10824 
10825 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10826                                      SourceLocation LinLoc) {
10827   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10828       LinKind == OMPC_LINEAR_unknown) {
10829     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10830     return true;
10831   }
10832   return false;
10833 }
10834 
10835 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10836                                  OpenMPLinearClauseKind LinKind,
10837                                  QualType Type) {
10838   auto *VD = dyn_cast_or_null<VarDecl>(D);
10839   // A variable must not have an incomplete type or a reference type.
10840   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10841     return true;
10842   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10843       !Type->isReferenceType()) {
10844     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10845         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10846     return true;
10847   }
10848   Type = Type.getNonReferenceType();
10849 
10850   // A list item must not be const-qualified.
10851   if (Type.isConstant(Context)) {
10852     Diag(ELoc, diag::err_omp_const_variable)
10853         << getOpenMPClauseName(OMPC_linear);
10854     if (D) {
10855       bool IsDecl =
10856           !VD ||
10857           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10858       Diag(D->getLocation(),
10859            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10860           << D;
10861     }
10862     return true;
10863   }
10864 
10865   // A list item must be of integral or pointer type.
10866   Type = Type.getUnqualifiedType().getCanonicalType();
10867   const auto *Ty = Type.getTypePtrOrNull();
10868   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10869               !Ty->isPointerType())) {
10870     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10871     if (D) {
10872       bool IsDecl =
10873           !VD ||
10874           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10875       Diag(D->getLocation(),
10876            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10877           << D;
10878     }
10879     return true;
10880   }
10881   return false;
10882 }
10883 
10884 OMPClause *Sema::ActOnOpenMPLinearClause(
10885     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10886     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10887     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10888   SmallVector<Expr *, 8> Vars;
10889   SmallVector<Expr *, 8> Privates;
10890   SmallVector<Expr *, 8> Inits;
10891   SmallVector<Decl *, 4> ExprCaptures;
10892   SmallVector<Expr *, 4> ExprPostUpdates;
10893   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
10894     LinKind = OMPC_LINEAR_val;
10895   for (auto &RefExpr : VarList) {
10896     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10897     SourceLocation ELoc;
10898     SourceRange ERange;
10899     Expr *SimpleRefExpr = RefExpr;
10900     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10901                               /*AllowArraySection=*/false);
10902     if (Res.second) {
10903       // It will be analyzed later.
10904       Vars.push_back(RefExpr);
10905       Privates.push_back(nullptr);
10906       Inits.push_back(nullptr);
10907     }
10908     ValueDecl *D = Res.first;
10909     if (!D)
10910       continue;
10911 
10912     QualType Type = D->getType();
10913     auto *VD = dyn_cast<VarDecl>(D);
10914 
10915     // OpenMP [2.14.3.7, linear clause]
10916     //  A list-item cannot appear in more than one linear clause.
10917     //  A list-item that appears in a linear clause cannot appear in any
10918     //  other data-sharing attribute clause.
10919     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
10920     if (DVar.RefExpr) {
10921       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10922                                           << getOpenMPClauseName(OMPC_linear);
10923       ReportOriginalDSA(*this, DSAStack, D, DVar);
10924       continue;
10925     }
10926 
10927     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
10928       continue;
10929     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
10930 
10931     // Build private copy of original var.
10932     auto *Private =
10933         buildVarDecl(*this, ELoc, Type, D->getName(),
10934                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10935                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10936     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
10937     // Build var to save initial value.
10938     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
10939     Expr *InitExpr;
10940     DeclRefExpr *Ref = nullptr;
10941     if (!VD && !CurContext->isDependentContext()) {
10942       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10943       if (!IsOpenMPCapturedDecl(D)) {
10944         ExprCaptures.push_back(Ref->getDecl());
10945         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10946           ExprResult RefRes = DefaultLvalueConversion(Ref);
10947           if (!RefRes.isUsable())
10948             continue;
10949           ExprResult PostUpdateRes =
10950               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10951                          SimpleRefExpr, RefRes.get());
10952           if (!PostUpdateRes.isUsable())
10953             continue;
10954           ExprPostUpdates.push_back(
10955               IgnoredValueConversions(PostUpdateRes.get()).get());
10956         }
10957       }
10958     }
10959     if (LinKind == OMPC_LINEAR_uval)
10960       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
10961     else
10962       InitExpr = VD ? SimpleRefExpr : Ref;
10963     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
10964                          /*DirectInit=*/false);
10965     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10966 
10967     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
10968     Vars.push_back((VD || CurContext->isDependentContext())
10969                        ? RefExpr->IgnoreParens()
10970                        : Ref);
10971     Privates.push_back(PrivateRef);
10972     Inits.push_back(InitRef);
10973   }
10974 
10975   if (Vars.empty())
10976     return nullptr;
10977 
10978   Expr *StepExpr = Step;
10979   Expr *CalcStepExpr = nullptr;
10980   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10981       !Step->isInstantiationDependent() &&
10982       !Step->containsUnexpandedParameterPack()) {
10983     SourceLocation StepLoc = Step->getLocStart();
10984     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
10985     if (Val.isInvalid())
10986       return nullptr;
10987     StepExpr = Val.get();
10988 
10989     // Build var to save the step value.
10990     VarDecl *SaveVar =
10991         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
10992     ExprResult SaveRef =
10993         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
10994     ExprResult CalcStep =
10995         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
10996     CalcStep = ActOnFinishFullExpr(CalcStep.get());
10997 
10998     // Warn about zero linear step (it would be probably better specified as
10999     // making corresponding variables 'const').
11000     llvm::APSInt Result;
11001     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11002     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
11003       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11004                                                      << (Vars.size() > 1);
11005     if (!IsConstant && CalcStep.isUsable()) {
11006       // Calculate the step beforehand instead of doing this on each iteration.
11007       // (This is not used if the number of iterations may be kfold-ed).
11008       CalcStepExpr = CalcStep.get();
11009     }
11010   }
11011 
11012   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11013                                  ColonLoc, EndLoc, Vars, Privates, Inits,
11014                                  StepExpr, CalcStepExpr,
11015                                  buildPreInits(Context, ExprCaptures),
11016                                  buildPostUpdate(*this, ExprPostUpdates));
11017 }
11018 
11019 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11020                                      Expr *NumIterations, Sema &SemaRef,
11021                                      Scope *S, DSAStackTy *Stack) {
11022   // Walk the vars and build update/final expressions for the CodeGen.
11023   SmallVector<Expr *, 8> Updates;
11024   SmallVector<Expr *, 8> Finals;
11025   Expr *Step = Clause.getStep();
11026   Expr *CalcStep = Clause.getCalcStep();
11027   // OpenMP [2.14.3.7, linear clause]
11028   // If linear-step is not specified it is assumed to be 1.
11029   if (Step == nullptr)
11030     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11031   else if (CalcStep) {
11032     Step = cast<BinaryOperator>(CalcStep)->getLHS();
11033   }
11034   bool HasErrors = false;
11035   auto CurInit = Clause.inits().begin();
11036   auto CurPrivate = Clause.privates().begin();
11037   auto LinKind = Clause.getModifier();
11038   for (auto &RefExpr : Clause.varlists()) {
11039     SourceLocation ELoc;
11040     SourceRange ERange;
11041     Expr *SimpleRefExpr = RefExpr;
11042     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11043                               /*AllowArraySection=*/false);
11044     ValueDecl *D = Res.first;
11045     if (Res.second || !D) {
11046       Updates.push_back(nullptr);
11047       Finals.push_back(nullptr);
11048       HasErrors = true;
11049       continue;
11050     }
11051     auto &&Info = Stack->isLoopControlVariable(D);
11052     // OpenMP [2.15.11, distribute simd Construct]
11053     // A list item may not appear in a linear clause, unless it is the loop
11054     // iteration variable.
11055     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11056         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11057       SemaRef.Diag(ELoc,
11058                    diag::err_omp_linear_distribute_var_non_loop_iteration);
11059       Updates.push_back(nullptr);
11060       Finals.push_back(nullptr);
11061       HasErrors = true;
11062       continue;
11063     }
11064     Expr *InitExpr = *CurInit;
11065 
11066     // Build privatized reference to the current linear var.
11067     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
11068     Expr *CapturedRef;
11069     if (LinKind == OMPC_LINEAR_uval)
11070       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11071     else
11072       CapturedRef =
11073           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11074                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11075                            /*RefersToCapture=*/true);
11076 
11077     // Build update: Var = InitExpr + IV * Step
11078     ExprResult Update;
11079     if (!Info.first) {
11080       Update =
11081           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11082                              InitExpr, IV, Step, /* Subtract */ false);
11083     } else
11084       Update = *CurPrivate;
11085     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11086                                          /*DiscardedValue=*/true);
11087 
11088     // Build final: Var = InitExpr + NumIterations * Step
11089     ExprResult Final;
11090     if (!Info.first) {
11091       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11092                                  InitExpr, NumIterations, Step,
11093                                  /* Subtract */ false);
11094     } else
11095       Final = *CurPrivate;
11096     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11097                                         /*DiscardedValue=*/true);
11098 
11099     if (!Update.isUsable() || !Final.isUsable()) {
11100       Updates.push_back(nullptr);
11101       Finals.push_back(nullptr);
11102       HasErrors = true;
11103     } else {
11104       Updates.push_back(Update.get());
11105       Finals.push_back(Final.get());
11106     }
11107     ++CurInit;
11108     ++CurPrivate;
11109   }
11110   Clause.setUpdates(Updates);
11111   Clause.setFinals(Finals);
11112   return HasErrors;
11113 }
11114 
11115 OMPClause *Sema::ActOnOpenMPAlignedClause(
11116     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11117     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11118 
11119   SmallVector<Expr *, 8> Vars;
11120   for (auto &RefExpr : VarList) {
11121     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11122     SourceLocation ELoc;
11123     SourceRange ERange;
11124     Expr *SimpleRefExpr = RefExpr;
11125     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11126                               /*AllowArraySection=*/false);
11127     if (Res.second) {
11128       // It will be analyzed later.
11129       Vars.push_back(RefExpr);
11130     }
11131     ValueDecl *D = Res.first;
11132     if (!D)
11133       continue;
11134 
11135     QualType QType = D->getType();
11136     auto *VD = dyn_cast<VarDecl>(D);
11137 
11138     // OpenMP  [2.8.1, simd construct, Restrictions]
11139     // The type of list items appearing in the aligned clause must be
11140     // array, pointer, reference to array, or reference to pointer.
11141     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11142     const Type *Ty = QType.getTypePtrOrNull();
11143     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11144       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11145           << QType << getLangOpts().CPlusPlus << ERange;
11146       bool IsDecl =
11147           !VD ||
11148           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11149       Diag(D->getLocation(),
11150            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11151           << D;
11152       continue;
11153     }
11154 
11155     // OpenMP  [2.8.1, simd construct, Restrictions]
11156     // A list-item cannot appear in more than one aligned clause.
11157     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11158       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11159       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11160           << getOpenMPClauseName(OMPC_aligned);
11161       continue;
11162     }
11163 
11164     DeclRefExpr *Ref = nullptr;
11165     if (!VD && IsOpenMPCapturedDecl(D))
11166       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11167     Vars.push_back(DefaultFunctionArrayConversion(
11168                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11169                        .get());
11170   }
11171 
11172   // OpenMP [2.8.1, simd construct, Description]
11173   // The parameter of the aligned clause, alignment, must be a constant
11174   // positive integer expression.
11175   // If no optional parameter is specified, implementation-defined default
11176   // alignments for SIMD instructions on the target platforms are assumed.
11177   if (Alignment != nullptr) {
11178     ExprResult AlignResult =
11179         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11180     if (AlignResult.isInvalid())
11181       return nullptr;
11182     Alignment = AlignResult.get();
11183   }
11184   if (Vars.empty())
11185     return nullptr;
11186 
11187   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11188                                   EndLoc, Vars, Alignment);
11189 }
11190 
11191 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11192                                          SourceLocation StartLoc,
11193                                          SourceLocation LParenLoc,
11194                                          SourceLocation EndLoc) {
11195   SmallVector<Expr *, 8> Vars;
11196   SmallVector<Expr *, 8> SrcExprs;
11197   SmallVector<Expr *, 8> DstExprs;
11198   SmallVector<Expr *, 8> AssignmentOps;
11199   for (auto &RefExpr : VarList) {
11200     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11201     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11202       // It will be analyzed later.
11203       Vars.push_back(RefExpr);
11204       SrcExprs.push_back(nullptr);
11205       DstExprs.push_back(nullptr);
11206       AssignmentOps.push_back(nullptr);
11207       continue;
11208     }
11209 
11210     SourceLocation ELoc = RefExpr->getExprLoc();
11211     // OpenMP [2.1, C/C++]
11212     //  A list item is a variable name.
11213     // OpenMP  [2.14.4.1, Restrictions, p.1]
11214     //  A list item that appears in a copyin clause must be threadprivate.
11215     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
11216     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11217       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11218           << 0 << RefExpr->getSourceRange();
11219       continue;
11220     }
11221 
11222     Decl *D = DE->getDecl();
11223     VarDecl *VD = cast<VarDecl>(D);
11224 
11225     QualType Type = VD->getType();
11226     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11227       // It will be analyzed later.
11228       Vars.push_back(DE);
11229       SrcExprs.push_back(nullptr);
11230       DstExprs.push_back(nullptr);
11231       AssignmentOps.push_back(nullptr);
11232       continue;
11233     }
11234 
11235     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11236     //  A list item that appears in a copyin clause must be threadprivate.
11237     if (!DSAStack->isThreadPrivate(VD)) {
11238       Diag(ELoc, diag::err_omp_required_access)
11239           << getOpenMPClauseName(OMPC_copyin)
11240           << getOpenMPDirectiveName(OMPD_threadprivate);
11241       continue;
11242     }
11243 
11244     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11245     //  A variable of class type (or array thereof) that appears in a
11246     //  copyin clause requires an accessible, unambiguous copy assignment
11247     //  operator for the class type.
11248     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11249     auto *SrcVD =
11250         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11251                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11252     auto *PseudoSrcExpr = buildDeclRefExpr(
11253         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11254     auto *DstVD =
11255         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11256                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11257     auto *PseudoDstExpr =
11258         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11259     // For arrays generate assignment operation for single element and replace
11260     // it by the original array element in CodeGen.
11261     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11262                                    PseudoDstExpr, PseudoSrcExpr);
11263     if (AssignmentOp.isInvalid())
11264       continue;
11265     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11266                                        /*DiscardedValue=*/true);
11267     if (AssignmentOp.isInvalid())
11268       continue;
11269 
11270     DSAStack->addDSA(VD, DE, OMPC_copyin);
11271     Vars.push_back(DE);
11272     SrcExprs.push_back(PseudoSrcExpr);
11273     DstExprs.push_back(PseudoDstExpr);
11274     AssignmentOps.push_back(AssignmentOp.get());
11275   }
11276 
11277   if (Vars.empty())
11278     return nullptr;
11279 
11280   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11281                                  SrcExprs, DstExprs, AssignmentOps);
11282 }
11283 
11284 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11285                                               SourceLocation StartLoc,
11286                                               SourceLocation LParenLoc,
11287                                               SourceLocation EndLoc) {
11288   SmallVector<Expr *, 8> Vars;
11289   SmallVector<Expr *, 8> SrcExprs;
11290   SmallVector<Expr *, 8> DstExprs;
11291   SmallVector<Expr *, 8> AssignmentOps;
11292   for (auto &RefExpr : VarList) {
11293     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11294     SourceLocation ELoc;
11295     SourceRange ERange;
11296     Expr *SimpleRefExpr = RefExpr;
11297     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11298                               /*AllowArraySection=*/false);
11299     if (Res.second) {
11300       // It will be analyzed later.
11301       Vars.push_back(RefExpr);
11302       SrcExprs.push_back(nullptr);
11303       DstExprs.push_back(nullptr);
11304       AssignmentOps.push_back(nullptr);
11305     }
11306     ValueDecl *D = Res.first;
11307     if (!D)
11308       continue;
11309 
11310     QualType Type = D->getType();
11311     auto *VD = dyn_cast<VarDecl>(D);
11312 
11313     // OpenMP [2.14.4.2, Restrictions, p.2]
11314     //  A list item that appears in a copyprivate clause may not appear in a
11315     //  private or firstprivate clause on the single construct.
11316     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11317       auto DVar = DSAStack->getTopDSA(D, false);
11318       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11319           DVar.RefExpr) {
11320         Diag(ELoc, diag::err_omp_wrong_dsa)
11321             << getOpenMPClauseName(DVar.CKind)
11322             << getOpenMPClauseName(OMPC_copyprivate);
11323         ReportOriginalDSA(*this, DSAStack, D, DVar);
11324         continue;
11325       }
11326 
11327       // OpenMP [2.11.4.2, Restrictions, p.1]
11328       //  All list items that appear in a copyprivate clause must be either
11329       //  threadprivate or private in the enclosing context.
11330       if (DVar.CKind == OMPC_unknown) {
11331         DVar = DSAStack->getImplicitDSA(D, false);
11332         if (DVar.CKind == OMPC_shared) {
11333           Diag(ELoc, diag::err_omp_required_access)
11334               << getOpenMPClauseName(OMPC_copyprivate)
11335               << "threadprivate or private in the enclosing context";
11336           ReportOriginalDSA(*this, DSAStack, D, DVar);
11337           continue;
11338         }
11339       }
11340     }
11341 
11342     // Variably modified types are not supported.
11343     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11344       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11345           << getOpenMPClauseName(OMPC_copyprivate) << Type
11346           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11347       bool IsDecl =
11348           !VD ||
11349           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11350       Diag(D->getLocation(),
11351            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11352           << D;
11353       continue;
11354     }
11355 
11356     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11357     //  A variable of class type (or array thereof) that appears in a
11358     //  copyin clause requires an accessible, unambiguous copy assignment
11359     //  operator for the class type.
11360     Type = Context.getBaseElementType(Type.getNonReferenceType())
11361                .getUnqualifiedType();
11362     auto *SrcVD =
11363         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11364                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11365     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11366     auto *DstVD =
11367         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11368                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11369     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11370     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11371                                    PseudoDstExpr, PseudoSrcExpr);
11372     if (AssignmentOp.isInvalid())
11373       continue;
11374     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
11375                                        /*DiscardedValue=*/true);
11376     if (AssignmentOp.isInvalid())
11377       continue;
11378 
11379     // No need to mark vars as copyprivate, they are already threadprivate or
11380     // implicitly private.
11381     assert(VD || IsOpenMPCapturedDecl(D));
11382     Vars.push_back(
11383         VD ? RefExpr->IgnoreParens()
11384            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
11385     SrcExprs.push_back(PseudoSrcExpr);
11386     DstExprs.push_back(PseudoDstExpr);
11387     AssignmentOps.push_back(AssignmentOp.get());
11388   }
11389 
11390   if (Vars.empty())
11391     return nullptr;
11392 
11393   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11394                                       Vars, SrcExprs, DstExprs, AssignmentOps);
11395 }
11396 
11397 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11398                                         SourceLocation StartLoc,
11399                                         SourceLocation LParenLoc,
11400                                         SourceLocation EndLoc) {
11401   if (VarList.empty())
11402     return nullptr;
11403 
11404   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11405 }
11406 
11407 OMPClause *
11408 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11409                               SourceLocation DepLoc, SourceLocation ColonLoc,
11410                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11411                               SourceLocation LParenLoc, SourceLocation EndLoc) {
11412   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
11413       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
11414     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11415         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
11416     return nullptr;
11417   }
11418   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
11419       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11420        DepKind == OMPC_DEPEND_sink)) {
11421     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
11422     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11423         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11424                                    /*Last=*/OMPC_DEPEND_unknown, Except)
11425         << getOpenMPClauseName(OMPC_depend);
11426     return nullptr;
11427   }
11428   SmallVector<Expr *, 8> Vars;
11429   DSAStackTy::OperatorOffsetTy OpsOffs;
11430   llvm::APSInt DepCounter(/*BitWidth=*/32);
11431   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11432   if (DepKind == OMPC_DEPEND_sink) {
11433     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11434       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11435       TotalDepCount.setIsUnsigned(/*Val=*/true);
11436     }
11437   }
11438   for (auto &RefExpr : VarList) {
11439     assert(RefExpr && "NULL expr in OpenMP shared clause.");
11440     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11441       // It will be analyzed later.
11442       Vars.push_back(RefExpr);
11443       continue;
11444     }
11445 
11446     SourceLocation ELoc = RefExpr->getExprLoc();
11447     auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11448     if (DepKind == OMPC_DEPEND_sink) {
11449       if (DSAStack->getParentOrderedRegionParam() &&
11450           DepCounter >= TotalDepCount) {
11451         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11452         continue;
11453       }
11454       ++DepCounter;
11455       // OpenMP  [2.13.9, Summary]
11456       // depend(dependence-type : vec), where dependence-type is:
11457       // 'sink' and where vec is the iteration vector, which has the form:
11458       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11459       // where n is the value specified by the ordered clause in the loop
11460       // directive, xi denotes the loop iteration variable of the i-th nested
11461       // loop associated with the loop directive, and di is a constant
11462       // non-negative integer.
11463       if (CurContext->isDependentContext()) {
11464         // It will be analyzed later.
11465         Vars.push_back(RefExpr);
11466         continue;
11467       }
11468       SimpleExpr = SimpleExpr->IgnoreImplicit();
11469       OverloadedOperatorKind OOK = OO_None;
11470       SourceLocation OOLoc;
11471       Expr *LHS = SimpleExpr;
11472       Expr *RHS = nullptr;
11473       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11474         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11475         OOLoc = BO->getOperatorLoc();
11476         LHS = BO->getLHS()->IgnoreParenImpCasts();
11477         RHS = BO->getRHS()->IgnoreParenImpCasts();
11478       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11479         OOK = OCE->getOperator();
11480         OOLoc = OCE->getOperatorLoc();
11481         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11482         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11483       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11484         OOK = MCE->getMethodDecl()
11485                   ->getNameInfo()
11486                   .getName()
11487                   .getCXXOverloadedOperator();
11488         OOLoc = MCE->getCallee()->getExprLoc();
11489         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11490         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11491       }
11492       SourceLocation ELoc;
11493       SourceRange ERange;
11494       auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11495                                 /*AllowArraySection=*/false);
11496       if (Res.second) {
11497         // It will be analyzed later.
11498         Vars.push_back(RefExpr);
11499       }
11500       ValueDecl *D = Res.first;
11501       if (!D)
11502         continue;
11503 
11504       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11505         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11506         continue;
11507       }
11508       if (RHS) {
11509         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11510             RHS, OMPC_depend, /*StrictlyPositive=*/false);
11511         if (RHSRes.isInvalid())
11512           continue;
11513       }
11514       if (!CurContext->isDependentContext() &&
11515           DSAStack->getParentOrderedRegionParam() &&
11516           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11517         ValueDecl *VD =
11518             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11519         if (VD) {
11520           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11521               << 1 << VD;
11522         } else {
11523           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11524         }
11525         continue;
11526       }
11527       OpsOffs.push_back({RHS, OOK});
11528     } else {
11529       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11530       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11531           (ASE &&
11532            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11533            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11534         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11535             << RefExpr->getSourceRange();
11536         continue;
11537       }
11538       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11539       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11540       ExprResult Res =
11541           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11542       getDiagnostics().setSuppressAllDiagnostics(Suppress);
11543       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11544         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11545             << RefExpr->getSourceRange();
11546         continue;
11547       }
11548     }
11549     Vars.push_back(RefExpr->IgnoreParenImpCasts());
11550   }
11551 
11552   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11553       TotalDepCount > VarList.size() &&
11554       DSAStack->getParentOrderedRegionParam() &&
11555       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11556     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11557         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11558   }
11559   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11560       Vars.empty())
11561     return nullptr;
11562 
11563   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11564                                     DepKind, DepLoc, ColonLoc, Vars);
11565   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11566       DSAStack->isParentOrderedRegion())
11567     DSAStack->addDoacrossDependClause(C, OpsOffs);
11568   return C;
11569 }
11570 
11571 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11572                                          SourceLocation LParenLoc,
11573                                          SourceLocation EndLoc) {
11574   Expr *ValExpr = Device;
11575   Stmt *HelperValStmt = nullptr;
11576 
11577   // OpenMP [2.9.1, Restrictions]
11578   // The device expression must evaluate to a non-negative integer value.
11579   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11580                                  /*StrictlyPositive=*/false))
11581     return nullptr;
11582 
11583   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11584   OpenMPDirectiveKind CaptureRegion =
11585       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11586   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11587     ValExpr = MakeFullExpr(ValExpr).get();
11588     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11589     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11590     HelperValStmt = buildPreInits(Context, Captures);
11591   }
11592 
11593   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11594                                        StartLoc, LParenLoc, EndLoc);
11595 }
11596 
11597 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11598                               DSAStackTy *Stack, QualType QTy,
11599                               bool FullCheck = true) {
11600   NamedDecl *ND;
11601   if (QTy->isIncompleteType(&ND)) {
11602     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11603     return false;
11604   }
11605   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11606       !QTy.isTrivialType(SemaRef.Context))
11607     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
11608   return true;
11609 }
11610 
11611 /// \brief Return true if it can be proven that the provided array expression
11612 /// (array section or array subscript) does NOT specify the whole size of the
11613 /// array whose base type is \a BaseQTy.
11614 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11615                                                         const Expr *E,
11616                                                         QualType BaseQTy) {
11617   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11618 
11619   // If this is an array subscript, it refers to the whole size if the size of
11620   // the dimension is constant and equals 1. Also, an array section assumes the
11621   // format of an array subscript if no colon is used.
11622   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11623     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11624       return ATy->getSize().getSExtValue() != 1;
11625     // Size can't be evaluated statically.
11626     return false;
11627   }
11628 
11629   assert(OASE && "Expecting array section if not an array subscript.");
11630   auto *LowerBound = OASE->getLowerBound();
11631   auto *Length = OASE->getLength();
11632 
11633   // If there is a lower bound that does not evaluates to zero, we are not
11634   // covering the whole dimension.
11635   if (LowerBound) {
11636     llvm::APSInt ConstLowerBound;
11637     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11638       return false; // Can't get the integer value as a constant.
11639     if (ConstLowerBound.getSExtValue())
11640       return true;
11641   }
11642 
11643   // If we don't have a length we covering the whole dimension.
11644   if (!Length)
11645     return false;
11646 
11647   // If the base is a pointer, we don't have a way to get the size of the
11648   // pointee.
11649   if (BaseQTy->isPointerType())
11650     return false;
11651 
11652   // We can only check if the length is the same as the size of the dimension
11653   // if we have a constant array.
11654   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11655   if (!CATy)
11656     return false;
11657 
11658   llvm::APSInt ConstLength;
11659   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11660     return false; // Can't get the integer value as a constant.
11661 
11662   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11663 }
11664 
11665 // Return true if it can be proven that the provided array expression (array
11666 // section or array subscript) does NOT specify a single element of the array
11667 // whose base type is \a BaseQTy.
11668 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
11669                                                         const Expr *E,
11670                                                         QualType BaseQTy) {
11671   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11672 
11673   // An array subscript always refer to a single element. Also, an array section
11674   // assumes the format of an array subscript if no colon is used.
11675   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11676     return false;
11677 
11678   assert(OASE && "Expecting array section if not an array subscript.");
11679   auto *Length = OASE->getLength();
11680 
11681   // If we don't have a length we have to check if the array has unitary size
11682   // for this dimension. Also, we should always expect a length if the base type
11683   // is pointer.
11684   if (!Length) {
11685     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11686       return ATy->getSize().getSExtValue() != 1;
11687     // We cannot assume anything.
11688     return false;
11689   }
11690 
11691   // Check if the length evaluates to 1.
11692   llvm::APSInt ConstLength;
11693   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11694     return false; // Can't get the integer value as a constant.
11695 
11696   return ConstLength.getSExtValue() != 1;
11697 }
11698 
11699 // Return the expression of the base of the mappable expression or null if it
11700 // cannot be determined and do all the necessary checks to see if the expression
11701 // is valid as a standalone mappable expression. In the process, record all the
11702 // components of the expression.
11703 static Expr *CheckMapClauseExpressionBase(
11704     Sema &SemaRef, Expr *E,
11705     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11706     OpenMPClauseKind CKind, bool NoDiagnose) {
11707   SourceLocation ELoc = E->getExprLoc();
11708   SourceRange ERange = E->getSourceRange();
11709 
11710   // The base of elements of list in a map clause have to be either:
11711   //  - a reference to variable or field.
11712   //  - a member expression.
11713   //  - an array expression.
11714   //
11715   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11716   // reference to 'r'.
11717   //
11718   // If we have:
11719   //
11720   // struct SS {
11721   //   Bla S;
11722   //   foo() {
11723   //     #pragma omp target map (S.Arr[:12]);
11724   //   }
11725   // }
11726   //
11727   // We want to retrieve the member expression 'this->S';
11728 
11729   Expr *RelevantExpr = nullptr;
11730 
11731   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11732   //  If a list item is an array section, it must specify contiguous storage.
11733   //
11734   // For this restriction it is sufficient that we make sure only references
11735   // to variables or fields and array expressions, and that no array sections
11736   // exist except in the rightmost expression (unless they cover the whole
11737   // dimension of the array). E.g. these would be invalid:
11738   //
11739   //   r.ArrS[3:5].Arr[6:7]
11740   //
11741   //   r.ArrS[3:5].x
11742   //
11743   // but these would be valid:
11744   //   r.ArrS[3].Arr[6:7]
11745   //
11746   //   r.ArrS[3].x
11747 
11748   bool AllowUnitySizeArraySection = true;
11749   bool AllowWholeSizeArraySection = true;
11750 
11751   while (!RelevantExpr) {
11752     E = E->IgnoreParenImpCasts();
11753 
11754     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11755       if (!isa<VarDecl>(CurE->getDecl()))
11756         return nullptr;
11757 
11758       RelevantExpr = CurE;
11759 
11760       // If we got a reference to a declaration, we should not expect any array
11761       // section before that.
11762       AllowUnitySizeArraySection = false;
11763       AllowWholeSizeArraySection = false;
11764 
11765       // Record the component.
11766       CurComponents.emplace_back(CurE, CurE->getDecl());
11767     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11768       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11769 
11770       if (isa<CXXThisExpr>(BaseE))
11771         // We found a base expression: this->Val.
11772         RelevantExpr = CurE;
11773       else
11774         E = BaseE;
11775 
11776       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11777         if (!NoDiagnose) {
11778           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11779               << CurE->getSourceRange();
11780           return nullptr;
11781         }
11782         if (RelevantExpr)
11783           return nullptr;
11784         continue;
11785       }
11786 
11787       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11788 
11789       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11790       //  A bit-field cannot appear in a map clause.
11791       //
11792       if (FD->isBitField()) {
11793         if (!NoDiagnose) {
11794           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11795               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11796           return nullptr;
11797         }
11798         if (RelevantExpr)
11799           return nullptr;
11800         continue;
11801       }
11802 
11803       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11804       //  If the type of a list item is a reference to a type T then the type
11805       //  will be considered to be T for all purposes of this clause.
11806       QualType CurType = BaseE->getType().getNonReferenceType();
11807 
11808       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11809       //  A list item cannot be a variable that is a member of a structure with
11810       //  a union type.
11811       //
11812       if (auto *RT = CurType->getAs<RecordType>()) {
11813         if (RT->isUnionType()) {
11814           if (!NoDiagnose) {
11815             SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11816                 << CurE->getSourceRange();
11817             return nullptr;
11818           }
11819           continue;
11820         }
11821       }
11822 
11823       // If we got a member expression, we should not expect any array section
11824       // before that:
11825       //
11826       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11827       //  If a list item is an element of a structure, only the rightmost symbol
11828       //  of the variable reference can be an array section.
11829       //
11830       AllowUnitySizeArraySection = false;
11831       AllowWholeSizeArraySection = false;
11832 
11833       // Record the component.
11834       CurComponents.emplace_back(CurE, FD);
11835     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11836       E = CurE->getBase()->IgnoreParenImpCasts();
11837 
11838       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11839         if (!NoDiagnose) {
11840           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11841               << 0 << CurE->getSourceRange();
11842           return nullptr;
11843         }
11844         continue;
11845       }
11846 
11847       // If we got an array subscript that express the whole dimension we
11848       // can have any array expressions before. If it only expressing part of
11849       // the dimension, we can only have unitary-size array expressions.
11850       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11851                                                       E->getType()))
11852         AllowWholeSizeArraySection = false;
11853 
11854       // Record the component - we don't have any declaration associated.
11855       CurComponents.emplace_back(CurE, nullptr);
11856     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
11857       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
11858       E = CurE->getBase()->IgnoreParenImpCasts();
11859 
11860       QualType CurType =
11861           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11862 
11863       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11864       //  If the type of a list item is a reference to a type T then the type
11865       //  will be considered to be T for all purposes of this clause.
11866       if (CurType->isReferenceType())
11867         CurType = CurType->getPointeeType();
11868 
11869       bool IsPointer = CurType->isAnyPointerType();
11870 
11871       if (!IsPointer && !CurType->isArrayType()) {
11872         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11873             << 0 << CurE->getSourceRange();
11874         return nullptr;
11875       }
11876 
11877       bool NotWhole =
11878           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11879       bool NotUnity =
11880           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11881 
11882       if (AllowWholeSizeArraySection) {
11883         // Any array section is currently allowed. Allowing a whole size array
11884         // section implies allowing a unity array section as well.
11885         //
11886         // If this array section refers to the whole dimension we can still
11887         // accept other array sections before this one, except if the base is a
11888         // pointer. Otherwise, only unitary sections are accepted.
11889         if (NotWhole || IsPointer)
11890           AllowWholeSizeArraySection = false;
11891       } else if (AllowUnitySizeArraySection && NotUnity) {
11892         // A unity or whole array section is not allowed and that is not
11893         // compatible with the properties of the current array section.
11894         SemaRef.Diag(
11895             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11896             << CurE->getSourceRange();
11897         return nullptr;
11898       }
11899 
11900       // Record the component - we don't have any declaration associated.
11901       CurComponents.emplace_back(CurE, nullptr);
11902     } else {
11903       if (!NoDiagnose) {
11904         // If nothing else worked, this is not a valid map clause expression.
11905         SemaRef.Diag(
11906             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11907             << ERange;
11908       }
11909       return nullptr;
11910     }
11911   }
11912 
11913   return RelevantExpr;
11914 }
11915 
11916 // Return true if expression E associated with value VD has conflicts with other
11917 // map information.
11918 static bool CheckMapConflicts(
11919     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11920     bool CurrentRegionOnly,
11921     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11922     OpenMPClauseKind CKind) {
11923   assert(VD && E);
11924   SourceLocation ELoc = E->getExprLoc();
11925   SourceRange ERange = E->getSourceRange();
11926 
11927   // In order to easily check the conflicts we need to match each component of
11928   // the expression under test with the components of the expressions that are
11929   // already in the stack.
11930 
11931   assert(!CurComponents.empty() && "Map clause expression with no components!");
11932   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
11933          "Map clause expression with unexpected base!");
11934 
11935   // Variables to help detecting enclosing problems in data environment nests.
11936   bool IsEnclosedByDataEnvironmentExpr = false;
11937   const Expr *EnclosingExpr = nullptr;
11938 
11939   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11940       VD, CurrentRegionOnly,
11941       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
11942               StackComponents,
11943           OpenMPClauseKind) -> bool {
11944 
11945         assert(!StackComponents.empty() &&
11946                "Map clause expression with no components!");
11947         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
11948                "Map clause expression with unexpected base!");
11949 
11950         // The whole expression in the stack.
11951         auto *RE = StackComponents.front().getAssociatedExpression();
11952 
11953         // Expressions must start from the same base. Here we detect at which
11954         // point both expressions diverge from each other and see if we can
11955         // detect if the memory referred to both expressions is contiguous and
11956         // do not overlap.
11957         auto CI = CurComponents.rbegin();
11958         auto CE = CurComponents.rend();
11959         auto SI = StackComponents.rbegin();
11960         auto SE = StackComponents.rend();
11961         for (; CI != CE && SI != SE; ++CI, ++SI) {
11962 
11963           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11964           //  At most one list item can be an array item derived from a given
11965           //  variable in map clauses of the same construct.
11966           if (CurrentRegionOnly &&
11967               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11968                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11969               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11970                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11971             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
11972                          diag::err_omp_multiple_array_items_in_map_clause)
11973                 << CI->getAssociatedExpression()->getSourceRange();
11974             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11975                          diag::note_used_here)
11976                 << SI->getAssociatedExpression()->getSourceRange();
11977             return true;
11978           }
11979 
11980           // Do both expressions have the same kind?
11981           if (CI->getAssociatedExpression()->getStmtClass() !=
11982               SI->getAssociatedExpression()->getStmtClass())
11983             break;
11984 
11985           // Are we dealing with different variables/fields?
11986           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
11987             break;
11988         }
11989         // Check if the extra components of the expressions in the enclosing
11990         // data environment are redundant for the current base declaration.
11991         // If they are, the maps completely overlap, which is legal.
11992         for (; SI != SE; ++SI) {
11993           QualType Type;
11994           if (auto *ASE =
11995                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
11996             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
11997           } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11998                          SI->getAssociatedExpression())) {
11999             auto *E = OASE->getBase()->IgnoreParenImpCasts();
12000             Type =
12001                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12002           }
12003           if (Type.isNull() || Type->isAnyPointerType() ||
12004               CheckArrayExpressionDoesNotReferToWholeSize(
12005                   SemaRef, SI->getAssociatedExpression(), Type))
12006             break;
12007         }
12008 
12009         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12010         //  List items of map clauses in the same construct must not share
12011         //  original storage.
12012         //
12013         // If the expressions are exactly the same or one is a subset of the
12014         // other, it means they are sharing storage.
12015         if (CI == CE && SI == SE) {
12016           if (CurrentRegionOnly) {
12017             if (CKind == OMPC_map)
12018               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12019             else {
12020               assert(CKind == OMPC_to || CKind == OMPC_from);
12021               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12022                   << ERange;
12023             }
12024             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12025                 << RE->getSourceRange();
12026             return true;
12027           } else {
12028             // If we find the same expression in the enclosing data environment,
12029             // that is legal.
12030             IsEnclosedByDataEnvironmentExpr = true;
12031             return false;
12032           }
12033         }
12034 
12035         QualType DerivedType =
12036             std::prev(CI)->getAssociatedDeclaration()->getType();
12037         SourceLocation DerivedLoc =
12038             std::prev(CI)->getAssociatedExpression()->getExprLoc();
12039 
12040         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12041         //  If the type of a list item is a reference to a type T then the type
12042         //  will be considered to be T for all purposes of this clause.
12043         DerivedType = DerivedType.getNonReferenceType();
12044 
12045         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12046         //  A variable for which the type is pointer and an array section
12047         //  derived from that variable must not appear as list items of map
12048         //  clauses of the same construct.
12049         //
12050         // Also, cover one of the cases in:
12051         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12052         //  If any part of the original storage of a list item has corresponding
12053         //  storage in the device data environment, all of the original storage
12054         //  must have corresponding storage in the device data environment.
12055         //
12056         if (DerivedType->isAnyPointerType()) {
12057           if (CI == CE || SI == SE) {
12058             SemaRef.Diag(
12059                 DerivedLoc,
12060                 diag::err_omp_pointer_mapped_along_with_derived_section)
12061                 << DerivedLoc;
12062             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12063                 << RE->getSourceRange();
12064             return true;
12065           } else if (CI->getAssociatedExpression()->getStmtClass() !=
12066                          SI->getAssociatedExpression()->getStmtClass() ||
12067                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12068                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
12069             assert(CI != CE && SI != SE);
12070             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
12071                 << DerivedLoc;
12072             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12073                 << RE->getSourceRange();
12074             return true;
12075           }
12076         }
12077 
12078         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12079         //  List items of map clauses in the same construct must not share
12080         //  original storage.
12081         //
12082         // An expression is a subset of the other.
12083         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
12084           if (CKind == OMPC_map)
12085             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12086           else {
12087             assert(CKind == OMPC_to || CKind == OMPC_from);
12088             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12089                 << ERange;
12090           }
12091           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12092               << RE->getSourceRange();
12093           return true;
12094         }
12095 
12096         // The current expression uses the same base as other expression in the
12097         // data environment but does not contain it completely.
12098         if (!CurrentRegionOnly && SI != SE)
12099           EnclosingExpr = RE;
12100 
12101         // The current expression is a subset of the expression in the data
12102         // environment.
12103         IsEnclosedByDataEnvironmentExpr |=
12104             (!CurrentRegionOnly && CI != CE && SI == SE);
12105 
12106         return false;
12107       });
12108 
12109   if (CurrentRegionOnly)
12110     return FoundError;
12111 
12112   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12113   //  If any part of the original storage of a list item has corresponding
12114   //  storage in the device data environment, all of the original storage must
12115   //  have corresponding storage in the device data environment.
12116   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12117   //  If a list item is an element of a structure, and a different element of
12118   //  the structure has a corresponding list item in the device data environment
12119   //  prior to a task encountering the construct associated with the map clause,
12120   //  then the list item must also have a corresponding list item in the device
12121   //  data environment prior to the task encountering the construct.
12122   //
12123   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12124     SemaRef.Diag(ELoc,
12125                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12126         << ERange;
12127     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12128         << EnclosingExpr->getSourceRange();
12129     return true;
12130   }
12131 
12132   return FoundError;
12133 }
12134 
12135 namespace {
12136 // Utility struct that gathers all the related lists associated with a mappable
12137 // expression.
12138 struct MappableVarListInfo final {
12139   // The list of expressions.
12140   ArrayRef<Expr *> VarList;
12141   // The list of processed expressions.
12142   SmallVector<Expr *, 16> ProcessedVarList;
12143   // The mappble components for each expression.
12144   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12145   // The base declaration of the variable.
12146   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12147 
12148   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12149     // We have a list of components and base declarations for each entry in the
12150     // variable list.
12151     VarComponents.reserve(VarList.size());
12152     VarBaseDeclarations.reserve(VarList.size());
12153   }
12154 };
12155 }
12156 
12157 // Check the validity of the provided variable list for the provided clause kind
12158 // \a CKind. In the check process the valid expressions, and mappable expression
12159 // components and variables are extracted and used to fill \a Vars,
12160 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12161 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12162 static void
12163 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12164                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12165                             SourceLocation StartLoc,
12166                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12167                             bool IsMapTypeImplicit = false) {
12168   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12169   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12170          "Unexpected clause kind with mappable expressions!");
12171 
12172   // Keep track of the mappable components and base declarations in this clause.
12173   // Each entry in the list is going to have a list of components associated. We
12174   // record each set of the components so that we can build the clause later on.
12175   // In the end we should have the same amount of declarations and component
12176   // lists.
12177 
12178   for (auto &RE : MVLI.VarList) {
12179     assert(RE && "Null expr in omp to/from/map clause");
12180     SourceLocation ELoc = RE->getExprLoc();
12181 
12182     auto *VE = RE->IgnoreParenLValueCasts();
12183 
12184     if (VE->isValueDependent() || VE->isTypeDependent() ||
12185         VE->isInstantiationDependent() ||
12186         VE->containsUnexpandedParameterPack()) {
12187       // We can only analyze this information once the missing information is
12188       // resolved.
12189       MVLI.ProcessedVarList.push_back(RE);
12190       continue;
12191     }
12192 
12193     auto *SimpleExpr = RE->IgnoreParenCasts();
12194 
12195     if (!RE->IgnoreParenImpCasts()->isLValue()) {
12196       SemaRef.Diag(ELoc,
12197                    diag::err_omp_expected_named_var_member_or_array_expression)
12198           << RE->getSourceRange();
12199       continue;
12200     }
12201 
12202     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12203     ValueDecl *CurDeclaration = nullptr;
12204 
12205     // Obtain the array or member expression bases if required. Also, fill the
12206     // components array with all the components identified in the process.
12207     auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12208                                             CKind, /*NoDiagnose=*/false);
12209     if (!BE)
12210       continue;
12211 
12212     assert(!CurComponents.empty() &&
12213            "Invalid mappable expression information.");
12214 
12215     // For the following checks, we rely on the base declaration which is
12216     // expected to be associated with the last component. The declaration is
12217     // expected to be a variable or a field (if 'this' is being mapped).
12218     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12219     assert(CurDeclaration && "Null decl on map clause.");
12220     assert(
12221         CurDeclaration->isCanonicalDecl() &&
12222         "Expecting components to have associated only canonical declarations.");
12223 
12224     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12225     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
12226 
12227     assert((VD || FD) && "Only variables or fields are expected here!");
12228     (void)FD;
12229 
12230     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
12231     // threadprivate variables cannot appear in a map clause.
12232     // OpenMP 4.5 [2.10.5, target update Construct]
12233     // threadprivate variables cannot appear in a from clause.
12234     if (VD && DSAS->isThreadPrivate(VD)) {
12235       auto DVar = DSAS->getTopDSA(VD, false);
12236       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12237           << getOpenMPClauseName(CKind);
12238       ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
12239       continue;
12240     }
12241 
12242     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12243     //  A list item cannot appear in both a map clause and a data-sharing
12244     //  attribute clause on the same construct.
12245 
12246     // Check conflicts with other map clause expressions. We check the conflicts
12247     // with the current construct separately from the enclosing data
12248     // environment, because the restrictions are different. We only have to
12249     // check conflicts across regions for the map clauses.
12250     if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12251                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
12252       break;
12253     if (CKind == OMPC_map &&
12254         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12255                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
12256       break;
12257 
12258     // OpenMP 4.5 [2.10.5, target update Construct]
12259     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12260     //  If the type of a list item is a reference to a type T then the type will
12261     //  be considered to be T for all purposes of this clause.
12262     QualType Type = CurDeclaration->getType().getNonReferenceType();
12263 
12264     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12265     // A list item in a to or from clause must have a mappable type.
12266     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12267     //  A list item must have a mappable type.
12268     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12269                            DSAS, Type))
12270       continue;
12271 
12272     if (CKind == OMPC_map) {
12273       // target enter data
12274       // OpenMP [2.10.2, Restrictions, p. 99]
12275       // A map-type must be specified in all map clauses and must be either
12276       // to or alloc.
12277       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12278       if (DKind == OMPD_target_enter_data &&
12279           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12280         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12281             << (IsMapTypeImplicit ? 1 : 0)
12282             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12283             << getOpenMPDirectiveName(DKind);
12284         continue;
12285       }
12286 
12287       // target exit_data
12288       // OpenMP [2.10.3, Restrictions, p. 102]
12289       // A map-type must be specified in all map clauses and must be either
12290       // from, release, or delete.
12291       if (DKind == OMPD_target_exit_data &&
12292           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12293             MapType == OMPC_MAP_delete)) {
12294         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12295             << (IsMapTypeImplicit ? 1 : 0)
12296             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12297             << getOpenMPDirectiveName(DKind);
12298         continue;
12299       }
12300 
12301       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12302       // A list item cannot appear in both a map clause and a data-sharing
12303       // attribute clause on the same construct
12304       if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
12305            DKind == OMPD_target_teams_distribute ||
12306            DKind == OMPD_target_teams_distribute_parallel_for ||
12307            DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12308            DKind == OMPD_target_teams_distribute_simd) && VD) {
12309         auto DVar = DSAS->getTopDSA(VD, false);
12310         if (isOpenMPPrivate(DVar.CKind)) {
12311           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12312               << getOpenMPClauseName(DVar.CKind)
12313               << getOpenMPClauseName(OMPC_map)
12314               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12315           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12316           continue;
12317         }
12318       }
12319     }
12320 
12321     // Save the current expression.
12322     MVLI.ProcessedVarList.push_back(RE);
12323 
12324     // Store the components in the stack so that they can be used to check
12325     // against other clauses later on.
12326     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12327                                           /*WhereFoundClauseKind=*/OMPC_map);
12328 
12329     // Save the components and declaration to create the clause. For purposes of
12330     // the clause creation, any component list that has has base 'this' uses
12331     // null as base declaration.
12332     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12333     MVLI.VarComponents.back().append(CurComponents.begin(),
12334                                      CurComponents.end());
12335     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12336                                                            : CurDeclaration);
12337   }
12338 }
12339 
12340 OMPClause *
12341 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12342                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12343                            SourceLocation MapLoc, SourceLocation ColonLoc,
12344                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12345                            SourceLocation LParenLoc, SourceLocation EndLoc) {
12346   MappableVarListInfo MVLI(VarList);
12347   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12348                               MapType, IsMapTypeImplicit);
12349 
12350   // We need to produce a map clause even if we don't have variables so that
12351   // other diagnostics related with non-existing map clauses are accurate.
12352   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12353                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12354                               MVLI.VarComponents, MapTypeModifier, MapType,
12355                               IsMapTypeImplicit, MapLoc);
12356 }
12357 
12358 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12359                                                TypeResult ParsedType) {
12360   assert(ParsedType.isUsable());
12361 
12362   QualType ReductionType = GetTypeFromParser(ParsedType.get());
12363   if (ReductionType.isNull())
12364     return QualType();
12365 
12366   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12367   // A type name in a declare reduction directive cannot be a function type, an
12368   // array type, a reference type, or a type qualified with const, volatile or
12369   // restrict.
12370   if (ReductionType.hasQualifiers()) {
12371     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12372     return QualType();
12373   }
12374 
12375   if (ReductionType->isFunctionType()) {
12376     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12377     return QualType();
12378   }
12379   if (ReductionType->isReferenceType()) {
12380     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12381     return QualType();
12382   }
12383   if (ReductionType->isArrayType()) {
12384     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12385     return QualType();
12386   }
12387   return ReductionType;
12388 }
12389 
12390 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12391     Scope *S, DeclContext *DC, DeclarationName Name,
12392     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12393     AccessSpecifier AS, Decl *PrevDeclInScope) {
12394   SmallVector<Decl *, 8> Decls;
12395   Decls.reserve(ReductionTypes.size());
12396 
12397   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
12398                       forRedeclarationInCurContext());
12399   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12400   // A reduction-identifier may not be re-declared in the current scope for the
12401   // same type or for a type that is compatible according to the base language
12402   // rules.
12403   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12404   OMPDeclareReductionDecl *PrevDRD = nullptr;
12405   bool InCompoundScope = true;
12406   if (S != nullptr) {
12407     // Find previous declaration with the same name not referenced in other
12408     // declarations.
12409     FunctionScopeInfo *ParentFn = getEnclosingFunction();
12410     InCompoundScope =
12411         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12412     LookupName(Lookup, S);
12413     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12414                          /*AllowInlineNamespace=*/false);
12415     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12416     auto Filter = Lookup.makeFilter();
12417     while (Filter.hasNext()) {
12418       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12419       if (InCompoundScope) {
12420         auto I = UsedAsPrevious.find(PrevDecl);
12421         if (I == UsedAsPrevious.end())
12422           UsedAsPrevious[PrevDecl] = false;
12423         if (auto *D = PrevDecl->getPrevDeclInScope())
12424           UsedAsPrevious[D] = true;
12425       }
12426       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12427           PrevDecl->getLocation();
12428     }
12429     Filter.done();
12430     if (InCompoundScope) {
12431       for (auto &PrevData : UsedAsPrevious) {
12432         if (!PrevData.second) {
12433           PrevDRD = PrevData.first;
12434           break;
12435         }
12436       }
12437     }
12438   } else if (PrevDeclInScope != nullptr) {
12439     auto *PrevDRDInScope = PrevDRD =
12440         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12441     do {
12442       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12443           PrevDRDInScope->getLocation();
12444       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12445     } while (PrevDRDInScope != nullptr);
12446   }
12447   for (auto &TyData : ReductionTypes) {
12448     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12449     bool Invalid = false;
12450     if (I != PreviousRedeclTypes.end()) {
12451       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12452           << TyData.first;
12453       Diag(I->second, diag::note_previous_definition);
12454       Invalid = true;
12455     }
12456     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12457     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12458                                                 Name, TyData.first, PrevDRD);
12459     DC->addDecl(DRD);
12460     DRD->setAccess(AS);
12461     Decls.push_back(DRD);
12462     if (Invalid)
12463       DRD->setInvalidDecl();
12464     else
12465       PrevDRD = DRD;
12466   }
12467 
12468   return DeclGroupPtrTy::make(
12469       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12470 }
12471 
12472 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12473   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12474 
12475   // Enter new function scope.
12476   PushFunctionScope();
12477   setFunctionHasBranchProtectedScope();
12478   getCurFunction()->setHasOMPDeclareReductionCombiner();
12479 
12480   if (S != nullptr)
12481     PushDeclContext(S, DRD);
12482   else
12483     CurContext = DRD;
12484 
12485   PushExpressionEvaluationContext(
12486       ExpressionEvaluationContext::PotentiallyEvaluated);
12487 
12488   QualType ReductionType = DRD->getType();
12489   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12490   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12491   // uses semantics of argument handles by value, but it should be passed by
12492   // reference. C lang does not support references, so pass all parameters as
12493   // pointers.
12494   // Create 'T omp_in;' variable.
12495   auto *OmpInParm =
12496       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
12497   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12498   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12499   // uses semantics of argument handles by value, but it should be passed by
12500   // reference. C lang does not support references, so pass all parameters as
12501   // pointers.
12502   // Create 'T omp_out;' variable.
12503   auto *OmpOutParm =
12504       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12505   if (S != nullptr) {
12506     PushOnScopeChains(OmpInParm, S);
12507     PushOnScopeChains(OmpOutParm, S);
12508   } else {
12509     DRD->addDecl(OmpInParm);
12510     DRD->addDecl(OmpOutParm);
12511   }
12512 }
12513 
12514 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12515   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12516   DiscardCleanupsInEvaluationContext();
12517   PopExpressionEvaluationContext();
12518 
12519   PopDeclContext();
12520   PopFunctionScopeInfo();
12521 
12522   if (Combiner != nullptr)
12523     DRD->setCombiner(Combiner);
12524   else
12525     DRD->setInvalidDecl();
12526 }
12527 
12528 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
12529   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12530 
12531   // Enter new function scope.
12532   PushFunctionScope();
12533   setFunctionHasBranchProtectedScope();
12534 
12535   if (S != nullptr)
12536     PushDeclContext(S, DRD);
12537   else
12538     CurContext = DRD;
12539 
12540   PushExpressionEvaluationContext(
12541       ExpressionEvaluationContext::PotentiallyEvaluated);
12542 
12543   QualType ReductionType = DRD->getType();
12544   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12545   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12546   // uses semantics of argument handles by value, but it should be passed by
12547   // reference. C lang does not support references, so pass all parameters as
12548   // pointers.
12549   // Create 'T omp_priv;' variable.
12550   auto *OmpPrivParm =
12551       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
12552   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12553   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12554   // uses semantics of argument handles by value, but it should be passed by
12555   // reference. C lang does not support references, so pass all parameters as
12556   // pointers.
12557   // Create 'T omp_orig;' variable.
12558   auto *OmpOrigParm =
12559       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
12560   if (S != nullptr) {
12561     PushOnScopeChains(OmpPrivParm, S);
12562     PushOnScopeChains(OmpOrigParm, S);
12563   } else {
12564     DRD->addDecl(OmpPrivParm);
12565     DRD->addDecl(OmpOrigParm);
12566   }
12567   return OmpPrivParm;
12568 }
12569 
12570 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12571                                                      VarDecl *OmpPrivParm) {
12572   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12573   DiscardCleanupsInEvaluationContext();
12574   PopExpressionEvaluationContext();
12575 
12576   PopDeclContext();
12577   PopFunctionScopeInfo();
12578 
12579   if (Initializer != nullptr) {
12580     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12581   } else if (OmpPrivParm->hasInit()) {
12582     DRD->setInitializer(OmpPrivParm->getInit(),
12583                         OmpPrivParm->isDirectInit()
12584                             ? OMPDeclareReductionDecl::DirectInit
12585                             : OMPDeclareReductionDecl::CopyInit);
12586   } else {
12587     DRD->setInvalidDecl();
12588   }
12589 }
12590 
12591 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12592     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12593   for (auto *D : DeclReductions.get()) {
12594     if (IsValid) {
12595       auto *DRD = cast<OMPDeclareReductionDecl>(D);
12596       if (S != nullptr)
12597         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12598     } else
12599       D->setInvalidDecl();
12600   }
12601   return DeclReductions;
12602 }
12603 
12604 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
12605                                            SourceLocation StartLoc,
12606                                            SourceLocation LParenLoc,
12607                                            SourceLocation EndLoc) {
12608   Expr *ValExpr = NumTeams;
12609   Stmt *HelperValStmt = nullptr;
12610 
12611   // OpenMP [teams Constrcut, Restrictions]
12612   // The num_teams expression must evaluate to a positive integer value.
12613   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12614                                  /*StrictlyPositive=*/true))
12615     return nullptr;
12616 
12617   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12618   OpenMPDirectiveKind CaptureRegion =
12619       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12620   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12621     ValExpr = MakeFullExpr(ValExpr).get();
12622     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12623     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12624     HelperValStmt = buildPreInits(Context, Captures);
12625   }
12626 
12627   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12628                                          StartLoc, LParenLoc, EndLoc);
12629 }
12630 
12631 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12632                                               SourceLocation StartLoc,
12633                                               SourceLocation LParenLoc,
12634                                               SourceLocation EndLoc) {
12635   Expr *ValExpr = ThreadLimit;
12636   Stmt *HelperValStmt = nullptr;
12637 
12638   // OpenMP [teams Constrcut, Restrictions]
12639   // The thread_limit expression must evaluate to a positive integer value.
12640   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12641                                  /*StrictlyPositive=*/true))
12642     return nullptr;
12643 
12644   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12645   OpenMPDirectiveKind CaptureRegion =
12646       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12647   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12648     ValExpr = MakeFullExpr(ValExpr).get();
12649     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12650     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12651     HelperValStmt = buildPreInits(Context, Captures);
12652   }
12653 
12654   return new (Context) OMPThreadLimitClause(
12655       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12656 }
12657 
12658 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12659                                            SourceLocation StartLoc,
12660                                            SourceLocation LParenLoc,
12661                                            SourceLocation EndLoc) {
12662   Expr *ValExpr = Priority;
12663 
12664   // OpenMP [2.9.1, task Constrcut]
12665   // The priority-value is a non-negative numerical scalar expression.
12666   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12667                                  /*StrictlyPositive=*/false))
12668     return nullptr;
12669 
12670   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12671 }
12672 
12673 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12674                                             SourceLocation StartLoc,
12675                                             SourceLocation LParenLoc,
12676                                             SourceLocation EndLoc) {
12677   Expr *ValExpr = Grainsize;
12678 
12679   // OpenMP [2.9.2, taskloop Constrcut]
12680   // The parameter of the grainsize clause must be a positive integer
12681   // expression.
12682   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12683                                  /*StrictlyPositive=*/true))
12684     return nullptr;
12685 
12686   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12687 }
12688 
12689 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12690                                            SourceLocation StartLoc,
12691                                            SourceLocation LParenLoc,
12692                                            SourceLocation EndLoc) {
12693   Expr *ValExpr = NumTasks;
12694 
12695   // OpenMP [2.9.2, taskloop Constrcut]
12696   // The parameter of the num_tasks clause must be a positive integer
12697   // expression.
12698   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12699                                  /*StrictlyPositive=*/true))
12700     return nullptr;
12701 
12702   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12703 }
12704 
12705 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12706                                        SourceLocation LParenLoc,
12707                                        SourceLocation EndLoc) {
12708   // OpenMP [2.13.2, critical construct, Description]
12709   // ... where hint-expression is an integer constant expression that evaluates
12710   // to a valid lock hint.
12711   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12712   if (HintExpr.isInvalid())
12713     return nullptr;
12714   return new (Context)
12715       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12716 }
12717 
12718 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12719     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12720     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12721     SourceLocation EndLoc) {
12722   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12723     std::string Values;
12724     Values += "'";
12725     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12726     Values += "'";
12727     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12728         << Values << getOpenMPClauseName(OMPC_dist_schedule);
12729     return nullptr;
12730   }
12731   Expr *ValExpr = ChunkSize;
12732   Stmt *HelperValStmt = nullptr;
12733   if (ChunkSize) {
12734     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12735         !ChunkSize->isInstantiationDependent() &&
12736         !ChunkSize->containsUnexpandedParameterPack()) {
12737       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12738       ExprResult Val =
12739           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12740       if (Val.isInvalid())
12741         return nullptr;
12742 
12743       ValExpr = Val.get();
12744 
12745       // OpenMP [2.7.1, Restrictions]
12746       //  chunk_size must be a loop invariant integer expression with a positive
12747       //  value.
12748       llvm::APSInt Result;
12749       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12750         if (Result.isSigned() && !Result.isStrictlyPositive()) {
12751           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12752               << "dist_schedule" << ChunkSize->getSourceRange();
12753           return nullptr;
12754         }
12755       } else if (getOpenMPCaptureRegionForClause(
12756                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12757                      OMPD_unknown &&
12758                  !CurContext->isDependentContext()) {
12759         ValExpr = MakeFullExpr(ValExpr).get();
12760         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12761         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12762         HelperValStmt = buildPreInits(Context, Captures);
12763       }
12764     }
12765   }
12766 
12767   return new (Context)
12768       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
12769                             Kind, ValExpr, HelperValStmt);
12770 }
12771 
12772 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12773     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12774     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12775     SourceLocation KindLoc, SourceLocation EndLoc) {
12776   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
12777   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
12778     std::string Value;
12779     SourceLocation Loc;
12780     Value += "'";
12781     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12782       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12783                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
12784       Loc = MLoc;
12785     } else {
12786       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12787                                              OMPC_DEFAULTMAP_scalar);
12788       Loc = KindLoc;
12789     }
12790     Value += "'";
12791     Diag(Loc, diag::err_omp_unexpected_clause_value)
12792         << Value << getOpenMPClauseName(OMPC_defaultmap);
12793     return nullptr;
12794   }
12795   DSAStack->setDefaultDMAToFromScalar(StartLoc);
12796 
12797   return new (Context)
12798       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12799 }
12800 
12801 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12802   DeclContext *CurLexicalContext = getCurLexicalContext();
12803   if (!CurLexicalContext->isFileContext() &&
12804       !CurLexicalContext->isExternCContext() &&
12805       !CurLexicalContext->isExternCXXContext() &&
12806       !isa<CXXRecordDecl>(CurLexicalContext) &&
12807       !isa<ClassTemplateDecl>(CurLexicalContext) &&
12808       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12809       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
12810     Diag(Loc, diag::err_omp_region_not_file_context);
12811     return false;
12812   }
12813   if (IsInOpenMPDeclareTargetContext) {
12814     Diag(Loc, diag::err_omp_enclosed_declare_target);
12815     return false;
12816   }
12817 
12818   IsInOpenMPDeclareTargetContext = true;
12819   return true;
12820 }
12821 
12822 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12823   assert(IsInOpenMPDeclareTargetContext &&
12824          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12825 
12826   IsInOpenMPDeclareTargetContext = false;
12827 }
12828 
12829 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12830                                         CXXScopeSpec &ScopeSpec,
12831                                         const DeclarationNameInfo &Id,
12832                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
12833                                         NamedDeclSetType &SameDirectiveDecls) {
12834   LookupResult Lookup(*this, Id, LookupOrdinaryName);
12835   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12836 
12837   if (Lookup.isAmbiguous())
12838     return;
12839   Lookup.suppressDiagnostics();
12840 
12841   if (!Lookup.isSingleResult()) {
12842     if (TypoCorrection Corrected =
12843             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12844                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12845                         CTK_ErrorRecovery)) {
12846       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12847                                   << Id.getName());
12848       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12849       return;
12850     }
12851 
12852     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12853     return;
12854   }
12855 
12856   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12857   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12858     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12859       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12860 
12861     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12862       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12863       ND->addAttr(A);
12864       if (ASTMutationListener *ML = Context.getASTMutationListener())
12865         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12866       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
12867     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12868       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12869           << Id.getName();
12870     }
12871   } else
12872     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12873 }
12874 
12875 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12876                                      Sema &SemaRef, Decl *D) {
12877   if (!D)
12878     return;
12879   const Decl *LD = nullptr;
12880   if (isa<TagDecl>(D)) {
12881     LD = cast<TagDecl>(D)->getDefinition();
12882   } else if (isa<VarDecl>(D)) {
12883     LD = cast<VarDecl>(D)->getDefinition();
12884 
12885     // If this is an implicit variable that is legal and we do not need to do
12886     // anything.
12887     if (cast<VarDecl>(D)->isImplicit()) {
12888       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12889           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12890       D->addAttr(A);
12891       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12892         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12893       return;
12894     }
12895   } else if (auto *F = dyn_cast<FunctionDecl>(D)) {
12896     const FunctionDecl *FD = nullptr;
12897     if (cast<FunctionDecl>(D)->hasBody(FD)) {
12898       LD = FD;
12899       // If the definition is associated with the current declaration in the
12900       // target region (it can be e.g. a lambda) that is legal and we do not
12901       // need to do anything else.
12902       if (LD == D) {
12903         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12904             SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12905         D->addAttr(A);
12906         if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12907           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12908         return;
12909       }
12910     } else if (F->isFunctionTemplateSpecialization() &&
12911                F->getTemplateSpecializationKind() ==
12912                    TSK_ImplicitInstantiation) {
12913       // Check if the function is implicitly instantiated from the template
12914       // defined in the declare target region.
12915       const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12916       if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12917         return;
12918     }
12919   }
12920   if (!LD)
12921     LD = D;
12922   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12923       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12924     // Outlined declaration is not declared target.
12925     if (LD->isOutOfLine()) {
12926       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12927       SemaRef.Diag(SL, diag::note_used_here) << SR;
12928     } else {
12929       const DeclContext *DC = LD->getDeclContext();
12930       while (DC) {
12931         if (isa<FunctionDecl>(DC) &&
12932             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12933           break;
12934         DC = DC->getParent();
12935       }
12936       if (DC)
12937         return;
12938 
12939       // Is not declared in target context.
12940       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12941       SemaRef.Diag(SL, diag::note_used_here) << SR;
12942     }
12943     // Mark decl as declared target to prevent further diagnostic.
12944     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12945         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12946     D->addAttr(A);
12947     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12948       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12949   }
12950 }
12951 
12952 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12953                                    Sema &SemaRef, DSAStackTy *Stack,
12954                                    ValueDecl *VD) {
12955   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12956     return true;
12957   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
12958                          /*FullCheck=*/false))
12959     return false;
12960   return true;
12961 }
12962 
12963 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12964                                             SourceLocation IdLoc) {
12965   if (!D || D->isInvalidDecl())
12966     return;
12967   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12968   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12969   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12970   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12971     if (DSAStack->isThreadPrivate(VD)) {
12972       Diag(SL, diag::err_omp_threadprivate_in_target);
12973       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12974       return;
12975     }
12976   }
12977   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12978     // Problem if any with var declared with incomplete type will be reported
12979     // as normal, so no need to check it here.
12980     if ((E || !VD->getType()->isIncompleteType()) &&
12981         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12982       // Mark decl as declared target to prevent further diagnostic.
12983       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
12984           isa<FunctionTemplateDecl>(VD)) {
12985         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12986             Context, OMPDeclareTargetDeclAttr::MT_To);
12987         VD->addAttr(A);
12988         if (ASTMutationListener *ML = Context.getASTMutationListener())
12989           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
12990       }
12991       return;
12992     }
12993   }
12994   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12995     if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12996         (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12997          OMPDeclareTargetDeclAttr::MT_Link)) {
12998       assert(IdLoc.isValid() && "Source location is expected");
12999       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13000       Diag(FD->getLocation(), diag::note_defined_here) << FD;
13001       return;
13002     }
13003   }
13004   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
13005     if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13006         (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13007          OMPDeclareTargetDeclAttr::MT_Link)) {
13008       assert(IdLoc.isValid() && "Source location is expected");
13009       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13010       Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
13011       return;
13012     }
13013   }
13014   if (!E) {
13015     // Checking declaration inside declare target region.
13016     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
13017         (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13018          isa<FunctionTemplateDecl>(D))) {
13019       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13020           Context, OMPDeclareTargetDeclAttr::MT_To);
13021       D->addAttr(A);
13022       if (ASTMutationListener *ML = Context.getASTMutationListener())
13023         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13024     }
13025     return;
13026   }
13027   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13028 }
13029 
13030 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13031                                      SourceLocation StartLoc,
13032                                      SourceLocation LParenLoc,
13033                                      SourceLocation EndLoc) {
13034   MappableVarListInfo MVLI(VarList);
13035   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13036   if (MVLI.ProcessedVarList.empty())
13037     return nullptr;
13038 
13039   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13040                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13041                              MVLI.VarComponents);
13042 }
13043 
13044 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13045                                        SourceLocation StartLoc,
13046                                        SourceLocation LParenLoc,
13047                                        SourceLocation EndLoc) {
13048   MappableVarListInfo MVLI(VarList);
13049   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13050   if (MVLI.ProcessedVarList.empty())
13051     return nullptr;
13052 
13053   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13054                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13055                                MVLI.VarComponents);
13056 }
13057 
13058 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13059                                                SourceLocation StartLoc,
13060                                                SourceLocation LParenLoc,
13061                                                SourceLocation EndLoc) {
13062   MappableVarListInfo MVLI(VarList);
13063   SmallVector<Expr *, 8> PrivateCopies;
13064   SmallVector<Expr *, 8> Inits;
13065 
13066   for (auto &RefExpr : VarList) {
13067     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13068     SourceLocation ELoc;
13069     SourceRange ERange;
13070     Expr *SimpleRefExpr = RefExpr;
13071     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13072     if (Res.second) {
13073       // It will be analyzed later.
13074       MVLI.ProcessedVarList.push_back(RefExpr);
13075       PrivateCopies.push_back(nullptr);
13076       Inits.push_back(nullptr);
13077     }
13078     ValueDecl *D = Res.first;
13079     if (!D)
13080       continue;
13081 
13082     QualType Type = D->getType();
13083     Type = Type.getNonReferenceType().getUnqualifiedType();
13084 
13085     auto *VD = dyn_cast<VarDecl>(D);
13086 
13087     // Item should be a pointer or reference to pointer.
13088     if (!Type->isPointerType()) {
13089       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13090           << 0 << RefExpr->getSourceRange();
13091       continue;
13092     }
13093 
13094     // Build the private variable and the expression that refers to it.
13095     auto VDPrivate =
13096         buildVarDecl(*this, ELoc, Type, D->getName(),
13097                      D->hasAttrs() ? &D->getAttrs() : nullptr,
13098                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13099     if (VDPrivate->isInvalidDecl())
13100       continue;
13101 
13102     CurContext->addDecl(VDPrivate);
13103     auto VDPrivateRefExpr = buildDeclRefExpr(
13104         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13105 
13106     // Add temporary variable to initialize the private copy of the pointer.
13107     auto *VDInit =
13108         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13109     auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13110                                            RefExpr->getExprLoc());
13111     AddInitializerToDecl(VDPrivate,
13112                          DefaultLvalueConversion(VDInitRefExpr).get(),
13113                          /*DirectInit=*/false);
13114 
13115     // If required, build a capture to implement the privatization initialized
13116     // with the current list item value.
13117     DeclRefExpr *Ref = nullptr;
13118     if (!VD)
13119       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13120     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13121     PrivateCopies.push_back(VDPrivateRefExpr);
13122     Inits.push_back(VDInitRefExpr);
13123 
13124     // We need to add a data sharing attribute for this variable to make sure it
13125     // is correctly captured. A variable that shows up in a use_device_ptr has
13126     // similar properties of a first private variable.
13127     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13128 
13129     // Create a mappable component for the list item. List items in this clause
13130     // only need a component.
13131     MVLI.VarBaseDeclarations.push_back(D);
13132     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13133     MVLI.VarComponents.back().push_back(
13134         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
13135   }
13136 
13137   if (MVLI.ProcessedVarList.empty())
13138     return nullptr;
13139 
13140   return OMPUseDevicePtrClause::Create(
13141       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13142       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
13143 }
13144 
13145 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13146                                               SourceLocation StartLoc,
13147                                               SourceLocation LParenLoc,
13148                                               SourceLocation EndLoc) {
13149   MappableVarListInfo MVLI(VarList);
13150   for (auto &RefExpr : VarList) {
13151     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
13152     SourceLocation ELoc;
13153     SourceRange ERange;
13154     Expr *SimpleRefExpr = RefExpr;
13155     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13156     if (Res.second) {
13157       // It will be analyzed later.
13158       MVLI.ProcessedVarList.push_back(RefExpr);
13159     }
13160     ValueDecl *D = Res.first;
13161     if (!D)
13162       continue;
13163 
13164     QualType Type = D->getType();
13165     // item should be a pointer or array or reference to pointer or array
13166     if (!Type.getNonReferenceType()->isPointerType() &&
13167         !Type.getNonReferenceType()->isArrayType()) {
13168       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13169           << 0 << RefExpr->getSourceRange();
13170       continue;
13171     }
13172 
13173     // Check if the declaration in the clause does not show up in any data
13174     // sharing attribute.
13175     auto DVar = DSAStack->getTopDSA(D, false);
13176     if (isOpenMPPrivate(DVar.CKind)) {
13177       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13178           << getOpenMPClauseName(DVar.CKind)
13179           << getOpenMPClauseName(OMPC_is_device_ptr)
13180           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13181       ReportOriginalDSA(*this, DSAStack, D, DVar);
13182       continue;
13183     }
13184 
13185     Expr *ConflictExpr;
13186     if (DSAStack->checkMappableExprComponentListsForDecl(
13187             D, /*CurrentRegionOnly=*/true,
13188             [&ConflictExpr](
13189                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13190                 OpenMPClauseKind) -> bool {
13191               ConflictExpr = R.front().getAssociatedExpression();
13192               return true;
13193             })) {
13194       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13195       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13196           << ConflictExpr->getSourceRange();
13197       continue;
13198     }
13199 
13200     // Store the components in the stack so that they can be used to check
13201     // against other clauses later on.
13202     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13203     DSAStack->addMappableExpressionComponents(
13204         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13205 
13206     // Record the expression we've just processed.
13207     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13208 
13209     // Create a mappable component for the list item. List items in this clause
13210     // only need a component. We use a null declaration to signal fields in
13211     // 'this'.
13212     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13213             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13214            "Unexpected device pointer expression!");
13215     MVLI.VarBaseDeclarations.push_back(
13216         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13217     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13218     MVLI.VarComponents.back().push_back(MC);
13219   }
13220 
13221   if (MVLI.ProcessedVarList.empty())
13222     return nullptr;
13223 
13224   return OMPIsDevicePtrClause::Create(
13225       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13226       MVLI.VarBaseDeclarations, MVLI.VarComponents);
13227 }
13228