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   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
182 
183   bool isForceVarCapturing() const { return ForceCapturing; }
184   void setForceVarCapturing(bool V) { ForceCapturing = V; }
185 
186   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
187             Scope *CurScope, SourceLocation Loc) {
188     if (Stack.empty() ||
189         Stack.back().second != CurrentNonCapturingFunctionScope)
190       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
191     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
192     Stack.back().first.back().DefaultAttrLoc = Loc;
193   }
194 
195   void pop() {
196     assert(!Stack.back().first.empty() &&
197            "Data-sharing attributes stack is empty!");
198     Stack.back().first.pop_back();
199   }
200 
201   /// Start new OpenMP region stack in new non-capturing function.
202   void pushFunction() {
203     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
204     assert(!isa<CapturingScopeInfo>(CurFnScope));
205     CurrentNonCapturingFunctionScope = CurFnScope;
206   }
207   /// Pop region stack for non-capturing function.
208   void popFunction(const FunctionScopeInfo *OldFSI) {
209     if (!Stack.empty() && Stack.back().second == OldFSI) {
210       assert(Stack.back().first.empty());
211       Stack.pop_back();
212     }
213     CurrentNonCapturingFunctionScope = nullptr;
214     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
215       if (!isa<CapturingScopeInfo>(FSI)) {
216         CurrentNonCapturingFunctionScope = FSI;
217         break;
218       }
219     }
220   }
221 
222   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
223     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
224   }
225   const std::pair<OMPCriticalDirective *, llvm::APSInt>
226   getCriticalWithHint(const DeclarationNameInfo &Name) const {
227     auto I = Criticals.find(Name.getAsString());
228     if (I != Criticals.end())
229       return I->second;
230     return std::make_pair(nullptr, llvm::APSInt());
231   }
232   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
233   /// add it and return NULL; otherwise return previous occurrence's expression
234   /// for diagnostics.
235   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
236 
237   /// \brief Register specified variable as loop control variable.
238   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
239   /// \brief Check if the specified variable is a loop control variable for
240   /// current region.
241   /// \return The index of the loop control variable in the list of associated
242   /// for-loops (from outer to inner).
243   LCDeclInfo isLoopControlVariable(ValueDecl *D);
244   /// \brief Check if the specified variable is a loop control variable for
245   /// parent region.
246   /// \return The index of the loop control variable in the list of associated
247   /// for-loops (from outer to inner).
248   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
249   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
250   /// parent directive.
251   ValueDecl *getParentLoopControlVariable(unsigned I);
252 
253   /// \brief Adds explicit data sharing attribute to the specified declaration.
254   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
255               DeclRefExpr *PrivateCopy = nullptr);
256 
257   /// Adds additional information for the reduction items with the reduction id
258   /// represented as an operator.
259   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
260                                  BinaryOperatorKind BOK);
261   /// Adds additional information for the reduction items with the reduction id
262   /// represented as reduction identifier.
263   void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264                                  const Expr *ReductionRef);
265   /// Returns the location and reduction operation from the innermost parent
266   /// region for the given \p D.
267   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
268                                               BinaryOperatorKind &BOK,
269                                               Expr *&TaskgroupDescriptor);
270   /// Returns the location and reduction operation from the innermost parent
271   /// region for the given \p D.
272   DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
273                                               const Expr *&ReductionRef,
274                                               Expr *&TaskgroupDescriptor);
275   /// Return reduction reference expression for the current taskgroup.
276   Expr *getTaskgroupReductionRef() const {
277     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
278            "taskgroup reference expression requested for non taskgroup "
279            "directive.");
280     return Stack.back().first.back().TaskgroupReductionRef;
281   }
282   /// Checks if the given \p VD declaration is actually a taskgroup reduction
283   /// descriptor variable at the \p Level of OpenMP regions.
284   bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
285     return Stack.back().first[Level].TaskgroupReductionRef &&
286            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
287                    ->getDecl() == VD;
288   }
289 
290   /// \brief Returns data sharing attributes from top of the stack for the
291   /// specified declaration.
292   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
293   /// \brief Returns data-sharing attributes for the specified declaration.
294   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
295   /// \brief Checks if the specified variables has data-sharing attributes which
296   /// match specified \a CPred predicate in any directive which matches \a DPred
297   /// predicate.
298   DSAVarData hasDSA(ValueDecl *D,
299                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
300                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
301                     bool FromParent);
302   /// \brief Checks if the specified variables has data-sharing attributes which
303   /// match specified \a CPred predicate in any innermost directive which
304   /// matches \a DPred predicate.
305   DSAVarData
306   hasInnermostDSA(ValueDecl *D,
307                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
308                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
309                   bool FromParent);
310   /// \brief Checks if the specified variables has explicit data-sharing
311   /// attributes which match specified \a CPred predicate at the specified
312   /// OpenMP region.
313   bool hasExplicitDSA(ValueDecl *D,
314                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
315                       unsigned Level, bool NotLastprivate = false);
316 
317   /// \brief Returns true if the directive at level \Level matches in the
318   /// specified \a DPred predicate.
319   bool hasExplicitDirective(
320       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
321       unsigned Level);
322 
323   /// \brief Finds a directive which matches specified \a DPred predicate.
324   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
325                                                   const DeclarationNameInfo &,
326                                                   SourceLocation)> &DPred,
327                     bool FromParent);
328 
329   /// \brief Returns currently analyzed directive.
330   OpenMPDirectiveKind getCurrentDirective() const {
331     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
332   }
333   /// \brief Returns directive kind at specified level.
334   OpenMPDirectiveKind getDirective(unsigned Level) const {
335     assert(!isStackEmpty() && "No directive at specified level.");
336     return Stack.back().first[Level].Directive;
337   }
338   /// \brief Returns parent directive.
339   OpenMPDirectiveKind getParentDirective() const {
340     if (isStackEmpty() || Stack.back().first.size() == 1)
341       return OMPD_unknown;
342     return std::next(Stack.back().first.rbegin())->Directive;
343   }
344 
345   /// \brief Set default data sharing attribute to none.
346   void setDefaultDSANone(SourceLocation Loc) {
347     assert(!isStackEmpty());
348     Stack.back().first.back().DefaultAttr = DSA_none;
349     Stack.back().first.back().DefaultAttrLoc = Loc;
350   }
351   /// \brief Set default data sharing attribute to shared.
352   void setDefaultDSAShared(SourceLocation Loc) {
353     assert(!isStackEmpty());
354     Stack.back().first.back().DefaultAttr = DSA_shared;
355     Stack.back().first.back().DefaultAttrLoc = Loc;
356   }
357   /// Set default data mapping attribute to 'tofrom:scalar'.
358   void setDefaultDMAToFromScalar(SourceLocation Loc) {
359     assert(!isStackEmpty());
360     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
361     Stack.back().first.back().DefaultMapAttrLoc = Loc;
362   }
363 
364   DefaultDataSharingAttributes getDefaultDSA() const {
365     return isStackEmpty() ? DSA_unspecified
366                           : Stack.back().first.back().DefaultAttr;
367   }
368   SourceLocation getDefaultDSALocation() const {
369     return isStackEmpty() ? SourceLocation()
370                           : Stack.back().first.back().DefaultAttrLoc;
371   }
372   DefaultMapAttributes getDefaultDMA() const {
373     return isStackEmpty() ? DMA_unspecified
374                           : Stack.back().first.back().DefaultMapAttr;
375   }
376   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
377     return Stack.back().first[Level].DefaultMapAttr;
378   }
379   SourceLocation getDefaultDMALocation() const {
380     return isStackEmpty() ? SourceLocation()
381                           : Stack.back().first.back().DefaultMapAttrLoc;
382   }
383 
384   /// \brief Checks if the specified variable is a threadprivate.
385   bool isThreadPrivate(VarDecl *D) {
386     DSAVarData DVar = getTopDSA(D, false);
387     return isOpenMPThreadPrivate(DVar.CKind);
388   }
389 
390   /// \brief Marks current region as ordered (it has an 'ordered' clause).
391   void setOrderedRegion(bool IsOrdered, Expr *Param) {
392     assert(!isStackEmpty());
393     Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
394     Stack.back().first.back().OrderedRegion.setPointer(Param);
395   }
396   /// \brief Returns true, if parent region is ordered (has associated
397   /// 'ordered' clause), false - otherwise.
398   bool isParentOrderedRegion() const {
399     if (isStackEmpty() || Stack.back().first.size() == 1)
400       return false;
401     return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
402   }
403   /// \brief Returns optional parameter for the ordered region.
404   Expr *getParentOrderedRegionParam() const {
405     if (isStackEmpty() || Stack.back().first.size() == 1)
406       return nullptr;
407     return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
408   }
409   /// \brief Marks current region as nowait (it has a 'nowait' clause).
410   void setNowaitRegion(bool IsNowait = true) {
411     assert(!isStackEmpty());
412     Stack.back().first.back().NowaitRegion = IsNowait;
413   }
414   /// \brief Returns true, if parent region is nowait (has associated
415   /// 'nowait' clause), false - otherwise.
416   bool isParentNowaitRegion() const {
417     if (isStackEmpty() || Stack.back().first.size() == 1)
418       return false;
419     return std::next(Stack.back().first.rbegin())->NowaitRegion;
420   }
421   /// \brief Marks parent region as cancel region.
422   void setParentCancelRegion(bool Cancel = true) {
423     if (!isStackEmpty() && Stack.back().first.size() > 1) {
424       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
425       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
426     }
427   }
428   /// \brief Return true if current region has inner cancel construct.
429   bool isCancelRegion() const {
430     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
431   }
432 
433   /// \brief Set collapse value for the region.
434   void setAssociatedLoops(unsigned Val) {
435     assert(!isStackEmpty());
436     Stack.back().first.back().AssociatedLoops = Val;
437   }
438   /// \brief Return collapse value for region.
439   unsigned getAssociatedLoops() const {
440     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
441   }
442 
443   /// \brief Marks current target region as one with closely nested teams
444   /// region.
445   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
446     if (!isStackEmpty() && Stack.back().first.size() > 1) {
447       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
448           TeamsRegionLoc;
449     }
450   }
451   /// \brief Returns true, if current region has closely nested teams region.
452   bool hasInnerTeamsRegion() const {
453     return getInnerTeamsRegionLoc().isValid();
454   }
455   /// \brief Returns location of the nested teams region (if any).
456   SourceLocation getInnerTeamsRegionLoc() const {
457     return isStackEmpty() ? SourceLocation()
458                           : Stack.back().first.back().InnerTeamsRegionLoc;
459   }
460 
461   Scope *getCurScope() const {
462     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
463   }
464   Scope *getCurScope() {
465     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
466   }
467   SourceLocation getConstructLoc() {
468     return isStackEmpty() ? SourceLocation()
469                           : Stack.back().first.back().ConstructLoc;
470   }
471 
472   /// Do the check specified in \a Check to all component lists and return true
473   /// if any issue is found.
474   bool checkMappableExprComponentListsForDecl(
475       ValueDecl *VD, bool CurrentRegionOnly,
476       const llvm::function_ref<
477           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
478                OpenMPClauseKind)> &Check) {
479     if (isStackEmpty())
480       return false;
481     auto SI = Stack.back().first.rbegin();
482     auto SE = Stack.back().first.rend();
483 
484     if (SI == SE)
485       return false;
486 
487     if (CurrentRegionOnly) {
488       SE = std::next(SI);
489     } else {
490       ++SI;
491     }
492 
493     for (; SI != SE; ++SI) {
494       auto MI = SI->MappedExprComponents.find(VD);
495       if (MI != SI->MappedExprComponents.end())
496         for (auto &L : MI->second.Components)
497           if (Check(L, MI->second.Kind))
498             return true;
499     }
500     return false;
501   }
502 
503   /// Do the check specified in \a Check to all component lists at a given level
504   /// and return true if any issue is found.
505   bool checkMappableExprComponentListsForDeclAtLevel(
506       ValueDecl *VD, unsigned Level,
507       const llvm::function_ref<
508           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
509                OpenMPClauseKind)> &Check) {
510     if (isStackEmpty())
511       return false;
512 
513     auto StartI = Stack.back().first.begin();
514     auto EndI = Stack.back().first.end();
515     if (std::distance(StartI, EndI) <= (int)Level)
516       return false;
517     std::advance(StartI, Level);
518 
519     auto MI = StartI->MappedExprComponents.find(VD);
520     if (MI != StartI->MappedExprComponents.end())
521       for (auto &L : MI->second.Components)
522         if (Check(L, MI->second.Kind))
523           return true;
524     return false;
525   }
526 
527   /// Create a new mappable expression component list associated with a given
528   /// declaration and initialize it with the provided list of components.
529   void addMappableExpressionComponents(
530       ValueDecl *VD,
531       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
532       OpenMPClauseKind WhereFoundClauseKind) {
533     assert(!isStackEmpty() &&
534            "Not expecting to retrieve components from a empty stack!");
535     auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
536     // Create new entry and append the new components there.
537     MEC.Components.resize(MEC.Components.size() + 1);
538     MEC.Components.back().append(Components.begin(), Components.end());
539     MEC.Kind = WhereFoundClauseKind;
540   }
541 
542   unsigned getNestingLevel() const {
543     assert(!isStackEmpty());
544     return Stack.back().first.size() - 1;
545   }
546   void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
547     assert(!isStackEmpty() && Stack.back().first.size() > 1);
548     auto &StackElem = *std::next(Stack.back().first.rbegin());
549     assert(isOpenMPWorksharingDirective(StackElem.Directive));
550     StackElem.DoacrossDepends.insert({C, OpsOffs});
551   }
552   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
553   getDoacrossDependClauses() const {
554     assert(!isStackEmpty());
555     auto &StackElem = Stack.back().first.back();
556     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
557       auto &Ref = StackElem.DoacrossDepends;
558       return llvm::make_range(Ref.begin(), Ref.end());
559     }
560     return llvm::make_range(StackElem.DoacrossDepends.end(),
561                             StackElem.DoacrossDepends.end());
562   }
563 };
564 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
565   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
566          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
567 }
568 } // namespace
569 
570 static Expr *getExprAsWritten(Expr *E) {
571   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
572     E = ExprTemp->getSubExpr();
573 
574   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
575     E = MTE->GetTemporaryExpr();
576 
577   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
578     E = Binder->getSubExpr();
579 
580   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
581     E = ICE->getSubExprAsWritten();
582   return E->IgnoreParens();
583 }
584 
585 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
586   if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
587     if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
588       D = ME->getMemberDecl();
589   auto *VD = dyn_cast<VarDecl>(D);
590   auto *FD = dyn_cast<FieldDecl>(D);
591   if (VD != nullptr) {
592     VD = VD->getCanonicalDecl();
593     D = VD;
594   } else {
595     assert(FD);
596     FD = FD->getCanonicalDecl();
597     D = FD;
598   }
599   return D;
600 }
601 
602 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
603                                           ValueDecl *D) {
604   D = getCanonicalDecl(D);
605   auto *VD = dyn_cast<VarDecl>(D);
606   auto *FD = dyn_cast<FieldDecl>(D);
607   DSAVarData DVar;
608   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
609     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
610     // in a region but not in construct]
611     //  File-scope or namespace-scope variables referenced in called routines
612     //  in the region are shared unless they appear in a threadprivate
613     //  directive.
614     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
615       DVar.CKind = OMPC_shared;
616 
617     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
618     // in a region but not in construct]
619     //  Variables with static storage duration that are declared in called
620     //  routines in the region are shared.
621     if (VD && VD->hasGlobalStorage())
622       DVar.CKind = OMPC_shared;
623 
624     // Non-static data members are shared by default.
625     if (FD)
626       DVar.CKind = OMPC_shared;
627 
628     return DVar;
629   }
630 
631   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
632   // in a Construct, C/C++, predetermined, p.1]
633   // Variables with automatic storage duration that are declared in a scope
634   // inside the construct are private.
635   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
636       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
637     DVar.CKind = OMPC_private;
638     return DVar;
639   }
640 
641   DVar.DKind = Iter->Directive;
642   // Explicitly specified attributes and local variables with predetermined
643   // attributes.
644   if (Iter->SharingMap.count(D)) {
645     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
646     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
647     DVar.CKind = Iter->SharingMap[D].Attributes;
648     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
649     return DVar;
650   }
651 
652   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
653   // in a Construct, C/C++, implicitly determined, p.1]
654   //  In a parallel or task construct, the data-sharing attributes of these
655   //  variables are determined by the default clause, if present.
656   switch (Iter->DefaultAttr) {
657   case DSA_shared:
658     DVar.CKind = OMPC_shared;
659     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
660     return DVar;
661   case DSA_none:
662     return DVar;
663   case DSA_unspecified:
664     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
665     // in a Construct, implicitly determined, p.2]
666     //  In a parallel construct, if no default clause is present, these
667     //  variables are shared.
668     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
669     if (isOpenMPParallelDirective(DVar.DKind) ||
670         isOpenMPTeamsDirective(DVar.DKind)) {
671       DVar.CKind = OMPC_shared;
672       return DVar;
673     }
674 
675     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
676     // in a Construct, implicitly determined, p.4]
677     //  In a task construct, if no default clause is present, a variable that in
678     //  the enclosing context is determined to be shared by all implicit tasks
679     //  bound to the current team is shared.
680     if (isOpenMPTaskingDirective(DVar.DKind)) {
681       DSAVarData DVarTemp;
682       auto I = Iter, E = Stack.back().first.rend();
683       do {
684         ++I;
685         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
686         // Referenced in a Construct, implicitly determined, p.6]
687         //  In a task construct, if no default clause is present, a variable
688         //  whose data-sharing attribute is not determined by the rules above is
689         //  firstprivate.
690         DVarTemp = getDSA(I, D);
691         if (DVarTemp.CKind != OMPC_shared) {
692           DVar.RefExpr = nullptr;
693           DVar.CKind = OMPC_firstprivate;
694           return DVar;
695         }
696       } while (I != E && !isParallelOrTaskRegion(I->Directive));
697       DVar.CKind =
698           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
699       return DVar;
700     }
701   }
702   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
703   // in a Construct, implicitly determined, p.3]
704   //  For constructs other than task, if no default clause is present, these
705   //  variables inherit their data-sharing attributes from the enclosing
706   //  context.
707   return getDSA(++Iter, D);
708 }
709 
710 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
711   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
712   D = getCanonicalDecl(D);
713   auto &StackElem = Stack.back().first.back();
714   auto It = StackElem.AlignedMap.find(D);
715   if (It == StackElem.AlignedMap.end()) {
716     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
717     StackElem.AlignedMap[D] = NewDE;
718     return nullptr;
719   } else {
720     assert(It->second && "Unexpected nullptr expr in the aligned map");
721     return It->second;
722   }
723   return nullptr;
724 }
725 
726 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
727   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
728   D = getCanonicalDecl(D);
729   auto &StackElem = Stack.back().first.back();
730   StackElem.LCVMap.insert(
731       {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
732 }
733 
734 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
735   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
736   D = getCanonicalDecl(D);
737   auto &StackElem = Stack.back().first.back();
738   auto It = StackElem.LCVMap.find(D);
739   if (It != StackElem.LCVMap.end())
740     return It->second;
741   return {0, nullptr};
742 }
743 
744 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
745   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
746          "Data-sharing attributes stack is empty");
747   D = getCanonicalDecl(D);
748   auto &StackElem = *std::next(Stack.back().first.rbegin());
749   auto It = StackElem.LCVMap.find(D);
750   if (It != StackElem.LCVMap.end())
751     return It->second;
752   return {0, nullptr};
753 }
754 
755 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
756   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
757          "Data-sharing attributes stack is empty");
758   auto &StackElem = *std::next(Stack.back().first.rbegin());
759   if (StackElem.LCVMap.size() < I)
760     return nullptr;
761   for (auto &Pair : StackElem.LCVMap)
762     if (Pair.second.first == I)
763       return Pair.first;
764   return nullptr;
765 }
766 
767 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
768                         DeclRefExpr *PrivateCopy) {
769   D = getCanonicalDecl(D);
770   if (A == OMPC_threadprivate) {
771     auto &Data = Threadprivates[D];
772     Data.Attributes = A;
773     Data.RefExpr.setPointer(E);
774     Data.PrivateCopy = nullptr;
775   } else {
776     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
777     auto &Data = Stack.back().first.back().SharingMap[D];
778     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
779            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
780            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
781            (isLoopControlVariable(D).first && A == OMPC_private));
782     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
783       Data.RefExpr.setInt(/*IntVal=*/true);
784       return;
785     }
786     const bool IsLastprivate =
787         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
788     Data.Attributes = A;
789     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
790     Data.PrivateCopy = PrivateCopy;
791     if (PrivateCopy) {
792       auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
793       Data.Attributes = A;
794       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
795       Data.PrivateCopy = nullptr;
796     }
797   }
798 }
799 
800 /// \brief Build a variable declaration for OpenMP loop iteration variable.
801 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
802                              StringRef Name, const AttrVec *Attrs = nullptr) {
803   DeclContext *DC = SemaRef.CurContext;
804   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
805   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
806   VarDecl *Decl =
807       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
808   if (Attrs) {
809     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
810          I != E; ++I)
811       Decl->addAttr(*I);
812   }
813   Decl->setImplicit();
814   return Decl;
815 }
816 
817 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
818                                      SourceLocation Loc,
819                                      bool RefersToCapture = false) {
820   D->setReferenced();
821   D->markUsed(S.Context);
822   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
823                              SourceLocation(), D, RefersToCapture, Loc, Ty,
824                              VK_LValue);
825 }
826 
827 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
828                                            BinaryOperatorKind BOK) {
829   D = getCanonicalDecl(D);
830   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
831   assert(
832       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
833       "Additional reduction info may be specified only for reduction items.");
834   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
835   assert(ReductionData.ReductionRange.isInvalid() &&
836          Stack.back().first.back().Directive == OMPD_taskgroup &&
837          "Additional reduction info may be specified only once for reduction "
838          "items.");
839   ReductionData.set(BOK, SR);
840   Expr *&TaskgroupReductionRef =
841       Stack.back().first.back().TaskgroupReductionRef;
842   if (!TaskgroupReductionRef) {
843     auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
844                             SemaRef.Context.VoidPtrTy, ".task_red.");
845     TaskgroupReductionRef =
846         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
847   }
848 }
849 
850 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
851                                            const Expr *ReductionRef) {
852   D = getCanonicalDecl(D);
853   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
854   assert(
855       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
856       "Additional reduction info may be specified only for reduction items.");
857   auto &ReductionData = Stack.back().first.back().ReductionMap[D];
858   assert(ReductionData.ReductionRange.isInvalid() &&
859          Stack.back().first.back().Directive == OMPD_taskgroup &&
860          "Additional reduction info may be specified only once for reduction "
861          "items.");
862   ReductionData.set(ReductionRef, SR);
863   Expr *&TaskgroupReductionRef =
864       Stack.back().first.back().TaskgroupReductionRef;
865   if (!TaskgroupReductionRef) {
866     auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
867                             ".task_red.");
868     TaskgroupReductionRef =
869         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
870   }
871 }
872 
873 DSAStackTy::DSAVarData
874 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
875                                              BinaryOperatorKind &BOK,
876                                              Expr *&TaskgroupDescriptor) {
877   D = getCanonicalDecl(D);
878   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
879   if (Stack.back().first.empty())
880       return DSAVarData();
881   for (auto I = std::next(Stack.back().first.rbegin(), 1),
882             E = Stack.back().first.rend();
883        I != E; std::advance(I, 1)) {
884     auto &Data = I->SharingMap[D];
885     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
886       continue;
887     auto &ReductionData = I->ReductionMap[D];
888     if (!ReductionData.ReductionOp ||
889         ReductionData.ReductionOp.is<const Expr *>())
890       return DSAVarData();
891     SR = ReductionData.ReductionRange;
892     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
893     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
894                                        "expression for the descriptor is not "
895                                        "set.");
896     TaskgroupDescriptor = I->TaskgroupReductionRef;
897     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
898                       Data.PrivateCopy, I->DefaultAttrLoc);
899   }
900   return DSAVarData();
901 }
902 
903 DSAStackTy::DSAVarData
904 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
905                                              const Expr *&ReductionRef,
906                                              Expr *&TaskgroupDescriptor) {
907   D = getCanonicalDecl(D);
908   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
909   if (Stack.back().first.empty())
910       return DSAVarData();
911   for (auto I = std::next(Stack.back().first.rbegin(), 1),
912             E = Stack.back().first.rend();
913        I != E; std::advance(I, 1)) {
914     auto &Data = I->SharingMap[D];
915     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
916       continue;
917     auto &ReductionData = I->ReductionMap[D];
918     if (!ReductionData.ReductionOp ||
919         !ReductionData.ReductionOp.is<const Expr *>())
920       return DSAVarData();
921     SR = ReductionData.ReductionRange;
922     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
923     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
924                                        "expression for the descriptor is not "
925                                        "set.");
926     TaskgroupDescriptor = I->TaskgroupReductionRef;
927     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
928                       Data.PrivateCopy, I->DefaultAttrLoc);
929   }
930   return DSAVarData();
931 }
932 
933 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
934   D = D->getCanonicalDecl();
935   if (!isStackEmpty() && Stack.back().first.size() > 1) {
936     reverse_iterator I = Iter, E = Stack.back().first.rend();
937     Scope *TopScope = nullptr;
938     while (I != E && !isParallelOrTaskRegion(I->Directive))
939       ++I;
940     if (I == E)
941       return false;
942     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
943     Scope *CurScope = getCurScope();
944     while (CurScope != TopScope && !CurScope->isDeclScope(D))
945       CurScope = CurScope->getParent();
946     return CurScope != TopScope;
947   }
948   return false;
949 }
950 
951 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
952   D = getCanonicalDecl(D);
953   DSAVarData DVar;
954 
955   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
956   // in a Construct, C/C++, predetermined, p.1]
957   //  Variables appearing in threadprivate directives are threadprivate.
958   auto *VD = dyn_cast<VarDecl>(D);
959   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
960        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
961          SemaRef.getLangOpts().OpenMPUseTLS &&
962          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
963       (VD && VD->getStorageClass() == SC_Register &&
964        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
965     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
966                                D->getLocation()),
967            OMPC_threadprivate);
968   }
969   auto TI = Threadprivates.find(D);
970   if (TI != Threadprivates.end()) {
971     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
972     DVar.CKind = OMPC_threadprivate;
973     return DVar;
974   } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
975     DVar.RefExpr = buildDeclRefExpr(
976         SemaRef, VD, D->getType().getNonReferenceType(),
977         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
978     DVar.CKind = OMPC_threadprivate;
979     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
980   }
981 
982   if (isStackEmpty())
983     // Not in OpenMP execution region and top scope was already checked.
984     return DVar;
985 
986   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
987   // in a Construct, C/C++, predetermined, p.4]
988   //  Static data members are shared.
989   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
990   // in a Construct, C/C++, predetermined, p.7]
991   //  Variables with static storage duration that are declared in a scope
992   //  inside the construct are shared.
993   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
994   if (VD && VD->isStaticDataMember()) {
995     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
996     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
997       return DVar;
998 
999     DVar.CKind = OMPC_shared;
1000     return DVar;
1001   }
1002 
1003   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
1004   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1005   Type = SemaRef.getASTContext().getBaseElementType(Type);
1006   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1007   // in a Construct, C/C++, predetermined, p.6]
1008   //  Variables with const qualified type having no mutable member are
1009   //  shared.
1010   CXXRecordDecl *RD =
1011       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
1012   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1013     if (auto *CTD = CTSD->getSpecializedTemplate())
1014       RD = CTD->getTemplatedDecl();
1015   if (IsConstant &&
1016       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1017         RD->hasMutableFields())) {
1018     // Variables with const-qualified type having no mutable member may be
1019     // listed in a firstprivate clause, even if they are static data members.
1020     DSAVarData DVarTemp = hasDSA(
1021         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1022         MatchesAlways, FromParent);
1023     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1024       return DVar;
1025 
1026     DVar.CKind = OMPC_shared;
1027     return DVar;
1028   }
1029 
1030   // Explicitly specified attributes and local variables with predetermined
1031   // attributes.
1032   auto I = Stack.back().first.rbegin();
1033   auto EndI = Stack.back().first.rend();
1034   if (FromParent && I != EndI)
1035     std::advance(I, 1);
1036   if (I->SharingMap.count(D)) {
1037     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
1038     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
1039     DVar.CKind = I->SharingMap[D].Attributes;
1040     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1041     DVar.DKind = I->Directive;
1042   }
1043 
1044   return DVar;
1045 }
1046 
1047 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1048                                                   bool FromParent) {
1049   if (isStackEmpty()) {
1050     StackTy::reverse_iterator I;
1051     return getDSA(I, D);
1052   }
1053   D = getCanonicalDecl(D);
1054   auto StartI = Stack.back().first.rbegin();
1055   auto EndI = Stack.back().first.rend();
1056   if (FromParent && StartI != EndI)
1057     std::advance(StartI, 1);
1058   return getDSA(StartI, D);
1059 }
1060 
1061 DSAStackTy::DSAVarData
1062 DSAStackTy::hasDSA(ValueDecl *D,
1063                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1064                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1065                    bool FromParent) {
1066   if (isStackEmpty())
1067     return {};
1068   D = getCanonicalDecl(D);
1069   auto I = Stack.back().first.rbegin();
1070   auto EndI = Stack.back().first.rend();
1071   if (FromParent && I != EndI)
1072     std::advance(I, 1);
1073   for (; I != EndI; std::advance(I, 1)) {
1074     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
1075       continue;
1076     auto NewI = I;
1077     DSAVarData DVar = getDSA(NewI, D);
1078     if (I == NewI && CPred(DVar.CKind))
1079       return DVar;
1080   }
1081   return {};
1082 }
1083 
1084 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1085     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1086     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1087     bool FromParent) {
1088   if (isStackEmpty())
1089     return {};
1090   D = getCanonicalDecl(D);
1091   auto StartI = Stack.back().first.rbegin();
1092   auto EndI = Stack.back().first.rend();
1093   if (FromParent && StartI != EndI)
1094     std::advance(StartI, 1);
1095   if (StartI == EndI || !DPred(StartI->Directive))
1096     return {};
1097   auto NewI = StartI;
1098   DSAVarData DVar = getDSA(NewI, D);
1099   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1100 }
1101 
1102 bool DSAStackTy::hasExplicitDSA(
1103     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1104     unsigned Level, bool NotLastprivate) {
1105   if (CPred(ClauseKindMode))
1106     return true;
1107   if (isStackEmpty())
1108     return false;
1109   D = getCanonicalDecl(D);
1110   auto StartI = Stack.back().first.begin();
1111   auto EndI = Stack.back().first.end();
1112   if (std::distance(StartI, EndI) <= (int)Level)
1113     return false;
1114   std::advance(StartI, Level);
1115   return (StartI->SharingMap.count(D) > 0) &&
1116          StartI->SharingMap[D].RefExpr.getPointer() &&
1117          CPred(StartI->SharingMap[D].Attributes) &&
1118          (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
1119 }
1120 
1121 bool DSAStackTy::hasExplicitDirective(
1122     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1123     unsigned Level) {
1124   if (isStackEmpty())
1125     return false;
1126   auto StartI = Stack.back().first.begin();
1127   auto EndI = Stack.back().first.end();
1128   if (std::distance(StartI, EndI) <= (int)Level)
1129     return false;
1130   std::advance(StartI, Level);
1131   return DPred(StartI->Directive);
1132 }
1133 
1134 bool DSAStackTy::hasDirective(
1135     const llvm::function_ref<bool(OpenMPDirectiveKind,
1136                                   const DeclarationNameInfo &, SourceLocation)>
1137         &DPred,
1138     bool FromParent) {
1139   // We look only in the enclosing region.
1140   if (isStackEmpty())
1141     return false;
1142   auto StartI = std::next(Stack.back().first.rbegin());
1143   auto EndI = Stack.back().first.rend();
1144   if (FromParent && StartI != EndI)
1145     StartI = std::next(StartI);
1146   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1147     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1148       return true;
1149   }
1150   return false;
1151 }
1152 
1153 void Sema::InitDataSharingAttributesStack() {
1154   VarDataSharingAttributesStack = new DSAStackTy(*this);
1155 }
1156 
1157 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1158 
1159 void Sema::pushOpenMPFunctionRegion() {
1160   DSAStack->pushFunction();
1161 }
1162 
1163 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1164   DSAStack->popFunction(OldFSI);
1165 }
1166 
1167 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
1168   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1169 
1170   auto &Ctx = getASTContext();
1171   bool IsByRef = true;
1172 
1173   // Find the directive that is associated with the provided scope.
1174   D = cast<ValueDecl>(D->getCanonicalDecl());
1175   auto Ty = D->getType();
1176 
1177   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1178     // This table summarizes how a given variable should be passed to the device
1179     // given its type and the clauses where it appears. This table is based on
1180     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1181     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1182     //
1183     // =========================================================================
1184     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1185     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1186     // =========================================================================
1187     // | scl  |               |     |       |       -       |          | bycopy|
1188     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1189     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1190     // | scl  |       x       |     |       |       -       |          | byref |
1191     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1192     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1193     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1194     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1195     //
1196     // | agg  |      n.a.     |     |       |       -       |          | byref |
1197     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1198     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1199     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1200     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1201     //
1202     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1203     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1204     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1205     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1206     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1207     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1208     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1209     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1210     // =========================================================================
1211     // Legend:
1212     //  scl - scalar
1213     //  ptr - pointer
1214     //  agg - aggregate
1215     //  x - applies
1216     //  - - invalid in this combination
1217     //  [] - mapped with an array section
1218     //  byref - should be mapped by reference
1219     //  byval - should be mapped by value
1220     //  null - initialize a local variable to null on the device
1221     //
1222     // Observations:
1223     //  - All scalar declarations that show up in a map clause have to be passed
1224     //    by reference, because they may have been mapped in the enclosing data
1225     //    environment.
1226     //  - If the scalar value does not fit the size of uintptr, it has to be
1227     //    passed by reference, regardless the result in the table above.
1228     //  - For pointers mapped by value that have either an implicit map or an
1229     //    array section, the runtime library may pass the NULL value to the
1230     //    device instead of the value passed to it by the compiler.
1231 
1232     if (Ty->isReferenceType())
1233       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1234 
1235     // Locate map clauses and see if the variable being captured is referred to
1236     // in any of those clauses. Here we only care about variables, not fields,
1237     // because fields are part of aggregates.
1238     bool IsVariableUsedInMapClause = false;
1239     bool IsVariableAssociatedWithSection = false;
1240 
1241     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1242         D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
1243                 MapExprComponents,
1244             OpenMPClauseKind WhereFoundClauseKind) {
1245           // Only the map clause information influences how a variable is
1246           // captured. E.g. is_device_ptr does not require changing the default
1247           // behavior.
1248           if (WhereFoundClauseKind != OMPC_map)
1249             return false;
1250 
1251           auto EI = MapExprComponents.rbegin();
1252           auto EE = MapExprComponents.rend();
1253 
1254           assert(EI != EE && "Invalid map expression!");
1255 
1256           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1257             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1258 
1259           ++EI;
1260           if (EI == EE)
1261             return false;
1262 
1263           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1264               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1265               isa<MemberExpr>(EI->getAssociatedExpression())) {
1266             IsVariableAssociatedWithSection = true;
1267             // There is nothing more we need to know about this variable.
1268             return true;
1269           }
1270 
1271           // Keep looking for more map info.
1272           return false;
1273         });
1274 
1275     if (IsVariableUsedInMapClause) {
1276       // If variable is identified in a map clause it is always captured by
1277       // reference except if it is a pointer that is dereferenced somehow.
1278       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1279     } else {
1280       // By default, all the data that has a scalar type is mapped by copy.
1281       IsByRef = !Ty->isScalarType() ||
1282                 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar;
1283     }
1284   }
1285 
1286   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1287     IsByRef = !DSAStack->hasExplicitDSA(
1288         D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1289         Level, /*NotLastprivate=*/true);
1290   }
1291 
1292   // When passing data by copy, we need to make sure it fits the uintptr size
1293   // and alignment, because the runtime library only deals with uintptr types.
1294   // If it does not fit the uintptr size, we need to pass the data by reference
1295   // instead.
1296   if (!IsByRef &&
1297       (Ctx.getTypeSizeInChars(Ty) >
1298            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1299        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1300     IsByRef = true;
1301   }
1302 
1303   return IsByRef;
1304 }
1305 
1306 unsigned Sema::getOpenMPNestingLevel() const {
1307   assert(getLangOpts().OpenMP);
1308   return DSAStack->getNestingLevel();
1309 }
1310 
1311 bool Sema::isInOpenMPTargetExecutionDirective() const {
1312   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1313           !DSAStack->isClauseParsingMode()) ||
1314          DSAStack->hasDirective(
1315              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1316                 SourceLocation) -> bool {
1317                return isOpenMPTargetExecutionDirective(K);
1318              },
1319              false);
1320 }
1321 
1322 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
1323   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1324   D = getCanonicalDecl(D);
1325 
1326   // If we are attempting to capture a global variable in a directive with
1327   // 'target' we return true so that this global is also mapped to the device.
1328   //
1329   // FIXME: If the declaration is enclosed in a 'declare target' directive,
1330   // then it should not be captured. Therefore, an extra check has to be
1331   // inserted here once support for 'declare target' is added.
1332   //
1333   auto *VD = dyn_cast<VarDecl>(D);
1334   if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1335     return VD;
1336 
1337   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1338       (!DSAStack->isClauseParsingMode() ||
1339        DSAStack->getParentDirective() != OMPD_unknown)) {
1340     auto &&Info = DSAStack->isLoopControlVariable(D);
1341     if (Info.first ||
1342         (VD && VD->hasLocalStorage() &&
1343          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1344         (VD && DSAStack->isForceVarCapturing()))
1345       return VD ? VD : Info.second;
1346     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1347     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1348       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1349     DVarPrivate = DSAStack->hasDSA(
1350         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1351         DSAStack->isClauseParsingMode());
1352     if (DVarPrivate.CKind != OMPC_unknown)
1353       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1354   }
1355   return nullptr;
1356 }
1357 
1358 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1359                                         unsigned Level) const {
1360   SmallVector<OpenMPDirectiveKind, 4> Regions;
1361   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1362   FunctionScopesIndex -= Regions.size();
1363 }
1364 
1365 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1366   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1367   return DSAStack->hasExplicitDSA(
1368              D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1369              Level) ||
1370          // Consider taskgroup reduction descriptor variable a private to avoid
1371          // possible capture in the region.
1372          (DSAStack->hasExplicitDirective(
1373               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1374               Level) &&
1375           DSAStack->isTaskgroupReductionRef(D, Level));
1376 }
1377 
1378 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1379   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1380   D = getCanonicalDecl(D);
1381   OpenMPClauseKind OMPC = OMPC_unknown;
1382   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1383     const unsigned NewLevel = I - 1;
1384     if (DSAStack->hasExplicitDSA(D,
1385                                  [&OMPC](const OpenMPClauseKind K) {
1386                                    if (isOpenMPPrivate(K)) {
1387                                      OMPC = K;
1388                                      return true;
1389                                    }
1390                                    return false;
1391                                  },
1392                                  NewLevel))
1393       break;
1394     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1395             D, NewLevel,
1396             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1397                OpenMPClauseKind) { return true; })) {
1398       OMPC = OMPC_map;
1399       break;
1400     }
1401     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1402                                        NewLevel)) {
1403       OMPC = OMPC_firstprivate;
1404       break;
1405     }
1406   }
1407   if (OMPC != OMPC_unknown)
1408     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1409 }
1410 
1411 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1412   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1413   // Return true if the current level is no longer enclosed in a target region.
1414 
1415   auto *VD = dyn_cast<VarDecl>(D);
1416   return VD && !VD->hasLocalStorage() &&
1417          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1418                                         Level);
1419 }
1420 
1421 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1422 
1423 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1424                                const DeclarationNameInfo &DirName,
1425                                Scope *CurScope, SourceLocation Loc) {
1426   DSAStack->push(DKind, DirName, CurScope, Loc);
1427   PushExpressionEvaluationContext(
1428       ExpressionEvaluationContext::PotentiallyEvaluated);
1429 }
1430 
1431 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1432   DSAStack->setClauseParsingMode(K);
1433 }
1434 
1435 void Sema::EndOpenMPClause() {
1436   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1437 }
1438 
1439 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1440   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1441   //  A variable of class type (or array thereof) that appears in a lastprivate
1442   //  clause requires an accessible, unambiguous default constructor for the
1443   //  class type, unless the list item is also specified in a firstprivate
1444   //  clause.
1445   if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1446     for (auto *C : D->clauses()) {
1447       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1448         SmallVector<Expr *, 8> PrivateCopies;
1449         for (auto *DE : Clause->varlists()) {
1450           if (DE->isValueDependent() || DE->isTypeDependent()) {
1451             PrivateCopies.push_back(nullptr);
1452             continue;
1453           }
1454           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1455           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1456           QualType Type = VD->getType().getNonReferenceType();
1457           auto DVar = DSAStack->getTopDSA(VD, false);
1458           if (DVar.CKind == OMPC_lastprivate) {
1459             // Generate helper private variable and initialize it with the
1460             // default value. The address of the original variable is replaced
1461             // by the address of the new private variable in CodeGen. This new
1462             // variable is not added to IdResolver, so the code in the OpenMP
1463             // region uses original variable for proper diagnostics.
1464             auto *VDPrivate = buildVarDecl(
1465                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1466                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1467             ActOnUninitializedDecl(VDPrivate);
1468             if (VDPrivate->isInvalidDecl())
1469               continue;
1470             PrivateCopies.push_back(buildDeclRefExpr(
1471                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1472           } else {
1473             // The variable is also a firstprivate, so initialization sequence
1474             // for private copy is generated already.
1475             PrivateCopies.push_back(nullptr);
1476           }
1477         }
1478         // Set initializers to private copies if no errors were found.
1479         if (PrivateCopies.size() == Clause->varlist_size())
1480           Clause->setPrivateCopies(PrivateCopies);
1481       }
1482     }
1483   }
1484 
1485   DSAStack->pop();
1486   DiscardCleanupsInEvaluationContext();
1487   PopExpressionEvaluationContext();
1488 }
1489 
1490 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1491                                      Expr *NumIterations, Sema &SemaRef,
1492                                      Scope *S, DSAStackTy *Stack);
1493 
1494 namespace {
1495 
1496 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1497 private:
1498   Sema &SemaRef;
1499 
1500 public:
1501   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1502   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1503     NamedDecl *ND = Candidate.getCorrectionDecl();
1504     if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1505       return VD->hasGlobalStorage() &&
1506              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1507                                    SemaRef.getCurScope());
1508     }
1509     return false;
1510   }
1511 };
1512 
1513 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1514 private:
1515   Sema &SemaRef;
1516 
1517 public:
1518   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1519   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1520     NamedDecl *ND = Candidate.getCorrectionDecl();
1521     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1522       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1523                                    SemaRef.getCurScope());
1524     }
1525     return false;
1526   }
1527 };
1528 
1529 } // namespace
1530 
1531 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1532                                          CXXScopeSpec &ScopeSpec,
1533                                          const DeclarationNameInfo &Id) {
1534   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1535   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1536 
1537   if (Lookup.isAmbiguous())
1538     return ExprError();
1539 
1540   VarDecl *VD;
1541   if (!Lookup.isSingleResult()) {
1542     if (TypoCorrection Corrected = CorrectTypo(
1543             Id, LookupOrdinaryName, CurScope, nullptr,
1544             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1545       diagnoseTypo(Corrected,
1546                    PDiag(Lookup.empty()
1547                              ? diag::err_undeclared_var_use_suggest
1548                              : diag::err_omp_expected_var_arg_suggest)
1549                        << Id.getName());
1550       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1551     } else {
1552       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1553                                        : diag::err_omp_expected_var_arg)
1554           << Id.getName();
1555       return ExprError();
1556     }
1557   } else {
1558     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1559       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1560       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1561       return ExprError();
1562     }
1563   }
1564   Lookup.suppressDiagnostics();
1565 
1566   // OpenMP [2.9.2, Syntax, C/C++]
1567   //   Variables must be file-scope, namespace-scope, or static block-scope.
1568   if (!VD->hasGlobalStorage()) {
1569     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1570         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1571     bool IsDecl =
1572         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1573     Diag(VD->getLocation(),
1574          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1575         << VD;
1576     return ExprError();
1577   }
1578 
1579   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1580   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1581   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1582   //   A threadprivate directive for file-scope variables must appear outside
1583   //   any definition or declaration.
1584   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1585       !getCurLexicalContext()->isTranslationUnit()) {
1586     Diag(Id.getLoc(), diag::err_omp_var_scope)
1587         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1588     bool IsDecl =
1589         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1590     Diag(VD->getLocation(),
1591          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1592         << VD;
1593     return ExprError();
1594   }
1595   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1596   //   A threadprivate directive for static class member variables must appear
1597   //   in the class definition, in the same scope in which the member
1598   //   variables are declared.
1599   if (CanonicalVD->isStaticDataMember() &&
1600       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1601     Diag(Id.getLoc(), diag::err_omp_var_scope)
1602         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1603     bool IsDecl =
1604         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1605     Diag(VD->getLocation(),
1606          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1607         << VD;
1608     return ExprError();
1609   }
1610   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1611   //   A threadprivate directive for namespace-scope variables must appear
1612   //   outside any definition or declaration other than the namespace
1613   //   definition itself.
1614   if (CanonicalVD->getDeclContext()->isNamespace() &&
1615       (!getCurLexicalContext()->isFileContext() ||
1616        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1617     Diag(Id.getLoc(), diag::err_omp_var_scope)
1618         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1619     bool IsDecl =
1620         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1621     Diag(VD->getLocation(),
1622          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1623         << VD;
1624     return ExprError();
1625   }
1626   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1627   //   A threadprivate directive for static block-scope variables must appear
1628   //   in the scope of the variable and not in a nested scope.
1629   if (CanonicalVD->isStaticLocal() && CurScope &&
1630       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1631     Diag(Id.getLoc(), diag::err_omp_var_scope)
1632         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1633     bool IsDecl =
1634         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1635     Diag(VD->getLocation(),
1636          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1637         << VD;
1638     return ExprError();
1639   }
1640 
1641   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1642   //   A threadprivate directive must lexically precede all references to any
1643   //   of the variables in its list.
1644   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1645     Diag(Id.getLoc(), diag::err_omp_var_used)
1646         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1647     return ExprError();
1648   }
1649 
1650   QualType ExprType = VD->getType().getNonReferenceType();
1651   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1652                              SourceLocation(), VD,
1653                              /*RefersToEnclosingVariableOrCapture=*/false,
1654                              Id.getLoc(), ExprType, VK_LValue);
1655 }
1656 
1657 Sema::DeclGroupPtrTy
1658 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1659                                         ArrayRef<Expr *> VarList) {
1660   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1661     CurContext->addDecl(D);
1662     return DeclGroupPtrTy::make(DeclGroupRef(D));
1663   }
1664   return nullptr;
1665 }
1666 
1667 namespace {
1668 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1669   Sema &SemaRef;
1670 
1671 public:
1672   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1673     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1674       if (VD->hasLocalStorage()) {
1675         SemaRef.Diag(E->getLocStart(),
1676                      diag::err_omp_local_var_in_threadprivate_init)
1677             << E->getSourceRange();
1678         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1679             << VD << VD->getSourceRange();
1680         return true;
1681       }
1682     }
1683     return false;
1684   }
1685   bool VisitStmt(const Stmt *S) {
1686     for (auto Child : S->children()) {
1687       if (Child && Visit(Child))
1688         return true;
1689     }
1690     return false;
1691   }
1692   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1693 };
1694 } // namespace
1695 
1696 OMPThreadPrivateDecl *
1697 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1698   SmallVector<Expr *, 8> Vars;
1699   for (auto &RefExpr : VarList) {
1700     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1701     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1702     SourceLocation ILoc = DE->getExprLoc();
1703 
1704     // Mark variable as used.
1705     VD->setReferenced();
1706     VD->markUsed(Context);
1707 
1708     QualType QType = VD->getType();
1709     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1710       // It will be analyzed later.
1711       Vars.push_back(DE);
1712       continue;
1713     }
1714 
1715     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1716     //   A threadprivate variable must not have an incomplete type.
1717     if (RequireCompleteType(ILoc, VD->getType(),
1718                             diag::err_omp_threadprivate_incomplete_type)) {
1719       continue;
1720     }
1721 
1722     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1723     //   A threadprivate variable must not have a reference type.
1724     if (VD->getType()->isReferenceType()) {
1725       Diag(ILoc, diag::err_omp_ref_type_arg)
1726           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1727       bool IsDecl =
1728           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1729       Diag(VD->getLocation(),
1730            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1731           << VD;
1732       continue;
1733     }
1734 
1735     // Check if this is a TLS variable. If TLS is not being supported, produce
1736     // the corresponding diagnostic.
1737     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1738          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1739            getLangOpts().OpenMPUseTLS &&
1740            getASTContext().getTargetInfo().isTLSSupported())) ||
1741         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1742          !VD->isLocalVarDecl())) {
1743       Diag(ILoc, diag::err_omp_var_thread_local)
1744           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1745       bool IsDecl =
1746           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1747       Diag(VD->getLocation(),
1748            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1749           << VD;
1750       continue;
1751     }
1752 
1753     // Check if initial value of threadprivate variable reference variable with
1754     // local storage (it is not supported by runtime).
1755     if (auto Init = VD->getAnyInitializer()) {
1756       LocalVarRefChecker Checker(*this);
1757       if (Checker.Visit(Init))
1758         continue;
1759     }
1760 
1761     Vars.push_back(RefExpr);
1762     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1763     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1764         Context, SourceRange(Loc, Loc)));
1765     if (auto *ML = Context.getASTMutationListener())
1766       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1767   }
1768   OMPThreadPrivateDecl *D = nullptr;
1769   if (!Vars.empty()) {
1770     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1771                                      Vars);
1772     D->setAccess(AS_public);
1773   }
1774   return D;
1775 }
1776 
1777 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1778                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1779                               bool IsLoopIterVar = false) {
1780   if (DVar.RefExpr) {
1781     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1782         << getOpenMPClauseName(DVar.CKind);
1783     return;
1784   }
1785   enum {
1786     PDSA_StaticMemberShared,
1787     PDSA_StaticLocalVarShared,
1788     PDSA_LoopIterVarPrivate,
1789     PDSA_LoopIterVarLinear,
1790     PDSA_LoopIterVarLastprivate,
1791     PDSA_ConstVarShared,
1792     PDSA_GlobalVarShared,
1793     PDSA_TaskVarFirstprivate,
1794     PDSA_LocalVarPrivate,
1795     PDSA_Implicit
1796   } Reason = PDSA_Implicit;
1797   bool ReportHint = false;
1798   auto ReportLoc = D->getLocation();
1799   auto *VD = dyn_cast<VarDecl>(D);
1800   if (IsLoopIterVar) {
1801     if (DVar.CKind == OMPC_private)
1802       Reason = PDSA_LoopIterVarPrivate;
1803     else if (DVar.CKind == OMPC_lastprivate)
1804       Reason = PDSA_LoopIterVarLastprivate;
1805     else
1806       Reason = PDSA_LoopIterVarLinear;
1807   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1808              DVar.CKind == OMPC_firstprivate) {
1809     Reason = PDSA_TaskVarFirstprivate;
1810     ReportLoc = DVar.ImplicitDSALoc;
1811   } else if (VD && VD->isStaticLocal())
1812     Reason = PDSA_StaticLocalVarShared;
1813   else if (VD && VD->isStaticDataMember())
1814     Reason = PDSA_StaticMemberShared;
1815   else if (VD && VD->isFileVarDecl())
1816     Reason = PDSA_GlobalVarShared;
1817   else if (D->getType().isConstant(SemaRef.getASTContext()))
1818     Reason = PDSA_ConstVarShared;
1819   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1820     ReportHint = true;
1821     Reason = PDSA_LocalVarPrivate;
1822   }
1823   if (Reason != PDSA_Implicit) {
1824     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1825         << Reason << ReportHint
1826         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1827   } else if (DVar.ImplicitDSALoc.isValid()) {
1828     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1829         << getOpenMPClauseName(DVar.CKind);
1830   }
1831 }
1832 
1833 namespace {
1834 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1835   DSAStackTy *Stack;
1836   Sema &SemaRef;
1837   bool ErrorFound;
1838   CapturedStmt *CS;
1839   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1840   llvm::SmallVector<Expr *, 8> ImplicitMap;
1841   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1842   llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
1843 
1844 public:
1845   void VisitDeclRefExpr(DeclRefExpr *E) {
1846     if (E->isTypeDependent() || E->isValueDependent() ||
1847         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1848       return;
1849     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1850       VD = VD->getCanonicalDecl();
1851       // Skip internally declared variables.
1852       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
1853         return;
1854 
1855       auto DVar = Stack->getTopDSA(VD, false);
1856       // Check if the variable has explicit DSA set and stop analysis if it so.
1857       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
1858         return;
1859 
1860       // Skip internally declared static variables.
1861       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1862         return;
1863 
1864       auto ELoc = E->getExprLoc();
1865       auto DKind = Stack->getCurrentDirective();
1866       // The default(none) clause requires that each variable that is referenced
1867       // in the construct, and does not have a predetermined data-sharing
1868       // attribute, must have its data-sharing attribute explicitly determined
1869       // by being listed in a data-sharing attribute clause.
1870       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1871           isParallelOrTaskRegion(DKind) &&
1872           VarsWithInheritedDSA.count(VD) == 0) {
1873         VarsWithInheritedDSA[VD] = E;
1874         return;
1875       }
1876 
1877       if (isOpenMPTargetExecutionDirective(DKind) &&
1878           !Stack->isLoopControlVariable(VD).first) {
1879         if (!Stack->checkMappableExprComponentListsForDecl(
1880                 VD, /*CurrentRegionOnly=*/true,
1881                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1882                        StackComponents,
1883                    OpenMPClauseKind) {
1884                   // Variable is used if it has been marked as an array, array
1885                   // section or the variable iself.
1886                   return StackComponents.size() == 1 ||
1887                          std::all_of(
1888                              std::next(StackComponents.rbegin()),
1889                              StackComponents.rend(),
1890                              [](const OMPClauseMappableExprCommon::
1891                                     MappableComponent &MC) {
1892                                return MC.getAssociatedDeclaration() ==
1893                                           nullptr &&
1894                                       (isa<OMPArraySectionExpr>(
1895                                            MC.getAssociatedExpression()) ||
1896                                        isa<ArraySubscriptExpr>(
1897                                            MC.getAssociatedExpression()));
1898                              });
1899                 })) {
1900           bool IsFirstprivate = false;
1901           // By default lambdas are captured as firstprivates.
1902           if (const auto *RD =
1903                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
1904             IsFirstprivate = RD->isLambda();
1905           IsFirstprivate =
1906               IsFirstprivate ||
1907               (VD->getType().getNonReferenceType()->isScalarType() &&
1908                Stack->getDefaultDMA() != DMA_tofrom_scalar);
1909           if (IsFirstprivate)
1910             ImplicitFirstprivate.emplace_back(E);
1911           else
1912             ImplicitMap.emplace_back(E);
1913           return;
1914         }
1915       }
1916 
1917       // OpenMP [2.9.3.6, Restrictions, p.2]
1918       //  A list item that appears in a reduction clause of the innermost
1919       //  enclosing worksharing or parallel construct may not be accessed in an
1920       //  explicit task.
1921       DVar = Stack->hasInnermostDSA(
1922           VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1923           [](OpenMPDirectiveKind K) -> bool {
1924             return isOpenMPParallelDirective(K) ||
1925                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1926           },
1927           /*FromParent=*/true);
1928       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1929         ErrorFound = true;
1930         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1931         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1932         return;
1933       }
1934 
1935       // Define implicit data-sharing attributes for task.
1936       DVar = Stack->getImplicitDSA(VD, false);
1937       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1938           !Stack->isLoopControlVariable(VD).first)
1939         ImplicitFirstprivate.push_back(E);
1940     }
1941   }
1942   void VisitMemberExpr(MemberExpr *E) {
1943     if (E->isTypeDependent() || E->isValueDependent() ||
1944         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1945       return;
1946     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1947     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
1948     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1949       if (!FD)
1950         return;
1951       auto DVar = Stack->getTopDSA(FD, false);
1952       // Check if the variable has explicit DSA set and stop analysis if it
1953       // so.
1954       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1955         return;
1956 
1957       if (isOpenMPTargetExecutionDirective(DKind) &&
1958           !Stack->isLoopControlVariable(FD).first &&
1959           !Stack->checkMappableExprComponentListsForDecl(
1960               FD, /*CurrentRegionOnly=*/true,
1961               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1962                      StackComponents,
1963                  OpenMPClauseKind) {
1964                 return isa<CXXThisExpr>(
1965                     cast<MemberExpr>(
1966                         StackComponents.back().getAssociatedExpression())
1967                         ->getBase()
1968                         ->IgnoreParens());
1969               })) {
1970         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1971         //  A bit-field cannot appear in a map clause.
1972         //
1973         if (FD->isBitField())
1974           return;
1975         ImplicitMap.emplace_back(E);
1976         return;
1977       }
1978 
1979       auto ELoc = E->getExprLoc();
1980       // OpenMP [2.9.3.6, Restrictions, p.2]
1981       //  A list item that appears in a reduction clause of the innermost
1982       //  enclosing worksharing or parallel construct may not be accessed in
1983       //  an  explicit task.
1984       DVar = Stack->hasInnermostDSA(
1985           FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1986           [](OpenMPDirectiveKind K) -> bool {
1987             return isOpenMPParallelDirective(K) ||
1988                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1989           },
1990           /*FromParent=*/true);
1991       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1992         ErrorFound = true;
1993         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1994         ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1995         return;
1996       }
1997 
1998       // Define implicit data-sharing attributes for task.
1999       DVar = Stack->getImplicitDSA(FD, false);
2000       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2001           !Stack->isLoopControlVariable(FD).first)
2002         ImplicitFirstprivate.push_back(E);
2003       return;
2004     }
2005     if (isOpenMPTargetExecutionDirective(DKind)) {
2006       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2007       if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2008                                         /*NoDiagnose=*/true))
2009         return;
2010       auto *VD = cast<ValueDecl>(
2011           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2012       if (!Stack->checkMappableExprComponentListsForDecl(
2013               VD, /*CurrentRegionOnly=*/true,
2014               [&CurComponents](
2015                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2016                       StackComponents,
2017                   OpenMPClauseKind) {
2018                 auto CCI = CurComponents.rbegin();
2019                 auto CCE = CurComponents.rend();
2020                 for (const auto &SC : llvm::reverse(StackComponents)) {
2021                   // Do both expressions have the same kind?
2022                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2023                       SC.getAssociatedExpression()->getStmtClass())
2024                     if (!(isa<OMPArraySectionExpr>(
2025                               SC.getAssociatedExpression()) &&
2026                           isa<ArraySubscriptExpr>(
2027                               CCI->getAssociatedExpression())))
2028                       return false;
2029 
2030                   Decl *CCD = CCI->getAssociatedDeclaration();
2031                   Decl *SCD = SC.getAssociatedDeclaration();
2032                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2033                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2034                   if (SCD != CCD)
2035                     return false;
2036                   std::advance(CCI, 1);
2037                   if (CCI == CCE)
2038                     break;
2039                 }
2040                 return true;
2041               })) {
2042         Visit(E->getBase());
2043       }
2044     } else
2045       Visit(E->getBase());
2046   }
2047   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2048     for (auto *C : S->clauses()) {
2049       // Skip analysis of arguments of implicitly defined firstprivate clause
2050       // for task|target directives.
2051       // Skip analysis of arguments of implicitly defined map clause for target
2052       // directives.
2053       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2054                  C->isImplicit())) {
2055         for (auto *CC : C->children()) {
2056           if (CC)
2057             Visit(CC);
2058         }
2059       }
2060     }
2061   }
2062   void VisitStmt(Stmt *S) {
2063     for (auto *C : S->children()) {
2064       if (C && !isa<OMPExecutableDirective>(C))
2065         Visit(C);
2066     }
2067   }
2068 
2069   bool isErrorFound() { return ErrorFound; }
2070   ArrayRef<Expr *> getImplicitFirstprivate() const {
2071     return ImplicitFirstprivate;
2072   }
2073   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2074   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
2075     return VarsWithInheritedDSA;
2076   }
2077 
2078   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2079       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2080 };
2081 } // namespace
2082 
2083 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2084   switch (DKind) {
2085   case OMPD_parallel:
2086   case OMPD_parallel_for:
2087   case OMPD_parallel_for_simd:
2088   case OMPD_parallel_sections:
2089   case OMPD_teams:
2090   case OMPD_teams_distribute:
2091   case OMPD_teams_distribute_simd: {
2092     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2093     QualType KmpInt32PtrTy =
2094         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2095     Sema::CapturedParamNameType Params[] = {
2096         std::make_pair(".global_tid.", KmpInt32PtrTy),
2097         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2098         std::make_pair(StringRef(), QualType()) // __context with shared vars
2099     };
2100     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2101                              Params);
2102     break;
2103   }
2104   case OMPD_target_teams:
2105   case OMPD_target_parallel:
2106   case OMPD_target_parallel_for:
2107   case OMPD_target_parallel_for_simd:
2108   case OMPD_target_teams_distribute: {
2109     Sema::CapturedParamNameType ParamsTarget[] = {
2110         std::make_pair(StringRef(), QualType()) // __context with shared vars
2111     };
2112     // Start a captured region for 'target' with no implicit parameters.
2113     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2114                              ParamsTarget);
2115     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2116     QualType KmpInt32PtrTy =
2117         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2118     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2119         std::make_pair(".global_tid.", KmpInt32PtrTy),
2120         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2121         std::make_pair(StringRef(), QualType()) // __context with shared vars
2122     };
2123     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2124     // the same implicit parameters.
2125     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2126                              ParamsTeamsOrParallel);
2127     break;
2128   }
2129   case OMPD_simd:
2130   case OMPD_for:
2131   case OMPD_for_simd:
2132   case OMPD_sections:
2133   case OMPD_section:
2134   case OMPD_single:
2135   case OMPD_master:
2136   case OMPD_critical:
2137   case OMPD_taskgroup:
2138   case OMPD_distribute:
2139   case OMPD_distribute_simd:
2140   case OMPD_ordered:
2141   case OMPD_atomic:
2142   case OMPD_target_data:
2143   case OMPD_target:
2144   case OMPD_target_simd: {
2145     Sema::CapturedParamNameType Params[] = {
2146         std::make_pair(StringRef(), QualType()) // __context with shared vars
2147     };
2148     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2149                              Params);
2150     break;
2151   }
2152   case OMPD_task: {
2153     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2154     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2155     FunctionProtoType::ExtProtoInfo EPI;
2156     EPI.Variadic = true;
2157     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2158     Sema::CapturedParamNameType Params[] = {
2159         std::make_pair(".global_tid.", KmpInt32Ty),
2160         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2161         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2162         std::make_pair(".copy_fn.",
2163                        Context.getPointerType(CopyFnType).withConst()),
2164         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2165         std::make_pair(StringRef(), QualType()) // __context with shared vars
2166     };
2167     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2168                              Params);
2169     // Mark this captured region as inlined, because we don't use outlined
2170     // function directly.
2171     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2172         AlwaysInlineAttr::CreateImplicit(
2173             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2174     break;
2175   }
2176   case OMPD_taskloop:
2177   case OMPD_taskloop_simd: {
2178     QualType KmpInt32Ty =
2179         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2180     QualType KmpUInt64Ty =
2181         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2182     QualType KmpInt64Ty =
2183         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2184     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2185     FunctionProtoType::ExtProtoInfo EPI;
2186     EPI.Variadic = true;
2187     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2188     Sema::CapturedParamNameType Params[] = {
2189         std::make_pair(".global_tid.", KmpInt32Ty),
2190         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2191         std::make_pair(".privates.",
2192                        Context.VoidPtrTy.withConst().withRestrict()),
2193         std::make_pair(
2194             ".copy_fn.",
2195             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2196         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2197         std::make_pair(".lb.", KmpUInt64Ty),
2198         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2199         std::make_pair(".liter.", KmpInt32Ty),
2200         std::make_pair(".reductions.",
2201                        Context.VoidPtrTy.withConst().withRestrict()),
2202         std::make_pair(StringRef(), QualType()) // __context with shared vars
2203     };
2204     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2205                              Params);
2206     // Mark this captured region as inlined, because we don't use outlined
2207     // function directly.
2208     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2209         AlwaysInlineAttr::CreateImplicit(
2210             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2211     break;
2212   }
2213   case OMPD_distribute_parallel_for_simd:
2214   case OMPD_distribute_parallel_for:
2215   case OMPD_target_teams_distribute_parallel_for:
2216   case OMPD_target_teams_distribute_parallel_for_simd:
2217   case OMPD_target_teams_distribute_simd: {
2218     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2219     QualType KmpInt32PtrTy =
2220         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2221     Sema::CapturedParamNameType Params[] = {
2222         std::make_pair(".global_tid.", KmpInt32PtrTy),
2223         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2224         std::make_pair(".previous.lb.", Context.getSizeType()),
2225         std::make_pair(".previous.ub.", Context.getSizeType()),
2226         std::make_pair(StringRef(), QualType()) // __context with shared vars
2227     };
2228     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2229                              Params);
2230     break;
2231   }
2232   case OMPD_teams_distribute_parallel_for:
2233   case OMPD_teams_distribute_parallel_for_simd: {
2234     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2235     QualType KmpInt32PtrTy =
2236         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2237 
2238     Sema::CapturedParamNameType ParamsTeams[] = {
2239         std::make_pair(".global_tid.", KmpInt32PtrTy),
2240         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2241         std::make_pair(StringRef(), QualType()) // __context with shared vars
2242     };
2243     // Start a captured region for 'target' with no implicit parameters.
2244     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2245                              ParamsTeams);
2246 
2247     Sema::CapturedParamNameType ParamsParallel[] = {
2248         std::make_pair(".global_tid.", KmpInt32PtrTy),
2249         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2250         std::make_pair(".previous.lb.", Context.getSizeType()),
2251         std::make_pair(".previous.ub.", Context.getSizeType()),
2252         std::make_pair(StringRef(), QualType()) // __context with shared vars
2253     };
2254     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2255     // the same implicit parameters.
2256     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2257                              ParamsParallel);
2258     break;
2259   }
2260   case OMPD_target_update:
2261   case OMPD_target_enter_data:
2262   case OMPD_target_exit_data: {
2263     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2264     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2265     FunctionProtoType::ExtProtoInfo EPI;
2266     EPI.Variadic = true;
2267     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2268     Sema::CapturedParamNameType Params[] = {
2269         std::make_pair(".global_tid.", KmpInt32Ty),
2270         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2271         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2272         std::make_pair(".copy_fn.",
2273                        Context.getPointerType(CopyFnType).withConst()),
2274         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2275         std::make_pair(StringRef(), QualType()) // __context with shared vars
2276     };
2277     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2278                              Params);
2279     // Mark this captured region as inlined, because we don't use outlined
2280     // function directly.
2281     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2282         AlwaysInlineAttr::CreateImplicit(
2283             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2284     break;
2285   }
2286   case OMPD_threadprivate:
2287   case OMPD_taskyield:
2288   case OMPD_barrier:
2289   case OMPD_taskwait:
2290   case OMPD_cancellation_point:
2291   case OMPD_cancel:
2292   case OMPD_flush:
2293   case OMPD_declare_reduction:
2294   case OMPD_declare_simd:
2295   case OMPD_declare_target:
2296   case OMPD_end_declare_target:
2297     llvm_unreachable("OpenMP Directive is not allowed");
2298   case OMPD_unknown:
2299     llvm_unreachable("Unknown OpenMP directive");
2300   }
2301 }
2302 
2303 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2304   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2305   getOpenMPCaptureRegions(CaptureRegions, DKind);
2306   return CaptureRegions.size();
2307 }
2308 
2309 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2310                                              Expr *CaptureExpr, bool WithInit,
2311                                              bool AsExpression) {
2312   assert(CaptureExpr);
2313   ASTContext &C = S.getASTContext();
2314   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2315   QualType Ty = Init->getType();
2316   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2317     if (S.getLangOpts().CPlusPlus)
2318       Ty = C.getLValueReferenceType(Ty);
2319     else {
2320       Ty = C.getPointerType(Ty);
2321       ExprResult Res =
2322           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2323       if (!Res.isUsable())
2324         return nullptr;
2325       Init = Res.get();
2326     }
2327     WithInit = true;
2328   }
2329   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2330                                           CaptureExpr->getLocStart());
2331   if (!WithInit)
2332     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
2333   S.CurContext->addHiddenDecl(CED);
2334   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2335   return CED;
2336 }
2337 
2338 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2339                                  bool WithInit) {
2340   OMPCapturedExprDecl *CD;
2341   if (auto *VD = S.IsOpenMPCapturedDecl(D))
2342     CD = cast<OMPCapturedExprDecl>(VD);
2343   else
2344     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2345                           /*AsExpression=*/false);
2346   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2347                           CaptureExpr->getExprLoc());
2348 }
2349 
2350 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2351   if (!Ref) {
2352     auto *CD =
2353         buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2354                          CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2355     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2356                            CaptureExpr->getExprLoc());
2357   }
2358   ExprResult Res = Ref;
2359   if (!S.getLangOpts().CPlusPlus &&
2360       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2361       Ref->getType()->isPointerType())
2362     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2363   if (!Res.isUsable())
2364     return ExprError();
2365   return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
2366 }
2367 
2368 namespace {
2369 // OpenMP directives parsed in this section are represented as a
2370 // CapturedStatement with an associated statement.  If a syntax error
2371 // is detected during the parsing of the associated statement, the
2372 // compiler must abort processing and close the CapturedStatement.
2373 //
2374 // Combined directives such as 'target parallel' have more than one
2375 // nested CapturedStatements.  This RAII ensures that we unwind out
2376 // of all the nested CapturedStatements when an error is found.
2377 class CaptureRegionUnwinderRAII {
2378 private:
2379   Sema &S;
2380   bool &ErrorFound;
2381   OpenMPDirectiveKind DKind;
2382 
2383 public:
2384   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2385                             OpenMPDirectiveKind DKind)
2386       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2387   ~CaptureRegionUnwinderRAII() {
2388     if (ErrorFound) {
2389       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2390       while (--ThisCaptureLevel >= 0)
2391         S.ActOnCapturedRegionError();
2392     }
2393   }
2394 };
2395 } // namespace
2396 
2397 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2398                                       ArrayRef<OMPClause *> Clauses) {
2399   bool ErrorFound = false;
2400   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2401       *this, ErrorFound, DSAStack->getCurrentDirective());
2402   if (!S.isUsable()) {
2403     ErrorFound = true;
2404     return StmtError();
2405   }
2406 
2407   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2408   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2409   OMPOrderedClause *OC = nullptr;
2410   OMPScheduleClause *SC = nullptr;
2411   SmallVector<OMPLinearClause *, 4> LCs;
2412   SmallVector<OMPClauseWithPreInit *, 8> PICs;
2413   // This is required for proper codegen.
2414   for (auto *Clause : Clauses) {
2415     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2416         Clause->getClauseKind() == OMPC_in_reduction) {
2417       // Capture taskgroup task_reduction descriptors inside the tasking regions
2418       // with the corresponding in_reduction items.
2419       auto *IRC = cast<OMPInReductionClause>(Clause);
2420       for (auto *E : IRC->taskgroup_descriptors())
2421         if (E)
2422           MarkDeclarationsReferencedInExpr(E);
2423     }
2424     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2425         Clause->getClauseKind() == OMPC_copyprivate ||
2426         (getLangOpts().OpenMPUseTLS &&
2427          getASTContext().getTargetInfo().isTLSSupported() &&
2428          Clause->getClauseKind() == OMPC_copyin)) {
2429       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2430       // Mark all variables in private list clauses as used in inner region.
2431       for (auto *VarRef : Clause->children()) {
2432         if (auto *E = cast_or_null<Expr>(VarRef)) {
2433           MarkDeclarationsReferencedInExpr(E);
2434         }
2435       }
2436       DSAStack->setForceVarCapturing(/*V=*/false);
2437     } else if (CaptureRegions.size() > 1 ||
2438                CaptureRegions.back() != OMPD_unknown) {
2439       if (auto *C = OMPClauseWithPreInit::get(Clause))
2440         PICs.push_back(C);
2441       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2442         if (auto *E = C->getPostUpdateExpr())
2443           MarkDeclarationsReferencedInExpr(E);
2444       }
2445     }
2446     if (Clause->getClauseKind() == OMPC_schedule)
2447       SC = cast<OMPScheduleClause>(Clause);
2448     else if (Clause->getClauseKind() == OMPC_ordered)
2449       OC = cast<OMPOrderedClause>(Clause);
2450     else if (Clause->getClauseKind() == OMPC_linear)
2451       LCs.push_back(cast<OMPLinearClause>(Clause));
2452   }
2453   // OpenMP, 2.7.1 Loop Construct, Restrictions
2454   // The nonmonotonic modifier cannot be specified if an ordered clause is
2455   // specified.
2456   if (SC &&
2457       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2458        SC->getSecondScheduleModifier() ==
2459            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2460       OC) {
2461     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2462              ? SC->getFirstScheduleModifierLoc()
2463              : SC->getSecondScheduleModifierLoc(),
2464          diag::err_omp_schedule_nonmonotonic_ordered)
2465         << SourceRange(OC->getLocStart(), OC->getLocEnd());
2466     ErrorFound = true;
2467   }
2468   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2469     for (auto *C : LCs) {
2470       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2471           << SourceRange(OC->getLocStart(), OC->getLocEnd());
2472     }
2473     ErrorFound = true;
2474   }
2475   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2476       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2477       OC->getNumForLoops()) {
2478     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2479         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2480     ErrorFound = true;
2481   }
2482   if (ErrorFound) {
2483     return StmtError();
2484   }
2485   StmtResult SR = S;
2486   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2487     // Mark all variables in private list clauses as used in inner region.
2488     // Required for proper codegen of combined directives.
2489     // TODO: add processing for other clauses.
2490     if (ThisCaptureRegion != OMPD_unknown) {
2491       for (auto *C : PICs) {
2492         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2493         // Find the particular capture region for the clause if the
2494         // directive is a combined one with multiple capture regions.
2495         // If the directive is not a combined one, the capture region
2496         // associated with the clause is OMPD_unknown and is generated
2497         // only once.
2498         if (CaptureRegion == ThisCaptureRegion ||
2499             CaptureRegion == OMPD_unknown) {
2500           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2501             for (auto *D : DS->decls())
2502               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2503           }
2504         }
2505       }
2506     }
2507     SR = ActOnCapturedRegionEnd(SR.get());
2508   }
2509   return SR;
2510 }
2511 
2512 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2513                               OpenMPDirectiveKind CancelRegion,
2514                               SourceLocation StartLoc) {
2515   // CancelRegion is only needed for cancel and cancellation_point.
2516   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2517     return false;
2518 
2519   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2520       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2521     return false;
2522 
2523   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2524       << getOpenMPDirectiveName(CancelRegion);
2525   return true;
2526 }
2527 
2528 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
2529                                   OpenMPDirectiveKind CurrentRegion,
2530                                   const DeclarationNameInfo &CurrentName,
2531                                   OpenMPDirectiveKind CancelRegion,
2532                                   SourceLocation StartLoc) {
2533   if (Stack->getCurScope()) {
2534     auto ParentRegion = Stack->getParentDirective();
2535     auto OffendingRegion = ParentRegion;
2536     bool NestingProhibited = false;
2537     bool CloseNesting = true;
2538     bool OrphanSeen = false;
2539     enum {
2540       NoRecommend,
2541       ShouldBeInParallelRegion,
2542       ShouldBeInOrderedRegion,
2543       ShouldBeInTargetRegion,
2544       ShouldBeInTeamsRegion
2545     } Recommend = NoRecommend;
2546     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2547       // OpenMP [2.16, Nesting of Regions]
2548       // OpenMP constructs may not be nested inside a simd region.
2549       // OpenMP [2.8.1,simd Construct, Restrictions]
2550       // An ordered construct with the simd clause is the only OpenMP
2551       // construct that can appear in the simd region.
2552       // Allowing a SIMD construct nested in another SIMD construct is an
2553       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2554       // message.
2555       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2556                                  ? diag::err_omp_prohibited_region_simd
2557                                  : diag::warn_omp_nesting_simd);
2558       return CurrentRegion != OMPD_simd;
2559     }
2560     if (ParentRegion == OMPD_atomic) {
2561       // OpenMP [2.16, Nesting of Regions]
2562       // OpenMP constructs may not be nested inside an atomic region.
2563       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2564       return true;
2565     }
2566     if (CurrentRegion == OMPD_section) {
2567       // OpenMP [2.7.2, sections Construct, Restrictions]
2568       // Orphaned section directives are prohibited. That is, the section
2569       // directives must appear within the sections construct and must not be
2570       // encountered elsewhere in the sections region.
2571       if (ParentRegion != OMPD_sections &&
2572           ParentRegion != OMPD_parallel_sections) {
2573         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2574             << (ParentRegion != OMPD_unknown)
2575             << getOpenMPDirectiveName(ParentRegion);
2576         return true;
2577       }
2578       return false;
2579     }
2580     // Allow some constructs (except teams) to be orphaned (they could be
2581     // used in functions, called from OpenMP regions with the required
2582     // preconditions).
2583     if (ParentRegion == OMPD_unknown &&
2584         !isOpenMPNestingTeamsDirective(CurrentRegion))
2585       return false;
2586     if (CurrentRegion == OMPD_cancellation_point ||
2587         CurrentRegion == OMPD_cancel) {
2588       // OpenMP [2.16, Nesting of Regions]
2589       // A cancellation point construct for which construct-type-clause is
2590       // taskgroup must be nested inside a task construct. A cancellation
2591       // point construct for which construct-type-clause is not taskgroup must
2592       // be closely nested inside an OpenMP construct that matches the type
2593       // specified in construct-type-clause.
2594       // A cancel construct for which construct-type-clause is taskgroup must be
2595       // nested inside a task construct. A cancel construct for which
2596       // construct-type-clause is not taskgroup must be closely nested inside an
2597       // OpenMP construct that matches the type specified in
2598       // construct-type-clause.
2599       NestingProhibited =
2600           !((CancelRegion == OMPD_parallel &&
2601              (ParentRegion == OMPD_parallel ||
2602               ParentRegion == OMPD_target_parallel)) ||
2603             (CancelRegion == OMPD_for &&
2604              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2605               ParentRegion == OMPD_target_parallel_for ||
2606               ParentRegion == OMPD_distribute_parallel_for ||
2607               ParentRegion == OMPD_teams_distribute_parallel_for ||
2608               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
2609             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2610             (CancelRegion == OMPD_sections &&
2611              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2612               ParentRegion == OMPD_parallel_sections)));
2613     } else if (CurrentRegion == OMPD_master) {
2614       // OpenMP [2.16, Nesting of Regions]
2615       // A master region may not be closely nested inside a worksharing,
2616       // atomic, or explicit task region.
2617       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2618                           isOpenMPTaskingDirective(ParentRegion);
2619     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2620       // OpenMP [2.16, Nesting of Regions]
2621       // A critical region may not be nested (closely or otherwise) inside a
2622       // critical region with the same name. Note that this restriction is not
2623       // sufficient to prevent deadlock.
2624       SourceLocation PreviousCriticalLoc;
2625       bool DeadLock = Stack->hasDirective(
2626           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2627                                               const DeclarationNameInfo &DNI,
2628                                               SourceLocation Loc) -> bool {
2629             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2630               PreviousCriticalLoc = Loc;
2631               return true;
2632             } else
2633               return false;
2634           },
2635           false /* skip top directive */);
2636       if (DeadLock) {
2637         SemaRef.Diag(StartLoc,
2638                      diag::err_omp_prohibited_region_critical_same_name)
2639             << CurrentName.getName();
2640         if (PreviousCriticalLoc.isValid())
2641           SemaRef.Diag(PreviousCriticalLoc,
2642                        diag::note_omp_previous_critical_region);
2643         return true;
2644       }
2645     } else if (CurrentRegion == OMPD_barrier) {
2646       // OpenMP [2.16, Nesting of Regions]
2647       // A barrier region may not be closely nested inside a worksharing,
2648       // explicit task, critical, ordered, atomic, or master region.
2649       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2650                           isOpenMPTaskingDirective(ParentRegion) ||
2651                           ParentRegion == OMPD_master ||
2652                           ParentRegion == OMPD_critical ||
2653                           ParentRegion == OMPD_ordered;
2654     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2655                !isOpenMPParallelDirective(CurrentRegion) &&
2656                !isOpenMPTeamsDirective(CurrentRegion)) {
2657       // OpenMP [2.16, Nesting of Regions]
2658       // A worksharing region may not be closely nested inside a worksharing,
2659       // explicit task, critical, ordered, atomic, or master region.
2660       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2661                           isOpenMPTaskingDirective(ParentRegion) ||
2662                           ParentRegion == OMPD_master ||
2663                           ParentRegion == OMPD_critical ||
2664                           ParentRegion == OMPD_ordered;
2665       Recommend = ShouldBeInParallelRegion;
2666     } else if (CurrentRegion == OMPD_ordered) {
2667       // OpenMP [2.16, Nesting of Regions]
2668       // An ordered region may not be closely nested inside a critical,
2669       // atomic, or explicit task region.
2670       // An ordered region must be closely nested inside a loop region (or
2671       // parallel loop region) with an ordered clause.
2672       // OpenMP [2.8.1,simd Construct, Restrictions]
2673       // An ordered construct with the simd clause is the only OpenMP construct
2674       // that can appear in the simd region.
2675       NestingProhibited = ParentRegion == OMPD_critical ||
2676                           isOpenMPTaskingDirective(ParentRegion) ||
2677                           !(isOpenMPSimdDirective(ParentRegion) ||
2678                             Stack->isParentOrderedRegion());
2679       Recommend = ShouldBeInOrderedRegion;
2680     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
2681       // OpenMP [2.16, Nesting of Regions]
2682       // If specified, a teams construct must be contained within a target
2683       // construct.
2684       NestingProhibited = ParentRegion != OMPD_target;
2685       OrphanSeen = ParentRegion == OMPD_unknown;
2686       Recommend = ShouldBeInTargetRegion;
2687     }
2688     if (!NestingProhibited &&
2689         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2690         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2691         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
2692       // OpenMP [2.16, Nesting of Regions]
2693       // distribute, parallel, parallel sections, parallel workshare, and the
2694       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2695       // constructs that can be closely nested in the teams region.
2696       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2697                           !isOpenMPDistributeDirective(CurrentRegion);
2698       Recommend = ShouldBeInParallelRegion;
2699     }
2700     if (!NestingProhibited &&
2701         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2702       // OpenMP 4.5 [2.17 Nesting of Regions]
2703       // The region associated with the distribute construct must be strictly
2704       // nested inside a teams region
2705       NestingProhibited =
2706           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
2707       Recommend = ShouldBeInTeamsRegion;
2708     }
2709     if (!NestingProhibited &&
2710         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2711          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2712       // OpenMP 4.5 [2.17 Nesting of Regions]
2713       // If a target, target update, target data, target enter data, or
2714       // target exit data construct is encountered during execution of a
2715       // target region, the behavior is unspecified.
2716       NestingProhibited = Stack->hasDirective(
2717           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2718                              SourceLocation) -> bool {
2719             if (isOpenMPTargetExecutionDirective(K)) {
2720               OffendingRegion = K;
2721               return true;
2722             } else
2723               return false;
2724           },
2725           false /* don't skip top directive */);
2726       CloseNesting = false;
2727     }
2728     if (NestingProhibited) {
2729       if (OrphanSeen) {
2730         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2731             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2732       } else {
2733         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2734             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2735             << Recommend << getOpenMPDirectiveName(CurrentRegion);
2736       }
2737       return true;
2738     }
2739   }
2740   return false;
2741 }
2742 
2743 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2744                            ArrayRef<OMPClause *> Clauses,
2745                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2746   bool ErrorFound = false;
2747   unsigned NamedModifiersNumber = 0;
2748   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2749       OMPD_unknown + 1);
2750   SmallVector<SourceLocation, 4> NameModifierLoc;
2751   for (const auto *C : Clauses) {
2752     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2753       // At most one if clause without a directive-name-modifier can appear on
2754       // the directive.
2755       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2756       if (FoundNameModifiers[CurNM]) {
2757         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2758             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2759             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2760         ErrorFound = true;
2761       } else if (CurNM != OMPD_unknown) {
2762         NameModifierLoc.push_back(IC->getNameModifierLoc());
2763         ++NamedModifiersNumber;
2764       }
2765       FoundNameModifiers[CurNM] = IC;
2766       if (CurNM == OMPD_unknown)
2767         continue;
2768       // Check if the specified name modifier is allowed for the current
2769       // directive.
2770       // At most one if clause with the particular directive-name-modifier can
2771       // appear on the directive.
2772       bool MatchFound = false;
2773       for (auto NM : AllowedNameModifiers) {
2774         if (CurNM == NM) {
2775           MatchFound = true;
2776           break;
2777         }
2778       }
2779       if (!MatchFound) {
2780         S.Diag(IC->getNameModifierLoc(),
2781                diag::err_omp_wrong_if_directive_name_modifier)
2782             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2783         ErrorFound = true;
2784       }
2785     }
2786   }
2787   // If any if clause on the directive includes a directive-name-modifier then
2788   // all if clauses on the directive must include a directive-name-modifier.
2789   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2790     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2791       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2792              diag::err_omp_no_more_if_clause);
2793     } else {
2794       std::string Values;
2795       std::string Sep(", ");
2796       unsigned AllowedCnt = 0;
2797       unsigned TotalAllowedNum =
2798           AllowedNameModifiers.size() - NamedModifiersNumber;
2799       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2800            ++Cnt) {
2801         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2802         if (!FoundNameModifiers[NM]) {
2803           Values += "'";
2804           Values += getOpenMPDirectiveName(NM);
2805           Values += "'";
2806           if (AllowedCnt + 2 == TotalAllowedNum)
2807             Values += " or ";
2808           else if (AllowedCnt + 1 != TotalAllowedNum)
2809             Values += Sep;
2810           ++AllowedCnt;
2811         }
2812       }
2813       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2814              diag::err_omp_unnamed_if_clause)
2815           << (TotalAllowedNum > 1) << Values;
2816     }
2817     for (auto Loc : NameModifierLoc) {
2818       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2819     }
2820     ErrorFound = true;
2821   }
2822   return ErrorFound;
2823 }
2824 
2825 StmtResult Sema::ActOnOpenMPExecutableDirective(
2826     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2827     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2828     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2829   StmtResult Res = StmtError();
2830   // First check CancelRegion which is then used in checkNestingOfRegions.
2831   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2832       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2833                             StartLoc))
2834     return StmtError();
2835 
2836   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2837   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2838   bool ErrorFound = false;
2839   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2840   if (AStmt && !CurContext->isDependentContext()) {
2841     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2842 
2843     // Check default data sharing attributes for referenced variables.
2844     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2845     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2846     Stmt *S = AStmt;
2847     while (--ThisCaptureLevel >= 0)
2848       S = cast<CapturedStmt>(S)->getCapturedStmt();
2849     DSAChecker.Visit(S);
2850     if (DSAChecker.isErrorFound())
2851       return StmtError();
2852     // Generate list of implicitly defined firstprivate variables.
2853     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2854 
2855     SmallVector<Expr *, 4> ImplicitFirstprivates(
2856         DSAChecker.getImplicitFirstprivate().begin(),
2857         DSAChecker.getImplicitFirstprivate().end());
2858     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2859                                         DSAChecker.getImplicitMap().end());
2860     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2861     for (auto *C : Clauses) {
2862       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2863         for (auto *E : IRC->taskgroup_descriptors())
2864           if (E)
2865             ImplicitFirstprivates.emplace_back(E);
2866       }
2867     }
2868     if (!ImplicitFirstprivates.empty()) {
2869       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2870               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2871               SourceLocation())) {
2872         ClausesWithImplicit.push_back(Implicit);
2873         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2874                      ImplicitFirstprivates.size();
2875       } else
2876         ErrorFound = true;
2877     }
2878     if (!ImplicitMaps.empty()) {
2879       if (OMPClause *Implicit = ActOnOpenMPMapClause(
2880               OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2881               SourceLocation(), SourceLocation(), ImplicitMaps,
2882               SourceLocation(), SourceLocation(), SourceLocation())) {
2883         ClausesWithImplicit.emplace_back(Implicit);
2884         ErrorFound |=
2885             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2886       } else
2887         ErrorFound = true;
2888     }
2889   }
2890 
2891   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2892   switch (Kind) {
2893   case OMPD_parallel:
2894     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2895                                        EndLoc);
2896     AllowedNameModifiers.push_back(OMPD_parallel);
2897     break;
2898   case OMPD_simd:
2899     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2900                                    VarsWithInheritedDSA);
2901     break;
2902   case OMPD_for:
2903     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2904                                   VarsWithInheritedDSA);
2905     break;
2906   case OMPD_for_simd:
2907     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2908                                       EndLoc, VarsWithInheritedDSA);
2909     break;
2910   case OMPD_sections:
2911     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2912                                        EndLoc);
2913     break;
2914   case OMPD_section:
2915     assert(ClausesWithImplicit.empty() &&
2916            "No clauses are allowed for 'omp section' directive");
2917     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2918     break;
2919   case OMPD_single:
2920     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2921                                      EndLoc);
2922     break;
2923   case OMPD_master:
2924     assert(ClausesWithImplicit.empty() &&
2925            "No clauses are allowed for 'omp master' directive");
2926     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2927     break;
2928   case OMPD_critical:
2929     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2930                                        StartLoc, EndLoc);
2931     break;
2932   case OMPD_parallel_for:
2933     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2934                                           EndLoc, VarsWithInheritedDSA);
2935     AllowedNameModifiers.push_back(OMPD_parallel);
2936     break;
2937   case OMPD_parallel_for_simd:
2938     Res = ActOnOpenMPParallelForSimdDirective(
2939         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2940     AllowedNameModifiers.push_back(OMPD_parallel);
2941     break;
2942   case OMPD_parallel_sections:
2943     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2944                                                StartLoc, EndLoc);
2945     AllowedNameModifiers.push_back(OMPD_parallel);
2946     break;
2947   case OMPD_task:
2948     Res =
2949         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2950     AllowedNameModifiers.push_back(OMPD_task);
2951     break;
2952   case OMPD_taskyield:
2953     assert(ClausesWithImplicit.empty() &&
2954            "No clauses are allowed for 'omp taskyield' directive");
2955     assert(AStmt == nullptr &&
2956            "No associated statement allowed for 'omp taskyield' directive");
2957     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2958     break;
2959   case OMPD_barrier:
2960     assert(ClausesWithImplicit.empty() &&
2961            "No clauses are allowed for 'omp barrier' directive");
2962     assert(AStmt == nullptr &&
2963            "No associated statement allowed for 'omp barrier' directive");
2964     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2965     break;
2966   case OMPD_taskwait:
2967     assert(ClausesWithImplicit.empty() &&
2968            "No clauses are allowed for 'omp taskwait' directive");
2969     assert(AStmt == nullptr &&
2970            "No associated statement allowed for 'omp taskwait' directive");
2971     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2972     break;
2973   case OMPD_taskgroup:
2974     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2975                                         EndLoc);
2976     break;
2977   case OMPD_flush:
2978     assert(AStmt == nullptr &&
2979            "No associated statement allowed for 'omp flush' directive");
2980     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2981     break;
2982   case OMPD_ordered:
2983     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2984                                       EndLoc);
2985     break;
2986   case OMPD_atomic:
2987     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2988                                      EndLoc);
2989     break;
2990   case OMPD_teams:
2991     Res =
2992         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2993     break;
2994   case OMPD_target:
2995     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2996                                      EndLoc);
2997     AllowedNameModifiers.push_back(OMPD_target);
2998     break;
2999   case OMPD_target_parallel:
3000     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3001                                              StartLoc, EndLoc);
3002     AllowedNameModifiers.push_back(OMPD_target);
3003     AllowedNameModifiers.push_back(OMPD_parallel);
3004     break;
3005   case OMPD_target_parallel_for:
3006     Res = ActOnOpenMPTargetParallelForDirective(
3007         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3008     AllowedNameModifiers.push_back(OMPD_target);
3009     AllowedNameModifiers.push_back(OMPD_parallel);
3010     break;
3011   case OMPD_cancellation_point:
3012     assert(ClausesWithImplicit.empty() &&
3013            "No clauses are allowed for 'omp cancellation point' directive");
3014     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3015                                "cancellation point' directive");
3016     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3017     break;
3018   case OMPD_cancel:
3019     assert(AStmt == nullptr &&
3020            "No associated statement allowed for 'omp cancel' directive");
3021     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3022                                      CancelRegion);
3023     AllowedNameModifiers.push_back(OMPD_cancel);
3024     break;
3025   case OMPD_target_data:
3026     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3027                                          EndLoc);
3028     AllowedNameModifiers.push_back(OMPD_target_data);
3029     break;
3030   case OMPD_target_enter_data:
3031     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3032                                               EndLoc, AStmt);
3033     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3034     break;
3035   case OMPD_target_exit_data:
3036     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3037                                              EndLoc, AStmt);
3038     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3039     break;
3040   case OMPD_taskloop:
3041     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3042                                        EndLoc, VarsWithInheritedDSA);
3043     AllowedNameModifiers.push_back(OMPD_taskloop);
3044     break;
3045   case OMPD_taskloop_simd:
3046     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3047                                            EndLoc, VarsWithInheritedDSA);
3048     AllowedNameModifiers.push_back(OMPD_taskloop);
3049     break;
3050   case OMPD_distribute:
3051     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3052                                          EndLoc, VarsWithInheritedDSA);
3053     break;
3054   case OMPD_target_update:
3055     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3056                                            EndLoc, AStmt);
3057     AllowedNameModifiers.push_back(OMPD_target_update);
3058     break;
3059   case OMPD_distribute_parallel_for:
3060     Res = ActOnOpenMPDistributeParallelForDirective(
3061         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3062     AllowedNameModifiers.push_back(OMPD_parallel);
3063     break;
3064   case OMPD_distribute_parallel_for_simd:
3065     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3066         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3067     AllowedNameModifiers.push_back(OMPD_parallel);
3068     break;
3069   case OMPD_distribute_simd:
3070     Res = ActOnOpenMPDistributeSimdDirective(
3071         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3072     break;
3073   case OMPD_target_parallel_for_simd:
3074     Res = ActOnOpenMPTargetParallelForSimdDirective(
3075         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3076     AllowedNameModifiers.push_back(OMPD_target);
3077     AllowedNameModifiers.push_back(OMPD_parallel);
3078     break;
3079   case OMPD_target_simd:
3080     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3081                                          EndLoc, VarsWithInheritedDSA);
3082     AllowedNameModifiers.push_back(OMPD_target);
3083     break;
3084   case OMPD_teams_distribute:
3085     Res = ActOnOpenMPTeamsDistributeDirective(
3086         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3087     break;
3088   case OMPD_teams_distribute_simd:
3089     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3090         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3091     break;
3092   case OMPD_teams_distribute_parallel_for_simd:
3093     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3094         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3095     AllowedNameModifiers.push_back(OMPD_parallel);
3096     break;
3097   case OMPD_teams_distribute_parallel_for:
3098     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3099         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3100     AllowedNameModifiers.push_back(OMPD_parallel);
3101     break;
3102   case OMPD_target_teams:
3103     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3104                                           EndLoc);
3105     AllowedNameModifiers.push_back(OMPD_target);
3106     break;
3107   case OMPD_target_teams_distribute:
3108     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3109         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3110     AllowedNameModifiers.push_back(OMPD_target);
3111     break;
3112   case OMPD_target_teams_distribute_parallel_for:
3113     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3114         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3115     AllowedNameModifiers.push_back(OMPD_target);
3116     AllowedNameModifiers.push_back(OMPD_parallel);
3117     break;
3118   case OMPD_target_teams_distribute_parallel_for_simd:
3119     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3120         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3121     AllowedNameModifiers.push_back(OMPD_target);
3122     AllowedNameModifiers.push_back(OMPD_parallel);
3123     break;
3124   case OMPD_target_teams_distribute_simd:
3125     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3126         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3127     AllowedNameModifiers.push_back(OMPD_target);
3128     break;
3129   case OMPD_declare_target:
3130   case OMPD_end_declare_target:
3131   case OMPD_threadprivate:
3132   case OMPD_declare_reduction:
3133   case OMPD_declare_simd:
3134     llvm_unreachable("OpenMP Directive is not allowed");
3135   case OMPD_unknown:
3136     llvm_unreachable("Unknown OpenMP directive");
3137   }
3138 
3139   for (auto P : VarsWithInheritedDSA) {
3140     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3141         << P.first << P.second->getSourceRange();
3142   }
3143   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3144 
3145   if (!AllowedNameModifiers.empty())
3146     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3147                  ErrorFound;
3148 
3149   if (ErrorFound)
3150     return StmtError();
3151   return Res;
3152 }
3153 
3154 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3155     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3156     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3157     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3158     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3159   assert(Aligneds.size() == Alignments.size());
3160   assert(Linears.size() == LinModifiers.size());
3161   assert(Linears.size() == Steps.size());
3162   if (!DG || DG.get().isNull())
3163     return DeclGroupPtrTy();
3164 
3165   if (!DG.get().isSingleDecl()) {
3166     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3167     return DG;
3168   }
3169   auto *ADecl = DG.get().getSingleDecl();
3170   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3171     ADecl = FTD->getTemplatedDecl();
3172 
3173   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3174   if (!FD) {
3175     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3176     return DeclGroupPtrTy();
3177   }
3178 
3179   // OpenMP [2.8.2, declare simd construct, Description]
3180   // The parameter of the simdlen clause must be a constant positive integer
3181   // expression.
3182   ExprResult SL;
3183   if (Simdlen)
3184     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3185   // OpenMP [2.8.2, declare simd construct, Description]
3186   // The special this pointer can be used as if was one of the arguments to the
3187   // function in any of the linear, aligned, or uniform clauses.
3188   // The uniform clause declares one or more arguments to have an invariant
3189   // value for all concurrent invocations of the function in the execution of a
3190   // single SIMD loop.
3191   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3192   Expr *UniformedLinearThis = nullptr;
3193   for (auto *E : Uniforms) {
3194     E = E->IgnoreParenImpCasts();
3195     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3196       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3197         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3198             FD->getParamDecl(PVD->getFunctionScopeIndex())
3199                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3200           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
3201           continue;
3202         }
3203     if (isa<CXXThisExpr>(E)) {
3204       UniformedLinearThis = E;
3205       continue;
3206     }
3207     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3208         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3209   }
3210   // OpenMP [2.8.2, declare simd construct, Description]
3211   // The aligned clause declares that the object to which each list item points
3212   // is aligned to the number of bytes expressed in the optional parameter of
3213   // the aligned clause.
3214   // The special this pointer can be used as if was one of the arguments to the
3215   // function in any of the linear, aligned, or uniform clauses.
3216   // The type of list items appearing in the aligned clause must be array,
3217   // pointer, reference to array, or reference to pointer.
3218   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3219   Expr *AlignedThis = nullptr;
3220   for (auto *E : Aligneds) {
3221     E = E->IgnoreParenImpCasts();
3222     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3223       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3224         auto *CanonPVD = PVD->getCanonicalDecl();
3225         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3226             FD->getParamDecl(PVD->getFunctionScopeIndex())
3227                     ->getCanonicalDecl() == CanonPVD) {
3228           // OpenMP  [2.8.1, simd construct, Restrictions]
3229           // A list-item cannot appear in more than one aligned clause.
3230           if (AlignedArgs.count(CanonPVD) > 0) {
3231             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3232                 << 1 << E->getSourceRange();
3233             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3234                  diag::note_omp_explicit_dsa)
3235                 << getOpenMPClauseName(OMPC_aligned);
3236             continue;
3237           }
3238           AlignedArgs[CanonPVD] = E;
3239           QualType QTy = PVD->getType()
3240                              .getNonReferenceType()
3241                              .getUnqualifiedType()
3242                              .getCanonicalType();
3243           const Type *Ty = QTy.getTypePtrOrNull();
3244           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3245             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3246                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3247             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3248           }
3249           continue;
3250         }
3251       }
3252     if (isa<CXXThisExpr>(E)) {
3253       if (AlignedThis) {
3254         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3255             << 2 << E->getSourceRange();
3256         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3257             << getOpenMPClauseName(OMPC_aligned);
3258       }
3259       AlignedThis = E;
3260       continue;
3261     }
3262     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3263         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3264   }
3265   // The optional parameter of the aligned clause, alignment, must be a constant
3266   // positive integer expression. If no optional parameter is specified,
3267   // implementation-defined default alignments for SIMD instructions on the
3268   // target platforms are assumed.
3269   SmallVector<Expr *, 4> NewAligns;
3270   for (auto *E : Alignments) {
3271     ExprResult Align;
3272     if (E)
3273       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3274     NewAligns.push_back(Align.get());
3275   }
3276   // OpenMP [2.8.2, declare simd construct, Description]
3277   // The linear clause declares one or more list items to be private to a SIMD
3278   // lane and to have a linear relationship with respect to the iteration space
3279   // of a loop.
3280   // The special this pointer can be used as if was one of the arguments to the
3281   // function in any of the linear, aligned, or uniform clauses.
3282   // When a linear-step expression is specified in a linear clause it must be
3283   // either a constant integer expression or an integer-typed parameter that is
3284   // specified in a uniform clause on the directive.
3285   llvm::DenseMap<Decl *, Expr *> LinearArgs;
3286   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3287   auto MI = LinModifiers.begin();
3288   for (auto *E : Linears) {
3289     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3290     ++MI;
3291     E = E->IgnoreParenImpCasts();
3292     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3293       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3294         auto *CanonPVD = PVD->getCanonicalDecl();
3295         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3296             FD->getParamDecl(PVD->getFunctionScopeIndex())
3297                     ->getCanonicalDecl() == CanonPVD) {
3298           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3299           // A list-item cannot appear in more than one linear clause.
3300           if (LinearArgs.count(CanonPVD) > 0) {
3301             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3302                 << getOpenMPClauseName(OMPC_linear)
3303                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3304             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3305                  diag::note_omp_explicit_dsa)
3306                 << getOpenMPClauseName(OMPC_linear);
3307             continue;
3308           }
3309           // Each argument can appear in at most one uniform or linear clause.
3310           if (UniformedArgs.count(CanonPVD) > 0) {
3311             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3312                 << getOpenMPClauseName(OMPC_linear)
3313                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3314             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3315                  diag::note_omp_explicit_dsa)
3316                 << getOpenMPClauseName(OMPC_uniform);
3317             continue;
3318           }
3319           LinearArgs[CanonPVD] = E;
3320           if (E->isValueDependent() || E->isTypeDependent() ||
3321               E->isInstantiationDependent() ||
3322               E->containsUnexpandedParameterPack())
3323             continue;
3324           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3325                                       PVD->getOriginalType());
3326           continue;
3327         }
3328       }
3329     if (isa<CXXThisExpr>(E)) {
3330       if (UniformedLinearThis) {
3331         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3332             << getOpenMPClauseName(OMPC_linear)
3333             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3334             << E->getSourceRange();
3335         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3336             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3337                                                    : OMPC_linear);
3338         continue;
3339       }
3340       UniformedLinearThis = E;
3341       if (E->isValueDependent() || E->isTypeDependent() ||
3342           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3343         continue;
3344       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3345                                   E->getType());
3346       continue;
3347     }
3348     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3349         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3350   }
3351   Expr *Step = nullptr;
3352   Expr *NewStep = nullptr;
3353   SmallVector<Expr *, 4> NewSteps;
3354   for (auto *E : Steps) {
3355     // Skip the same step expression, it was checked already.
3356     if (Step == E || !E) {
3357       NewSteps.push_back(E ? NewStep : nullptr);
3358       continue;
3359     }
3360     Step = E;
3361     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3362       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3363         auto *CanonPVD = PVD->getCanonicalDecl();
3364         if (UniformedArgs.count(CanonPVD) == 0) {
3365           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3366               << Step->getSourceRange();
3367         } else if (E->isValueDependent() || E->isTypeDependent() ||
3368                    E->isInstantiationDependent() ||
3369                    E->containsUnexpandedParameterPack() ||
3370                    CanonPVD->getType()->hasIntegerRepresentation())
3371           NewSteps.push_back(Step);
3372         else {
3373           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3374               << Step->getSourceRange();
3375         }
3376         continue;
3377       }
3378     NewStep = Step;
3379     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3380         !Step->isInstantiationDependent() &&
3381         !Step->containsUnexpandedParameterPack()) {
3382       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3383                     .get();
3384       if (NewStep)
3385         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3386     }
3387     NewSteps.push_back(NewStep);
3388   }
3389   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3390       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3391       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3392       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3393       const_cast<Expr **>(Linears.data()), Linears.size(),
3394       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3395       NewSteps.data(), NewSteps.size(), SR);
3396   ADecl->addAttr(NewAttr);
3397   return ConvertDeclToDeclGroup(ADecl);
3398 }
3399 
3400 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3401                                               Stmt *AStmt,
3402                                               SourceLocation StartLoc,
3403                                               SourceLocation EndLoc) {
3404   if (!AStmt)
3405     return StmtError();
3406 
3407   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3408   // 1.2.2 OpenMP Language Terminology
3409   // Structured block - An executable statement with a single entry at the
3410   // top and a single exit at the bottom.
3411   // The point of exit cannot be a branch out of the structured block.
3412   // longjmp() and throw() must not violate the entry/exit criteria.
3413   CS->getCapturedDecl()->setNothrow();
3414 
3415   getCurFunction()->setHasBranchProtectedScope();
3416 
3417   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3418                                       DSAStack->isCancelRegion());
3419 }
3420 
3421 namespace {
3422 /// \brief Helper class for checking canonical form of the OpenMP loops and
3423 /// extracting iteration space of each loop in the loop nest, that will be used
3424 /// for IR generation.
3425 class OpenMPIterationSpaceChecker {
3426   /// \brief Reference to Sema.
3427   Sema &SemaRef;
3428   /// \brief A location for diagnostics (when there is no some better location).
3429   SourceLocation DefaultLoc;
3430   /// \brief A location for diagnostics (when increment is not compatible).
3431   SourceLocation ConditionLoc;
3432   /// \brief A source location for referring to loop init later.
3433   SourceRange InitSrcRange;
3434   /// \brief A source location for referring to condition later.
3435   SourceRange ConditionSrcRange;
3436   /// \brief A source location for referring to increment later.
3437   SourceRange IncrementSrcRange;
3438   /// \brief Loop variable.
3439   ValueDecl *LCDecl = nullptr;
3440   /// \brief Reference to loop variable.
3441   Expr *LCRef = nullptr;
3442   /// \brief Lower bound (initializer for the var).
3443   Expr *LB = nullptr;
3444   /// \brief Upper bound.
3445   Expr *UB = nullptr;
3446   /// \brief Loop step (increment).
3447   Expr *Step = nullptr;
3448   /// \brief This flag is true when condition is one of:
3449   ///   Var <  UB
3450   ///   Var <= UB
3451   ///   UB  >  Var
3452   ///   UB  >= Var
3453   bool TestIsLessOp = false;
3454   /// \brief This flag is true when condition is strict ( < or > ).
3455   bool TestIsStrictOp = false;
3456   /// \brief This flag is true when step is subtracted on each iteration.
3457   bool SubtractStep = false;
3458 
3459 public:
3460   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3461       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3462   /// \brief Check init-expr for canonical loop form and save loop counter
3463   /// variable - #Var and its initialization value - #LB.
3464   bool CheckInit(Stmt *S, bool EmitDiags = true);
3465   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3466   /// for less/greater and for strict/non-strict comparison.
3467   bool CheckCond(Expr *S);
3468   /// \brief Check incr-expr for canonical loop form and return true if it
3469   /// does not conform, otherwise save loop step (#Step).
3470   bool CheckInc(Expr *S);
3471   /// \brief Return the loop counter variable.
3472   ValueDecl *GetLoopDecl() const { return LCDecl; }
3473   /// \brief Return the reference expression to loop counter variable.
3474   Expr *GetLoopDeclRefExpr() const { return LCRef; }
3475   /// \brief Source range of the loop init.
3476   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3477   /// \brief Source range of the loop condition.
3478   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3479   /// \brief Source range of the loop increment.
3480   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3481   /// \brief True if the step should be subtracted.
3482   bool ShouldSubtractStep() const { return SubtractStep; }
3483   /// \brief Build the expression to calculate the number of iterations.
3484   Expr *
3485   BuildNumIterations(Scope *S, const bool LimitedType,
3486                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3487   /// \brief Build the precondition expression for the loops.
3488   Expr *BuildPreCond(Scope *S, Expr *Cond,
3489                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3490   /// \brief Build reference expression to the counter be used for codegen.
3491   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3492                                DSAStackTy &DSA) const;
3493   /// \brief Build reference expression to the private counter be used for
3494   /// codegen.
3495   Expr *BuildPrivateCounterVar() const;
3496   /// \brief Build initialization of the counter be used for codegen.
3497   Expr *BuildCounterInit() const;
3498   /// \brief Build step of the counter be used for codegen.
3499   Expr *BuildCounterStep() const;
3500   /// \brief Return true if any expression is dependent.
3501   bool Dependent() const;
3502 
3503 private:
3504   /// \brief Check the right-hand side of an assignment in the increment
3505   /// expression.
3506   bool CheckIncRHS(Expr *RHS);
3507   /// \brief Helper to set loop counter variable and its initializer.
3508   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3509   /// \brief Helper to set upper bound.
3510   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3511              SourceLocation SL);
3512   /// \brief Helper to set loop increment.
3513   bool SetStep(Expr *NewStep, bool Subtract);
3514 };
3515 
3516 bool OpenMPIterationSpaceChecker::Dependent() const {
3517   if (!LCDecl) {
3518     assert(!LB && !UB && !Step);
3519     return false;
3520   }
3521   return LCDecl->getType()->isDependentType() ||
3522          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3523          (Step && Step->isValueDependent());
3524 }
3525 
3526 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3527                                                  Expr *NewLCRefExpr,
3528                                                  Expr *NewLB) {
3529   // State consistency checking to ensure correct usage.
3530   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3531          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3532   if (!NewLCDecl || !NewLB)
3533     return true;
3534   LCDecl = getCanonicalDecl(NewLCDecl);
3535   LCRef = NewLCRefExpr;
3536   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3537     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3538       if ((Ctor->isCopyOrMoveConstructor() ||
3539            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3540           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3541         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3542   LB = NewLB;
3543   return false;
3544 }
3545 
3546 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3547                                         SourceRange SR, SourceLocation SL) {
3548   // State consistency checking to ensure correct usage.
3549   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3550          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3551   if (!NewUB)
3552     return true;
3553   UB = NewUB;
3554   TestIsLessOp = LessOp;
3555   TestIsStrictOp = StrictOp;
3556   ConditionSrcRange = SR;
3557   ConditionLoc = SL;
3558   return false;
3559 }
3560 
3561 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3562   // State consistency checking to ensure correct usage.
3563   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3564   if (!NewStep)
3565     return true;
3566   if (!NewStep->isValueDependent()) {
3567     // Check that the step is integer expression.
3568     SourceLocation StepLoc = NewStep->getLocStart();
3569     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3570         StepLoc, getExprAsWritten(NewStep));
3571     if (Val.isInvalid())
3572       return true;
3573     NewStep = Val.get();
3574 
3575     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3576     //  If test-expr is of form var relational-op b and relational-op is < or
3577     //  <= then incr-expr must cause var to increase on each iteration of the
3578     //  loop. If test-expr is of form var relational-op b and relational-op is
3579     //  > or >= then incr-expr must cause var to decrease on each iteration of
3580     //  the loop.
3581     //  If test-expr is of form b relational-op var and relational-op is < or
3582     //  <= then incr-expr must cause var to decrease on each iteration of the
3583     //  loop. If test-expr is of form b relational-op var and relational-op is
3584     //  > or >= then incr-expr must cause var to increase on each iteration of
3585     //  the loop.
3586     llvm::APSInt Result;
3587     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3588     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3589     bool IsConstNeg =
3590         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3591     bool IsConstPos =
3592         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3593     bool IsConstZero = IsConstant && !Result.getBoolValue();
3594     if (UB && (IsConstZero ||
3595                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3596                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3597       SemaRef.Diag(NewStep->getExprLoc(),
3598                    diag::err_omp_loop_incr_not_compatible)
3599           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3600       SemaRef.Diag(ConditionLoc,
3601                    diag::note_omp_loop_cond_requres_compatible_incr)
3602           << TestIsLessOp << ConditionSrcRange;
3603       return true;
3604     }
3605     if (TestIsLessOp == Subtract) {
3606       NewStep =
3607           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3608               .get();
3609       Subtract = !Subtract;
3610     }
3611   }
3612 
3613   Step = NewStep;
3614   SubtractStep = Subtract;
3615   return false;
3616 }
3617 
3618 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3619   // Check init-expr for canonical loop form and save loop counter
3620   // variable - #Var and its initialization value - #LB.
3621   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3622   //   var = lb
3623   //   integer-type var = lb
3624   //   random-access-iterator-type var = lb
3625   //   pointer-type var = lb
3626   //
3627   if (!S) {
3628     if (EmitDiags) {
3629       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3630     }
3631     return true;
3632   }
3633   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3634     if (!ExprTemp->cleanupsHaveSideEffects())
3635       S = ExprTemp->getSubExpr();
3636 
3637   InitSrcRange = S->getSourceRange();
3638   if (Expr *E = dyn_cast<Expr>(S))
3639     S = E->IgnoreParens();
3640   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3641     if (BO->getOpcode() == BO_Assign) {
3642       auto *LHS = BO->getLHS()->IgnoreParens();
3643       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3644         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3645           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3646             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3647         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3648       }
3649       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3650         if (ME->isArrow() &&
3651             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3652           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3653       }
3654     }
3655   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
3656     if (DS->isSingleDecl()) {
3657       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3658         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3659           // Accept non-canonical init form here but emit ext. warning.
3660           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3661             SemaRef.Diag(S->getLocStart(),
3662                          diag::ext_omp_loop_not_canonical_init)
3663                 << S->getSourceRange();
3664           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3665         }
3666       }
3667     }
3668   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3669     if (CE->getOperator() == OO_Equal) {
3670       auto *LHS = CE->getArg(0);
3671       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3672         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3673           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3674             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3675         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3676       }
3677       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3678         if (ME->isArrow() &&
3679             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3680           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3681       }
3682     }
3683   }
3684 
3685   if (Dependent() || SemaRef.CurContext->isDependentContext())
3686     return false;
3687   if (EmitDiags) {
3688     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3689         << S->getSourceRange();
3690   }
3691   return true;
3692 }
3693 
3694 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3695 /// variable (which may be the loop variable) if possible.
3696 static const ValueDecl *GetInitLCDecl(Expr *E) {
3697   if (!E)
3698     return nullptr;
3699   E = getExprAsWritten(E);
3700   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3701     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3702       if ((Ctor->isCopyOrMoveConstructor() ||
3703            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3704           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3705         E = CE->getArg(0)->IgnoreParenImpCasts();
3706   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3707     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
3708       return getCanonicalDecl(VD);
3709   }
3710   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3711     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3712       return getCanonicalDecl(ME->getMemberDecl());
3713   return nullptr;
3714 }
3715 
3716 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3717   // Check test-expr for canonical form, save upper-bound UB, flags for
3718   // less/greater and for strict/non-strict comparison.
3719   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3720   //   var relational-op b
3721   //   b relational-op var
3722   //
3723   if (!S) {
3724     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3725     return true;
3726   }
3727   S = getExprAsWritten(S);
3728   SourceLocation CondLoc = S->getLocStart();
3729   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3730     if (BO->isRelationalOp()) {
3731       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3732         return SetUB(BO->getRHS(),
3733                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3734                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3735                      BO->getSourceRange(), BO->getOperatorLoc());
3736       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3737         return SetUB(BO->getLHS(),
3738                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3739                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3740                      BO->getSourceRange(), BO->getOperatorLoc());
3741     }
3742   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3743     if (CE->getNumArgs() == 2) {
3744       auto Op = CE->getOperator();
3745       switch (Op) {
3746       case OO_Greater:
3747       case OO_GreaterEqual:
3748       case OO_Less:
3749       case OO_LessEqual:
3750         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3751           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3752                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3753                        CE->getOperatorLoc());
3754         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3755           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3756                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3757                        CE->getOperatorLoc());
3758         break;
3759       default:
3760         break;
3761       }
3762     }
3763   }
3764   if (Dependent() || SemaRef.CurContext->isDependentContext())
3765     return false;
3766   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3767       << S->getSourceRange() << LCDecl;
3768   return true;
3769 }
3770 
3771 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3772   // RHS of canonical loop form increment can be:
3773   //   var + incr
3774   //   incr + var
3775   //   var - incr
3776   //
3777   RHS = RHS->IgnoreParenImpCasts();
3778   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3779     if (BO->isAdditiveOp()) {
3780       bool IsAdd = BO->getOpcode() == BO_Add;
3781       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3782         return SetStep(BO->getRHS(), !IsAdd);
3783       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3784         return SetStep(BO->getLHS(), false);
3785     }
3786   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3787     bool IsAdd = CE->getOperator() == OO_Plus;
3788     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3789       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3790         return SetStep(CE->getArg(1), !IsAdd);
3791       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3792         return SetStep(CE->getArg(0), false);
3793     }
3794   }
3795   if (Dependent() || SemaRef.CurContext->isDependentContext())
3796     return false;
3797   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3798       << RHS->getSourceRange() << LCDecl;
3799   return true;
3800 }
3801 
3802 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3803   // Check incr-expr for canonical loop form and return true if it
3804   // does not conform.
3805   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3806   //   ++var
3807   //   var++
3808   //   --var
3809   //   var--
3810   //   var += incr
3811   //   var -= incr
3812   //   var = var + incr
3813   //   var = incr + var
3814   //   var = var - incr
3815   //
3816   if (!S) {
3817     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3818     return true;
3819   }
3820   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3821     if (!ExprTemp->cleanupsHaveSideEffects())
3822       S = ExprTemp->getSubExpr();
3823 
3824   IncrementSrcRange = S->getSourceRange();
3825   S = S->IgnoreParens();
3826   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3827     if (UO->isIncrementDecrementOp() &&
3828         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3829       return SetStep(SemaRef
3830                          .ActOnIntegerConstant(UO->getLocStart(),
3831                                                (UO->isDecrementOp() ? -1 : 1))
3832                          .get(),
3833                      false);
3834   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3835     switch (BO->getOpcode()) {
3836     case BO_AddAssign:
3837     case BO_SubAssign:
3838       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3839         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3840       break;
3841     case BO_Assign:
3842       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3843         return CheckIncRHS(BO->getRHS());
3844       break;
3845     default:
3846       break;
3847     }
3848   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3849     switch (CE->getOperator()) {
3850     case OO_PlusPlus:
3851     case OO_MinusMinus:
3852       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3853         return SetStep(SemaRef
3854                            .ActOnIntegerConstant(
3855                                CE->getLocStart(),
3856                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3857                            .get(),
3858                        false);
3859       break;
3860     case OO_PlusEqual:
3861     case OO_MinusEqual:
3862       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3863         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3864       break;
3865     case OO_Equal:
3866       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3867         return CheckIncRHS(CE->getArg(1));
3868       break;
3869     default:
3870       break;
3871     }
3872   }
3873   if (Dependent() || SemaRef.CurContext->isDependentContext())
3874     return false;
3875   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3876       << S->getSourceRange() << LCDecl;
3877   return true;
3878 }
3879 
3880 static ExprResult
3881 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3882                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3883   if (SemaRef.CurContext->isDependentContext())
3884     return ExprResult(Capture);
3885   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3886     return SemaRef.PerformImplicitConversion(
3887         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3888         /*AllowExplicit=*/true);
3889   auto I = Captures.find(Capture);
3890   if (I != Captures.end())
3891     return buildCapture(SemaRef, Capture, I->second);
3892   DeclRefExpr *Ref = nullptr;
3893   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3894   Captures[Capture] = Ref;
3895   return Res;
3896 }
3897 
3898 /// \brief Build the expression to calculate the number of iterations.
3899 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3900     Scope *S, const bool LimitedType,
3901     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3902   ExprResult Diff;
3903   auto VarType = LCDecl->getType().getNonReferenceType();
3904   if (VarType->isIntegerType() || VarType->isPointerType() ||
3905       SemaRef.getLangOpts().CPlusPlus) {
3906     // Upper - Lower
3907     auto *UBExpr = TestIsLessOp ? UB : LB;
3908     auto *LBExpr = TestIsLessOp ? LB : UB;
3909     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3910     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3911     if (!Upper || !Lower)
3912       return nullptr;
3913 
3914     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3915 
3916     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3917       // BuildBinOp already emitted error, this one is to point user to upper
3918       // and lower bound, and to tell what is passed to 'operator-'.
3919       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3920           << Upper->getSourceRange() << Lower->getSourceRange();
3921       return nullptr;
3922     }
3923   }
3924 
3925   if (!Diff.isUsable())
3926     return nullptr;
3927 
3928   // Upper - Lower [- 1]
3929   if (TestIsStrictOp)
3930     Diff = SemaRef.BuildBinOp(
3931         S, DefaultLoc, BO_Sub, Diff.get(),
3932         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3933   if (!Diff.isUsable())
3934     return nullptr;
3935 
3936   // Upper - Lower [- 1] + Step
3937   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3938   if (!NewStep.isUsable())
3939     return nullptr;
3940   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3941   if (!Diff.isUsable())
3942     return nullptr;
3943 
3944   // Parentheses (for dumping/debugging purposes only).
3945   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3946   if (!Diff.isUsable())
3947     return nullptr;
3948 
3949   // (Upper - Lower [- 1] + Step) / Step
3950   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3951   if (!Diff.isUsable())
3952     return nullptr;
3953 
3954   // OpenMP runtime requires 32-bit or 64-bit loop variables.
3955   QualType Type = Diff.get()->getType();
3956   auto &C = SemaRef.Context;
3957   bool UseVarType = VarType->hasIntegerRepresentation() &&
3958                     C.getTypeSize(Type) > C.getTypeSize(VarType);
3959   if (!Type->isIntegerType() || UseVarType) {
3960     unsigned NewSize =
3961         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3962     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3963                                : Type->hasSignedIntegerRepresentation();
3964     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3965     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3966       Diff = SemaRef.PerformImplicitConversion(
3967           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3968       if (!Diff.isUsable())
3969         return nullptr;
3970     }
3971   }
3972   if (LimitedType) {
3973     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3974     if (NewSize != C.getTypeSize(Type)) {
3975       if (NewSize < C.getTypeSize(Type)) {
3976         assert(NewSize == 64 && "incorrect loop var size");
3977         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3978             << InitSrcRange << ConditionSrcRange;
3979       }
3980       QualType NewType = C.getIntTypeForBitwidth(
3981           NewSize, Type->hasSignedIntegerRepresentation() ||
3982                        C.getTypeSize(Type) < NewSize);
3983       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3984         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3985                                                  Sema::AA_Converting, true);
3986         if (!Diff.isUsable())
3987           return nullptr;
3988       }
3989     }
3990   }
3991 
3992   return Diff.get();
3993 }
3994 
3995 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3996     Scope *S, Expr *Cond,
3997     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3998   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3999   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4000   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4001 
4002   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4003   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4004   if (!NewLB.isUsable() || !NewUB.isUsable())
4005     return nullptr;
4006 
4007   auto CondExpr = SemaRef.BuildBinOp(
4008       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4009                                   : (TestIsStrictOp ? BO_GT : BO_GE),
4010       NewLB.get(), NewUB.get());
4011   if (CondExpr.isUsable()) {
4012     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4013                                                 SemaRef.Context.BoolTy))
4014       CondExpr = SemaRef.PerformImplicitConversion(
4015           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4016           /*AllowExplicit=*/true);
4017   }
4018   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4019   // Otherwise use original loop conditon and evaluate it in runtime.
4020   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4021 }
4022 
4023 /// \brief Build reference expression to the counter be used for codegen.
4024 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
4025     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
4026   auto *VD = dyn_cast<VarDecl>(LCDecl);
4027   if (!VD) {
4028     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4029     auto *Ref = buildDeclRefExpr(
4030         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4031     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4032     // If the loop control decl is explicitly marked as private, do not mark it
4033     // as captured again.
4034     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4035       Captures.insert(std::make_pair(LCRef, Ref));
4036     return Ref;
4037   }
4038   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4039                           DefaultLoc);
4040 }
4041 
4042 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
4043   if (LCDecl && !LCDecl->isInvalidDecl()) {
4044     auto Type = LCDecl->getType().getNonReferenceType();
4045     auto *PrivateVar =
4046         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4047                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
4048     if (PrivateVar->isInvalidDecl())
4049       return nullptr;
4050     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4051   }
4052   return nullptr;
4053 }
4054 
4055 /// \brief Build initialization of the counter to be used for codegen.
4056 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4057 
4058 /// \brief Build step of the counter be used for codegen.
4059 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4060 
4061 /// \brief Iteration space of a single for loop.
4062 struct LoopIterationSpace final {
4063   /// \brief Condition of the loop.
4064   Expr *PreCond = nullptr;
4065   /// \brief This expression calculates the number of iterations in the loop.
4066   /// It is always possible to calculate it before starting the loop.
4067   Expr *NumIterations = nullptr;
4068   /// \brief The loop counter variable.
4069   Expr *CounterVar = nullptr;
4070   /// \brief Private loop counter variable.
4071   Expr *PrivateCounterVar = nullptr;
4072   /// \brief This is initializer for the initial value of #CounterVar.
4073   Expr *CounterInit = nullptr;
4074   /// \brief This is step for the #CounterVar used to generate its update:
4075   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4076   Expr *CounterStep = nullptr;
4077   /// \brief Should step be subtracted?
4078   bool Subtract = false;
4079   /// \brief Source range of the loop init.
4080   SourceRange InitSrcRange;
4081   /// \brief Source range of the loop condition.
4082   SourceRange CondSrcRange;
4083   /// \brief Source range of the loop increment.
4084   SourceRange IncSrcRange;
4085 };
4086 
4087 } // namespace
4088 
4089 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4090   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4091   assert(Init && "Expected loop in canonical form.");
4092   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4093   if (AssociatedLoops > 0 &&
4094       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4095     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4096     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4097       if (auto *D = ISC.GetLoopDecl()) {
4098         auto *VD = dyn_cast<VarDecl>(D);
4099         if (!VD) {
4100           if (auto *Private = IsOpenMPCapturedDecl(D))
4101             VD = Private;
4102           else {
4103             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4104                                      /*WithInit=*/false);
4105             VD = cast<VarDecl>(Ref->getDecl());
4106           }
4107         }
4108         DSAStack->addLoopControlVariable(D, VD);
4109       }
4110     }
4111     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4112   }
4113 }
4114 
4115 /// \brief Called on a for stmt to check and extract its iteration space
4116 /// for further processing (such as collapsing).
4117 static bool CheckOpenMPIterationSpace(
4118     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4119     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4120     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4121     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4122     LoopIterationSpace &ResultIterSpace,
4123     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4124   // OpenMP [2.6, Canonical Loop Form]
4125   //   for (init-expr; test-expr; incr-expr) structured-block
4126   auto *For = dyn_cast_or_null<ForStmt>(S);
4127   if (!For) {
4128     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4129         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4130         << getOpenMPDirectiveName(DKind) << NestedLoopCount
4131         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4132     if (NestedLoopCount > 1) {
4133       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4134         SemaRef.Diag(DSA.getConstructLoc(),
4135                      diag::note_omp_collapse_ordered_expr)
4136             << 2 << CollapseLoopCountExpr->getSourceRange()
4137             << OrderedLoopCountExpr->getSourceRange();
4138       else if (CollapseLoopCountExpr)
4139         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4140                      diag::note_omp_collapse_ordered_expr)
4141             << 0 << CollapseLoopCountExpr->getSourceRange();
4142       else
4143         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4144                      diag::note_omp_collapse_ordered_expr)
4145             << 1 << OrderedLoopCountExpr->getSourceRange();
4146     }
4147     return true;
4148   }
4149   assert(For->getBody());
4150 
4151   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4152 
4153   // Check init.
4154   auto Init = For->getInit();
4155   if (ISC.CheckInit(Init))
4156     return true;
4157 
4158   bool HasErrors = false;
4159 
4160   // Check loop variable's type.
4161   if (auto *LCDecl = ISC.GetLoopDecl()) {
4162     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
4163 
4164     // OpenMP [2.6, Canonical Loop Form]
4165     // Var is one of the following:
4166     //   A variable of signed or unsigned integer type.
4167     //   For C++, a variable of a random access iterator type.
4168     //   For C, a variable of a pointer type.
4169     auto VarType = LCDecl->getType().getNonReferenceType();
4170     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4171         !VarType->isPointerType() &&
4172         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4173       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4174           << SemaRef.getLangOpts().CPlusPlus;
4175       HasErrors = true;
4176     }
4177 
4178     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4179     // a Construct
4180     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4181     // parallel for construct is (are) private.
4182     // The loop iteration variable in the associated for-loop of a simd
4183     // construct with just one associated for-loop is linear with a
4184     // constant-linear-step that is the increment of the associated for-loop.
4185     // Exclude loop var from the list of variables with implicitly defined data
4186     // sharing attributes.
4187     VarsWithImplicitDSA.erase(LCDecl);
4188 
4189     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4190     // in a Construct, C/C++].
4191     // The loop iteration variable in the associated for-loop of a simd
4192     // construct with just one associated for-loop may be listed in a linear
4193     // clause with a constant-linear-step that is the increment of the
4194     // associated for-loop.
4195     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4196     // parallel for construct may be listed in a private or lastprivate clause.
4197     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4198     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4199     // declared in the loop and it is predetermined as a private.
4200     auto PredeterminedCKind =
4201         isOpenMPSimdDirective(DKind)
4202             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4203             : OMPC_private;
4204     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4205           DVar.CKind != PredeterminedCKind) ||
4206          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4207            isOpenMPDistributeDirective(DKind)) &&
4208           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4209           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4210         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4211       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4212           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4213           << getOpenMPClauseName(PredeterminedCKind);
4214       if (DVar.RefExpr == nullptr)
4215         DVar.CKind = PredeterminedCKind;
4216       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4217       HasErrors = true;
4218     } else if (LoopDeclRefExpr != nullptr) {
4219       // Make the loop iteration variable private (for worksharing constructs),
4220       // linear (for simd directives with the only one associated loop) or
4221       // lastprivate (for simd directives with several collapsed or ordered
4222       // loops).
4223       if (DVar.CKind == OMPC_unknown)
4224         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4225                           [](OpenMPDirectiveKind) -> bool { return true; },
4226                           /*FromParent=*/false);
4227       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4228     }
4229 
4230     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4231 
4232     // Check test-expr.
4233     HasErrors |= ISC.CheckCond(For->getCond());
4234 
4235     // Check incr-expr.
4236     HasErrors |= ISC.CheckInc(For->getInc());
4237   }
4238 
4239   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4240     return HasErrors;
4241 
4242   // Build the loop's iteration space representation.
4243   ResultIterSpace.PreCond =
4244       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4245   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4246       DSA.getCurScope(),
4247       (isOpenMPWorksharingDirective(DKind) ||
4248        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4249       Captures);
4250   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
4251   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4252   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4253   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4254   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4255   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4256   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4257   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4258 
4259   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4260                 ResultIterSpace.NumIterations == nullptr ||
4261                 ResultIterSpace.CounterVar == nullptr ||
4262                 ResultIterSpace.PrivateCounterVar == nullptr ||
4263                 ResultIterSpace.CounterInit == nullptr ||
4264                 ResultIterSpace.CounterStep == nullptr);
4265 
4266   return HasErrors;
4267 }
4268 
4269 /// \brief Build 'VarRef = Start.
4270 static ExprResult
4271 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4272                  ExprResult Start,
4273                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4274   // Build 'VarRef = Start.
4275   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4276   if (!NewStart.isUsable())
4277     return ExprError();
4278   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4279                                    VarRef.get()->getType())) {
4280     NewStart = SemaRef.PerformImplicitConversion(
4281         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4282         /*AllowExplicit=*/true);
4283     if (!NewStart.isUsable())
4284       return ExprError();
4285   }
4286 
4287   auto Init =
4288       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4289   return Init;
4290 }
4291 
4292 /// \brief Build 'VarRef = Start + Iter * Step'.
4293 static ExprResult
4294 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4295                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
4296                    ExprResult Step, bool Subtract,
4297                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4298   // Add parentheses (for debugging purposes only).
4299   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4300   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4301       !Step.isUsable())
4302     return ExprError();
4303 
4304   ExprResult NewStep = Step;
4305   if (Captures)
4306     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4307   if (NewStep.isInvalid())
4308     return ExprError();
4309   ExprResult Update =
4310       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4311   if (!Update.isUsable())
4312     return ExprError();
4313 
4314   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4315   // 'VarRef = Start (+|-) Iter * Step'.
4316   ExprResult NewStart = Start;
4317   if (Captures)
4318     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4319   if (NewStart.isInvalid())
4320     return ExprError();
4321 
4322   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4323   ExprResult SavedUpdate = Update;
4324   ExprResult UpdateVal;
4325   if (VarRef.get()->getType()->isOverloadableType() ||
4326       NewStart.get()->getType()->isOverloadableType() ||
4327       Update.get()->getType()->isOverloadableType()) {
4328     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4329     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4330     Update =
4331         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4332     if (Update.isUsable()) {
4333       UpdateVal =
4334           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4335                              VarRef.get(), SavedUpdate.get());
4336       if (UpdateVal.isUsable()) {
4337         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4338                                             UpdateVal.get());
4339       }
4340     }
4341     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4342   }
4343 
4344   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4345   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4346     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4347                                 NewStart.get(), SavedUpdate.get());
4348     if (!Update.isUsable())
4349       return ExprError();
4350 
4351     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4352                                      VarRef.get()->getType())) {
4353       Update = SemaRef.PerformImplicitConversion(
4354           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4355       if (!Update.isUsable())
4356         return ExprError();
4357     }
4358 
4359     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4360   }
4361   return Update;
4362 }
4363 
4364 /// \brief Convert integer expression \a E to make it have at least \a Bits
4365 /// bits.
4366 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
4367   if (E == nullptr)
4368     return ExprError();
4369   auto &C = SemaRef.Context;
4370   QualType OldType = E->getType();
4371   unsigned HasBits = C.getTypeSize(OldType);
4372   if (HasBits >= Bits)
4373     return ExprResult(E);
4374   // OK to convert to signed, because new type has more bits than old.
4375   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4376   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4377                                            true);
4378 }
4379 
4380 /// \brief Check if the given expression \a E is a constant integer that fits
4381 /// into \a Bits bits.
4382 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4383   if (E == nullptr)
4384     return false;
4385   llvm::APSInt Result;
4386   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4387     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4388   return false;
4389 }
4390 
4391 /// Build preinits statement for the given declarations.
4392 static Stmt *buildPreInits(ASTContext &Context,
4393                            MutableArrayRef<Decl *> PreInits) {
4394   if (!PreInits.empty()) {
4395     return new (Context) DeclStmt(
4396         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4397         SourceLocation(), SourceLocation());
4398   }
4399   return nullptr;
4400 }
4401 
4402 /// Build preinits statement for the given declarations.
4403 static Stmt *
4404 buildPreInits(ASTContext &Context,
4405               const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4406   if (!Captures.empty()) {
4407     SmallVector<Decl *, 16> PreInits;
4408     for (auto &Pair : Captures)
4409       PreInits.push_back(Pair.second->getDecl());
4410     return buildPreInits(Context, PreInits);
4411   }
4412   return nullptr;
4413 }
4414 
4415 /// Build postupdate expression for the given list of postupdates expressions.
4416 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4417   Expr *PostUpdate = nullptr;
4418   if (!PostUpdates.empty()) {
4419     for (auto *E : PostUpdates) {
4420       Expr *ConvE = S.BuildCStyleCastExpr(
4421                          E->getExprLoc(),
4422                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4423                          E->getExprLoc(), E)
4424                         .get();
4425       PostUpdate = PostUpdate
4426                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4427                                               PostUpdate, ConvE)
4428                              .get()
4429                        : ConvE;
4430     }
4431   }
4432   return PostUpdate;
4433 }
4434 
4435 /// \brief Called on a for stmt to check itself and nested loops (if any).
4436 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4437 /// number of collapsed loops otherwise.
4438 static unsigned
4439 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4440                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4441                 DSAStackTy &DSA,
4442                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4443                 OMPLoopDirective::HelperExprs &Built) {
4444   unsigned NestedLoopCount = 1;
4445   if (CollapseLoopCountExpr) {
4446     // Found 'collapse' clause - calculate collapse number.
4447     llvm::APSInt Result;
4448     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4449       NestedLoopCount = Result.getLimitedValue();
4450   }
4451   if (OrderedLoopCountExpr) {
4452     // Found 'ordered' clause - calculate collapse number.
4453     llvm::APSInt Result;
4454     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4455       if (Result.getLimitedValue() < NestedLoopCount) {
4456         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4457                      diag::err_omp_wrong_ordered_loop_count)
4458             << OrderedLoopCountExpr->getSourceRange();
4459         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4460                      diag::note_collapse_loop_count)
4461             << CollapseLoopCountExpr->getSourceRange();
4462       }
4463       NestedLoopCount = Result.getLimitedValue();
4464     }
4465   }
4466   // This is helper routine for loop directives (e.g., 'for', 'simd',
4467   // 'for simd', etc.).
4468   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4469   SmallVector<LoopIterationSpace, 4> IterSpaces;
4470   IterSpaces.resize(NestedLoopCount);
4471   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4472   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4473     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4474                                   NestedLoopCount, CollapseLoopCountExpr,
4475                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4476                                   IterSpaces[Cnt], Captures))
4477       return 0;
4478     // Move on to the next nested for loop, or to the loop body.
4479     // OpenMP [2.8.1, simd construct, Restrictions]
4480     // All loops associated with the construct must be perfectly nested; that
4481     // is, there must be no intervening code nor any OpenMP directive between
4482     // any two loops.
4483     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4484   }
4485 
4486   Built.clear(/* size */ NestedLoopCount);
4487 
4488   if (SemaRef.CurContext->isDependentContext())
4489     return NestedLoopCount;
4490 
4491   // An example of what is generated for the following code:
4492   //
4493   //   #pragma omp simd collapse(2) ordered(2)
4494   //   for (i = 0; i < NI; ++i)
4495   //     for (k = 0; k < NK; ++k)
4496   //       for (j = J0; j < NJ; j+=2) {
4497   //         <loop body>
4498   //       }
4499   //
4500   // We generate the code below.
4501   // Note: the loop body may be outlined in CodeGen.
4502   // Note: some counters may be C++ classes, operator- is used to find number of
4503   // iterations and operator+= to calculate counter value.
4504   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4505   // or i64 is currently supported).
4506   //
4507   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4508   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4509   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4510   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4511   //     // similar updates for vars in clauses (e.g. 'linear')
4512   //     <loop body (using local i and j)>
4513   //   }
4514   //   i = NI; // assign final values of counters
4515   //   j = NJ;
4516   //
4517 
4518   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4519   // the iteration counts of the collapsed for loops.
4520   // Precondition tests if there is at least one iteration (all conditions are
4521   // true).
4522   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4523   auto N0 = IterSpaces[0].NumIterations;
4524   ExprResult LastIteration32 = WidenIterationCount(
4525       32 /* Bits */, SemaRef
4526                          .PerformImplicitConversion(
4527                              N0->IgnoreImpCasts(), N0->getType(),
4528                              Sema::AA_Converting, /*AllowExplicit=*/true)
4529                          .get(),
4530       SemaRef);
4531   ExprResult LastIteration64 = WidenIterationCount(
4532       64 /* Bits */, SemaRef
4533                          .PerformImplicitConversion(
4534                              N0->IgnoreImpCasts(), N0->getType(),
4535                              Sema::AA_Converting, /*AllowExplicit=*/true)
4536                          .get(),
4537       SemaRef);
4538 
4539   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4540     return NestedLoopCount;
4541 
4542   auto &C = SemaRef.Context;
4543   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4544 
4545   Scope *CurScope = DSA.getCurScope();
4546   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4547     if (PreCond.isUsable()) {
4548       PreCond =
4549           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4550                              PreCond.get(), IterSpaces[Cnt].PreCond);
4551     }
4552     auto N = IterSpaces[Cnt].NumIterations;
4553     SourceLocation Loc = N->getExprLoc();
4554     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4555     if (LastIteration32.isUsable())
4556       LastIteration32 = SemaRef.BuildBinOp(
4557           CurScope, Loc, BO_Mul, LastIteration32.get(),
4558           SemaRef
4559               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4560                                          Sema::AA_Converting,
4561                                          /*AllowExplicit=*/true)
4562               .get());
4563     if (LastIteration64.isUsable())
4564       LastIteration64 = SemaRef.BuildBinOp(
4565           CurScope, Loc, BO_Mul, LastIteration64.get(),
4566           SemaRef
4567               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4568                                          Sema::AA_Converting,
4569                                          /*AllowExplicit=*/true)
4570               .get());
4571   }
4572 
4573   // Choose either the 32-bit or 64-bit version.
4574   ExprResult LastIteration = LastIteration64;
4575   if (LastIteration32.isUsable() &&
4576       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4577       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4578        FitsInto(
4579            32 /* Bits */,
4580            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4581            LastIteration64.get(), SemaRef)))
4582     LastIteration = LastIteration32;
4583   QualType VType = LastIteration.get()->getType();
4584   QualType RealVType = VType;
4585   QualType StrideVType = VType;
4586   if (isOpenMPTaskLoopDirective(DKind)) {
4587     VType =
4588         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4589     StrideVType =
4590         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4591   }
4592 
4593   if (!LastIteration.isUsable())
4594     return 0;
4595 
4596   // Save the number of iterations.
4597   ExprResult NumIterations = LastIteration;
4598   {
4599     LastIteration = SemaRef.BuildBinOp(
4600         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4601         LastIteration.get(),
4602         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4603     if (!LastIteration.isUsable())
4604       return 0;
4605   }
4606 
4607   // Calculate the last iteration number beforehand instead of doing this on
4608   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4609   llvm::APSInt Result;
4610   bool IsConstant =
4611       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4612   ExprResult CalcLastIteration;
4613   if (!IsConstant) {
4614     ExprResult SaveRef =
4615         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4616     LastIteration = SaveRef;
4617 
4618     // Prepare SaveRef + 1.
4619     NumIterations = SemaRef.BuildBinOp(
4620         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
4621         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4622     if (!NumIterations.isUsable())
4623       return 0;
4624   }
4625 
4626   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4627 
4628   // Build variables passed into runtime, necessary for worksharing directives.
4629   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
4630   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4631       isOpenMPDistributeDirective(DKind)) {
4632     // Lower bound variable, initialized with zero.
4633     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4634     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4635     SemaRef.AddInitializerToDecl(LBDecl,
4636                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4637                                  /*DirectInit*/ false);
4638 
4639     // Upper bound variable, initialized with last iteration number.
4640     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4641     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4642     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4643                                  /*DirectInit*/ false);
4644 
4645     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4646     // This will be used to implement clause 'lastprivate'.
4647     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4648     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4649     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4650     SemaRef.AddInitializerToDecl(ILDecl,
4651                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4652                                  /*DirectInit*/ false);
4653 
4654     // Stride variable returned by runtime (we initialize it to 1 by default).
4655     VarDecl *STDecl =
4656         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4657     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4658     SemaRef.AddInitializerToDecl(STDecl,
4659                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4660                                  /*DirectInit*/ false);
4661 
4662     // Build expression: UB = min(UB, LastIteration)
4663     // It is necessary for CodeGen of directives with static scheduling.
4664     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4665                                                 UB.get(), LastIteration.get());
4666     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4667         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4668     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4669                              CondOp.get());
4670     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4671 
4672     // If we have a combined directive that combines 'distribute', 'for' or
4673     // 'simd' we need to be able to access the bounds of the schedule of the
4674     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4675     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4676     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4677 
4678       // Lower bound variable, initialized with zero.
4679       VarDecl *CombLBDecl =
4680           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4681       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4682       SemaRef.AddInitializerToDecl(
4683           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4684           /*DirectInit*/ false);
4685 
4686       // Upper bound variable, initialized with last iteration number.
4687       VarDecl *CombUBDecl =
4688           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4689       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4690       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4691                                    /*DirectInit*/ false);
4692 
4693       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4694           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4695       ExprResult CombCondOp =
4696           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4697                                      LastIteration.get(), CombUB.get());
4698       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4699                                    CombCondOp.get());
4700       CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4701 
4702       auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4703       // We expect to have at least 2 more parameters than the 'parallel'
4704       // directive does - the lower and upper bounds of the previous schedule.
4705       assert(CD->getNumParams() >= 4 &&
4706              "Unexpected number of parameters in loop combined directive");
4707 
4708       // Set the proper type for the bounds given what we learned from the
4709       // enclosed loops.
4710       auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4711       auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4712 
4713       // Previous lower and upper bounds are obtained from the region
4714       // parameters.
4715       PrevLB =
4716           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4717       PrevUB =
4718           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4719     }
4720   }
4721 
4722   // Build the iteration variable and its initialization before loop.
4723   ExprResult IV;
4724   ExprResult Init, CombInit;
4725   {
4726     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4727     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4728     Expr *RHS =
4729         (isOpenMPWorksharingDirective(DKind) ||
4730          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4731             ? LB.get()
4732             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4733     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4734     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4735 
4736     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4737       Expr *CombRHS =
4738           (isOpenMPWorksharingDirective(DKind) ||
4739            isOpenMPTaskLoopDirective(DKind) ||
4740            isOpenMPDistributeDirective(DKind))
4741               ? CombLB.get()
4742               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4743       CombInit =
4744           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4745       CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4746     }
4747   }
4748 
4749   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4750   SourceLocation CondLoc;
4751   ExprResult Cond =
4752       (isOpenMPWorksharingDirective(DKind) ||
4753        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4754           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4755           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4756                                NumIterations.get());
4757   ExprResult CombCond;
4758   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4759     CombCond =
4760         SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4761   }
4762   // Loop increment (IV = IV + 1)
4763   SourceLocation IncLoc;
4764   ExprResult Inc =
4765       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4766                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4767   if (!Inc.isUsable())
4768     return 0;
4769   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4770   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4771   if (!Inc.isUsable())
4772     return 0;
4773 
4774   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4775   // Used for directives with static scheduling.
4776   // In combined construct, add combined version that use CombLB and CombUB
4777   // base variables for the update
4778   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
4779   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4780       isOpenMPDistributeDirective(DKind)) {
4781     // LB + ST
4782     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4783     if (!NextLB.isUsable())
4784       return 0;
4785     // LB = LB + ST
4786     NextLB =
4787         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4788     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4789     if (!NextLB.isUsable())
4790       return 0;
4791     // UB + ST
4792     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4793     if (!NextUB.isUsable())
4794       return 0;
4795     // UB = UB + ST
4796     NextUB =
4797         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4798     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4799     if (!NextUB.isUsable())
4800       return 0;
4801     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4802       CombNextLB =
4803           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4804       if (!NextLB.isUsable())
4805         return 0;
4806       // LB = LB + ST
4807       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4808                                       CombNextLB.get());
4809       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4810       if (!CombNextLB.isUsable())
4811         return 0;
4812       // UB + ST
4813       CombNextUB =
4814           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4815       if (!CombNextUB.isUsable())
4816         return 0;
4817       // UB = UB + ST
4818       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4819                                       CombNextUB.get());
4820       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4821       if (!CombNextUB.isUsable())
4822         return 0;
4823     }
4824   }
4825 
4826   // Create increment expression for distribute loop when combined in a same
4827   // directive with for as IV = IV + ST; ensure upper bound expression based
4828   // on PrevUB instead of NumIterations - used to implement 'for' when found
4829   // in combination with 'distribute', like in 'distribute parallel for'
4830   SourceLocation DistIncLoc;
4831   ExprResult DistCond, DistInc, PrevEUB;
4832   if (isOpenMPLoopBoundSharingDirective(DKind)) {
4833     DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4834     assert(DistCond.isUsable() && "distribute cond expr was not built");
4835 
4836     DistInc =
4837         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4838     assert(DistInc.isUsable() && "distribute inc expr was not built");
4839     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4840                                  DistInc.get());
4841     DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4842     assert(DistInc.isUsable() && "distribute inc expr was not built");
4843 
4844     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4845     // construct
4846     SourceLocation DistEUBLoc;
4847     ExprResult IsUBGreater =
4848         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4849     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4850         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4851     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4852                                  CondOp.get());
4853     PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4854   }
4855 
4856   // Build updates and final values of the loop counters.
4857   bool HasErrors = false;
4858   Built.Counters.resize(NestedLoopCount);
4859   Built.Inits.resize(NestedLoopCount);
4860   Built.Updates.resize(NestedLoopCount);
4861   Built.Finals.resize(NestedLoopCount);
4862   SmallVector<Expr *, 4> LoopMultipliers;
4863   {
4864     ExprResult Div;
4865     // Go from inner nested loop to outer.
4866     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4867       LoopIterationSpace &IS = IterSpaces[Cnt];
4868       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4869       // Build: Iter = (IV / Div) % IS.NumIters
4870       // where Div is product of previous iterations' IS.NumIters.
4871       ExprResult Iter;
4872       if (Div.isUsable()) {
4873         Iter =
4874             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4875       } else {
4876         Iter = IV;
4877         assert((Cnt == (int)NestedLoopCount - 1) &&
4878                "unusable div expected on first iteration only");
4879       }
4880 
4881       if (Cnt != 0 && Iter.isUsable())
4882         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4883                                   IS.NumIterations);
4884       if (!Iter.isUsable()) {
4885         HasErrors = true;
4886         break;
4887       }
4888 
4889       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4890       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4891       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4892                                           IS.CounterVar->getExprLoc(),
4893                                           /*RefersToCapture=*/true);
4894       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4895                                          IS.CounterInit, Captures);
4896       if (!Init.isUsable()) {
4897         HasErrors = true;
4898         break;
4899       }
4900       ExprResult Update = BuildCounterUpdate(
4901           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4902           IS.CounterStep, IS.Subtract, &Captures);
4903       if (!Update.isUsable()) {
4904         HasErrors = true;
4905         break;
4906       }
4907 
4908       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4909       ExprResult Final = BuildCounterUpdate(
4910           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4911           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4912       if (!Final.isUsable()) {
4913         HasErrors = true;
4914         break;
4915       }
4916 
4917       // Build Div for the next iteration: Div <- Div * IS.NumIters
4918       if (Cnt != 0) {
4919         if (Div.isUnset())
4920           Div = IS.NumIterations;
4921         else
4922           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4923                                    IS.NumIterations);
4924 
4925         // Add parentheses (for debugging purposes only).
4926         if (Div.isUsable())
4927           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4928         if (!Div.isUsable()) {
4929           HasErrors = true;
4930           break;
4931         }
4932         LoopMultipliers.push_back(Div.get());
4933       }
4934       if (!Update.isUsable() || !Final.isUsable()) {
4935         HasErrors = true;
4936         break;
4937       }
4938       // Save results
4939       Built.Counters[Cnt] = IS.CounterVar;
4940       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4941       Built.Inits[Cnt] = Init.get();
4942       Built.Updates[Cnt] = Update.get();
4943       Built.Finals[Cnt] = Final.get();
4944     }
4945   }
4946 
4947   if (HasErrors)
4948     return 0;
4949 
4950   // Save results
4951   Built.IterationVarRef = IV.get();
4952   Built.LastIteration = LastIteration.get();
4953   Built.NumIterations = NumIterations.get();
4954   Built.CalcLastIteration =
4955       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4956   Built.PreCond = PreCond.get();
4957   Built.PreInits = buildPreInits(C, Captures);
4958   Built.Cond = Cond.get();
4959   Built.Init = Init.get();
4960   Built.Inc = Inc.get();
4961   Built.LB = LB.get();
4962   Built.UB = UB.get();
4963   Built.IL = IL.get();
4964   Built.ST = ST.get();
4965   Built.EUB = EUB.get();
4966   Built.NLB = NextLB.get();
4967   Built.NUB = NextUB.get();
4968   Built.PrevLB = PrevLB.get();
4969   Built.PrevUB = PrevUB.get();
4970   Built.DistInc = DistInc.get();
4971   Built.PrevEUB = PrevEUB.get();
4972   Built.DistCombinedFields.LB = CombLB.get();
4973   Built.DistCombinedFields.UB = CombUB.get();
4974   Built.DistCombinedFields.EUB = CombEUB.get();
4975   Built.DistCombinedFields.Init = CombInit.get();
4976   Built.DistCombinedFields.Cond = CombCond.get();
4977   Built.DistCombinedFields.NLB = CombNextLB.get();
4978   Built.DistCombinedFields.NUB = CombNextUB.get();
4979 
4980   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4981   // Fill data for doacross depend clauses.
4982   for (auto Pair : DSA.getDoacrossDependClauses()) {
4983     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4984       Pair.first->setCounterValue(CounterVal);
4985     else {
4986       if (NestedLoopCount != Pair.second.size() ||
4987           NestedLoopCount != LoopMultipliers.size() + 1) {
4988         // Erroneous case - clause has some problems.
4989         Pair.first->setCounterValue(CounterVal);
4990         continue;
4991       }
4992       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4993       auto I = Pair.second.rbegin();
4994       auto IS = IterSpaces.rbegin();
4995       auto ILM = LoopMultipliers.rbegin();
4996       Expr *UpCounterVal = CounterVal;
4997       Expr *Multiplier = nullptr;
4998       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4999         if (I->first) {
5000           assert(IS->CounterStep);
5001           Expr *NormalizedOffset =
5002               SemaRef
5003                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5004                               I->first, IS->CounterStep)
5005                   .get();
5006           if (Multiplier) {
5007             NormalizedOffset =
5008                 SemaRef
5009                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5010                                 NormalizedOffset, Multiplier)
5011                     .get();
5012           }
5013           assert(I->second == OO_Plus || I->second == OO_Minus);
5014           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
5015           UpCounterVal = SemaRef
5016                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5017                                          UpCounterVal, NormalizedOffset)
5018                              .get();
5019         }
5020         Multiplier = *ILM;
5021         ++I;
5022         ++IS;
5023         ++ILM;
5024       }
5025       Pair.first->setCounterValue(UpCounterVal);
5026     }
5027   }
5028 
5029   return NestedLoopCount;
5030 }
5031 
5032 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5033   auto CollapseClauses =
5034       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5035   if (CollapseClauses.begin() != CollapseClauses.end())
5036     return (*CollapseClauses.begin())->getNumForLoops();
5037   return nullptr;
5038 }
5039 
5040 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5041   auto OrderedClauses =
5042       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5043   if (OrderedClauses.begin() != OrderedClauses.end())
5044     return (*OrderedClauses.begin())->getNumForLoops();
5045   return nullptr;
5046 }
5047 
5048 static bool checkSimdlenSafelenSpecified(Sema &S,
5049                                          const ArrayRef<OMPClause *> Clauses) {
5050   OMPSafelenClause *Safelen = nullptr;
5051   OMPSimdlenClause *Simdlen = nullptr;
5052 
5053   for (auto *Clause : Clauses) {
5054     if (Clause->getClauseKind() == OMPC_safelen)
5055       Safelen = cast<OMPSafelenClause>(Clause);
5056     else if (Clause->getClauseKind() == OMPC_simdlen)
5057       Simdlen = cast<OMPSimdlenClause>(Clause);
5058     if (Safelen && Simdlen)
5059       break;
5060   }
5061 
5062   if (Simdlen && Safelen) {
5063     llvm::APSInt SimdlenRes, SafelenRes;
5064     auto SimdlenLength = Simdlen->getSimdlen();
5065     auto SafelenLength = Safelen->getSafelen();
5066     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5067         SimdlenLength->isInstantiationDependent() ||
5068         SimdlenLength->containsUnexpandedParameterPack())
5069       return false;
5070     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5071         SafelenLength->isInstantiationDependent() ||
5072         SafelenLength->containsUnexpandedParameterPack())
5073       return false;
5074     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5075     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5076     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5077     // If both simdlen and safelen clauses are specified, the value of the
5078     // simdlen parameter must be less than or equal to the value of the safelen
5079     // parameter.
5080     if (SimdlenRes > SafelenRes) {
5081       S.Diag(SimdlenLength->getExprLoc(),
5082              diag::err_omp_wrong_simdlen_safelen_values)
5083           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5084       return true;
5085     }
5086   }
5087   return false;
5088 }
5089 
5090 StmtResult Sema::ActOnOpenMPSimdDirective(
5091     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5092     SourceLocation EndLoc,
5093     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5094   if (!AStmt)
5095     return StmtError();
5096 
5097   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5098   OMPLoopDirective::HelperExprs B;
5099   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5100   // define the nested loops number.
5101   unsigned NestedLoopCount = CheckOpenMPLoop(
5102       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5103       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5104   if (NestedLoopCount == 0)
5105     return StmtError();
5106 
5107   assert((CurContext->isDependentContext() || B.builtAll()) &&
5108          "omp simd loop exprs were not built");
5109 
5110   if (!CurContext->isDependentContext()) {
5111     // Finalize the clauses that need pre-built expressions for CodeGen.
5112     for (auto C : Clauses) {
5113       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5114         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5115                                      B.NumIterations, *this, CurScope,
5116                                      DSAStack))
5117           return StmtError();
5118     }
5119   }
5120 
5121   if (checkSimdlenSafelenSpecified(*this, Clauses))
5122     return StmtError();
5123 
5124   getCurFunction()->setHasBranchProtectedScope();
5125   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5126                                   Clauses, AStmt, B);
5127 }
5128 
5129 StmtResult Sema::ActOnOpenMPForDirective(
5130     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5131     SourceLocation EndLoc,
5132     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5133   if (!AStmt)
5134     return StmtError();
5135 
5136   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5137   OMPLoopDirective::HelperExprs B;
5138   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5139   // define the nested loops number.
5140   unsigned NestedLoopCount = CheckOpenMPLoop(
5141       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5142       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5143   if (NestedLoopCount == 0)
5144     return StmtError();
5145 
5146   assert((CurContext->isDependentContext() || B.builtAll()) &&
5147          "omp for loop exprs were not built");
5148 
5149   if (!CurContext->isDependentContext()) {
5150     // Finalize the clauses that need pre-built expressions for CodeGen.
5151     for (auto C : Clauses) {
5152       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5153         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5154                                      B.NumIterations, *this, CurScope,
5155                                      DSAStack))
5156           return StmtError();
5157     }
5158   }
5159 
5160   getCurFunction()->setHasBranchProtectedScope();
5161   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5162                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5163 }
5164 
5165 StmtResult Sema::ActOnOpenMPForSimdDirective(
5166     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5167     SourceLocation EndLoc,
5168     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5169   if (!AStmt)
5170     return StmtError();
5171 
5172   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5173   OMPLoopDirective::HelperExprs B;
5174   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5175   // define the nested loops number.
5176   unsigned NestedLoopCount =
5177       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5178                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5179                       VarsWithImplicitDSA, B);
5180   if (NestedLoopCount == 0)
5181     return StmtError();
5182 
5183   assert((CurContext->isDependentContext() || B.builtAll()) &&
5184          "omp for simd loop exprs were not built");
5185 
5186   if (!CurContext->isDependentContext()) {
5187     // Finalize the clauses that need pre-built expressions for CodeGen.
5188     for (auto C : Clauses) {
5189       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5190         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5191                                      B.NumIterations, *this, CurScope,
5192                                      DSAStack))
5193           return StmtError();
5194     }
5195   }
5196 
5197   if (checkSimdlenSafelenSpecified(*this, Clauses))
5198     return StmtError();
5199 
5200   getCurFunction()->setHasBranchProtectedScope();
5201   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5202                                      Clauses, AStmt, B);
5203 }
5204 
5205 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5206                                               Stmt *AStmt,
5207                                               SourceLocation StartLoc,
5208                                               SourceLocation EndLoc) {
5209   if (!AStmt)
5210     return StmtError();
5211 
5212   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5213   auto BaseStmt = AStmt;
5214   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5215     BaseStmt = CS->getCapturedStmt();
5216   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5217     auto S = C->children();
5218     if (S.begin() == S.end())
5219       return StmtError();
5220     // All associated statements must be '#pragma omp section' except for
5221     // the first one.
5222     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5223       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5224         if (SectionStmt)
5225           Diag(SectionStmt->getLocStart(),
5226                diag::err_omp_sections_substmt_not_section);
5227         return StmtError();
5228       }
5229       cast<OMPSectionDirective>(SectionStmt)
5230           ->setHasCancel(DSAStack->isCancelRegion());
5231     }
5232   } else {
5233     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5234     return StmtError();
5235   }
5236 
5237   getCurFunction()->setHasBranchProtectedScope();
5238 
5239   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5240                                       DSAStack->isCancelRegion());
5241 }
5242 
5243 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5244                                              SourceLocation StartLoc,
5245                                              SourceLocation EndLoc) {
5246   if (!AStmt)
5247     return StmtError();
5248 
5249   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5250 
5251   getCurFunction()->setHasBranchProtectedScope();
5252   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5253 
5254   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5255                                      DSAStack->isCancelRegion());
5256 }
5257 
5258 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5259                                             Stmt *AStmt,
5260                                             SourceLocation StartLoc,
5261                                             SourceLocation EndLoc) {
5262   if (!AStmt)
5263     return StmtError();
5264 
5265   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5266 
5267   getCurFunction()->setHasBranchProtectedScope();
5268 
5269   // OpenMP [2.7.3, single Construct, Restrictions]
5270   // The copyprivate clause must not be used with the nowait clause.
5271   OMPClause *Nowait = nullptr;
5272   OMPClause *Copyprivate = nullptr;
5273   for (auto *Clause : Clauses) {
5274     if (Clause->getClauseKind() == OMPC_nowait)
5275       Nowait = Clause;
5276     else if (Clause->getClauseKind() == OMPC_copyprivate)
5277       Copyprivate = Clause;
5278     if (Copyprivate && Nowait) {
5279       Diag(Copyprivate->getLocStart(),
5280            diag::err_omp_single_copyprivate_with_nowait);
5281       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5282       return StmtError();
5283     }
5284   }
5285 
5286   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5287 }
5288 
5289 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5290                                             SourceLocation StartLoc,
5291                                             SourceLocation EndLoc) {
5292   if (!AStmt)
5293     return StmtError();
5294 
5295   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5296 
5297   getCurFunction()->setHasBranchProtectedScope();
5298 
5299   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5300 }
5301 
5302 StmtResult Sema::ActOnOpenMPCriticalDirective(
5303     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5304     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5305   if (!AStmt)
5306     return StmtError();
5307 
5308   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5309 
5310   bool ErrorFound = false;
5311   llvm::APSInt Hint;
5312   SourceLocation HintLoc;
5313   bool DependentHint = false;
5314   for (auto *C : Clauses) {
5315     if (C->getClauseKind() == OMPC_hint) {
5316       if (!DirName.getName()) {
5317         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5318         ErrorFound = true;
5319       }
5320       Expr *E = cast<OMPHintClause>(C)->getHint();
5321       if (E->isTypeDependent() || E->isValueDependent() ||
5322           E->isInstantiationDependent())
5323         DependentHint = true;
5324       else {
5325         Hint = E->EvaluateKnownConstInt(Context);
5326         HintLoc = C->getLocStart();
5327       }
5328     }
5329   }
5330   if (ErrorFound)
5331     return StmtError();
5332   auto Pair = DSAStack->getCriticalWithHint(DirName);
5333   if (Pair.first && DirName.getName() && !DependentHint) {
5334     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5335       Diag(StartLoc, diag::err_omp_critical_with_hint);
5336       if (HintLoc.isValid()) {
5337         Diag(HintLoc, diag::note_omp_critical_hint_here)
5338             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5339       } else
5340         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5341       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5342         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5343             << 1
5344             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5345                    /*Radix=*/10, /*Signed=*/false);
5346       } else
5347         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5348     }
5349   }
5350 
5351   getCurFunction()->setHasBranchProtectedScope();
5352 
5353   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5354                                            Clauses, AStmt);
5355   if (!Pair.first && DirName.getName() && !DependentHint)
5356     DSAStack->addCriticalWithHint(Dir, Hint);
5357   return Dir;
5358 }
5359 
5360 StmtResult Sema::ActOnOpenMPParallelForDirective(
5361     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5362     SourceLocation EndLoc,
5363     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5364   if (!AStmt)
5365     return StmtError();
5366 
5367   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5368   // 1.2.2 OpenMP Language Terminology
5369   // Structured block - An executable statement with a single entry at the
5370   // top and a single exit at the bottom.
5371   // The point of exit cannot be a branch out of the structured block.
5372   // longjmp() and throw() must not violate the entry/exit criteria.
5373   CS->getCapturedDecl()->setNothrow();
5374 
5375   OMPLoopDirective::HelperExprs B;
5376   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5377   // define the nested loops number.
5378   unsigned NestedLoopCount =
5379       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5380                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5381                       VarsWithImplicitDSA, B);
5382   if (NestedLoopCount == 0)
5383     return StmtError();
5384 
5385   assert((CurContext->isDependentContext() || B.builtAll()) &&
5386          "omp parallel for loop exprs were not built");
5387 
5388   if (!CurContext->isDependentContext()) {
5389     // Finalize the clauses that need pre-built expressions for CodeGen.
5390     for (auto C : Clauses) {
5391       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5392         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5393                                      B.NumIterations, *this, CurScope,
5394                                      DSAStack))
5395           return StmtError();
5396     }
5397   }
5398 
5399   getCurFunction()->setHasBranchProtectedScope();
5400   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5401                                          NestedLoopCount, Clauses, AStmt, B,
5402                                          DSAStack->isCancelRegion());
5403 }
5404 
5405 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5406     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5407     SourceLocation EndLoc,
5408     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5409   if (!AStmt)
5410     return StmtError();
5411 
5412   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5413   // 1.2.2 OpenMP Language Terminology
5414   // Structured block - An executable statement with a single entry at the
5415   // top and a single exit at the bottom.
5416   // The point of exit cannot be a branch out of the structured block.
5417   // longjmp() and throw() must not violate the entry/exit criteria.
5418   CS->getCapturedDecl()->setNothrow();
5419 
5420   OMPLoopDirective::HelperExprs B;
5421   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5422   // define the nested loops number.
5423   unsigned NestedLoopCount =
5424       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5425                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5426                       VarsWithImplicitDSA, B);
5427   if (NestedLoopCount == 0)
5428     return StmtError();
5429 
5430   if (!CurContext->isDependentContext()) {
5431     // Finalize the clauses that need pre-built expressions for CodeGen.
5432     for (auto C : Clauses) {
5433       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5434         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5435                                      B.NumIterations, *this, CurScope,
5436                                      DSAStack))
5437           return StmtError();
5438     }
5439   }
5440 
5441   if (checkSimdlenSafelenSpecified(*this, Clauses))
5442     return StmtError();
5443 
5444   getCurFunction()->setHasBranchProtectedScope();
5445   return OMPParallelForSimdDirective::Create(
5446       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5447 }
5448 
5449 StmtResult
5450 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5451                                            Stmt *AStmt, SourceLocation StartLoc,
5452                                            SourceLocation EndLoc) {
5453   if (!AStmt)
5454     return StmtError();
5455 
5456   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5457   auto BaseStmt = AStmt;
5458   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5459     BaseStmt = CS->getCapturedStmt();
5460   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5461     auto S = C->children();
5462     if (S.begin() == S.end())
5463       return StmtError();
5464     // All associated statements must be '#pragma omp section' except for
5465     // the first one.
5466     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5467       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5468         if (SectionStmt)
5469           Diag(SectionStmt->getLocStart(),
5470                diag::err_omp_parallel_sections_substmt_not_section);
5471         return StmtError();
5472       }
5473       cast<OMPSectionDirective>(SectionStmt)
5474           ->setHasCancel(DSAStack->isCancelRegion());
5475     }
5476   } else {
5477     Diag(AStmt->getLocStart(),
5478          diag::err_omp_parallel_sections_not_compound_stmt);
5479     return StmtError();
5480   }
5481 
5482   getCurFunction()->setHasBranchProtectedScope();
5483 
5484   return OMPParallelSectionsDirective::Create(
5485       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5486 }
5487 
5488 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5489                                           Stmt *AStmt, SourceLocation StartLoc,
5490                                           SourceLocation EndLoc) {
5491   if (!AStmt)
5492     return StmtError();
5493 
5494   auto *CS = cast<CapturedStmt>(AStmt);
5495   // 1.2.2 OpenMP Language Terminology
5496   // Structured block - An executable statement with a single entry at the
5497   // top and a single exit at the bottom.
5498   // The point of exit cannot be a branch out of the structured block.
5499   // longjmp() and throw() must not violate the entry/exit criteria.
5500   CS->getCapturedDecl()->setNothrow();
5501 
5502   getCurFunction()->setHasBranchProtectedScope();
5503 
5504   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5505                                   DSAStack->isCancelRegion());
5506 }
5507 
5508 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5509                                                SourceLocation EndLoc) {
5510   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5511 }
5512 
5513 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5514                                              SourceLocation EndLoc) {
5515   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5516 }
5517 
5518 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5519                                               SourceLocation EndLoc) {
5520   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5521 }
5522 
5523 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5524                                                Stmt *AStmt,
5525                                                SourceLocation StartLoc,
5526                                                SourceLocation EndLoc) {
5527   if (!AStmt)
5528     return StmtError();
5529 
5530   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5531 
5532   getCurFunction()->setHasBranchProtectedScope();
5533 
5534   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
5535                                        AStmt,
5536                                        DSAStack->getTaskgroupReductionRef());
5537 }
5538 
5539 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5540                                            SourceLocation StartLoc,
5541                                            SourceLocation EndLoc) {
5542   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5543   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5544 }
5545 
5546 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5547                                              Stmt *AStmt,
5548                                              SourceLocation StartLoc,
5549                                              SourceLocation EndLoc) {
5550   OMPClause *DependFound = nullptr;
5551   OMPClause *DependSourceClause = nullptr;
5552   OMPClause *DependSinkClause = nullptr;
5553   bool ErrorFound = false;
5554   OMPThreadsClause *TC = nullptr;
5555   OMPSIMDClause *SC = nullptr;
5556   for (auto *C : Clauses) {
5557     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5558       DependFound = C;
5559       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5560         if (DependSourceClause) {
5561           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5562               << getOpenMPDirectiveName(OMPD_ordered)
5563               << getOpenMPClauseName(OMPC_depend) << 2;
5564           ErrorFound = true;
5565         } else
5566           DependSourceClause = C;
5567         if (DependSinkClause) {
5568           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5569               << 0;
5570           ErrorFound = true;
5571         }
5572       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5573         if (DependSourceClause) {
5574           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5575               << 1;
5576           ErrorFound = true;
5577         }
5578         DependSinkClause = C;
5579       }
5580     } else if (C->getClauseKind() == OMPC_threads)
5581       TC = cast<OMPThreadsClause>(C);
5582     else if (C->getClauseKind() == OMPC_simd)
5583       SC = cast<OMPSIMDClause>(C);
5584   }
5585   if (!ErrorFound && !SC &&
5586       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5587     // OpenMP [2.8.1,simd Construct, Restrictions]
5588     // An ordered construct with the simd clause is the only OpenMP construct
5589     // that can appear in the simd region.
5590     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5591     ErrorFound = true;
5592   } else if (DependFound && (TC || SC)) {
5593     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5594         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5595     ErrorFound = true;
5596   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5597     Diag(DependFound->getLocStart(),
5598          diag::err_omp_ordered_directive_without_param);
5599     ErrorFound = true;
5600   } else if (TC || Clauses.empty()) {
5601     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5602       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5603       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5604           << (TC != nullptr);
5605       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5606       ErrorFound = true;
5607     }
5608   }
5609   if ((!AStmt && !DependFound) || ErrorFound)
5610     return StmtError();
5611 
5612   if (AStmt) {
5613     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5614 
5615     getCurFunction()->setHasBranchProtectedScope();
5616   }
5617 
5618   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5619 }
5620 
5621 namespace {
5622 /// \brief Helper class for checking expression in 'omp atomic [update]'
5623 /// construct.
5624 class OpenMPAtomicUpdateChecker {
5625   /// \brief Error results for atomic update expressions.
5626   enum ExprAnalysisErrorCode {
5627     /// \brief A statement is not an expression statement.
5628     NotAnExpression,
5629     /// \brief Expression is not builtin binary or unary operation.
5630     NotABinaryOrUnaryExpression,
5631     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5632     NotAnUnaryIncDecExpression,
5633     /// \brief An expression is not of scalar type.
5634     NotAScalarType,
5635     /// \brief A binary operation is not an assignment operation.
5636     NotAnAssignmentOp,
5637     /// \brief RHS part of the binary operation is not a binary expression.
5638     NotABinaryExpression,
5639     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5640     /// expression.
5641     NotABinaryOperator,
5642     /// \brief RHS binary operation does not have reference to the updated LHS
5643     /// part.
5644     NotAnUpdateExpression,
5645     /// \brief No errors is found.
5646     NoError
5647   };
5648   /// \brief Reference to Sema.
5649   Sema &SemaRef;
5650   /// \brief A location for note diagnostics (when error is found).
5651   SourceLocation NoteLoc;
5652   /// \brief 'x' lvalue part of the source atomic expression.
5653   Expr *X;
5654   /// \brief 'expr' rvalue part of the source atomic expression.
5655   Expr *E;
5656   /// \brief Helper expression of the form
5657   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5658   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5659   Expr *UpdateExpr;
5660   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5661   /// important for non-associative operations.
5662   bool IsXLHSInRHSPart;
5663   BinaryOperatorKind Op;
5664   SourceLocation OpLoc;
5665   /// \brief true if the source expression is a postfix unary operation, false
5666   /// if it is a prefix unary operation.
5667   bool IsPostfixUpdate;
5668 
5669 public:
5670   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5671       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5672         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5673   /// \brief Check specified statement that it is suitable for 'atomic update'
5674   /// constructs and extract 'x', 'expr' and Operation from the original
5675   /// expression. If DiagId and NoteId == 0, then only check is performed
5676   /// without error notification.
5677   /// \param DiagId Diagnostic which should be emitted if error is found.
5678   /// \param NoteId Diagnostic note for the main error message.
5679   /// \return true if statement is not an update expression, false otherwise.
5680   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5681   /// \brief Return the 'x' lvalue part of the source atomic expression.
5682   Expr *getX() const { return X; }
5683   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5684   Expr *getExpr() const { return E; }
5685   /// \brief Return the update expression used in calculation of the updated
5686   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5687   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5688   Expr *getUpdateExpr() const { return UpdateExpr; }
5689   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5690   /// false otherwise.
5691   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5692 
5693   /// \brief true if the source expression is a postfix unary operation, false
5694   /// if it is a prefix unary operation.
5695   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5696 
5697 private:
5698   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5699                             unsigned NoteId = 0);
5700 };
5701 } // namespace
5702 
5703 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5704     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5705   ExprAnalysisErrorCode ErrorFound = NoError;
5706   SourceLocation ErrorLoc, NoteLoc;
5707   SourceRange ErrorRange, NoteRange;
5708   // Allowed constructs are:
5709   //  x = x binop expr;
5710   //  x = expr binop x;
5711   if (AtomicBinOp->getOpcode() == BO_Assign) {
5712     X = AtomicBinOp->getLHS();
5713     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5714             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5715       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5716           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5717           AtomicInnerBinOp->isBitwiseOp()) {
5718         Op = AtomicInnerBinOp->getOpcode();
5719         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5720         auto *LHS = AtomicInnerBinOp->getLHS();
5721         auto *RHS = AtomicInnerBinOp->getRHS();
5722         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5723         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5724                                           /*Canonical=*/true);
5725         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5726                                             /*Canonical=*/true);
5727         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5728                                             /*Canonical=*/true);
5729         if (XId == LHSId) {
5730           E = RHS;
5731           IsXLHSInRHSPart = true;
5732         } else if (XId == RHSId) {
5733           E = LHS;
5734           IsXLHSInRHSPart = false;
5735         } else {
5736           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5737           ErrorRange = AtomicInnerBinOp->getSourceRange();
5738           NoteLoc = X->getExprLoc();
5739           NoteRange = X->getSourceRange();
5740           ErrorFound = NotAnUpdateExpression;
5741         }
5742       } else {
5743         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5744         ErrorRange = AtomicInnerBinOp->getSourceRange();
5745         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5746         NoteRange = SourceRange(NoteLoc, NoteLoc);
5747         ErrorFound = NotABinaryOperator;
5748       }
5749     } else {
5750       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5751       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5752       ErrorFound = NotABinaryExpression;
5753     }
5754   } else {
5755     ErrorLoc = AtomicBinOp->getExprLoc();
5756     ErrorRange = AtomicBinOp->getSourceRange();
5757     NoteLoc = AtomicBinOp->getOperatorLoc();
5758     NoteRange = SourceRange(NoteLoc, NoteLoc);
5759     ErrorFound = NotAnAssignmentOp;
5760   }
5761   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5762     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5763     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5764     return true;
5765   } else if (SemaRef.CurContext->isDependentContext())
5766     E = X = UpdateExpr = nullptr;
5767   return ErrorFound != NoError;
5768 }
5769 
5770 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5771                                                unsigned NoteId) {
5772   ExprAnalysisErrorCode ErrorFound = NoError;
5773   SourceLocation ErrorLoc, NoteLoc;
5774   SourceRange ErrorRange, NoteRange;
5775   // Allowed constructs are:
5776   //  x++;
5777   //  x--;
5778   //  ++x;
5779   //  --x;
5780   //  x binop= expr;
5781   //  x = x binop expr;
5782   //  x = expr binop x;
5783   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5784     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5785     if (AtomicBody->getType()->isScalarType() ||
5786         AtomicBody->isInstantiationDependent()) {
5787       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5788               AtomicBody->IgnoreParenImpCasts())) {
5789         // Check for Compound Assignment Operation
5790         Op = BinaryOperator::getOpForCompoundAssignment(
5791             AtomicCompAssignOp->getOpcode());
5792         OpLoc = AtomicCompAssignOp->getOperatorLoc();
5793         E = AtomicCompAssignOp->getRHS();
5794         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
5795         IsXLHSInRHSPart = true;
5796       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5797                      AtomicBody->IgnoreParenImpCasts())) {
5798         // Check for Binary Operation
5799         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
5800           return true;
5801       } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5802                      AtomicBody->IgnoreParenImpCasts())) {
5803         // Check for Unary Operation
5804         if (AtomicUnaryOp->isIncrementDecrementOp()) {
5805           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
5806           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5807           OpLoc = AtomicUnaryOp->getOperatorLoc();
5808           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
5809           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5810           IsXLHSInRHSPart = true;
5811         } else {
5812           ErrorFound = NotAnUnaryIncDecExpression;
5813           ErrorLoc = AtomicUnaryOp->getExprLoc();
5814           ErrorRange = AtomicUnaryOp->getSourceRange();
5815           NoteLoc = AtomicUnaryOp->getOperatorLoc();
5816           NoteRange = SourceRange(NoteLoc, NoteLoc);
5817         }
5818       } else if (!AtomicBody->isInstantiationDependent()) {
5819         ErrorFound = NotABinaryOrUnaryExpression;
5820         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5821         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5822       }
5823     } else {
5824       ErrorFound = NotAScalarType;
5825       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5826       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5827     }
5828   } else {
5829     ErrorFound = NotAnExpression;
5830     NoteLoc = ErrorLoc = S->getLocStart();
5831     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5832   }
5833   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5834     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5835     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5836     return true;
5837   } else if (SemaRef.CurContext->isDependentContext())
5838     E = X = UpdateExpr = nullptr;
5839   if (ErrorFound == NoError && E && X) {
5840     // Build an update expression of form 'OpaqueValueExpr(x) binop
5841     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5842     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5843     auto *OVEX = new (SemaRef.getASTContext())
5844         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5845     auto *OVEExpr = new (SemaRef.getASTContext())
5846         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5847     auto Update =
5848         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5849                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
5850     if (Update.isInvalid())
5851       return true;
5852     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5853                                                Sema::AA_Casting);
5854     if (Update.isInvalid())
5855       return true;
5856     UpdateExpr = Update.get();
5857   }
5858   return ErrorFound != NoError;
5859 }
5860 
5861 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5862                                             Stmt *AStmt,
5863                                             SourceLocation StartLoc,
5864                                             SourceLocation EndLoc) {
5865   if (!AStmt)
5866     return StmtError();
5867 
5868   auto *CS = cast<CapturedStmt>(AStmt);
5869   // 1.2.2 OpenMP Language Terminology
5870   // Structured block - An executable statement with a single entry at the
5871   // top and a single exit at the bottom.
5872   // The point of exit cannot be a branch out of the structured block.
5873   // longjmp() and throw() must not violate the entry/exit criteria.
5874   OpenMPClauseKind AtomicKind = OMPC_unknown;
5875   SourceLocation AtomicKindLoc;
5876   for (auto *C : Clauses) {
5877     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5878         C->getClauseKind() == OMPC_update ||
5879         C->getClauseKind() == OMPC_capture) {
5880       if (AtomicKind != OMPC_unknown) {
5881         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5882             << SourceRange(C->getLocStart(), C->getLocEnd());
5883         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5884             << getOpenMPClauseName(AtomicKind);
5885       } else {
5886         AtomicKind = C->getClauseKind();
5887         AtomicKindLoc = C->getLocStart();
5888       }
5889     }
5890   }
5891 
5892   auto Body = CS->getCapturedStmt();
5893   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5894     Body = EWC->getSubExpr();
5895 
5896   Expr *X = nullptr;
5897   Expr *V = nullptr;
5898   Expr *E = nullptr;
5899   Expr *UE = nullptr;
5900   bool IsXLHSInRHSPart = false;
5901   bool IsPostfixUpdate = false;
5902   // OpenMP [2.12.6, atomic Construct]
5903   // In the next expressions:
5904   // * x and v (as applicable) are both l-value expressions with scalar type.
5905   // * During the execution of an atomic region, multiple syntactic
5906   // occurrences of x must designate the same storage location.
5907   // * Neither of v and expr (as applicable) may access the storage location
5908   // designated by x.
5909   // * Neither of x and expr (as applicable) may access the storage location
5910   // designated by v.
5911   // * expr is an expression with scalar type.
5912   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5913   // * binop, binop=, ++, and -- are not overloaded operators.
5914   // * The expression x binop expr must be numerically equivalent to x binop
5915   // (expr). This requirement is satisfied if the operators in expr have
5916   // precedence greater than binop, or by using parentheses around expr or
5917   // subexpressions of expr.
5918   // * The expression expr binop x must be numerically equivalent to (expr)
5919   // binop x. This requirement is satisfied if the operators in expr have
5920   // precedence equal to or greater than binop, or by using parentheses around
5921   // expr or subexpressions of expr.
5922   // * For forms that allow multiple occurrences of x, the number of times
5923   // that x is evaluated is unspecified.
5924   if (AtomicKind == OMPC_read) {
5925     enum {
5926       NotAnExpression,
5927       NotAnAssignmentOp,
5928       NotAScalarType,
5929       NotAnLValue,
5930       NoError
5931     } ErrorFound = NoError;
5932     SourceLocation ErrorLoc, NoteLoc;
5933     SourceRange ErrorRange, NoteRange;
5934     // If clause is read:
5935     //  v = x;
5936     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5937       auto *AtomicBinOp =
5938           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5939       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5940         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5941         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5942         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5943             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5944           if (!X->isLValue() || !V->isLValue()) {
5945             auto NotLValueExpr = X->isLValue() ? V : X;
5946             ErrorFound = NotAnLValue;
5947             ErrorLoc = AtomicBinOp->getExprLoc();
5948             ErrorRange = AtomicBinOp->getSourceRange();
5949             NoteLoc = NotLValueExpr->getExprLoc();
5950             NoteRange = NotLValueExpr->getSourceRange();
5951           }
5952         } else if (!X->isInstantiationDependent() ||
5953                    !V->isInstantiationDependent()) {
5954           auto NotScalarExpr =
5955               (X->isInstantiationDependent() || X->getType()->isScalarType())
5956                   ? V
5957                   : X;
5958           ErrorFound = NotAScalarType;
5959           ErrorLoc = AtomicBinOp->getExprLoc();
5960           ErrorRange = AtomicBinOp->getSourceRange();
5961           NoteLoc = NotScalarExpr->getExprLoc();
5962           NoteRange = NotScalarExpr->getSourceRange();
5963         }
5964       } else if (!AtomicBody->isInstantiationDependent()) {
5965         ErrorFound = NotAnAssignmentOp;
5966         ErrorLoc = AtomicBody->getExprLoc();
5967         ErrorRange = AtomicBody->getSourceRange();
5968         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5969                               : AtomicBody->getExprLoc();
5970         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5971                                 : AtomicBody->getSourceRange();
5972       }
5973     } else {
5974       ErrorFound = NotAnExpression;
5975       NoteLoc = ErrorLoc = Body->getLocStart();
5976       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5977     }
5978     if (ErrorFound != NoError) {
5979       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5980           << ErrorRange;
5981       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5982                                                       << NoteRange;
5983       return StmtError();
5984     } else if (CurContext->isDependentContext())
5985       V = X = nullptr;
5986   } else if (AtomicKind == OMPC_write) {
5987     enum {
5988       NotAnExpression,
5989       NotAnAssignmentOp,
5990       NotAScalarType,
5991       NotAnLValue,
5992       NoError
5993     } ErrorFound = NoError;
5994     SourceLocation ErrorLoc, NoteLoc;
5995     SourceRange ErrorRange, NoteRange;
5996     // If clause is write:
5997     //  x = expr;
5998     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5999       auto *AtomicBinOp =
6000           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6001       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6002         X = AtomicBinOp->getLHS();
6003         E = AtomicBinOp->getRHS();
6004         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6005             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6006           if (!X->isLValue()) {
6007             ErrorFound = NotAnLValue;
6008             ErrorLoc = AtomicBinOp->getExprLoc();
6009             ErrorRange = AtomicBinOp->getSourceRange();
6010             NoteLoc = X->getExprLoc();
6011             NoteRange = X->getSourceRange();
6012           }
6013         } else if (!X->isInstantiationDependent() ||
6014                    !E->isInstantiationDependent()) {
6015           auto NotScalarExpr =
6016               (X->isInstantiationDependent() || X->getType()->isScalarType())
6017                   ? E
6018                   : X;
6019           ErrorFound = NotAScalarType;
6020           ErrorLoc = AtomicBinOp->getExprLoc();
6021           ErrorRange = AtomicBinOp->getSourceRange();
6022           NoteLoc = NotScalarExpr->getExprLoc();
6023           NoteRange = NotScalarExpr->getSourceRange();
6024         }
6025       } else if (!AtomicBody->isInstantiationDependent()) {
6026         ErrorFound = NotAnAssignmentOp;
6027         ErrorLoc = AtomicBody->getExprLoc();
6028         ErrorRange = AtomicBody->getSourceRange();
6029         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6030                               : AtomicBody->getExprLoc();
6031         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6032                                 : AtomicBody->getSourceRange();
6033       }
6034     } else {
6035       ErrorFound = NotAnExpression;
6036       NoteLoc = ErrorLoc = Body->getLocStart();
6037       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6038     }
6039     if (ErrorFound != NoError) {
6040       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6041           << ErrorRange;
6042       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6043                                                       << NoteRange;
6044       return StmtError();
6045     } else if (CurContext->isDependentContext())
6046       E = X = nullptr;
6047   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6048     // If clause is update:
6049     //  x++;
6050     //  x--;
6051     //  ++x;
6052     //  --x;
6053     //  x binop= expr;
6054     //  x = x binop expr;
6055     //  x = expr binop x;
6056     OpenMPAtomicUpdateChecker Checker(*this);
6057     if (Checker.checkStatement(
6058             Body, (AtomicKind == OMPC_update)
6059                       ? diag::err_omp_atomic_update_not_expression_statement
6060                       : diag::err_omp_atomic_not_expression_statement,
6061             diag::note_omp_atomic_update))
6062       return StmtError();
6063     if (!CurContext->isDependentContext()) {
6064       E = Checker.getExpr();
6065       X = Checker.getX();
6066       UE = Checker.getUpdateExpr();
6067       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6068     }
6069   } else if (AtomicKind == OMPC_capture) {
6070     enum {
6071       NotAnAssignmentOp,
6072       NotACompoundStatement,
6073       NotTwoSubstatements,
6074       NotASpecificExpression,
6075       NoError
6076     } ErrorFound = NoError;
6077     SourceLocation ErrorLoc, NoteLoc;
6078     SourceRange ErrorRange, NoteRange;
6079     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6080       // If clause is a capture:
6081       //  v = x++;
6082       //  v = x--;
6083       //  v = ++x;
6084       //  v = --x;
6085       //  v = x binop= expr;
6086       //  v = x = x binop expr;
6087       //  v = x = expr binop x;
6088       auto *AtomicBinOp =
6089           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6090       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6091         V = AtomicBinOp->getLHS();
6092         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6093         OpenMPAtomicUpdateChecker Checker(*this);
6094         if (Checker.checkStatement(
6095                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6096                 diag::note_omp_atomic_update))
6097           return StmtError();
6098         E = Checker.getExpr();
6099         X = Checker.getX();
6100         UE = Checker.getUpdateExpr();
6101         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6102         IsPostfixUpdate = Checker.isPostfixUpdate();
6103       } else if (!AtomicBody->isInstantiationDependent()) {
6104         ErrorLoc = AtomicBody->getExprLoc();
6105         ErrorRange = AtomicBody->getSourceRange();
6106         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6107                               : AtomicBody->getExprLoc();
6108         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6109                                 : AtomicBody->getSourceRange();
6110         ErrorFound = NotAnAssignmentOp;
6111       }
6112       if (ErrorFound != NoError) {
6113         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6114             << ErrorRange;
6115         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6116         return StmtError();
6117       } else if (CurContext->isDependentContext()) {
6118         UE = V = E = X = nullptr;
6119       }
6120     } else {
6121       // If clause is a capture:
6122       //  { v = x; x = expr; }
6123       //  { v = x; x++; }
6124       //  { v = x; x--; }
6125       //  { v = x; ++x; }
6126       //  { v = x; --x; }
6127       //  { v = x; x binop= expr; }
6128       //  { v = x; x = x binop expr; }
6129       //  { v = x; x = expr binop x; }
6130       //  { x++; v = x; }
6131       //  { x--; v = x; }
6132       //  { ++x; v = x; }
6133       //  { --x; v = x; }
6134       //  { x binop= expr; v = x; }
6135       //  { x = x binop expr; v = x; }
6136       //  { x = expr binop x; v = x; }
6137       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6138         // Check that this is { expr1; expr2; }
6139         if (CS->size() == 2) {
6140           auto *First = CS->body_front();
6141           auto *Second = CS->body_back();
6142           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6143             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6144           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6145             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6146           // Need to find what subexpression is 'v' and what is 'x'.
6147           OpenMPAtomicUpdateChecker Checker(*this);
6148           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6149           BinaryOperator *BinOp = nullptr;
6150           if (IsUpdateExprFound) {
6151             BinOp = dyn_cast<BinaryOperator>(First);
6152             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6153           }
6154           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6155             //  { v = x; x++; }
6156             //  { v = x; x--; }
6157             //  { v = x; ++x; }
6158             //  { v = x; --x; }
6159             //  { v = x; x binop= expr; }
6160             //  { v = x; x = x binop expr; }
6161             //  { v = x; x = expr binop x; }
6162             // Check that the first expression has form v = x.
6163             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6164             llvm::FoldingSetNodeID XId, PossibleXId;
6165             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6166             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6167             IsUpdateExprFound = XId == PossibleXId;
6168             if (IsUpdateExprFound) {
6169               V = BinOp->getLHS();
6170               X = Checker.getX();
6171               E = Checker.getExpr();
6172               UE = Checker.getUpdateExpr();
6173               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6174               IsPostfixUpdate = true;
6175             }
6176           }
6177           if (!IsUpdateExprFound) {
6178             IsUpdateExprFound = !Checker.checkStatement(First);
6179             BinOp = nullptr;
6180             if (IsUpdateExprFound) {
6181               BinOp = dyn_cast<BinaryOperator>(Second);
6182               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6183             }
6184             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6185               //  { x++; v = x; }
6186               //  { x--; v = x; }
6187               //  { ++x; v = x; }
6188               //  { --x; v = x; }
6189               //  { x binop= expr; v = x; }
6190               //  { x = x binop expr; v = x; }
6191               //  { x = expr binop x; v = x; }
6192               // Check that the second expression has form v = x.
6193               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6194               llvm::FoldingSetNodeID XId, PossibleXId;
6195               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6196               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6197               IsUpdateExprFound = XId == PossibleXId;
6198               if (IsUpdateExprFound) {
6199                 V = BinOp->getLHS();
6200                 X = Checker.getX();
6201                 E = Checker.getExpr();
6202                 UE = Checker.getUpdateExpr();
6203                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6204                 IsPostfixUpdate = false;
6205               }
6206             }
6207           }
6208           if (!IsUpdateExprFound) {
6209             //  { v = x; x = expr; }
6210             auto *FirstExpr = dyn_cast<Expr>(First);
6211             auto *SecondExpr = dyn_cast<Expr>(Second);
6212             if (!FirstExpr || !SecondExpr ||
6213                 !(FirstExpr->isInstantiationDependent() ||
6214                   SecondExpr->isInstantiationDependent())) {
6215               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6216               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6217                 ErrorFound = NotAnAssignmentOp;
6218                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6219                                                 : First->getLocStart();
6220                 NoteRange = ErrorRange = FirstBinOp
6221                                              ? FirstBinOp->getSourceRange()
6222                                              : SourceRange(ErrorLoc, ErrorLoc);
6223               } else {
6224                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6225                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6226                   ErrorFound = NotAnAssignmentOp;
6227                   NoteLoc = ErrorLoc = SecondBinOp
6228                                            ? SecondBinOp->getOperatorLoc()
6229                                            : Second->getLocStart();
6230                   NoteRange = ErrorRange =
6231                       SecondBinOp ? SecondBinOp->getSourceRange()
6232                                   : SourceRange(ErrorLoc, ErrorLoc);
6233                 } else {
6234                   auto *PossibleXRHSInFirst =
6235                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6236                   auto *PossibleXLHSInSecond =
6237                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6238                   llvm::FoldingSetNodeID X1Id, X2Id;
6239                   PossibleXRHSInFirst->Profile(X1Id, Context,
6240                                                /*Canonical=*/true);
6241                   PossibleXLHSInSecond->Profile(X2Id, Context,
6242                                                 /*Canonical=*/true);
6243                   IsUpdateExprFound = X1Id == X2Id;
6244                   if (IsUpdateExprFound) {
6245                     V = FirstBinOp->getLHS();
6246                     X = SecondBinOp->getLHS();
6247                     E = SecondBinOp->getRHS();
6248                     UE = nullptr;
6249                     IsXLHSInRHSPart = false;
6250                     IsPostfixUpdate = true;
6251                   } else {
6252                     ErrorFound = NotASpecificExpression;
6253                     ErrorLoc = FirstBinOp->getExprLoc();
6254                     ErrorRange = FirstBinOp->getSourceRange();
6255                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6256                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6257                   }
6258                 }
6259               }
6260             }
6261           }
6262         } else {
6263           NoteLoc = ErrorLoc = Body->getLocStart();
6264           NoteRange = ErrorRange =
6265               SourceRange(Body->getLocStart(), Body->getLocStart());
6266           ErrorFound = NotTwoSubstatements;
6267         }
6268       } else {
6269         NoteLoc = ErrorLoc = Body->getLocStart();
6270         NoteRange = ErrorRange =
6271             SourceRange(Body->getLocStart(), Body->getLocStart());
6272         ErrorFound = NotACompoundStatement;
6273       }
6274       if (ErrorFound != NoError) {
6275         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6276             << ErrorRange;
6277         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6278         return StmtError();
6279       } else if (CurContext->isDependentContext()) {
6280         UE = V = E = X = nullptr;
6281       }
6282     }
6283   }
6284 
6285   getCurFunction()->setHasBranchProtectedScope();
6286 
6287   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6288                                     X, V, E, UE, IsXLHSInRHSPart,
6289                                     IsPostfixUpdate);
6290 }
6291 
6292 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6293                                             Stmt *AStmt,
6294                                             SourceLocation StartLoc,
6295                                             SourceLocation EndLoc) {
6296   if (!AStmt)
6297     return StmtError();
6298 
6299   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6300   // 1.2.2 OpenMP Language Terminology
6301   // Structured block - An executable statement with a single entry at the
6302   // top and a single exit at the bottom.
6303   // The point of exit cannot be a branch out of the structured block.
6304   // longjmp() and throw() must not violate the entry/exit criteria.
6305   CS->getCapturedDecl()->setNothrow();
6306 
6307   // OpenMP [2.16, Nesting of Regions]
6308   // If specified, a teams construct must be contained within a target
6309   // construct. That target construct must contain no statements or directives
6310   // outside of the teams construct.
6311   if (DSAStack->hasInnerTeamsRegion()) {
6312     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6313     bool OMPTeamsFound = true;
6314     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6315       auto I = CS->body_begin();
6316       while (I != CS->body_end()) {
6317         auto *OED = dyn_cast<OMPExecutableDirective>(*I);
6318         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6319           OMPTeamsFound = false;
6320           break;
6321         }
6322         ++I;
6323       }
6324       assert(I != CS->body_end() && "Not found statement");
6325       S = *I;
6326     } else {
6327       auto *OED = dyn_cast<OMPExecutableDirective>(S);
6328       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6329     }
6330     if (!OMPTeamsFound) {
6331       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6332       Diag(DSAStack->getInnerTeamsRegionLoc(),
6333            diag::note_omp_nested_teams_construct_here);
6334       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6335           << isa<OMPExecutableDirective>(S);
6336       return StmtError();
6337     }
6338   }
6339 
6340   getCurFunction()->setHasBranchProtectedScope();
6341 
6342   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6343 }
6344 
6345 StmtResult
6346 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6347                                          Stmt *AStmt, SourceLocation StartLoc,
6348                                          SourceLocation EndLoc) {
6349   if (!AStmt)
6350     return StmtError();
6351 
6352   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6353   // 1.2.2 OpenMP Language Terminology
6354   // Structured block - An executable statement with a single entry at the
6355   // top and a single exit at the bottom.
6356   // The point of exit cannot be a branch out of the structured block.
6357   // longjmp() and throw() must not violate the entry/exit criteria.
6358   CS->getCapturedDecl()->setNothrow();
6359 
6360   getCurFunction()->setHasBranchProtectedScope();
6361 
6362   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6363                                             AStmt);
6364 }
6365 
6366 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6367     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6368     SourceLocation EndLoc,
6369     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6370   if (!AStmt)
6371     return StmtError();
6372 
6373   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6374   // 1.2.2 OpenMP Language Terminology
6375   // Structured block - An executable statement with a single entry at the
6376   // top and a single exit at the bottom.
6377   // The point of exit cannot be a branch out of the structured block.
6378   // longjmp() and throw() must not violate the entry/exit criteria.
6379   CS->getCapturedDecl()->setNothrow();
6380   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6381        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6382     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6383     // 1.2.2 OpenMP Language Terminology
6384     // Structured block - An executable statement with a single entry at the
6385     // top and a single exit at the bottom.
6386     // The point of exit cannot be a branch out of the structured block.
6387     // longjmp() and throw() must not violate the entry/exit criteria.
6388     CS->getCapturedDecl()->setNothrow();
6389   }
6390 
6391   OMPLoopDirective::HelperExprs B;
6392   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6393   // define the nested loops number.
6394   unsigned NestedLoopCount =
6395       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6396                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
6397                       VarsWithImplicitDSA, B);
6398   if (NestedLoopCount == 0)
6399     return StmtError();
6400 
6401   assert((CurContext->isDependentContext() || B.builtAll()) &&
6402          "omp target parallel for loop exprs were not built");
6403 
6404   if (!CurContext->isDependentContext()) {
6405     // Finalize the clauses that need pre-built expressions for CodeGen.
6406     for (auto C : Clauses) {
6407       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6408         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6409                                      B.NumIterations, *this, CurScope,
6410                                      DSAStack))
6411           return StmtError();
6412     }
6413   }
6414 
6415   getCurFunction()->setHasBranchProtectedScope();
6416   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6417                                                NestedLoopCount, Clauses, AStmt,
6418                                                B, DSAStack->isCancelRegion());
6419 }
6420 
6421 /// Check for existence of a map clause in the list of clauses.
6422 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6423                        const OpenMPClauseKind K) {
6424   return llvm::any_of(
6425       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6426 }
6427 
6428 template <typename... Params>
6429 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6430                        const Params... ClauseTypes) {
6431   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
6432 }
6433 
6434 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6435                                                 Stmt *AStmt,
6436                                                 SourceLocation StartLoc,
6437                                                 SourceLocation EndLoc) {
6438   if (!AStmt)
6439     return StmtError();
6440 
6441   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6442 
6443   // OpenMP [2.10.1, Restrictions, p. 97]
6444   // At least one map clause must appear on the directive.
6445   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6446     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6447         << "'map' or 'use_device_ptr'"
6448         << getOpenMPDirectiveName(OMPD_target_data);
6449     return StmtError();
6450   }
6451 
6452   getCurFunction()->setHasBranchProtectedScope();
6453 
6454   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6455                                         AStmt);
6456 }
6457 
6458 StmtResult
6459 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6460                                           SourceLocation StartLoc,
6461                                           SourceLocation EndLoc, Stmt *AStmt) {
6462   if (!AStmt)
6463     return StmtError();
6464 
6465   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6466   // 1.2.2 OpenMP Language Terminology
6467   // Structured block - An executable statement with a single entry at the
6468   // top and a single exit at the bottom.
6469   // The point of exit cannot be a branch out of the structured block.
6470   // longjmp() and throw() must not violate the entry/exit criteria.
6471   CS->getCapturedDecl()->setNothrow();
6472   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6473        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6474     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6475     // 1.2.2 OpenMP Language Terminology
6476     // Structured block - An executable statement with a single entry at the
6477     // top and a single exit at the bottom.
6478     // The point of exit cannot be a branch out of the structured block.
6479     // longjmp() and throw() must not violate the entry/exit criteria.
6480     CS->getCapturedDecl()->setNothrow();
6481   }
6482 
6483   // OpenMP [2.10.2, Restrictions, p. 99]
6484   // At least one map clause must appear on the directive.
6485   if (!hasClauses(Clauses, OMPC_map)) {
6486     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6487         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
6488     return StmtError();
6489   }
6490 
6491   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6492                                              AStmt);
6493 }
6494 
6495 StmtResult
6496 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6497                                          SourceLocation StartLoc,
6498                                          SourceLocation EndLoc, Stmt *AStmt) {
6499   if (!AStmt)
6500     return StmtError();
6501 
6502   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6503   // 1.2.2 OpenMP Language Terminology
6504   // Structured block - An executable statement with a single entry at the
6505   // top and a single exit at the bottom.
6506   // The point of exit cannot be a branch out of the structured block.
6507   // longjmp() and throw() must not violate the entry/exit criteria.
6508   CS->getCapturedDecl()->setNothrow();
6509   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6510        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6511     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6512     // 1.2.2 OpenMP Language Terminology
6513     // Structured block - An executable statement with a single entry at the
6514     // top and a single exit at the bottom.
6515     // The point of exit cannot be a branch out of the structured block.
6516     // longjmp() and throw() must not violate the entry/exit criteria.
6517     CS->getCapturedDecl()->setNothrow();
6518   }
6519 
6520   // OpenMP [2.10.3, Restrictions, p. 102]
6521   // At least one map clause must appear on the directive.
6522   if (!hasClauses(Clauses, OMPC_map)) {
6523     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6524         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
6525     return StmtError();
6526   }
6527 
6528   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6529                                             AStmt);
6530 }
6531 
6532 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6533                                                   SourceLocation StartLoc,
6534                                                   SourceLocation EndLoc,
6535                                                   Stmt *AStmt) {
6536   if (!AStmt)
6537     return StmtError();
6538 
6539   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6540   // 1.2.2 OpenMP Language Terminology
6541   // Structured block - An executable statement with a single entry at the
6542   // top and a single exit at the bottom.
6543   // The point of exit cannot be a branch out of the structured block.
6544   // longjmp() and throw() must not violate the entry/exit criteria.
6545   CS->getCapturedDecl()->setNothrow();
6546   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6547        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6548     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6549     // 1.2.2 OpenMP Language Terminology
6550     // Structured block - An executable statement with a single entry at the
6551     // top and a single exit at the bottom.
6552     // The point of exit cannot be a branch out of the structured block.
6553     // longjmp() and throw() must not violate the entry/exit criteria.
6554     CS->getCapturedDecl()->setNothrow();
6555   }
6556 
6557   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
6558     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6559     return StmtError();
6560   }
6561   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6562                                           AStmt);
6563 }
6564 
6565 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6566                                            Stmt *AStmt, SourceLocation StartLoc,
6567                                            SourceLocation EndLoc) {
6568   if (!AStmt)
6569     return StmtError();
6570 
6571   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6572   // 1.2.2 OpenMP Language Terminology
6573   // Structured block - An executable statement with a single entry at the
6574   // top and a single exit at the bottom.
6575   // The point of exit cannot be a branch out of the structured block.
6576   // longjmp() and throw() must not violate the entry/exit criteria.
6577   CS->getCapturedDecl()->setNothrow();
6578 
6579   getCurFunction()->setHasBranchProtectedScope();
6580 
6581   DSAStack->setParentTeamsRegionLoc(StartLoc);
6582 
6583   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6584 }
6585 
6586 StmtResult
6587 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6588                                             SourceLocation EndLoc,
6589                                             OpenMPDirectiveKind CancelRegion) {
6590   if (DSAStack->isParentNowaitRegion()) {
6591     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6592     return StmtError();
6593   }
6594   if (DSAStack->isParentOrderedRegion()) {
6595     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6596     return StmtError();
6597   }
6598   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6599                                                CancelRegion);
6600 }
6601 
6602 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6603                                             SourceLocation StartLoc,
6604                                             SourceLocation EndLoc,
6605                                             OpenMPDirectiveKind CancelRegion) {
6606   if (DSAStack->isParentNowaitRegion()) {
6607     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6608     return StmtError();
6609   }
6610   if (DSAStack->isParentOrderedRegion()) {
6611     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6612     return StmtError();
6613   }
6614   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6615   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6616                                     CancelRegion);
6617 }
6618 
6619 static bool checkGrainsizeNumTasksClauses(Sema &S,
6620                                           ArrayRef<OMPClause *> Clauses) {
6621   OMPClause *PrevClause = nullptr;
6622   bool ErrorFound = false;
6623   for (auto *C : Clauses) {
6624     if (C->getClauseKind() == OMPC_grainsize ||
6625         C->getClauseKind() == OMPC_num_tasks) {
6626       if (!PrevClause)
6627         PrevClause = C;
6628       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6629         S.Diag(C->getLocStart(),
6630                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6631             << getOpenMPClauseName(C->getClauseKind())
6632             << getOpenMPClauseName(PrevClause->getClauseKind());
6633         S.Diag(PrevClause->getLocStart(),
6634                diag::note_omp_previous_grainsize_num_tasks)
6635             << getOpenMPClauseName(PrevClause->getClauseKind());
6636         ErrorFound = true;
6637       }
6638     }
6639   }
6640   return ErrorFound;
6641 }
6642 
6643 static bool checkReductionClauseWithNogroup(Sema &S,
6644                                             ArrayRef<OMPClause *> Clauses) {
6645   OMPClause *ReductionClause = nullptr;
6646   OMPClause *NogroupClause = nullptr;
6647   for (auto *C : Clauses) {
6648     if (C->getClauseKind() == OMPC_reduction) {
6649       ReductionClause = C;
6650       if (NogroupClause)
6651         break;
6652       continue;
6653     }
6654     if (C->getClauseKind() == OMPC_nogroup) {
6655       NogroupClause = C;
6656       if (ReductionClause)
6657         break;
6658       continue;
6659     }
6660   }
6661   if (ReductionClause && NogroupClause) {
6662     S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6663         << SourceRange(NogroupClause->getLocStart(),
6664                        NogroupClause->getLocEnd());
6665     return true;
6666   }
6667   return false;
6668 }
6669 
6670 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6671     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6672     SourceLocation EndLoc,
6673     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6674   if (!AStmt)
6675     return StmtError();
6676 
6677   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6678   OMPLoopDirective::HelperExprs B;
6679   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6680   // define the nested loops number.
6681   unsigned NestedLoopCount =
6682       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6683                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6684                       VarsWithImplicitDSA, B);
6685   if (NestedLoopCount == 0)
6686     return StmtError();
6687 
6688   assert((CurContext->isDependentContext() || B.builtAll()) &&
6689          "omp for loop exprs were not built");
6690 
6691   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6692   // The grainsize clause and num_tasks clause are mutually exclusive and may
6693   // not appear on the same taskloop directive.
6694   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6695     return StmtError();
6696   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6697   // If a reduction clause is present on the taskloop directive, the nogroup
6698   // clause must not be specified.
6699   if (checkReductionClauseWithNogroup(*this, Clauses))
6700     return StmtError();
6701 
6702   getCurFunction()->setHasBranchProtectedScope();
6703   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6704                                       NestedLoopCount, Clauses, AStmt, B);
6705 }
6706 
6707 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6708     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6709     SourceLocation EndLoc,
6710     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6711   if (!AStmt)
6712     return StmtError();
6713 
6714   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6715   OMPLoopDirective::HelperExprs B;
6716   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6717   // define the nested loops number.
6718   unsigned NestedLoopCount =
6719       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6720                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6721                       VarsWithImplicitDSA, B);
6722   if (NestedLoopCount == 0)
6723     return StmtError();
6724 
6725   assert((CurContext->isDependentContext() || B.builtAll()) &&
6726          "omp for loop exprs were not built");
6727 
6728   if (!CurContext->isDependentContext()) {
6729     // Finalize the clauses that need pre-built expressions for CodeGen.
6730     for (auto C : Clauses) {
6731       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6732         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6733                                      B.NumIterations, *this, CurScope,
6734                                      DSAStack))
6735           return StmtError();
6736     }
6737   }
6738 
6739   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6740   // The grainsize clause and num_tasks clause are mutually exclusive and may
6741   // not appear on the same taskloop directive.
6742   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6743     return StmtError();
6744   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6745   // If a reduction clause is present on the taskloop directive, the nogroup
6746   // clause must not be specified.
6747   if (checkReductionClauseWithNogroup(*this, Clauses))
6748     return StmtError();
6749   if (checkSimdlenSafelenSpecified(*this, Clauses))
6750     return StmtError();
6751 
6752   getCurFunction()->setHasBranchProtectedScope();
6753   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6754                                           NestedLoopCount, Clauses, AStmt, B);
6755 }
6756 
6757 StmtResult Sema::ActOnOpenMPDistributeDirective(
6758     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6759     SourceLocation EndLoc,
6760     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6761   if (!AStmt)
6762     return StmtError();
6763 
6764   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6765   OMPLoopDirective::HelperExprs B;
6766   // In presence of clause 'collapse' with number of loops, it will
6767   // define the nested loops number.
6768   unsigned NestedLoopCount =
6769       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6770                       nullptr /*ordered not a clause on distribute*/, AStmt,
6771                       *this, *DSAStack, VarsWithImplicitDSA, B);
6772   if (NestedLoopCount == 0)
6773     return StmtError();
6774 
6775   assert((CurContext->isDependentContext() || B.builtAll()) &&
6776          "omp for loop exprs were not built");
6777 
6778   getCurFunction()->setHasBranchProtectedScope();
6779   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6780                                         NestedLoopCount, Clauses, AStmt, B);
6781 }
6782 
6783 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6784     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6785     SourceLocation EndLoc,
6786     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6787   if (!AStmt)
6788     return StmtError();
6789 
6790   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6791   // 1.2.2 OpenMP Language Terminology
6792   // Structured block - An executable statement with a single entry at the
6793   // top and a single exit at the bottom.
6794   // The point of exit cannot be a branch out of the structured block.
6795   // longjmp() and throw() must not violate the entry/exit criteria.
6796   CS->getCapturedDecl()->setNothrow();
6797   for (int ThisCaptureLevel =
6798            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6799        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6800     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6801     // 1.2.2 OpenMP Language Terminology
6802     // Structured block - An executable statement with a single entry at the
6803     // top and a single exit at the bottom.
6804     // The point of exit cannot be a branch out of the structured block.
6805     // longjmp() and throw() must not violate the entry/exit criteria.
6806     CS->getCapturedDecl()->setNothrow();
6807   }
6808 
6809   OMPLoopDirective::HelperExprs B;
6810   // In presence of clause 'collapse' with number of loops, it will
6811   // define the nested loops number.
6812   unsigned NestedLoopCount = CheckOpenMPLoop(
6813       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6814       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
6815       VarsWithImplicitDSA, B);
6816   if (NestedLoopCount == 0)
6817     return StmtError();
6818 
6819   assert((CurContext->isDependentContext() || B.builtAll()) &&
6820          "omp for loop exprs were not built");
6821 
6822   getCurFunction()->setHasBranchProtectedScope();
6823   return OMPDistributeParallelForDirective::Create(
6824       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6825       DSAStack->isCancelRegion());
6826 }
6827 
6828 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6829     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6830     SourceLocation EndLoc,
6831     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6832   if (!AStmt)
6833     return StmtError();
6834 
6835   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6836   // 1.2.2 OpenMP Language Terminology
6837   // Structured block - An executable statement with a single entry at the
6838   // top and a single exit at the bottom.
6839   // The point of exit cannot be a branch out of the structured block.
6840   // longjmp() and throw() must not violate the entry/exit criteria.
6841   CS->getCapturedDecl()->setNothrow();
6842   for (int ThisCaptureLevel =
6843            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6844        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6845     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6846     // 1.2.2 OpenMP Language Terminology
6847     // Structured block - An executable statement with a single entry at the
6848     // top and a single exit at the bottom.
6849     // The point of exit cannot be a branch out of the structured block.
6850     // longjmp() and throw() must not violate the entry/exit criteria.
6851     CS->getCapturedDecl()->setNothrow();
6852   }
6853 
6854   OMPLoopDirective::HelperExprs B;
6855   // In presence of clause 'collapse' with number of loops, it will
6856   // define the nested loops number.
6857   unsigned NestedLoopCount = CheckOpenMPLoop(
6858       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6859       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
6860       VarsWithImplicitDSA, B);
6861   if (NestedLoopCount == 0)
6862     return StmtError();
6863 
6864   assert((CurContext->isDependentContext() || B.builtAll()) &&
6865          "omp for loop exprs were not built");
6866 
6867   if (!CurContext->isDependentContext()) {
6868     // Finalize the clauses that need pre-built expressions for CodeGen.
6869     for (auto C : Clauses) {
6870       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6871         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6872                                      B.NumIterations, *this, CurScope,
6873                                      DSAStack))
6874           return StmtError();
6875     }
6876   }
6877 
6878   if (checkSimdlenSafelenSpecified(*this, Clauses))
6879     return StmtError();
6880 
6881   getCurFunction()->setHasBranchProtectedScope();
6882   return OMPDistributeParallelForSimdDirective::Create(
6883       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6884 }
6885 
6886 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6887     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6888     SourceLocation EndLoc,
6889     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6890   if (!AStmt)
6891     return StmtError();
6892 
6893   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6894   // 1.2.2 OpenMP Language Terminology
6895   // Structured block - An executable statement with a single entry at the
6896   // top and a single exit at the bottom.
6897   // The point of exit cannot be a branch out of the structured block.
6898   // longjmp() and throw() must not violate the entry/exit criteria.
6899   CS->getCapturedDecl()->setNothrow();
6900   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
6901        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6902     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6903     // 1.2.2 OpenMP Language Terminology
6904     // Structured block - An executable statement with a single entry at the
6905     // top and a single exit at the bottom.
6906     // The point of exit cannot be a branch out of the structured block.
6907     // longjmp() and throw() must not violate the entry/exit criteria.
6908     CS->getCapturedDecl()->setNothrow();
6909   }
6910 
6911   OMPLoopDirective::HelperExprs B;
6912   // In presence of clause 'collapse' with number of loops, it will
6913   // define the nested loops number.
6914   unsigned NestedLoopCount =
6915       CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6916                       nullptr /*ordered not a clause on distribute*/, CS, *this,
6917                       *DSAStack, 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   if (checkSimdlenSafelenSpecified(*this, Clauses))
6936     return StmtError();
6937 
6938   getCurFunction()->setHasBranchProtectedScope();
6939   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6940                                             NestedLoopCount, Clauses, AStmt, B);
6941 }
6942 
6943 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6944     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6945     SourceLocation EndLoc,
6946     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6947   if (!AStmt)
6948     return StmtError();
6949 
6950   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6951   // 1.2.2 OpenMP Language Terminology
6952   // Structured block - An executable statement with a single entry at the
6953   // top and a single exit at the bottom.
6954   // The point of exit cannot be a branch out of the structured block.
6955   // longjmp() and throw() must not violate the entry/exit criteria.
6956   CS->getCapturedDecl()->setNothrow();
6957   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6958        ThisCaptureLevel > 1; --ThisCaptureLevel) {
6959     CS = cast<CapturedStmt>(CS->getCapturedStmt());
6960     // 1.2.2 OpenMP Language Terminology
6961     // Structured block - An executable statement with a single entry at the
6962     // top and a single exit at the bottom.
6963     // The point of exit cannot be a branch out of the structured block.
6964     // longjmp() and throw() must not violate the entry/exit criteria.
6965     CS->getCapturedDecl()->setNothrow();
6966   }
6967 
6968   OMPLoopDirective::HelperExprs B;
6969   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6970   // define the nested loops number.
6971   unsigned NestedLoopCount = CheckOpenMPLoop(
6972       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6973       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
6974       VarsWithImplicitDSA, B);
6975   if (NestedLoopCount == 0)
6976     return StmtError();
6977 
6978   assert((CurContext->isDependentContext() || B.builtAll()) &&
6979          "omp target parallel for simd loop exprs were not built");
6980 
6981   if (!CurContext->isDependentContext()) {
6982     // Finalize the clauses that need pre-built expressions for CodeGen.
6983     for (auto C : Clauses) {
6984       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6985         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6986                                      B.NumIterations, *this, CurScope,
6987                                      DSAStack))
6988           return StmtError();
6989     }
6990   }
6991   if (checkSimdlenSafelenSpecified(*this, Clauses))
6992     return StmtError();
6993 
6994   getCurFunction()->setHasBranchProtectedScope();
6995   return OMPTargetParallelForSimdDirective::Create(
6996       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6997 }
6998 
6999 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7000     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7001     SourceLocation EndLoc,
7002     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7003   if (!AStmt)
7004     return StmtError();
7005 
7006   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7007   // 1.2.2 OpenMP Language Terminology
7008   // Structured block - An executable statement with a single entry at the
7009   // top and a single exit at the bottom.
7010   // The point of exit cannot be a branch out of the structured block.
7011   // longjmp() and throw() must not violate the entry/exit criteria.
7012   CS->getCapturedDecl()->setNothrow();
7013   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7014        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7015     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7016     // 1.2.2 OpenMP Language Terminology
7017     // Structured block - An executable statement with a single entry at the
7018     // top and a single exit at the bottom.
7019     // The point of exit cannot be a branch out of the structured block.
7020     // longjmp() and throw() must not violate the entry/exit criteria.
7021     CS->getCapturedDecl()->setNothrow();
7022   }
7023 
7024   OMPLoopDirective::HelperExprs B;
7025   // In presence of clause 'collapse' with number of loops, it will define the
7026   // nested loops number.
7027   unsigned NestedLoopCount =
7028       CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7029                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7030                       VarsWithImplicitDSA, B);
7031   if (NestedLoopCount == 0)
7032     return StmtError();
7033 
7034   assert((CurContext->isDependentContext() || B.builtAll()) &&
7035          "omp target simd loop exprs were not built");
7036 
7037   if (!CurContext->isDependentContext()) {
7038     // Finalize the clauses that need pre-built expressions for CodeGen.
7039     for (auto C : Clauses) {
7040       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7041         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7042                                      B.NumIterations, *this, CurScope,
7043                                      DSAStack))
7044           return StmtError();
7045     }
7046   }
7047 
7048   if (checkSimdlenSafelenSpecified(*this, Clauses))
7049     return StmtError();
7050 
7051   getCurFunction()->setHasBranchProtectedScope();
7052   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7053                                         NestedLoopCount, Clauses, AStmt, B);
7054 }
7055 
7056 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7057     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7058     SourceLocation EndLoc,
7059     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7060   if (!AStmt)
7061     return StmtError();
7062 
7063   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7064   // 1.2.2 OpenMP Language Terminology
7065   // Structured block - An executable statement with a single entry at the
7066   // top and a single exit at the bottom.
7067   // The point of exit cannot be a branch out of the structured block.
7068   // longjmp() and throw() must not violate the entry/exit criteria.
7069   CS->getCapturedDecl()->setNothrow();
7070   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7071        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7072     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7073     // 1.2.2 OpenMP Language Terminology
7074     // Structured block - An executable statement with a single entry at the
7075     // top and a single exit at the bottom.
7076     // The point of exit cannot be a branch out of the structured block.
7077     // longjmp() and throw() must not violate the entry/exit criteria.
7078     CS->getCapturedDecl()->setNothrow();
7079   }
7080 
7081   OMPLoopDirective::HelperExprs B;
7082   // In presence of clause 'collapse' with number of loops, it will
7083   // define the nested loops number.
7084   unsigned NestedLoopCount =
7085       CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7086                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7087                       *DSAStack, VarsWithImplicitDSA, B);
7088   if (NestedLoopCount == 0)
7089     return StmtError();
7090 
7091   assert((CurContext->isDependentContext() || B.builtAll()) &&
7092          "omp teams distribute loop exprs were not built");
7093 
7094   getCurFunction()->setHasBranchProtectedScope();
7095 
7096   DSAStack->setParentTeamsRegionLoc(StartLoc);
7097 
7098   return OMPTeamsDistributeDirective::Create(
7099       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7100 }
7101 
7102 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7103     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7104     SourceLocation EndLoc,
7105     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7106   if (!AStmt)
7107     return StmtError();
7108 
7109   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7110   // 1.2.2 OpenMP Language Terminology
7111   // Structured block - An executable statement with a single entry at the
7112   // top and a single exit at the bottom.
7113   // The point of exit cannot be a branch out of the structured block.
7114   // longjmp() and throw() must not violate the entry/exit criteria.
7115   CS->getCapturedDecl()->setNothrow();
7116   for (int ThisCaptureLevel =
7117            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7118        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7119     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7120     // 1.2.2 OpenMP Language Terminology
7121     // Structured block - An executable statement with a single entry at the
7122     // top and a single exit at the bottom.
7123     // The point of exit cannot be a branch out of the structured block.
7124     // longjmp() and throw() must not violate the entry/exit criteria.
7125     CS->getCapturedDecl()->setNothrow();
7126   }
7127 
7128 
7129   OMPLoopDirective::HelperExprs B;
7130   // In presence of clause 'collapse' with number of loops, it will
7131   // define the nested loops number.
7132   unsigned NestedLoopCount = CheckOpenMPLoop(
7133       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7134       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7135       VarsWithImplicitDSA, B);
7136 
7137   if (NestedLoopCount == 0)
7138     return StmtError();
7139 
7140   assert((CurContext->isDependentContext() || B.builtAll()) &&
7141          "omp teams distribute simd loop exprs were not built");
7142 
7143   if (!CurContext->isDependentContext()) {
7144     // Finalize the clauses that need pre-built expressions for CodeGen.
7145     for (auto C : Clauses) {
7146       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7147         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7148                                      B.NumIterations, *this, CurScope,
7149                                      DSAStack))
7150           return StmtError();
7151     }
7152   }
7153 
7154   if (checkSimdlenSafelenSpecified(*this, Clauses))
7155     return StmtError();
7156 
7157   getCurFunction()->setHasBranchProtectedScope();
7158 
7159   DSAStack->setParentTeamsRegionLoc(StartLoc);
7160 
7161   return OMPTeamsDistributeSimdDirective::Create(
7162       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7163 }
7164 
7165 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7166     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7167     SourceLocation EndLoc,
7168     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7169   if (!AStmt)
7170     return StmtError();
7171 
7172   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7173   // 1.2.2 OpenMP Language Terminology
7174   // Structured block - An executable statement with a single entry at the
7175   // top and a single exit at the bottom.
7176   // The point of exit cannot be a branch out of the structured block.
7177   // longjmp() and throw() must not violate the entry/exit criteria.
7178   CS->getCapturedDecl()->setNothrow();
7179 
7180   for (int ThisCaptureLevel =
7181            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7182        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7183     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7184     // 1.2.2 OpenMP Language Terminology
7185     // Structured block - An executable statement with a single entry at the
7186     // top and a single exit at the bottom.
7187     // The point of exit cannot be a branch out of the structured block.
7188     // longjmp() and throw() must not violate the entry/exit criteria.
7189     CS->getCapturedDecl()->setNothrow();
7190   }
7191 
7192   OMPLoopDirective::HelperExprs B;
7193   // In presence of clause 'collapse' with number of loops, it will
7194   // define the nested loops number.
7195   auto NestedLoopCount = CheckOpenMPLoop(
7196       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7197       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7198       VarsWithImplicitDSA, B);
7199 
7200   if (NestedLoopCount == 0)
7201     return StmtError();
7202 
7203   assert((CurContext->isDependentContext() || B.builtAll()) &&
7204          "omp for loop exprs were not built");
7205 
7206   if (!CurContext->isDependentContext()) {
7207     // Finalize the clauses that need pre-built expressions for CodeGen.
7208     for (auto C : Clauses) {
7209       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7210         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7211                                      B.NumIterations, *this, CurScope,
7212                                      DSAStack))
7213           return StmtError();
7214     }
7215   }
7216 
7217   if (checkSimdlenSafelenSpecified(*this, Clauses))
7218     return StmtError();
7219 
7220   getCurFunction()->setHasBranchProtectedScope();
7221 
7222   DSAStack->setParentTeamsRegionLoc(StartLoc);
7223 
7224   return OMPTeamsDistributeParallelForSimdDirective::Create(
7225       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7226 }
7227 
7228 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7229     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7230     SourceLocation EndLoc,
7231     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7232   if (!AStmt)
7233     return StmtError();
7234 
7235   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7236   // 1.2.2 OpenMP Language Terminology
7237   // Structured block - An executable statement with a single entry at the
7238   // top and a single exit at the bottom.
7239   // The point of exit cannot be a branch out of the structured block.
7240   // longjmp() and throw() must not violate the entry/exit criteria.
7241   CS->getCapturedDecl()->setNothrow();
7242 
7243   for (int ThisCaptureLevel =
7244            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7245        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7246     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7247     // 1.2.2 OpenMP Language Terminology
7248     // Structured block - An executable statement with a single entry at the
7249     // top and a single exit at the bottom.
7250     // The point of exit cannot be a branch out of the structured block.
7251     // longjmp() and throw() must not violate the entry/exit criteria.
7252     CS->getCapturedDecl()->setNothrow();
7253   }
7254 
7255   OMPLoopDirective::HelperExprs B;
7256   // In presence of clause 'collapse' with number of loops, it will
7257   // define the nested loops number.
7258   unsigned NestedLoopCount = CheckOpenMPLoop(
7259       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7260       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7261       VarsWithImplicitDSA, B);
7262 
7263   if (NestedLoopCount == 0)
7264     return StmtError();
7265 
7266   assert((CurContext->isDependentContext() || B.builtAll()) &&
7267          "omp for loop exprs were not built");
7268 
7269   getCurFunction()->setHasBranchProtectedScope();
7270 
7271   DSAStack->setParentTeamsRegionLoc(StartLoc);
7272 
7273   return OMPTeamsDistributeParallelForDirective::Create(
7274       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7275       DSAStack->isCancelRegion());
7276 }
7277 
7278 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7279                                                  Stmt *AStmt,
7280                                                  SourceLocation StartLoc,
7281                                                  SourceLocation EndLoc) {
7282   if (!AStmt)
7283     return StmtError();
7284 
7285   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7286   // 1.2.2 OpenMP Language Terminology
7287   // Structured block - An executable statement with a single entry at the
7288   // top and a single exit at the bottom.
7289   // The point of exit cannot be a branch out of the structured block.
7290   // longjmp() and throw() must not violate the entry/exit criteria.
7291   CS->getCapturedDecl()->setNothrow();
7292 
7293   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7294        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7295     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7296     // 1.2.2 OpenMP Language Terminology
7297     // Structured block - An executable statement with a single entry at the
7298     // top and a single exit at the bottom.
7299     // The point of exit cannot be a branch out of the structured block.
7300     // longjmp() and throw() must not violate the entry/exit criteria.
7301     CS->getCapturedDecl()->setNothrow();
7302   }
7303   getCurFunction()->setHasBranchProtectedScope();
7304 
7305   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7306                                          AStmt);
7307 }
7308 
7309 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7310     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7311     SourceLocation EndLoc,
7312     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7313   if (!AStmt)
7314     return StmtError();
7315 
7316   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7317   // 1.2.2 OpenMP Language Terminology
7318   // Structured block - An executable statement with a single entry at the
7319   // top and a single exit at the bottom.
7320   // The point of exit cannot be a branch out of the structured block.
7321   // longjmp() and throw() must not violate the entry/exit criteria.
7322   CS->getCapturedDecl()->setNothrow();
7323   for (int ThisCaptureLevel =
7324            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7325        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7326     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7327     // 1.2.2 OpenMP Language Terminology
7328     // Structured block - An executable statement with a single entry at the
7329     // top and a single exit at the bottom.
7330     // The point of exit cannot be a branch out of the structured block.
7331     // longjmp() and throw() must not violate the entry/exit criteria.
7332     CS->getCapturedDecl()->setNothrow();
7333   }
7334 
7335   OMPLoopDirective::HelperExprs B;
7336   // In presence of clause 'collapse' with number of loops, it will
7337   // define the nested loops number.
7338   auto NestedLoopCount = CheckOpenMPLoop(
7339       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7340       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7341       VarsWithImplicitDSA, B);
7342   if (NestedLoopCount == 0)
7343     return StmtError();
7344 
7345   assert((CurContext->isDependentContext() || B.builtAll()) &&
7346          "omp target teams distribute loop exprs were not built");
7347 
7348   getCurFunction()->setHasBranchProtectedScope();
7349   return OMPTargetTeamsDistributeDirective::Create(
7350       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7351 }
7352 
7353 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7354     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7355     SourceLocation EndLoc,
7356     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7357   if (!AStmt)
7358     return StmtError();
7359 
7360   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7361   // 1.2.2 OpenMP Language Terminology
7362   // Structured block - An executable statement with a single entry at the
7363   // top and a single exit at the bottom.
7364   // The point of exit cannot be a branch out of the structured block.
7365   // longjmp() and throw() must not violate the entry/exit criteria.
7366   CS->getCapturedDecl()->setNothrow();
7367 
7368   OMPLoopDirective::HelperExprs B;
7369   // In presence of clause 'collapse' with number of loops, it will
7370   // define the nested loops number.
7371   auto NestedLoopCount = CheckOpenMPLoop(
7372       OMPD_target_teams_distribute_parallel_for,
7373       getCollapseNumberExpr(Clauses),
7374       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7375       VarsWithImplicitDSA, B);
7376   if (NestedLoopCount == 0)
7377     return StmtError();
7378 
7379   assert((CurContext->isDependentContext() || B.builtAll()) &&
7380          "omp target teams distribute parallel for loop exprs were not built");
7381 
7382   getCurFunction()->setHasBranchProtectedScope();
7383   return OMPTargetTeamsDistributeParallelForDirective::Create(
7384       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7385       DSAStack->isCancelRegion());
7386 }
7387 
7388 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7389     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7390     SourceLocation EndLoc,
7391     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7392   if (!AStmt)
7393     return StmtError();
7394 
7395   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7396   // 1.2.2 OpenMP Language Terminology
7397   // Structured block - An executable statement with a single entry at the
7398   // top and a single exit at the bottom.
7399   // The point of exit cannot be a branch out of the structured block.
7400   // longjmp() and throw() must not violate the entry/exit criteria.
7401   CS->getCapturedDecl()->setNothrow();
7402 
7403   OMPLoopDirective::HelperExprs B;
7404   // In presence of clause 'collapse' with number of loops, it will
7405   // define the nested loops number.
7406   auto NestedLoopCount = CheckOpenMPLoop(
7407       OMPD_target_teams_distribute_parallel_for_simd,
7408       getCollapseNumberExpr(Clauses),
7409       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7410       VarsWithImplicitDSA, B);
7411   if (NestedLoopCount == 0)
7412     return StmtError();
7413 
7414   assert((CurContext->isDependentContext() || B.builtAll()) &&
7415          "omp target teams distribute parallel for simd loop exprs were not "
7416          "built");
7417 
7418   if (!CurContext->isDependentContext()) {
7419     // Finalize the clauses that need pre-built expressions for CodeGen.
7420     for (auto C : Clauses) {
7421       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7422         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7423                                      B.NumIterations, *this, CurScope,
7424                                      DSAStack))
7425           return StmtError();
7426     }
7427   }
7428 
7429   if (checkSimdlenSafelenSpecified(*this, Clauses))
7430     return StmtError();
7431 
7432   getCurFunction()->setHasBranchProtectedScope();
7433   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7434       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7435 }
7436 
7437 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7438     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7439     SourceLocation EndLoc,
7440     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7441   if (!AStmt)
7442     return StmtError();
7443 
7444   auto *CS = cast<CapturedStmt>(AStmt);
7445   // 1.2.2 OpenMP Language Terminology
7446   // Structured block - An executable statement with a single entry at the
7447   // top and a single exit at the bottom.
7448   // The point of exit cannot be a branch out of the structured block.
7449   // longjmp() and throw() must not violate the entry/exit criteria.
7450   CS->getCapturedDecl()->setNothrow();
7451 
7452   OMPLoopDirective::HelperExprs B;
7453   // In presence of clause 'collapse' with number of loops, it will
7454   // define the nested loops number.
7455   auto NestedLoopCount = CheckOpenMPLoop(
7456       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7457       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
7458       VarsWithImplicitDSA, B);
7459   if (NestedLoopCount == 0)
7460     return StmtError();
7461 
7462   assert((CurContext->isDependentContext() || B.builtAll()) &&
7463          "omp target teams distribute simd loop exprs were not built");
7464 
7465   if (!CurContext->isDependentContext()) {
7466     // Finalize the clauses that need pre-built expressions for CodeGen.
7467     for (auto C : Clauses) {
7468       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7469         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7470                                      B.NumIterations, *this, CurScope,
7471                                      DSAStack))
7472           return StmtError();
7473     }
7474   }
7475 
7476   if (checkSimdlenSafelenSpecified(*this, Clauses))
7477     return StmtError();
7478 
7479   getCurFunction()->setHasBranchProtectedScope();
7480   return OMPTargetTeamsDistributeSimdDirective::Create(
7481       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7482 }
7483 
7484 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
7485                                              SourceLocation StartLoc,
7486                                              SourceLocation LParenLoc,
7487                                              SourceLocation EndLoc) {
7488   OMPClause *Res = nullptr;
7489   switch (Kind) {
7490   case OMPC_final:
7491     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7492     break;
7493   case OMPC_num_threads:
7494     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7495     break;
7496   case OMPC_safelen:
7497     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7498     break;
7499   case OMPC_simdlen:
7500     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7501     break;
7502   case OMPC_collapse:
7503     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7504     break;
7505   case OMPC_ordered:
7506     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7507     break;
7508   case OMPC_device:
7509     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7510     break;
7511   case OMPC_num_teams:
7512     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7513     break;
7514   case OMPC_thread_limit:
7515     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7516     break;
7517   case OMPC_priority:
7518     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7519     break;
7520   case OMPC_grainsize:
7521     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7522     break;
7523   case OMPC_num_tasks:
7524     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7525     break;
7526   case OMPC_hint:
7527     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7528     break;
7529   case OMPC_if:
7530   case OMPC_default:
7531   case OMPC_proc_bind:
7532   case OMPC_schedule:
7533   case OMPC_private:
7534   case OMPC_firstprivate:
7535   case OMPC_lastprivate:
7536   case OMPC_shared:
7537   case OMPC_reduction:
7538   case OMPC_task_reduction:
7539   case OMPC_in_reduction:
7540   case OMPC_linear:
7541   case OMPC_aligned:
7542   case OMPC_copyin:
7543   case OMPC_copyprivate:
7544   case OMPC_nowait:
7545   case OMPC_untied:
7546   case OMPC_mergeable:
7547   case OMPC_threadprivate:
7548   case OMPC_flush:
7549   case OMPC_read:
7550   case OMPC_write:
7551   case OMPC_update:
7552   case OMPC_capture:
7553   case OMPC_seq_cst:
7554   case OMPC_depend:
7555   case OMPC_threads:
7556   case OMPC_simd:
7557   case OMPC_map:
7558   case OMPC_nogroup:
7559   case OMPC_dist_schedule:
7560   case OMPC_defaultmap:
7561   case OMPC_unknown:
7562   case OMPC_uniform:
7563   case OMPC_to:
7564   case OMPC_from:
7565   case OMPC_use_device_ptr:
7566   case OMPC_is_device_ptr:
7567     llvm_unreachable("Clause is not allowed.");
7568   }
7569   return Res;
7570 }
7571 
7572 // An OpenMP directive such as 'target parallel' has two captured regions:
7573 // for the 'target' and 'parallel' respectively.  This function returns
7574 // the region in which to capture expressions associated with a clause.
7575 // A return value of OMPD_unknown signifies that the expression should not
7576 // be captured.
7577 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7578     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7579     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
7580   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7581   switch (CKind) {
7582   case OMPC_if:
7583     switch (DKind) {
7584     case OMPD_target_parallel:
7585     case OMPD_target_parallel_for:
7586     case OMPD_target_parallel_for_simd:
7587     case OMPD_target_teams_distribute_parallel_for:
7588     case OMPD_target_teams_distribute_parallel_for_simd:
7589       // If this clause applies to the nested 'parallel' region, capture within
7590       // the 'target' region, otherwise do not capture.
7591       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7592         CaptureRegion = OMPD_target;
7593       break;
7594     case OMPD_teams_distribute_parallel_for:
7595     case OMPD_teams_distribute_parallel_for_simd:
7596       CaptureRegion = OMPD_teams;
7597       break;
7598     case OMPD_cancel:
7599     case OMPD_parallel:
7600     case OMPD_parallel_sections:
7601     case OMPD_parallel_for:
7602     case OMPD_parallel_for_simd:
7603     case OMPD_target:
7604     case OMPD_target_simd:
7605     case OMPD_target_teams:
7606     case OMPD_target_teams_distribute:
7607     case OMPD_target_teams_distribute_simd:
7608     case OMPD_distribute_parallel_for:
7609     case OMPD_distribute_parallel_for_simd:
7610     case OMPD_task:
7611     case OMPD_taskloop:
7612     case OMPD_taskloop_simd:
7613     case OMPD_target_data:
7614     case OMPD_target_enter_data:
7615     case OMPD_target_exit_data:
7616     case OMPD_target_update:
7617       // Do not capture if-clause expressions.
7618       break;
7619     case OMPD_threadprivate:
7620     case OMPD_taskyield:
7621     case OMPD_barrier:
7622     case OMPD_taskwait:
7623     case OMPD_cancellation_point:
7624     case OMPD_flush:
7625     case OMPD_declare_reduction:
7626     case OMPD_declare_simd:
7627     case OMPD_declare_target:
7628     case OMPD_end_declare_target:
7629     case OMPD_teams:
7630     case OMPD_simd:
7631     case OMPD_for:
7632     case OMPD_for_simd:
7633     case OMPD_sections:
7634     case OMPD_section:
7635     case OMPD_single:
7636     case OMPD_master:
7637     case OMPD_critical:
7638     case OMPD_taskgroup:
7639     case OMPD_distribute:
7640     case OMPD_ordered:
7641     case OMPD_atomic:
7642     case OMPD_distribute_simd:
7643     case OMPD_teams_distribute:
7644     case OMPD_teams_distribute_simd:
7645       llvm_unreachable("Unexpected OpenMP directive with if-clause");
7646     case OMPD_unknown:
7647       llvm_unreachable("Unknown OpenMP directive");
7648     }
7649     break;
7650   case OMPC_num_threads:
7651     switch (DKind) {
7652     case OMPD_target_parallel:
7653     case OMPD_target_parallel_for:
7654     case OMPD_target_parallel_for_simd:
7655     case OMPD_target_teams_distribute_parallel_for:
7656     case OMPD_target_teams_distribute_parallel_for_simd:
7657       CaptureRegion = OMPD_target;
7658       break;
7659     case OMPD_teams_distribute_parallel_for:
7660     case OMPD_teams_distribute_parallel_for_simd:
7661       CaptureRegion = OMPD_teams;
7662       break;
7663     case OMPD_parallel:
7664     case OMPD_parallel_sections:
7665     case OMPD_parallel_for:
7666     case OMPD_parallel_for_simd:
7667     case OMPD_distribute_parallel_for:
7668     case OMPD_distribute_parallel_for_simd:
7669       // Do not capture num_threads-clause expressions.
7670       break;
7671     case OMPD_target_data:
7672     case OMPD_target_enter_data:
7673     case OMPD_target_exit_data:
7674     case OMPD_target_update:
7675     case OMPD_target:
7676     case OMPD_target_simd:
7677     case OMPD_target_teams:
7678     case OMPD_target_teams_distribute:
7679     case OMPD_target_teams_distribute_simd:
7680     case OMPD_cancel:
7681     case OMPD_task:
7682     case OMPD_taskloop:
7683     case OMPD_taskloop_simd:
7684     case OMPD_threadprivate:
7685     case OMPD_taskyield:
7686     case OMPD_barrier:
7687     case OMPD_taskwait:
7688     case OMPD_cancellation_point:
7689     case OMPD_flush:
7690     case OMPD_declare_reduction:
7691     case OMPD_declare_simd:
7692     case OMPD_declare_target:
7693     case OMPD_end_declare_target:
7694     case OMPD_teams:
7695     case OMPD_simd:
7696     case OMPD_for:
7697     case OMPD_for_simd:
7698     case OMPD_sections:
7699     case OMPD_section:
7700     case OMPD_single:
7701     case OMPD_master:
7702     case OMPD_critical:
7703     case OMPD_taskgroup:
7704     case OMPD_distribute:
7705     case OMPD_ordered:
7706     case OMPD_atomic:
7707     case OMPD_distribute_simd:
7708     case OMPD_teams_distribute:
7709     case OMPD_teams_distribute_simd:
7710       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7711     case OMPD_unknown:
7712       llvm_unreachable("Unknown OpenMP directive");
7713     }
7714     break;
7715   case OMPC_num_teams:
7716     switch (DKind) {
7717     case OMPD_target_teams:
7718     case OMPD_target_teams_distribute:
7719     case OMPD_target_teams_distribute_simd:
7720     case OMPD_target_teams_distribute_parallel_for:
7721     case OMPD_target_teams_distribute_parallel_for_simd:
7722       CaptureRegion = OMPD_target;
7723       break;
7724     case OMPD_teams_distribute_parallel_for:
7725     case OMPD_teams_distribute_parallel_for_simd:
7726     case OMPD_teams:
7727     case OMPD_teams_distribute:
7728     case OMPD_teams_distribute_simd:
7729       // Do not capture num_teams-clause expressions.
7730       break;
7731     case OMPD_distribute_parallel_for:
7732     case OMPD_distribute_parallel_for_simd:
7733     case OMPD_task:
7734     case OMPD_taskloop:
7735     case OMPD_taskloop_simd:
7736     case OMPD_target_data:
7737     case OMPD_target_enter_data:
7738     case OMPD_target_exit_data:
7739     case OMPD_target_update:
7740     case OMPD_cancel:
7741     case OMPD_parallel:
7742     case OMPD_parallel_sections:
7743     case OMPD_parallel_for:
7744     case OMPD_parallel_for_simd:
7745     case OMPD_target:
7746     case OMPD_target_simd:
7747     case OMPD_target_parallel:
7748     case OMPD_target_parallel_for:
7749     case OMPD_target_parallel_for_simd:
7750     case OMPD_threadprivate:
7751     case OMPD_taskyield:
7752     case OMPD_barrier:
7753     case OMPD_taskwait:
7754     case OMPD_cancellation_point:
7755     case OMPD_flush:
7756     case OMPD_declare_reduction:
7757     case OMPD_declare_simd:
7758     case OMPD_declare_target:
7759     case OMPD_end_declare_target:
7760     case OMPD_simd:
7761     case OMPD_for:
7762     case OMPD_for_simd:
7763     case OMPD_sections:
7764     case OMPD_section:
7765     case OMPD_single:
7766     case OMPD_master:
7767     case OMPD_critical:
7768     case OMPD_taskgroup:
7769     case OMPD_distribute:
7770     case OMPD_ordered:
7771     case OMPD_atomic:
7772     case OMPD_distribute_simd:
7773       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7774     case OMPD_unknown:
7775       llvm_unreachable("Unknown OpenMP directive");
7776     }
7777     break;
7778   case OMPC_thread_limit:
7779     switch (DKind) {
7780     case OMPD_target_teams:
7781     case OMPD_target_teams_distribute:
7782     case OMPD_target_teams_distribute_simd:
7783     case OMPD_target_teams_distribute_parallel_for:
7784     case OMPD_target_teams_distribute_parallel_for_simd:
7785       CaptureRegion = OMPD_target;
7786       break;
7787     case OMPD_teams_distribute_parallel_for:
7788     case OMPD_teams_distribute_parallel_for_simd:
7789     case OMPD_teams:
7790     case OMPD_teams_distribute:
7791     case OMPD_teams_distribute_simd:
7792       // Do not capture thread_limit-clause expressions.
7793       break;
7794     case OMPD_distribute_parallel_for:
7795     case OMPD_distribute_parallel_for_simd:
7796     case OMPD_task:
7797     case OMPD_taskloop:
7798     case OMPD_taskloop_simd:
7799     case OMPD_target_data:
7800     case OMPD_target_enter_data:
7801     case OMPD_target_exit_data:
7802     case OMPD_target_update:
7803     case OMPD_cancel:
7804     case OMPD_parallel:
7805     case OMPD_parallel_sections:
7806     case OMPD_parallel_for:
7807     case OMPD_parallel_for_simd:
7808     case OMPD_target:
7809     case OMPD_target_simd:
7810     case OMPD_target_parallel:
7811     case OMPD_target_parallel_for:
7812     case OMPD_target_parallel_for_simd:
7813     case OMPD_threadprivate:
7814     case OMPD_taskyield:
7815     case OMPD_barrier:
7816     case OMPD_taskwait:
7817     case OMPD_cancellation_point:
7818     case OMPD_flush:
7819     case OMPD_declare_reduction:
7820     case OMPD_declare_simd:
7821     case OMPD_declare_target:
7822     case OMPD_end_declare_target:
7823     case OMPD_simd:
7824     case OMPD_for:
7825     case OMPD_for_simd:
7826     case OMPD_sections:
7827     case OMPD_section:
7828     case OMPD_single:
7829     case OMPD_master:
7830     case OMPD_critical:
7831     case OMPD_taskgroup:
7832     case OMPD_distribute:
7833     case OMPD_ordered:
7834     case OMPD_atomic:
7835     case OMPD_distribute_simd:
7836       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7837     case OMPD_unknown:
7838       llvm_unreachable("Unknown OpenMP directive");
7839     }
7840     break;
7841   case OMPC_schedule:
7842     switch (DKind) {
7843     case OMPD_target_parallel_for:
7844     case OMPD_target_parallel_for_simd:
7845     case OMPD_target_teams_distribute_parallel_for:
7846     case OMPD_target_teams_distribute_parallel_for_simd:
7847       CaptureRegion = OMPD_target;
7848       break;
7849     case OMPD_teams_distribute_parallel_for:
7850     case OMPD_teams_distribute_parallel_for_simd:
7851       CaptureRegion = OMPD_teams;
7852       break;
7853     case OMPD_parallel_for:
7854     case OMPD_parallel_for_simd:
7855     case OMPD_distribute_parallel_for:
7856     case OMPD_distribute_parallel_for_simd:
7857       CaptureRegion = OMPD_parallel;
7858       break;
7859     case OMPD_for:
7860     case OMPD_for_simd:
7861       // Do not capture schedule-clause expressions.
7862       break;
7863     case OMPD_task:
7864     case OMPD_taskloop:
7865     case OMPD_taskloop_simd:
7866     case OMPD_target_data:
7867     case OMPD_target_enter_data:
7868     case OMPD_target_exit_data:
7869     case OMPD_target_update:
7870     case OMPD_teams:
7871     case OMPD_teams_distribute:
7872     case OMPD_teams_distribute_simd:
7873     case OMPD_target_teams_distribute:
7874     case OMPD_target_teams_distribute_simd:
7875     case OMPD_target:
7876     case OMPD_target_simd:
7877     case OMPD_target_parallel:
7878     case OMPD_cancel:
7879     case OMPD_parallel:
7880     case OMPD_parallel_sections:
7881     case OMPD_threadprivate:
7882     case OMPD_taskyield:
7883     case OMPD_barrier:
7884     case OMPD_taskwait:
7885     case OMPD_cancellation_point:
7886     case OMPD_flush:
7887     case OMPD_declare_reduction:
7888     case OMPD_declare_simd:
7889     case OMPD_declare_target:
7890     case OMPD_end_declare_target:
7891     case OMPD_simd:
7892     case OMPD_sections:
7893     case OMPD_section:
7894     case OMPD_single:
7895     case OMPD_master:
7896     case OMPD_critical:
7897     case OMPD_taskgroup:
7898     case OMPD_distribute:
7899     case OMPD_ordered:
7900     case OMPD_atomic:
7901     case OMPD_distribute_simd:
7902     case OMPD_target_teams:
7903       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7904     case OMPD_unknown:
7905       llvm_unreachable("Unknown OpenMP directive");
7906     }
7907     break;
7908   case OMPC_dist_schedule:
7909     switch (DKind) {
7910     case OMPD_teams_distribute_parallel_for:
7911     case OMPD_teams_distribute_parallel_for_simd:
7912     case OMPD_teams_distribute:
7913     case OMPD_teams_distribute_simd:
7914       CaptureRegion = OMPD_teams;
7915       break;
7916     case OMPD_target_teams_distribute_parallel_for:
7917     case OMPD_target_teams_distribute_parallel_for_simd:
7918     case OMPD_target_teams_distribute:
7919     case OMPD_target_teams_distribute_simd:
7920       CaptureRegion = OMPD_target;
7921       break;
7922     case OMPD_distribute_parallel_for:
7923     case OMPD_distribute_parallel_for_simd:
7924       CaptureRegion = OMPD_parallel;
7925       break;
7926     case OMPD_distribute:
7927     case OMPD_distribute_simd:
7928       // Do not capture thread_limit-clause expressions.
7929       break;
7930     case OMPD_parallel_for:
7931     case OMPD_parallel_for_simd:
7932     case OMPD_target_parallel_for_simd:
7933     case OMPD_target_parallel_for:
7934     case OMPD_task:
7935     case OMPD_taskloop:
7936     case OMPD_taskloop_simd:
7937     case OMPD_target_data:
7938     case OMPD_target_enter_data:
7939     case OMPD_target_exit_data:
7940     case OMPD_target_update:
7941     case OMPD_teams:
7942     case OMPD_target:
7943     case OMPD_target_simd:
7944     case OMPD_target_parallel:
7945     case OMPD_cancel:
7946     case OMPD_parallel:
7947     case OMPD_parallel_sections:
7948     case OMPD_threadprivate:
7949     case OMPD_taskyield:
7950     case OMPD_barrier:
7951     case OMPD_taskwait:
7952     case OMPD_cancellation_point:
7953     case OMPD_flush:
7954     case OMPD_declare_reduction:
7955     case OMPD_declare_simd:
7956     case OMPD_declare_target:
7957     case OMPD_end_declare_target:
7958     case OMPD_simd:
7959     case OMPD_for:
7960     case OMPD_for_simd:
7961     case OMPD_sections:
7962     case OMPD_section:
7963     case OMPD_single:
7964     case OMPD_master:
7965     case OMPD_critical:
7966     case OMPD_taskgroup:
7967     case OMPD_ordered:
7968     case OMPD_atomic:
7969     case OMPD_target_teams:
7970       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
7971     case OMPD_unknown:
7972       llvm_unreachable("Unknown OpenMP directive");
7973     }
7974     break;
7975   case OMPC_device:
7976     switch (DKind) {
7977     case OMPD_target_teams:
7978     case OMPD_target_teams_distribute:
7979     case OMPD_target_teams_distribute_simd:
7980     case OMPD_target_teams_distribute_parallel_for:
7981     case OMPD_target_teams_distribute_parallel_for_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_target:
7987     case OMPD_target_simd:
7988     case OMPD_target_parallel:
7989     case OMPD_target_parallel_for:
7990     case OMPD_target_parallel_for_simd:
7991       // Do not capture device-clause expressions.
7992       break;
7993     case OMPD_teams_distribute_parallel_for:
7994     case OMPD_teams_distribute_parallel_for_simd:
7995     case OMPD_teams:
7996     case OMPD_teams_distribute:
7997     case OMPD_teams_distribute_simd:
7998     case OMPD_distribute_parallel_for:
7999     case OMPD_distribute_parallel_for_simd:
8000     case OMPD_task:
8001     case OMPD_taskloop:
8002     case OMPD_taskloop_simd:
8003     case OMPD_cancel:
8004     case OMPD_parallel:
8005     case OMPD_parallel_sections:
8006     case OMPD_parallel_for:
8007     case OMPD_parallel_for_simd:
8008     case OMPD_threadprivate:
8009     case OMPD_taskyield:
8010     case OMPD_barrier:
8011     case OMPD_taskwait:
8012     case OMPD_cancellation_point:
8013     case OMPD_flush:
8014     case OMPD_declare_reduction:
8015     case OMPD_declare_simd:
8016     case OMPD_declare_target:
8017     case OMPD_end_declare_target:
8018     case OMPD_simd:
8019     case OMPD_for:
8020     case OMPD_for_simd:
8021     case OMPD_sections:
8022     case OMPD_section:
8023     case OMPD_single:
8024     case OMPD_master:
8025     case OMPD_critical:
8026     case OMPD_taskgroup:
8027     case OMPD_distribute:
8028     case OMPD_ordered:
8029     case OMPD_atomic:
8030     case OMPD_distribute_simd:
8031       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8032     case OMPD_unknown:
8033       llvm_unreachable("Unknown OpenMP directive");
8034     }
8035     break;
8036   case OMPC_firstprivate:
8037   case OMPC_lastprivate:
8038   case OMPC_reduction:
8039   case OMPC_task_reduction:
8040   case OMPC_in_reduction:
8041   case OMPC_linear:
8042   case OMPC_default:
8043   case OMPC_proc_bind:
8044   case OMPC_final:
8045   case OMPC_safelen:
8046   case OMPC_simdlen:
8047   case OMPC_collapse:
8048   case OMPC_private:
8049   case OMPC_shared:
8050   case OMPC_aligned:
8051   case OMPC_copyin:
8052   case OMPC_copyprivate:
8053   case OMPC_ordered:
8054   case OMPC_nowait:
8055   case OMPC_untied:
8056   case OMPC_mergeable:
8057   case OMPC_threadprivate:
8058   case OMPC_flush:
8059   case OMPC_read:
8060   case OMPC_write:
8061   case OMPC_update:
8062   case OMPC_capture:
8063   case OMPC_seq_cst:
8064   case OMPC_depend:
8065   case OMPC_threads:
8066   case OMPC_simd:
8067   case OMPC_map:
8068   case OMPC_priority:
8069   case OMPC_grainsize:
8070   case OMPC_nogroup:
8071   case OMPC_num_tasks:
8072   case OMPC_hint:
8073   case OMPC_defaultmap:
8074   case OMPC_unknown:
8075   case OMPC_uniform:
8076   case OMPC_to:
8077   case OMPC_from:
8078   case OMPC_use_device_ptr:
8079   case OMPC_is_device_ptr:
8080     llvm_unreachable("Unexpected OpenMP clause.");
8081   }
8082   return CaptureRegion;
8083 }
8084 
8085 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8086                                      Expr *Condition, SourceLocation StartLoc,
8087                                      SourceLocation LParenLoc,
8088                                      SourceLocation NameModifierLoc,
8089                                      SourceLocation ColonLoc,
8090                                      SourceLocation EndLoc) {
8091   Expr *ValExpr = Condition;
8092   Stmt *HelperValStmt = nullptr;
8093   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8094   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8095       !Condition->isInstantiationDependent() &&
8096       !Condition->containsUnexpandedParameterPack()) {
8097     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8098     if (Val.isInvalid())
8099       return nullptr;
8100 
8101     ValExpr = MakeFullExpr(Val.get()).get();
8102 
8103     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8104     CaptureRegion =
8105         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8106     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8107       llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8108       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8109       HelperValStmt = buildPreInits(Context, Captures);
8110     }
8111   }
8112 
8113   return new (Context)
8114       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8115                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8116 }
8117 
8118 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8119                                         SourceLocation StartLoc,
8120                                         SourceLocation LParenLoc,
8121                                         SourceLocation EndLoc) {
8122   Expr *ValExpr = Condition;
8123   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8124       !Condition->isInstantiationDependent() &&
8125       !Condition->containsUnexpandedParameterPack()) {
8126     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8127     if (Val.isInvalid())
8128       return nullptr;
8129 
8130     ValExpr = MakeFullExpr(Val.get()).get();
8131   }
8132 
8133   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8134 }
8135 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8136                                                         Expr *Op) {
8137   if (!Op)
8138     return ExprError();
8139 
8140   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8141   public:
8142     IntConvertDiagnoser()
8143         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8144     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8145                                          QualType T) override {
8146       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8147     }
8148     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8149                                              QualType T) override {
8150       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8151     }
8152     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8153                                                QualType T,
8154                                                QualType ConvTy) override {
8155       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8156     }
8157     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8158                                            QualType ConvTy) override {
8159       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8160              << ConvTy->isEnumeralType() << ConvTy;
8161     }
8162     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8163                                             QualType T) override {
8164       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8165     }
8166     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8167                                         QualType ConvTy) override {
8168       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8169              << ConvTy->isEnumeralType() << ConvTy;
8170     }
8171     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8172                                              QualType) override {
8173       llvm_unreachable("conversion functions are permitted");
8174     }
8175   } ConvertDiagnoser;
8176   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8177 }
8178 
8179 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8180                                       OpenMPClauseKind CKind,
8181                                       bool StrictlyPositive) {
8182   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8183       !ValExpr->isInstantiationDependent()) {
8184     SourceLocation Loc = ValExpr->getExprLoc();
8185     ExprResult Value =
8186         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8187     if (Value.isInvalid())
8188       return false;
8189 
8190     ValExpr = Value.get();
8191     // The expression must evaluate to a non-negative integer value.
8192     llvm::APSInt Result;
8193     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
8194         Result.isSigned() &&
8195         !((!StrictlyPositive && Result.isNonNegative()) ||
8196           (StrictlyPositive && Result.isStrictlyPositive()))) {
8197       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
8198           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8199           << ValExpr->getSourceRange();
8200       return false;
8201     }
8202   }
8203   return true;
8204 }
8205 
8206 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8207                                              SourceLocation StartLoc,
8208                                              SourceLocation LParenLoc,
8209                                              SourceLocation EndLoc) {
8210   Expr *ValExpr = NumThreads;
8211   Stmt *HelperValStmt = nullptr;
8212 
8213   // OpenMP [2.5, Restrictions]
8214   //  The num_threads expression must evaluate to a positive integer value.
8215   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8216                                  /*StrictlyPositive=*/true))
8217     return nullptr;
8218 
8219   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8220   OpenMPDirectiveKind CaptureRegion =
8221       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8222   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8223     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8224     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8225     HelperValStmt = buildPreInits(Context, Captures);
8226   }
8227 
8228   return new (Context) OMPNumThreadsClause(
8229       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
8230 }
8231 
8232 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
8233                                                        OpenMPClauseKind CKind,
8234                                                        bool StrictlyPositive) {
8235   if (!E)
8236     return ExprError();
8237   if (E->isValueDependent() || E->isTypeDependent() ||
8238       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
8239     return E;
8240   llvm::APSInt Result;
8241   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8242   if (ICE.isInvalid())
8243     return ExprError();
8244   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8245       (!StrictlyPositive && !Result.isNonNegative())) {
8246     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8247         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8248         << E->getSourceRange();
8249     return ExprError();
8250   }
8251   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8252     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8253         << E->getSourceRange();
8254     return ExprError();
8255   }
8256   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8257     DSAStack->setAssociatedLoops(Result.getExtValue());
8258   else if (CKind == OMPC_ordered)
8259     DSAStack->setAssociatedLoops(Result.getExtValue());
8260   return ICE;
8261 }
8262 
8263 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8264                                           SourceLocation LParenLoc,
8265                                           SourceLocation EndLoc) {
8266   // OpenMP [2.8.1, simd construct, Description]
8267   // The parameter of the safelen clause must be a constant
8268   // positive integer expression.
8269   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8270   if (Safelen.isInvalid())
8271     return nullptr;
8272   return new (Context)
8273       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
8274 }
8275 
8276 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8277                                           SourceLocation LParenLoc,
8278                                           SourceLocation EndLoc) {
8279   // OpenMP [2.8.1, simd construct, Description]
8280   // The parameter of the simdlen clause must be a constant
8281   // positive integer expression.
8282   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8283   if (Simdlen.isInvalid())
8284     return nullptr;
8285   return new (Context)
8286       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8287 }
8288 
8289 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8290                                            SourceLocation StartLoc,
8291                                            SourceLocation LParenLoc,
8292                                            SourceLocation EndLoc) {
8293   // OpenMP [2.7.1, loop construct, Description]
8294   // OpenMP [2.8.1, simd construct, Description]
8295   // OpenMP [2.9.6, distribute construct, Description]
8296   // The parameter of the collapse clause must be a constant
8297   // positive integer expression.
8298   ExprResult NumForLoopsResult =
8299       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8300   if (NumForLoopsResult.isInvalid())
8301     return nullptr;
8302   return new (Context)
8303       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
8304 }
8305 
8306 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8307                                           SourceLocation EndLoc,
8308                                           SourceLocation LParenLoc,
8309                                           Expr *NumForLoops) {
8310   // OpenMP [2.7.1, loop construct, Description]
8311   // OpenMP [2.8.1, simd construct, Description]
8312   // OpenMP [2.9.6, distribute construct, Description]
8313   // The parameter of the ordered clause must be a constant
8314   // positive integer expression if any.
8315   if (NumForLoops && LParenLoc.isValid()) {
8316     ExprResult NumForLoopsResult =
8317         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8318     if (NumForLoopsResult.isInvalid())
8319       return nullptr;
8320     NumForLoops = NumForLoopsResult.get();
8321   } else
8322     NumForLoops = nullptr;
8323   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
8324   return new (Context)
8325       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8326 }
8327 
8328 OMPClause *Sema::ActOnOpenMPSimpleClause(
8329     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8330     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8331   OMPClause *Res = nullptr;
8332   switch (Kind) {
8333   case OMPC_default:
8334     Res =
8335         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8336                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
8337     break;
8338   case OMPC_proc_bind:
8339     Res = ActOnOpenMPProcBindClause(
8340         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8341         LParenLoc, EndLoc);
8342     break;
8343   case OMPC_if:
8344   case OMPC_final:
8345   case OMPC_num_threads:
8346   case OMPC_safelen:
8347   case OMPC_simdlen:
8348   case OMPC_collapse:
8349   case OMPC_schedule:
8350   case OMPC_private:
8351   case OMPC_firstprivate:
8352   case OMPC_lastprivate:
8353   case OMPC_shared:
8354   case OMPC_reduction:
8355   case OMPC_task_reduction:
8356   case OMPC_in_reduction:
8357   case OMPC_linear:
8358   case OMPC_aligned:
8359   case OMPC_copyin:
8360   case OMPC_copyprivate:
8361   case OMPC_ordered:
8362   case OMPC_nowait:
8363   case OMPC_untied:
8364   case OMPC_mergeable:
8365   case OMPC_threadprivate:
8366   case OMPC_flush:
8367   case OMPC_read:
8368   case OMPC_write:
8369   case OMPC_update:
8370   case OMPC_capture:
8371   case OMPC_seq_cst:
8372   case OMPC_depend:
8373   case OMPC_device:
8374   case OMPC_threads:
8375   case OMPC_simd:
8376   case OMPC_map:
8377   case OMPC_num_teams:
8378   case OMPC_thread_limit:
8379   case OMPC_priority:
8380   case OMPC_grainsize:
8381   case OMPC_nogroup:
8382   case OMPC_num_tasks:
8383   case OMPC_hint:
8384   case OMPC_dist_schedule:
8385   case OMPC_defaultmap:
8386   case OMPC_unknown:
8387   case OMPC_uniform:
8388   case OMPC_to:
8389   case OMPC_from:
8390   case OMPC_use_device_ptr:
8391   case OMPC_is_device_ptr:
8392     llvm_unreachable("Clause is not allowed.");
8393   }
8394   return Res;
8395 }
8396 
8397 static std::string
8398 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8399                         ArrayRef<unsigned> Exclude = llvm::None) {
8400   std::string Values;
8401   unsigned Bound = Last >= 2 ? Last - 2 : 0;
8402   unsigned Skipped = Exclude.size();
8403   auto S = Exclude.begin(), E = Exclude.end();
8404   for (unsigned i = First; i < Last; ++i) {
8405     if (std::find(S, E, i) != E) {
8406       --Skipped;
8407       continue;
8408     }
8409     Values += "'";
8410     Values += getOpenMPSimpleClauseTypeName(K, i);
8411     Values += "'";
8412     if (i == Bound - Skipped)
8413       Values += " or ";
8414     else if (i != Bound + 1 - Skipped)
8415       Values += ", ";
8416   }
8417   return Values;
8418 }
8419 
8420 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8421                                           SourceLocation KindKwLoc,
8422                                           SourceLocation StartLoc,
8423                                           SourceLocation LParenLoc,
8424                                           SourceLocation EndLoc) {
8425   if (Kind == OMPC_DEFAULT_unknown) {
8426     static_assert(OMPC_DEFAULT_unknown > 0,
8427                   "OMPC_DEFAULT_unknown not greater than 0");
8428     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8429         << getListOfPossibleValues(OMPC_default, /*First=*/0,
8430                                    /*Last=*/OMPC_DEFAULT_unknown)
8431         << getOpenMPClauseName(OMPC_default);
8432     return nullptr;
8433   }
8434   switch (Kind) {
8435   case OMPC_DEFAULT_none:
8436     DSAStack->setDefaultDSANone(KindKwLoc);
8437     break;
8438   case OMPC_DEFAULT_shared:
8439     DSAStack->setDefaultDSAShared(KindKwLoc);
8440     break;
8441   case OMPC_DEFAULT_unknown:
8442     llvm_unreachable("Clause kind is not allowed.");
8443     break;
8444   }
8445   return new (Context)
8446       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8447 }
8448 
8449 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8450                                            SourceLocation KindKwLoc,
8451                                            SourceLocation StartLoc,
8452                                            SourceLocation LParenLoc,
8453                                            SourceLocation EndLoc) {
8454   if (Kind == OMPC_PROC_BIND_unknown) {
8455     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
8456         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8457                                    /*Last=*/OMPC_PROC_BIND_unknown)
8458         << getOpenMPClauseName(OMPC_proc_bind);
8459     return nullptr;
8460   }
8461   return new (Context)
8462       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
8463 }
8464 
8465 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
8466     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
8467     SourceLocation StartLoc, SourceLocation LParenLoc,
8468     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
8469     SourceLocation EndLoc) {
8470   OMPClause *Res = nullptr;
8471   switch (Kind) {
8472   case OMPC_schedule:
8473     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8474     assert(Argument.size() == NumberOfElements &&
8475            ArgumentLoc.size() == NumberOfElements);
8476     Res = ActOnOpenMPScheduleClause(
8477         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8478         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8479         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8480         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8481         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
8482     break;
8483   case OMPC_if:
8484     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8485     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8486                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8487                               DelimLoc, EndLoc);
8488     break;
8489   case OMPC_dist_schedule:
8490     Res = ActOnOpenMPDistScheduleClause(
8491         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8492         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8493     break;
8494   case OMPC_defaultmap:
8495     enum { Modifier, DefaultmapKind };
8496     Res = ActOnOpenMPDefaultmapClause(
8497         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8498         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
8499         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8500         EndLoc);
8501     break;
8502   case OMPC_final:
8503   case OMPC_num_threads:
8504   case OMPC_safelen:
8505   case OMPC_simdlen:
8506   case OMPC_collapse:
8507   case OMPC_default:
8508   case OMPC_proc_bind:
8509   case OMPC_private:
8510   case OMPC_firstprivate:
8511   case OMPC_lastprivate:
8512   case OMPC_shared:
8513   case OMPC_reduction:
8514   case OMPC_task_reduction:
8515   case OMPC_in_reduction:
8516   case OMPC_linear:
8517   case OMPC_aligned:
8518   case OMPC_copyin:
8519   case OMPC_copyprivate:
8520   case OMPC_ordered:
8521   case OMPC_nowait:
8522   case OMPC_untied:
8523   case OMPC_mergeable:
8524   case OMPC_threadprivate:
8525   case OMPC_flush:
8526   case OMPC_read:
8527   case OMPC_write:
8528   case OMPC_update:
8529   case OMPC_capture:
8530   case OMPC_seq_cst:
8531   case OMPC_depend:
8532   case OMPC_device:
8533   case OMPC_threads:
8534   case OMPC_simd:
8535   case OMPC_map:
8536   case OMPC_num_teams:
8537   case OMPC_thread_limit:
8538   case OMPC_priority:
8539   case OMPC_grainsize:
8540   case OMPC_nogroup:
8541   case OMPC_num_tasks:
8542   case OMPC_hint:
8543   case OMPC_unknown:
8544   case OMPC_uniform:
8545   case OMPC_to:
8546   case OMPC_from:
8547   case OMPC_use_device_ptr:
8548   case OMPC_is_device_ptr:
8549     llvm_unreachable("Clause is not allowed.");
8550   }
8551   return Res;
8552 }
8553 
8554 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8555                                    OpenMPScheduleClauseModifier M2,
8556                                    SourceLocation M1Loc, SourceLocation M2Loc) {
8557   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8558     SmallVector<unsigned, 2> Excluded;
8559     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8560       Excluded.push_back(M2);
8561     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8562       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8563     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8564       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8565     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8566         << getListOfPossibleValues(OMPC_schedule,
8567                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8568                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8569                                    Excluded)
8570         << getOpenMPClauseName(OMPC_schedule);
8571     return true;
8572   }
8573   return false;
8574 }
8575 
8576 OMPClause *Sema::ActOnOpenMPScheduleClause(
8577     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8578     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8579     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8580     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8581   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8582       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8583     return nullptr;
8584   // OpenMP, 2.7.1, Loop Construct, Restrictions
8585   // Either the monotonic modifier or the nonmonotonic modifier can be specified
8586   // but not both.
8587   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8588       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8589        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8590       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8591        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8592     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8593         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8594         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8595     return nullptr;
8596   }
8597   if (Kind == OMPC_SCHEDULE_unknown) {
8598     std::string Values;
8599     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8600       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8601       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8602                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8603                                        Exclude);
8604     } else {
8605       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8606                                        /*Last=*/OMPC_SCHEDULE_unknown);
8607     }
8608     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8609         << Values << getOpenMPClauseName(OMPC_schedule);
8610     return nullptr;
8611   }
8612   // OpenMP, 2.7.1, Loop Construct, Restrictions
8613   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8614   // schedule(guided).
8615   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8616        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8617       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8618     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8619          diag::err_omp_schedule_nonmonotonic_static);
8620     return nullptr;
8621   }
8622   Expr *ValExpr = ChunkSize;
8623   Stmt *HelperValStmt = nullptr;
8624   if (ChunkSize) {
8625     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8626         !ChunkSize->isInstantiationDependent() &&
8627         !ChunkSize->containsUnexpandedParameterPack()) {
8628       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8629       ExprResult Val =
8630           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8631       if (Val.isInvalid())
8632         return nullptr;
8633 
8634       ValExpr = Val.get();
8635 
8636       // OpenMP [2.7.1, Restrictions]
8637       //  chunk_size must be a loop invariant integer expression with a positive
8638       //  value.
8639       llvm::APSInt Result;
8640       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8641         if (Result.isSigned() && !Result.isStrictlyPositive()) {
8642           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
8643               << "schedule" << 1 << ChunkSize->getSourceRange();
8644           return nullptr;
8645         }
8646       } else if (getOpenMPCaptureRegionForClause(
8647                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
8648                      OMPD_unknown &&
8649                  !CurContext->isDependentContext()) {
8650         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8651         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8652         HelperValStmt = buildPreInits(Context, Captures);
8653       }
8654     }
8655   }
8656 
8657   return new (Context)
8658       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
8659                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
8660 }
8661 
8662 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8663                                    SourceLocation StartLoc,
8664                                    SourceLocation EndLoc) {
8665   OMPClause *Res = nullptr;
8666   switch (Kind) {
8667   case OMPC_ordered:
8668     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8669     break;
8670   case OMPC_nowait:
8671     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8672     break;
8673   case OMPC_untied:
8674     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8675     break;
8676   case OMPC_mergeable:
8677     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8678     break;
8679   case OMPC_read:
8680     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8681     break;
8682   case OMPC_write:
8683     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8684     break;
8685   case OMPC_update:
8686     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8687     break;
8688   case OMPC_capture:
8689     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8690     break;
8691   case OMPC_seq_cst:
8692     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8693     break;
8694   case OMPC_threads:
8695     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8696     break;
8697   case OMPC_simd:
8698     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8699     break;
8700   case OMPC_nogroup:
8701     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8702     break;
8703   case OMPC_if:
8704   case OMPC_final:
8705   case OMPC_num_threads:
8706   case OMPC_safelen:
8707   case OMPC_simdlen:
8708   case OMPC_collapse:
8709   case OMPC_schedule:
8710   case OMPC_private:
8711   case OMPC_firstprivate:
8712   case OMPC_lastprivate:
8713   case OMPC_shared:
8714   case OMPC_reduction:
8715   case OMPC_task_reduction:
8716   case OMPC_in_reduction:
8717   case OMPC_linear:
8718   case OMPC_aligned:
8719   case OMPC_copyin:
8720   case OMPC_copyprivate:
8721   case OMPC_default:
8722   case OMPC_proc_bind:
8723   case OMPC_threadprivate:
8724   case OMPC_flush:
8725   case OMPC_depend:
8726   case OMPC_device:
8727   case OMPC_map:
8728   case OMPC_num_teams:
8729   case OMPC_thread_limit:
8730   case OMPC_priority:
8731   case OMPC_grainsize:
8732   case OMPC_num_tasks:
8733   case OMPC_hint:
8734   case OMPC_dist_schedule:
8735   case OMPC_defaultmap:
8736   case OMPC_unknown:
8737   case OMPC_uniform:
8738   case OMPC_to:
8739   case OMPC_from:
8740   case OMPC_use_device_ptr:
8741   case OMPC_is_device_ptr:
8742     llvm_unreachable("Clause is not allowed.");
8743   }
8744   return Res;
8745 }
8746 
8747 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8748                                          SourceLocation EndLoc) {
8749   DSAStack->setNowaitRegion();
8750   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8751 }
8752 
8753 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8754                                          SourceLocation EndLoc) {
8755   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8756 }
8757 
8758 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8759                                             SourceLocation EndLoc) {
8760   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8761 }
8762 
8763 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8764                                        SourceLocation EndLoc) {
8765   return new (Context) OMPReadClause(StartLoc, EndLoc);
8766 }
8767 
8768 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8769                                         SourceLocation EndLoc) {
8770   return new (Context) OMPWriteClause(StartLoc, EndLoc);
8771 }
8772 
8773 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8774                                          SourceLocation EndLoc) {
8775   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8776 }
8777 
8778 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8779                                           SourceLocation EndLoc) {
8780   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8781 }
8782 
8783 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8784                                          SourceLocation EndLoc) {
8785   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8786 }
8787 
8788 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8789                                           SourceLocation EndLoc) {
8790   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8791 }
8792 
8793 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8794                                        SourceLocation EndLoc) {
8795   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8796 }
8797 
8798 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8799                                           SourceLocation EndLoc) {
8800   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8801 }
8802 
8803 OMPClause *Sema::ActOnOpenMPVarListClause(
8804     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8805     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8806     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
8807     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8808     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8809     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8810     SourceLocation DepLinMapLoc) {
8811   OMPClause *Res = nullptr;
8812   switch (Kind) {
8813   case OMPC_private:
8814     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8815     break;
8816   case OMPC_firstprivate:
8817     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8818     break;
8819   case OMPC_lastprivate:
8820     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8821     break;
8822   case OMPC_shared:
8823     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8824     break;
8825   case OMPC_reduction:
8826     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8827                                      EndLoc, ReductionIdScopeSpec, ReductionId);
8828     break;
8829   case OMPC_task_reduction:
8830     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8831                                          EndLoc, ReductionIdScopeSpec,
8832                                          ReductionId);
8833     break;
8834   case OMPC_in_reduction:
8835     Res =
8836         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8837                                      EndLoc, ReductionIdScopeSpec, ReductionId);
8838     break;
8839   case OMPC_linear:
8840     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
8841                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
8842     break;
8843   case OMPC_aligned:
8844     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8845                                    ColonLoc, EndLoc);
8846     break;
8847   case OMPC_copyin:
8848     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8849     break;
8850   case OMPC_copyprivate:
8851     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8852     break;
8853   case OMPC_flush:
8854     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8855     break;
8856   case OMPC_depend:
8857     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
8858                                   StartLoc, LParenLoc, EndLoc);
8859     break;
8860   case OMPC_map:
8861     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8862                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
8863                                LParenLoc, EndLoc);
8864     break;
8865   case OMPC_to:
8866     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8867     break;
8868   case OMPC_from:
8869     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8870     break;
8871   case OMPC_use_device_ptr:
8872     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8873     break;
8874   case OMPC_is_device_ptr:
8875     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8876     break;
8877   case OMPC_if:
8878   case OMPC_final:
8879   case OMPC_num_threads:
8880   case OMPC_safelen:
8881   case OMPC_simdlen:
8882   case OMPC_collapse:
8883   case OMPC_default:
8884   case OMPC_proc_bind:
8885   case OMPC_schedule:
8886   case OMPC_ordered:
8887   case OMPC_nowait:
8888   case OMPC_untied:
8889   case OMPC_mergeable:
8890   case OMPC_threadprivate:
8891   case OMPC_read:
8892   case OMPC_write:
8893   case OMPC_update:
8894   case OMPC_capture:
8895   case OMPC_seq_cst:
8896   case OMPC_device:
8897   case OMPC_threads:
8898   case OMPC_simd:
8899   case OMPC_num_teams:
8900   case OMPC_thread_limit:
8901   case OMPC_priority:
8902   case OMPC_grainsize:
8903   case OMPC_nogroup:
8904   case OMPC_num_tasks:
8905   case OMPC_hint:
8906   case OMPC_dist_schedule:
8907   case OMPC_defaultmap:
8908   case OMPC_unknown:
8909   case OMPC_uniform:
8910     llvm_unreachable("Clause is not allowed.");
8911   }
8912   return Res;
8913 }
8914 
8915 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8916                                        ExprObjectKind OK, SourceLocation Loc) {
8917   ExprResult Res = BuildDeclRefExpr(
8918       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8919   if (!Res.isUsable())
8920     return ExprError();
8921   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8922     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8923     if (!Res.isUsable())
8924       return ExprError();
8925   }
8926   if (VK != VK_LValue && Res.get()->isGLValue()) {
8927     Res = DefaultLvalueConversion(Res.get());
8928     if (!Res.isUsable())
8929       return ExprError();
8930   }
8931   return Res;
8932 }
8933 
8934 static std::pair<ValueDecl *, bool>
8935 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8936                SourceRange &ERange, bool AllowArraySection = false) {
8937   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8938       RefExpr->containsUnexpandedParameterPack())
8939     return std::make_pair(nullptr, true);
8940 
8941   // OpenMP [3.1, C/C++]
8942   //  A list item is a variable name.
8943   // OpenMP  [2.9.3.3, Restrictions, p.1]
8944   //  A variable that is part of another variable (as an array or
8945   //  structure element) cannot appear in a private clause.
8946   RefExpr = RefExpr->IgnoreParens();
8947   enum {
8948     NoArrayExpr = -1,
8949     ArraySubscript = 0,
8950     OMPArraySection = 1
8951   } IsArrayExpr = NoArrayExpr;
8952   if (AllowArraySection) {
8953     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8954       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8955       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8956         Base = TempASE->getBase()->IgnoreParenImpCasts();
8957       RefExpr = Base;
8958       IsArrayExpr = ArraySubscript;
8959     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8960       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8961       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8962         Base = TempOASE->getBase()->IgnoreParenImpCasts();
8963       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8964         Base = TempASE->getBase()->IgnoreParenImpCasts();
8965       RefExpr = Base;
8966       IsArrayExpr = OMPArraySection;
8967     }
8968   }
8969   ELoc = RefExpr->getExprLoc();
8970   ERange = RefExpr->getSourceRange();
8971   RefExpr = RefExpr->IgnoreParenImpCasts();
8972   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8973   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8974   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8975       (S.getCurrentThisType().isNull() || !ME ||
8976        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8977        !isa<FieldDecl>(ME->getMemberDecl()))) {
8978     if (IsArrayExpr != NoArrayExpr)
8979       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8980                                                          << ERange;
8981     else {
8982       S.Diag(ELoc,
8983              AllowArraySection
8984                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
8985                  : diag::err_omp_expected_var_name_member_expr)
8986           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8987     }
8988     return std::make_pair(nullptr, false);
8989   }
8990   return std::make_pair(
8991       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
8992 }
8993 
8994 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8995                                           SourceLocation StartLoc,
8996                                           SourceLocation LParenLoc,
8997                                           SourceLocation EndLoc) {
8998   SmallVector<Expr *, 8> Vars;
8999   SmallVector<Expr *, 8> PrivateCopies;
9000   for (auto &RefExpr : VarList) {
9001     assert(RefExpr && "NULL expr in OpenMP private clause.");
9002     SourceLocation ELoc;
9003     SourceRange ERange;
9004     Expr *SimpleRefExpr = RefExpr;
9005     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9006     if (Res.second) {
9007       // It will be analyzed later.
9008       Vars.push_back(RefExpr);
9009       PrivateCopies.push_back(nullptr);
9010     }
9011     ValueDecl *D = Res.first;
9012     if (!D)
9013       continue;
9014 
9015     QualType Type = D->getType();
9016     auto *VD = dyn_cast<VarDecl>(D);
9017 
9018     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9019     //  A variable that appears in a private clause must not have an incomplete
9020     //  type or a reference type.
9021     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9022       continue;
9023     Type = Type.getNonReferenceType();
9024 
9025     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9026     // in a Construct]
9027     //  Variables with the predetermined data-sharing attributes may not be
9028     //  listed in data-sharing attributes clauses, except for the cases
9029     //  listed below. For these exceptions only, listing a predetermined
9030     //  variable in a data-sharing attribute clause is allowed and overrides
9031     //  the variable's predetermined data-sharing attributes.
9032     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9033     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9034       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9035                                           << getOpenMPClauseName(OMPC_private);
9036       ReportOriginalDSA(*this, DSAStack, D, DVar);
9037       continue;
9038     }
9039 
9040     auto CurrDir = DSAStack->getCurrentDirective();
9041     // Variably modified types are not supported for tasks.
9042     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9043         isOpenMPTaskingDirective(CurrDir)) {
9044       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9045           << getOpenMPClauseName(OMPC_private) << Type
9046           << getOpenMPDirectiveName(CurrDir);
9047       bool IsDecl =
9048           !VD ||
9049           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9050       Diag(D->getLocation(),
9051            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9052           << D;
9053       continue;
9054     }
9055 
9056     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9057     // A list item cannot appear in both a map clause and a data-sharing
9058     // attribute clause on the same construct
9059     if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
9060         CurrDir == OMPD_target_teams ||
9061         CurrDir == OMPD_target_teams_distribute ||
9062         CurrDir == OMPD_target_teams_distribute_parallel_for ||
9063         CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
9064         CurrDir == OMPD_target_teams_distribute_simd ||
9065         CurrDir == OMPD_target_parallel_for_simd ||
9066         CurrDir == OMPD_target_parallel_for) {
9067       OpenMPClauseKind ConflictKind;
9068       if (DSAStack->checkMappableExprComponentListsForDecl(
9069               VD, /*CurrentRegionOnly=*/true,
9070               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9071                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9072                 ConflictKind = WhereFoundClauseKind;
9073                 return true;
9074               })) {
9075         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9076             << getOpenMPClauseName(OMPC_private)
9077             << getOpenMPClauseName(ConflictKind)
9078             << getOpenMPDirectiveName(CurrDir);
9079         ReportOriginalDSA(*this, DSAStack, D, DVar);
9080         continue;
9081       }
9082     }
9083 
9084     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9085     //  A variable of class type (or array thereof) that appears in a private
9086     //  clause requires an accessible, unambiguous default constructor for the
9087     //  class type.
9088     // Generate helper private variable and initialize it with the default
9089     // value. The address of the original variable is replaced by the address of
9090     // the new private variable in CodeGen. This new variable is not added to
9091     // IdResolver, so the code in the OpenMP region uses original variable for
9092     // proper diagnostics.
9093     Type = Type.getUnqualifiedType();
9094     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9095                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
9096     ActOnUninitializedDecl(VDPrivate);
9097     if (VDPrivate->isInvalidDecl())
9098       continue;
9099     auto VDPrivateRefExpr = buildDeclRefExpr(
9100         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9101 
9102     DeclRefExpr *Ref = nullptr;
9103     if (!VD && !CurContext->isDependentContext())
9104       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9105     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
9106     Vars.push_back((VD || CurContext->isDependentContext())
9107                        ? RefExpr->IgnoreParens()
9108                        : Ref);
9109     PrivateCopies.push_back(VDPrivateRefExpr);
9110   }
9111 
9112   if (Vars.empty())
9113     return nullptr;
9114 
9115   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9116                                   PrivateCopies);
9117 }
9118 
9119 namespace {
9120 class DiagsUninitializedSeveretyRAII {
9121 private:
9122   DiagnosticsEngine &Diags;
9123   SourceLocation SavedLoc;
9124   bool IsIgnored;
9125 
9126 public:
9127   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9128                                  bool IsIgnored)
9129       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9130     if (!IsIgnored) {
9131       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9132                         /*Map*/ diag::Severity::Ignored, Loc);
9133     }
9134   }
9135   ~DiagsUninitializedSeveretyRAII() {
9136     if (!IsIgnored)
9137       Diags.popMappings(SavedLoc);
9138   }
9139 };
9140 }
9141 
9142 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9143                                                SourceLocation StartLoc,
9144                                                SourceLocation LParenLoc,
9145                                                SourceLocation EndLoc) {
9146   SmallVector<Expr *, 8> Vars;
9147   SmallVector<Expr *, 8> PrivateCopies;
9148   SmallVector<Expr *, 8> Inits;
9149   SmallVector<Decl *, 4> ExprCaptures;
9150   bool IsImplicitClause =
9151       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9152   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9153 
9154   for (auto &RefExpr : VarList) {
9155     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
9156     SourceLocation ELoc;
9157     SourceRange ERange;
9158     Expr *SimpleRefExpr = RefExpr;
9159     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9160     if (Res.second) {
9161       // It will be analyzed later.
9162       Vars.push_back(RefExpr);
9163       PrivateCopies.push_back(nullptr);
9164       Inits.push_back(nullptr);
9165     }
9166     ValueDecl *D = Res.first;
9167     if (!D)
9168       continue;
9169 
9170     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
9171     QualType Type = D->getType();
9172     auto *VD = dyn_cast<VarDecl>(D);
9173 
9174     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9175     //  A variable that appears in a private clause must not have an incomplete
9176     //  type or a reference type.
9177     if (RequireCompleteType(ELoc, Type,
9178                             diag::err_omp_firstprivate_incomplete_type))
9179       continue;
9180     Type = Type.getNonReferenceType();
9181 
9182     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9183     //  A variable of class type (or array thereof) that appears in a private
9184     //  clause requires an accessible, unambiguous copy constructor for the
9185     //  class type.
9186     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9187 
9188     // If an implicit firstprivate variable found it was checked already.
9189     DSAStackTy::DSAVarData TopDVar;
9190     if (!IsImplicitClause) {
9191       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9192       TopDVar = DVar;
9193       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9194       bool IsConstant = ElemType.isConstant(Context);
9195       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9196       //  A list item that specifies a given variable may not appear in more
9197       // than one clause on the same directive, except that a variable may be
9198       //  specified in both firstprivate and lastprivate clauses.
9199       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9200       // A list item may appear in a firstprivate or lastprivate clause but not
9201       // both.
9202       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
9203           (isOpenMPDistributeDirective(CurrDir) ||
9204            DVar.CKind != OMPC_lastprivate) &&
9205           DVar.RefExpr) {
9206         Diag(ELoc, diag::err_omp_wrong_dsa)
9207             << getOpenMPClauseName(DVar.CKind)
9208             << getOpenMPClauseName(OMPC_firstprivate);
9209         ReportOriginalDSA(*this, DSAStack, D, DVar);
9210         continue;
9211       }
9212 
9213       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9214       // in a Construct]
9215       //  Variables with the predetermined data-sharing attributes may not be
9216       //  listed in data-sharing attributes clauses, except for the cases
9217       //  listed below. For these exceptions only, listing a predetermined
9218       //  variable in a data-sharing attribute clause is allowed and overrides
9219       //  the variable's predetermined data-sharing attributes.
9220       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9221       // in a Construct, C/C++, p.2]
9222       //  Variables with const-qualified type having no mutable member may be
9223       //  listed in a firstprivate clause, even if they are static data members.
9224       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
9225           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9226         Diag(ELoc, diag::err_omp_wrong_dsa)
9227             << getOpenMPClauseName(DVar.CKind)
9228             << getOpenMPClauseName(OMPC_firstprivate);
9229         ReportOriginalDSA(*this, DSAStack, D, DVar);
9230         continue;
9231       }
9232 
9233       // OpenMP [2.9.3.4, Restrictions, p.2]
9234       //  A list item that is private within a parallel region must not appear
9235       //  in a firstprivate clause on a worksharing construct if any of the
9236       //  worksharing regions arising from the worksharing construct ever bind
9237       //  to any of the parallel regions arising from the parallel construct.
9238       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9239       // A list item that is private within a teams region must not appear in a
9240       // firstprivate clause on a distribute construct if any of the distribute
9241       // regions arising from the distribute construct ever bind to any of the
9242       // teams regions arising from the teams construct.
9243       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9244       // A list item that appears in a reduction clause of a teams construct
9245       // must not appear in a firstprivate clause on a distribute construct if
9246       // any of the distribute regions arising from the distribute construct
9247       // ever bind to any of the teams regions arising from the teams construct.
9248       if ((isOpenMPWorksharingDirective(CurrDir) ||
9249            isOpenMPDistributeDirective(CurrDir)) &&
9250           !isOpenMPParallelDirective(CurrDir) &&
9251           !isOpenMPTeamsDirective(CurrDir)) {
9252         DVar = DSAStack->getImplicitDSA(D, true);
9253         if (DVar.CKind != OMPC_shared &&
9254             (isOpenMPParallelDirective(DVar.DKind) ||
9255              isOpenMPTeamsDirective(DVar.DKind) ||
9256              DVar.DKind == OMPD_unknown)) {
9257           Diag(ELoc, diag::err_omp_required_access)
9258               << getOpenMPClauseName(OMPC_firstprivate)
9259               << getOpenMPClauseName(OMPC_shared);
9260           ReportOriginalDSA(*this, DSAStack, D, DVar);
9261           continue;
9262         }
9263       }
9264       // OpenMP [2.9.3.4, Restrictions, p.3]
9265       //  A list item that appears in a reduction clause of a parallel construct
9266       //  must not appear in a firstprivate clause on a worksharing or task
9267       //  construct if any of the worksharing or task regions arising from the
9268       //  worksharing or task construct ever bind to any of the parallel regions
9269       //  arising from the parallel construct.
9270       // OpenMP [2.9.3.4, Restrictions, p.4]
9271       //  A list item that appears in a reduction clause in worksharing
9272       //  construct must not appear in a firstprivate clause in a task construct
9273       //  encountered during execution of any of the worksharing regions arising
9274       //  from the worksharing construct.
9275       if (isOpenMPTaskingDirective(CurrDir)) {
9276         DVar = DSAStack->hasInnermostDSA(
9277             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9278             [](OpenMPDirectiveKind K) -> bool {
9279               return isOpenMPParallelDirective(K) ||
9280                      isOpenMPWorksharingDirective(K) ||
9281                      isOpenMPTeamsDirective(K);
9282             },
9283             /*FromParent=*/true);
9284         if (DVar.CKind == OMPC_reduction &&
9285             (isOpenMPParallelDirective(DVar.DKind) ||
9286              isOpenMPWorksharingDirective(DVar.DKind) ||
9287              isOpenMPTeamsDirective(DVar.DKind))) {
9288           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9289               << getOpenMPDirectiveName(DVar.DKind);
9290           ReportOriginalDSA(*this, DSAStack, D, DVar);
9291           continue;
9292         }
9293       }
9294 
9295       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9296       // A list item cannot appear in both a map clause and a data-sharing
9297       // attribute clause on the same construct
9298       if (isOpenMPTargetExecutionDirective(CurrDir)) {
9299         OpenMPClauseKind ConflictKind;
9300         if (DSAStack->checkMappableExprComponentListsForDecl(
9301                 VD, /*CurrentRegionOnly=*/true,
9302                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9303                     OpenMPClauseKind WhereFoundClauseKind) -> bool {
9304                   ConflictKind = WhereFoundClauseKind;
9305                   return true;
9306                 })) {
9307           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9308               << getOpenMPClauseName(OMPC_firstprivate)
9309               << getOpenMPClauseName(ConflictKind)
9310               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9311           ReportOriginalDSA(*this, DSAStack, D, DVar);
9312           continue;
9313         }
9314       }
9315     }
9316 
9317     // Variably modified types are not supported for tasks.
9318     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9319         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
9320       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9321           << getOpenMPClauseName(OMPC_firstprivate) << Type
9322           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9323       bool IsDecl =
9324           !VD ||
9325           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9326       Diag(D->getLocation(),
9327            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9328           << D;
9329       continue;
9330     }
9331 
9332     Type = Type.getUnqualifiedType();
9333     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9334                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
9335     // Generate helper private variable and initialize it with the value of the
9336     // original variable. The address of the original variable is replaced by
9337     // the address of the new private variable in the CodeGen. This new variable
9338     // is not added to IdResolver, so the code in the OpenMP region uses
9339     // original variable for proper diagnostics and variable capturing.
9340     Expr *VDInitRefExpr = nullptr;
9341     // For arrays generate initializer for single element and replace it by the
9342     // original array element in CodeGen.
9343     if (Type->isArrayType()) {
9344       auto VDInit =
9345           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
9346       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
9347       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
9348       ElemType = ElemType.getUnqualifiedType();
9349       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
9350                                       ".firstprivate.temp");
9351       InitializedEntity Entity =
9352           InitializedEntity::InitializeVariable(VDInitTemp);
9353       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9354 
9355       InitializationSequence InitSeq(*this, Entity, Kind, Init);
9356       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9357       if (Result.isInvalid())
9358         VDPrivate->setInvalidDecl();
9359       else
9360         VDPrivate->setInit(Result.getAs<Expr>());
9361       // Remove temp variable declaration.
9362       Context.Deallocate(VDInitTemp);
9363     } else {
9364       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9365                                   ".firstprivate.temp");
9366       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9367                                        RefExpr->getExprLoc());
9368       AddInitializerToDecl(VDPrivate,
9369                            DefaultLvalueConversion(VDInitRefExpr).get(),
9370                            /*DirectInit=*/false);
9371     }
9372     if (VDPrivate->isInvalidDecl()) {
9373       if (IsImplicitClause) {
9374         Diag(RefExpr->getExprLoc(),
9375              diag::note_omp_task_predetermined_firstprivate_here);
9376       }
9377       continue;
9378     }
9379     CurContext->addDecl(VDPrivate);
9380     auto VDPrivateRefExpr = buildDeclRefExpr(
9381         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9382         RefExpr->getExprLoc());
9383     DeclRefExpr *Ref = nullptr;
9384     if (!VD && !CurContext->isDependentContext()) {
9385       if (TopDVar.CKind == OMPC_lastprivate)
9386         Ref = TopDVar.PrivateCopy;
9387       else {
9388         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9389         if (!IsOpenMPCapturedDecl(D))
9390           ExprCaptures.push_back(Ref->getDecl());
9391       }
9392     }
9393     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
9394     Vars.push_back((VD || CurContext->isDependentContext())
9395                        ? RefExpr->IgnoreParens()
9396                        : Ref);
9397     PrivateCopies.push_back(VDPrivateRefExpr);
9398     Inits.push_back(VDInitRefExpr);
9399   }
9400 
9401   if (Vars.empty())
9402     return nullptr;
9403 
9404   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9405                                        Vars, PrivateCopies, Inits,
9406                                        buildPreInits(Context, ExprCaptures));
9407 }
9408 
9409 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9410                                               SourceLocation StartLoc,
9411                                               SourceLocation LParenLoc,
9412                                               SourceLocation EndLoc) {
9413   SmallVector<Expr *, 8> Vars;
9414   SmallVector<Expr *, 8> SrcExprs;
9415   SmallVector<Expr *, 8> DstExprs;
9416   SmallVector<Expr *, 8> AssignmentOps;
9417   SmallVector<Decl *, 4> ExprCaptures;
9418   SmallVector<Expr *, 4> ExprPostUpdates;
9419   for (auto &RefExpr : VarList) {
9420     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9421     SourceLocation ELoc;
9422     SourceRange ERange;
9423     Expr *SimpleRefExpr = RefExpr;
9424     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9425     if (Res.second) {
9426       // It will be analyzed later.
9427       Vars.push_back(RefExpr);
9428       SrcExprs.push_back(nullptr);
9429       DstExprs.push_back(nullptr);
9430       AssignmentOps.push_back(nullptr);
9431     }
9432     ValueDecl *D = Res.first;
9433     if (!D)
9434       continue;
9435 
9436     QualType Type = D->getType();
9437     auto *VD = dyn_cast<VarDecl>(D);
9438 
9439     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9440     //  A variable that appears in a lastprivate clause must not have an
9441     //  incomplete type or a reference type.
9442     if (RequireCompleteType(ELoc, Type,
9443                             diag::err_omp_lastprivate_incomplete_type))
9444       continue;
9445     Type = Type.getNonReferenceType();
9446 
9447     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9448     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9449     // in a Construct]
9450     //  Variables with the predetermined data-sharing attributes may not be
9451     //  listed in data-sharing attributes clauses, except for the cases
9452     //  listed below.
9453     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9454     // A list item may appear in a firstprivate or lastprivate clause but not
9455     // both.
9456     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9457     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
9458         (isOpenMPDistributeDirective(CurrDir) ||
9459          DVar.CKind != OMPC_firstprivate) &&
9460         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9461       Diag(ELoc, diag::err_omp_wrong_dsa)
9462           << getOpenMPClauseName(DVar.CKind)
9463           << getOpenMPClauseName(OMPC_lastprivate);
9464       ReportOriginalDSA(*this, DSAStack, D, DVar);
9465       continue;
9466     }
9467 
9468     // OpenMP [2.14.3.5, Restrictions, p.2]
9469     // A list item that is private within a parallel region, or that appears in
9470     // the reduction clause of a parallel construct, must not appear in a
9471     // lastprivate clause on a worksharing construct if any of the corresponding
9472     // worksharing regions ever binds to any of the corresponding parallel
9473     // regions.
9474     DSAStackTy::DSAVarData TopDVar = DVar;
9475     if (isOpenMPWorksharingDirective(CurrDir) &&
9476         !isOpenMPParallelDirective(CurrDir) &&
9477         !isOpenMPTeamsDirective(CurrDir)) {
9478       DVar = DSAStack->getImplicitDSA(D, true);
9479       if (DVar.CKind != OMPC_shared) {
9480         Diag(ELoc, diag::err_omp_required_access)
9481             << getOpenMPClauseName(OMPC_lastprivate)
9482             << getOpenMPClauseName(OMPC_shared);
9483         ReportOriginalDSA(*this, DSAStack, D, DVar);
9484         continue;
9485       }
9486     }
9487 
9488     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
9489     //  A variable of class type (or array thereof) that appears in a
9490     //  lastprivate clause requires an accessible, unambiguous default
9491     //  constructor for the class type, unless the list item is also specified
9492     //  in a firstprivate clause.
9493     //  A variable of class type (or array thereof) that appears in a
9494     //  lastprivate clause requires an accessible, unambiguous copy assignment
9495     //  operator for the class type.
9496     Type = Context.getBaseElementType(Type).getNonReferenceType();
9497     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
9498                                Type.getUnqualifiedType(), ".lastprivate.src",
9499                                D->hasAttrs() ? &D->getAttrs() : nullptr);
9500     auto *PseudoSrcExpr =
9501         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
9502     auto *DstVD =
9503         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
9504                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9505     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
9506     // For arrays generate assignment operation for single element and replace
9507     // it by the original array element in CodeGen.
9508     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
9509                                    PseudoDstExpr, PseudoSrcExpr);
9510     if (AssignmentOp.isInvalid())
9511       continue;
9512     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9513                                        /*DiscardedValue=*/true);
9514     if (AssignmentOp.isInvalid())
9515       continue;
9516 
9517     DeclRefExpr *Ref = nullptr;
9518     if (!VD && !CurContext->isDependentContext()) {
9519       if (TopDVar.CKind == OMPC_firstprivate)
9520         Ref = TopDVar.PrivateCopy;
9521       else {
9522         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9523         if (!IsOpenMPCapturedDecl(D))
9524           ExprCaptures.push_back(Ref->getDecl());
9525       }
9526       if (TopDVar.CKind == OMPC_firstprivate ||
9527           (!IsOpenMPCapturedDecl(D) &&
9528            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
9529         ExprResult RefRes = DefaultLvalueConversion(Ref);
9530         if (!RefRes.isUsable())
9531           continue;
9532         ExprResult PostUpdateRes =
9533             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9534                        RefRes.get());
9535         if (!PostUpdateRes.isUsable())
9536           continue;
9537         ExprPostUpdates.push_back(
9538             IgnoredValueConversions(PostUpdateRes.get()).get());
9539       }
9540     }
9541     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
9542     Vars.push_back((VD || CurContext->isDependentContext())
9543                        ? RefExpr->IgnoreParens()
9544                        : Ref);
9545     SrcExprs.push_back(PseudoSrcExpr);
9546     DstExprs.push_back(PseudoDstExpr);
9547     AssignmentOps.push_back(AssignmentOp.get());
9548   }
9549 
9550   if (Vars.empty())
9551     return nullptr;
9552 
9553   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9554                                       Vars, SrcExprs, DstExprs, AssignmentOps,
9555                                       buildPreInits(Context, ExprCaptures),
9556                                       buildPostUpdate(*this, ExprPostUpdates));
9557 }
9558 
9559 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9560                                          SourceLocation StartLoc,
9561                                          SourceLocation LParenLoc,
9562                                          SourceLocation EndLoc) {
9563   SmallVector<Expr *, 8> Vars;
9564   for (auto &RefExpr : VarList) {
9565     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
9566     SourceLocation ELoc;
9567     SourceRange ERange;
9568     Expr *SimpleRefExpr = RefExpr;
9569     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9570     if (Res.second) {
9571       // It will be analyzed later.
9572       Vars.push_back(RefExpr);
9573     }
9574     ValueDecl *D = Res.first;
9575     if (!D)
9576       continue;
9577 
9578     auto *VD = dyn_cast<VarDecl>(D);
9579     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9580     // in a Construct]
9581     //  Variables with the predetermined data-sharing attributes may not be
9582     //  listed in data-sharing attributes clauses, except for the cases
9583     //  listed below. For these exceptions only, listing a predetermined
9584     //  variable in a data-sharing attribute clause is allowed and overrides
9585     //  the variable's predetermined data-sharing attributes.
9586     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9587     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9588         DVar.RefExpr) {
9589       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9590                                           << getOpenMPClauseName(OMPC_shared);
9591       ReportOriginalDSA(*this, DSAStack, D, DVar);
9592       continue;
9593     }
9594 
9595     DeclRefExpr *Ref = nullptr;
9596     if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
9597       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9598     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
9599     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9600                        ? RefExpr->IgnoreParens()
9601                        : Ref);
9602   }
9603 
9604   if (Vars.empty())
9605     return nullptr;
9606 
9607   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9608 }
9609 
9610 namespace {
9611 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9612   DSAStackTy *Stack;
9613 
9614 public:
9615   bool VisitDeclRefExpr(DeclRefExpr *E) {
9616     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
9617       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
9618       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9619         return false;
9620       if (DVar.CKind != OMPC_unknown)
9621         return true;
9622       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9623           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
9624           /*FromParent=*/true);
9625       if (DVarPrivate.CKind != OMPC_unknown)
9626         return true;
9627       return false;
9628     }
9629     return false;
9630   }
9631   bool VisitStmt(Stmt *S) {
9632     for (auto Child : S->children()) {
9633       if (Child && Visit(Child))
9634         return true;
9635     }
9636     return false;
9637   }
9638   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
9639 };
9640 } // namespace
9641 
9642 namespace {
9643 // Transform MemberExpression for specified FieldDecl of current class to
9644 // DeclRefExpr to specified OMPCapturedExprDecl.
9645 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9646   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9647   ValueDecl *Field;
9648   DeclRefExpr *CapturedExpr;
9649 
9650 public:
9651   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9652       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9653 
9654   ExprResult TransformMemberExpr(MemberExpr *E) {
9655     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9656         E->getMemberDecl() == Field) {
9657       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
9658       return CapturedExpr;
9659     }
9660     return BaseTransform::TransformMemberExpr(E);
9661   }
9662   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9663 };
9664 } // namespace
9665 
9666 template <typename T>
9667 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9668                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
9669   for (auto &Set : Lookups) {
9670     for (auto *D : Set) {
9671       if (auto Res = Gen(cast<ValueDecl>(D)))
9672         return Res;
9673     }
9674   }
9675   return T();
9676 }
9677 
9678 static ExprResult
9679 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9680                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9681                          const DeclarationNameInfo &ReductionId, QualType Ty,
9682                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9683   if (ReductionIdScopeSpec.isInvalid())
9684     return ExprError();
9685   SmallVector<UnresolvedSet<8>, 4> Lookups;
9686   if (S) {
9687     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9688     Lookup.suppressDiagnostics();
9689     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9690       auto *D = Lookup.getRepresentativeDecl();
9691       do {
9692         S = S->getParent();
9693       } while (S && !S->isDeclScope(D));
9694       if (S)
9695         S = S->getParent();
9696       Lookups.push_back(UnresolvedSet<8>());
9697       Lookups.back().append(Lookup.begin(), Lookup.end());
9698       Lookup.clear();
9699     }
9700   } else if (auto *ULE =
9701                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9702     Lookups.push_back(UnresolvedSet<8>());
9703     Decl *PrevD = nullptr;
9704     for (auto *D : ULE->decls()) {
9705       if (D == PrevD)
9706         Lookups.push_back(UnresolvedSet<8>());
9707       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9708         Lookups.back().addDecl(DRD);
9709       PrevD = D;
9710     }
9711   }
9712   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9713       Ty->isInstantiationDependentType() ||
9714       Ty->containsUnexpandedParameterPack() ||
9715       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9716         return !D->isInvalidDecl() &&
9717                (D->getType()->isDependentType() ||
9718                 D->getType()->isInstantiationDependentType() ||
9719                 D->getType()->containsUnexpandedParameterPack());
9720       })) {
9721     UnresolvedSet<8> ResSet;
9722     for (auto &Set : Lookups) {
9723       ResSet.append(Set.begin(), Set.end());
9724       // The last item marks the end of all declarations at the specified scope.
9725       ResSet.addDecl(Set[Set.size() - 1]);
9726     }
9727     return UnresolvedLookupExpr::Create(
9728         SemaRef.Context, /*NamingClass=*/nullptr,
9729         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9730         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9731   }
9732   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9733           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9734             if (!D->isInvalidDecl() &&
9735                 SemaRef.Context.hasSameType(D->getType(), Ty))
9736               return D;
9737             return nullptr;
9738           }))
9739     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9740   if (auto *VD = filterLookupForUDR<ValueDecl *>(
9741           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9742             if (!D->isInvalidDecl() &&
9743                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9744                 !Ty.isMoreQualifiedThan(D->getType()))
9745               return D;
9746             return nullptr;
9747           })) {
9748     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9749                        /*DetectVirtual=*/false);
9750     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9751       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9752               VD->getType().getUnqualifiedType()))) {
9753         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9754                                          /*DiagID=*/0) !=
9755             Sema::AR_inaccessible) {
9756           SemaRef.BuildBasePathArray(Paths, BasePath);
9757           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9758         }
9759       }
9760     }
9761   }
9762   if (ReductionIdScopeSpec.isSet()) {
9763     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9764     return ExprError();
9765   }
9766   return ExprEmpty();
9767 }
9768 
9769 namespace {
9770 /// Data for the reduction-based clauses.
9771 struct ReductionData {
9772   /// List of original reduction items.
9773   SmallVector<Expr *, 8> Vars;
9774   /// List of private copies of the reduction items.
9775   SmallVector<Expr *, 8> Privates;
9776   /// LHS expressions for the reduction_op expressions.
9777   SmallVector<Expr *, 8> LHSs;
9778   /// RHS expressions for the reduction_op expressions.
9779   SmallVector<Expr *, 8> RHSs;
9780   /// Reduction operation expression.
9781   SmallVector<Expr *, 8> ReductionOps;
9782   /// Taskgroup descriptors for the corresponding reduction items in
9783   /// in_reduction clauses.
9784   SmallVector<Expr *, 8> TaskgroupDescriptors;
9785   /// List of captures for clause.
9786   SmallVector<Decl *, 4> ExprCaptures;
9787   /// List of postupdate expressions.
9788   SmallVector<Expr *, 4> ExprPostUpdates;
9789   ReductionData() = delete;
9790   /// Reserves required memory for the reduction data.
9791   ReductionData(unsigned Size) {
9792     Vars.reserve(Size);
9793     Privates.reserve(Size);
9794     LHSs.reserve(Size);
9795     RHSs.reserve(Size);
9796     ReductionOps.reserve(Size);
9797     TaskgroupDescriptors.reserve(Size);
9798     ExprCaptures.reserve(Size);
9799     ExprPostUpdates.reserve(Size);
9800   }
9801   /// Stores reduction item and reduction operation only (required for dependent
9802   /// reduction item).
9803   void push(Expr *Item, Expr *ReductionOp) {
9804     Vars.emplace_back(Item);
9805     Privates.emplace_back(nullptr);
9806     LHSs.emplace_back(nullptr);
9807     RHSs.emplace_back(nullptr);
9808     ReductionOps.emplace_back(ReductionOp);
9809     TaskgroupDescriptors.emplace_back(nullptr);
9810   }
9811   /// Stores reduction data.
9812   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9813             Expr *TaskgroupDescriptor) {
9814     Vars.emplace_back(Item);
9815     Privates.emplace_back(Private);
9816     LHSs.emplace_back(LHS);
9817     RHSs.emplace_back(RHS);
9818     ReductionOps.emplace_back(ReductionOp);
9819     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
9820   }
9821 };
9822 } // namespace
9823 
9824 static bool CheckOMPArraySectionConstantForReduction(
9825     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9826     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
9827   const Expr *Length = OASE->getLength();
9828   if (Length == nullptr) {
9829     // For array sections of the form [1:] or [:], we would need to analyze
9830     // the lower bound...
9831     if (OASE->getColonLoc().isValid())
9832       return false;
9833 
9834     // This is an array subscript which has implicit length 1!
9835     SingleElement = true;
9836     ArraySizes.push_back(llvm::APSInt::get(1));
9837   } else {
9838     llvm::APSInt ConstantLengthValue;
9839     if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
9840       return false;
9841 
9842     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
9843     ArraySizes.push_back(ConstantLengthValue);
9844   }
9845 
9846   // Get the base of this array section and walk up from there.
9847   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9848 
9849   // We require length = 1 for all array sections except the right-most to
9850   // guarantee that the memory region is contiguous and has no holes in it.
9851   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
9852     Length = TempOASE->getLength();
9853     if (Length == nullptr) {
9854       // For array sections of the form [1:] or [:], we would need to analyze
9855       // the lower bound...
9856       if (OASE->getColonLoc().isValid())
9857         return false;
9858 
9859       // This is an array subscript which has implicit length 1!
9860       ArraySizes.push_back(llvm::APSInt::get(1));
9861     } else {
9862       llvm::APSInt ConstantLengthValue;
9863       if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
9864           ConstantLengthValue.getSExtValue() != 1)
9865         return false;
9866 
9867       ArraySizes.push_back(ConstantLengthValue);
9868     }
9869     Base = TempOASE->getBase()->IgnoreParenImpCasts();
9870   }
9871 
9872   // If we have a single element, we don't need to add the implicit lengths.
9873   if (!SingleElement) {
9874     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
9875       // Has implicit length 1!
9876       ArraySizes.push_back(llvm::APSInt::get(1));
9877       Base = TempASE->getBase()->IgnoreParenImpCasts();
9878     }
9879   }
9880 
9881   // This array section can be privatized as a single value or as a constant
9882   // sized array.
9883   return true;
9884 }
9885 
9886 static bool ActOnOMPReductionKindClause(
9887     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9888     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9889     SourceLocation ColonLoc, SourceLocation EndLoc,
9890     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9891     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
9892   auto DN = ReductionId.getName();
9893   auto OOK = DN.getCXXOverloadedOperator();
9894   BinaryOperatorKind BOK = BO_Comma;
9895 
9896   ASTContext &Context = S.Context;
9897   // OpenMP [2.14.3.6, reduction clause]
9898   // C
9899   // reduction-identifier is either an identifier or one of the following
9900   // operators: +, -, *,  &, |, ^, && and ||
9901   // C++
9902   // reduction-identifier is either an id-expression or one of the following
9903   // operators: +, -, *, &, |, ^, && and ||
9904   switch (OOK) {
9905   case OO_Plus:
9906   case OO_Minus:
9907     BOK = BO_Add;
9908     break;
9909   case OO_Star:
9910     BOK = BO_Mul;
9911     break;
9912   case OO_Amp:
9913     BOK = BO_And;
9914     break;
9915   case OO_Pipe:
9916     BOK = BO_Or;
9917     break;
9918   case OO_Caret:
9919     BOK = BO_Xor;
9920     break;
9921   case OO_AmpAmp:
9922     BOK = BO_LAnd;
9923     break;
9924   case OO_PipePipe:
9925     BOK = BO_LOr;
9926     break;
9927   case OO_New:
9928   case OO_Delete:
9929   case OO_Array_New:
9930   case OO_Array_Delete:
9931   case OO_Slash:
9932   case OO_Percent:
9933   case OO_Tilde:
9934   case OO_Exclaim:
9935   case OO_Equal:
9936   case OO_Less:
9937   case OO_Greater:
9938   case OO_LessEqual:
9939   case OO_GreaterEqual:
9940   case OO_PlusEqual:
9941   case OO_MinusEqual:
9942   case OO_StarEqual:
9943   case OO_SlashEqual:
9944   case OO_PercentEqual:
9945   case OO_CaretEqual:
9946   case OO_AmpEqual:
9947   case OO_PipeEqual:
9948   case OO_LessLess:
9949   case OO_GreaterGreater:
9950   case OO_LessLessEqual:
9951   case OO_GreaterGreaterEqual:
9952   case OO_EqualEqual:
9953   case OO_ExclaimEqual:
9954   case OO_Spaceship:
9955   case OO_PlusPlus:
9956   case OO_MinusMinus:
9957   case OO_Comma:
9958   case OO_ArrowStar:
9959   case OO_Arrow:
9960   case OO_Call:
9961   case OO_Subscript:
9962   case OO_Conditional:
9963   case OO_Coawait:
9964   case NUM_OVERLOADED_OPERATORS:
9965     llvm_unreachable("Unexpected reduction identifier");
9966   case OO_None:
9967     if (auto *II = DN.getAsIdentifierInfo()) {
9968       if (II->isStr("max"))
9969         BOK = BO_GT;
9970       else if (II->isStr("min"))
9971         BOK = BO_LT;
9972     }
9973     break;
9974   }
9975   SourceRange ReductionIdRange;
9976   if (ReductionIdScopeSpec.isValid())
9977     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
9978   else
9979     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
9980   ReductionIdRange.setEnd(ReductionId.getEndLoc());
9981 
9982   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9983   bool FirstIter = true;
9984   for (auto RefExpr : VarList) {
9985     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
9986     // OpenMP [2.1, C/C++]
9987     //  A list item is a variable or array section, subject to the restrictions
9988     //  specified in Section 2.4 on page 42 and in each of the sections
9989     // describing clauses and directives for which a list appears.
9990     // OpenMP  [2.14.3.3, Restrictions, p.1]
9991     //  A variable that is part of another variable (as an array or
9992     //  structure element) cannot appear in a private clause.
9993     if (!FirstIter && IR != ER)
9994       ++IR;
9995     FirstIter = false;
9996     SourceLocation ELoc;
9997     SourceRange ERange;
9998     Expr *SimpleRefExpr = RefExpr;
9999     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
10000                               /*AllowArraySection=*/true);
10001     if (Res.second) {
10002       // Try to find 'declare reduction' corresponding construct before using
10003       // builtin/overloaded operators.
10004       QualType Type = Context.DependentTy;
10005       CXXCastPath BasePath;
10006       ExprResult DeclareReductionRef = buildDeclareReductionRef(
10007           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10008           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10009       Expr *ReductionOp = nullptr;
10010       if (S.CurContext->isDependentContext() &&
10011           (DeclareReductionRef.isUnset() ||
10012            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
10013         ReductionOp = DeclareReductionRef.get();
10014       // It will be analyzed later.
10015       RD.push(RefExpr, ReductionOp);
10016     }
10017     ValueDecl *D = Res.first;
10018     if (!D)
10019       continue;
10020 
10021     Expr *TaskgroupDescriptor = nullptr;
10022     QualType Type;
10023     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10024     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10025     if (ASE)
10026       Type = ASE->getType().getNonReferenceType();
10027     else if (OASE) {
10028       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10029       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10030         Type = ATy->getElementType();
10031       else
10032         Type = BaseType->getPointeeType();
10033       Type = Type.getNonReferenceType();
10034     } else
10035       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10036     auto *VD = dyn_cast<VarDecl>(D);
10037 
10038     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10039     //  A variable that appears in a private clause must not have an incomplete
10040     //  type or a reference type.
10041     if (S.RequireCompleteType(ELoc, Type,
10042                               diag::err_omp_reduction_incomplete_type))
10043       continue;
10044     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10045     // A list item that appears in a reduction clause must not be
10046     // const-qualified.
10047     if (Type.getNonReferenceType().isConstant(Context)) {
10048       S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
10049       if (!ASE && !OASE) {
10050         bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10051                                  VarDecl::DeclarationOnly;
10052         S.Diag(D->getLocation(),
10053                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10054             << D;
10055       }
10056       continue;
10057     }
10058     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10059     //  If a list-item is a reference type then it must bind to the same object
10060     //  for all threads of the team.
10061     if (!ASE && !OASE && VD) {
10062       VarDecl *VDDef = VD->getDefinition();
10063       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
10064         DSARefChecker Check(Stack);
10065         if (Check.Visit(VDDef->getInit())) {
10066           S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10067               << getOpenMPClauseName(ClauseKind) << ERange;
10068           S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
10069           continue;
10070         }
10071       }
10072     }
10073 
10074     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10075     // in a Construct]
10076     //  Variables with the predetermined data-sharing attributes may not be
10077     //  listed in data-sharing attributes clauses, except for the cases
10078     //  listed below. For these exceptions only, listing a predetermined
10079     //  variable in a data-sharing attribute clause is allowed and overrides
10080     //  the variable's predetermined data-sharing attributes.
10081     // OpenMP [2.14.3.6, Restrictions, p.3]
10082     //  Any number of reduction clauses can be specified on the directive,
10083     //  but a list item can appear only once in the reduction clauses for that
10084     //  directive.
10085     DSAStackTy::DSAVarData DVar;
10086     DVar = Stack->getTopDSA(D, false);
10087     if (DVar.CKind == OMPC_reduction) {
10088       S.Diag(ELoc, diag::err_omp_once_referenced)
10089           << getOpenMPClauseName(ClauseKind);
10090       if (DVar.RefExpr)
10091         S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
10092       continue;
10093     } else if (DVar.CKind != OMPC_unknown) {
10094       S.Diag(ELoc, diag::err_omp_wrong_dsa)
10095           << getOpenMPClauseName(DVar.CKind)
10096           << getOpenMPClauseName(OMPC_reduction);
10097       ReportOriginalDSA(S, Stack, D, DVar);
10098       continue;
10099     }
10100 
10101     // OpenMP [2.14.3.6, Restrictions, p.1]
10102     //  A list item that appears in a reduction clause of a worksharing
10103     //  construct must be shared in the parallel regions to which any of the
10104     //  worksharing regions arising from the worksharing construct bind.
10105     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
10106     if (isOpenMPWorksharingDirective(CurrDir) &&
10107         !isOpenMPParallelDirective(CurrDir) &&
10108         !isOpenMPTeamsDirective(CurrDir)) {
10109       DVar = Stack->getImplicitDSA(D, true);
10110       if (DVar.CKind != OMPC_shared) {
10111         S.Diag(ELoc, diag::err_omp_required_access)
10112             << getOpenMPClauseName(OMPC_reduction)
10113             << getOpenMPClauseName(OMPC_shared);
10114         ReportOriginalDSA(S, Stack, D, DVar);
10115         continue;
10116       }
10117     }
10118 
10119     // Try to find 'declare reduction' corresponding construct before using
10120     // builtin/overloaded operators.
10121     CXXCastPath BasePath;
10122     ExprResult DeclareReductionRef = buildDeclareReductionRef(
10123         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
10124         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10125     if (DeclareReductionRef.isInvalid())
10126       continue;
10127     if (S.CurContext->isDependentContext() &&
10128         (DeclareReductionRef.isUnset() ||
10129          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
10130       RD.push(RefExpr, DeclareReductionRef.get());
10131       continue;
10132     }
10133     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10134       // Not allowed reduction identifier is found.
10135       S.Diag(ReductionId.getLocStart(),
10136              diag::err_omp_unknown_reduction_identifier)
10137           << Type << ReductionIdRange;
10138       continue;
10139     }
10140 
10141     // OpenMP [2.14.3.6, reduction clause, Restrictions]
10142     // The type of a list item that appears in a reduction clause must be valid
10143     // for the reduction-identifier. For a max or min reduction in C, the type
10144     // of the list item must be an allowed arithmetic data type: char, int,
10145     // float, double, or _Bool, possibly modified with long, short, signed, or
10146     // unsigned. For a max or min reduction in C++, the type of the list item
10147     // must be an allowed arithmetic data type: char, wchar_t, int, float,
10148     // double, or bool, possibly modified with long, short, signed, or unsigned.
10149     if (DeclareReductionRef.isUnset()) {
10150       if ((BOK == BO_GT || BOK == BO_LT) &&
10151           !(Type->isScalarType() ||
10152             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10153         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
10154             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
10155         if (!ASE && !OASE) {
10156           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10157                                    VarDecl::DeclarationOnly;
10158           S.Diag(D->getLocation(),
10159                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10160               << D;
10161         }
10162         continue;
10163       }
10164       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
10165           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
10166         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10167             << getOpenMPClauseName(ClauseKind);
10168         if (!ASE && !OASE) {
10169           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10170                                    VarDecl::DeclarationOnly;
10171           S.Diag(D->getLocation(),
10172                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10173               << D;
10174         }
10175         continue;
10176       }
10177     }
10178 
10179     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
10180     auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
10181                                D->hasAttrs() ? &D->getAttrs() : nullptr);
10182     auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
10183                                D->hasAttrs() ? &D->getAttrs() : nullptr);
10184     auto PrivateTy = Type;
10185 
10186     // Try if we can determine constant lengths for all array sections and avoid
10187     // the VLA.
10188     bool ConstantLengthOASE = false;
10189     if (OASE) {
10190       bool SingleElement;
10191       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10192       ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10193           Context, OASE, SingleElement, ArraySizes);
10194 
10195       // If we don't have a single element, we must emit a constant array type.
10196       if (ConstantLengthOASE && !SingleElement) {
10197         for (auto &Size : ArraySizes) {
10198           PrivateTy = Context.getConstantArrayType(
10199               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10200         }
10201       }
10202     }
10203 
10204     if ((OASE && !ConstantLengthOASE) ||
10205         (!OASE && !ASE &&
10206          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
10207       if (!Context.getTargetInfo().isVLASupported() &&
10208           S.shouldDiagnoseTargetSupportFromOpenMP()) {
10209         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10210         S.Diag(ELoc, diag::note_vla_unsupported);
10211         continue;
10212       }
10213       // For arrays/array sections only:
10214       // Create pseudo array type for private copy. The size for this array will
10215       // be generated during codegen.
10216       // For array subscripts or single variables Private Ty is the same as Type
10217       // (type of the variable or single array element).
10218       PrivateTy = Context.getVariableArrayType(
10219           Type,
10220           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
10221           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
10222     } else if (!ASE && !OASE &&
10223                Context.getAsArrayType(D->getType().getNonReferenceType()))
10224       PrivateTy = D->getType().getNonReferenceType();
10225     // Private copy.
10226     auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10227                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
10228     // Add initializer for private variable.
10229     Expr *Init = nullptr;
10230     auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10231     auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
10232     if (DeclareReductionRef.isUsable()) {
10233       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10234       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10235       if (DRD->getInitializer()) {
10236         Init = DRDRef;
10237         RHSVD->setInit(DRDRef);
10238         RHSVD->setInitStyle(VarDecl::CallInit);
10239       }
10240     } else {
10241       switch (BOK) {
10242       case BO_Add:
10243       case BO_Xor:
10244       case BO_Or:
10245       case BO_LOr:
10246         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10247         if (Type->isScalarType() || Type->isAnyComplexType())
10248           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
10249         break;
10250       case BO_Mul:
10251       case BO_LAnd:
10252         if (Type->isScalarType() || Type->isAnyComplexType()) {
10253           // '*' and '&&' reduction ops - initializer is '1'.
10254           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
10255         }
10256         break;
10257       case BO_And: {
10258         // '&' reduction op - initializer is '~0'.
10259         QualType OrigType = Type;
10260         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10261           Type = ComplexTy->getElementType();
10262         if (Type->isRealFloatingType()) {
10263           llvm::APFloat InitValue =
10264               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10265                                              /*isIEEE=*/true);
10266           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10267                                          Type, ELoc);
10268         } else if (Type->isScalarType()) {
10269           auto Size = Context.getTypeSize(Type);
10270           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10271           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10272           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10273         }
10274         if (Init && OrigType->isAnyComplexType()) {
10275           // Init = 0xFFFF + 0xFFFFi;
10276           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
10277           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
10278         }
10279         Type = OrigType;
10280         break;
10281       }
10282       case BO_LT:
10283       case BO_GT: {
10284         // 'min' reduction op - initializer is 'Largest representable number in
10285         // the reduction list item type'.
10286         // 'max' reduction op - initializer is 'Least representable number in
10287         // the reduction list item type'.
10288         if (Type->isIntegerType() || Type->isPointerType()) {
10289           bool IsSigned = Type->hasSignedIntegerRepresentation();
10290           auto Size = Context.getTypeSize(Type);
10291           QualType IntTy =
10292               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10293           llvm::APInt InitValue =
10294               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10295                                         : llvm::APInt::getMinValue(Size)
10296                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10297                                         : llvm::APInt::getMaxValue(Size);
10298           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10299           if (Type->isPointerType()) {
10300             // Cast to pointer type.
10301             auto CastExpr = S.BuildCStyleCastExpr(
10302                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
10303             if (CastExpr.isInvalid())
10304               continue;
10305             Init = CastExpr.get();
10306           }
10307         } else if (Type->isRealFloatingType()) {
10308           llvm::APFloat InitValue = llvm::APFloat::getLargest(
10309               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10310           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10311                                          Type, ELoc);
10312         }
10313         break;
10314       }
10315       case BO_PtrMemD:
10316       case BO_PtrMemI:
10317       case BO_MulAssign:
10318       case BO_Div:
10319       case BO_Rem:
10320       case BO_Sub:
10321       case BO_Shl:
10322       case BO_Shr:
10323       case BO_LE:
10324       case BO_GE:
10325       case BO_EQ:
10326       case BO_NE:
10327       case BO_AndAssign:
10328       case BO_XorAssign:
10329       case BO_OrAssign:
10330       case BO_Assign:
10331       case BO_AddAssign:
10332       case BO_SubAssign:
10333       case BO_DivAssign:
10334       case BO_RemAssign:
10335       case BO_ShlAssign:
10336       case BO_ShrAssign:
10337       case BO_Comma:
10338         llvm_unreachable("Unexpected reduction operation");
10339       }
10340     }
10341     if (Init && DeclareReductionRef.isUnset())
10342       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10343     else if (!Init)
10344       S.ActOnUninitializedDecl(RHSVD);
10345     if (RHSVD->isInvalidDecl())
10346       continue;
10347     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
10348       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10349           << Type << ReductionIdRange;
10350       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10351                                VarDecl::DeclarationOnly;
10352       S.Diag(D->getLocation(),
10353              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10354           << D;
10355       continue;
10356     }
10357     // Store initializer for single element in private copy. Will be used during
10358     // codegen.
10359     PrivateVD->setInit(RHSVD->getInit());
10360     PrivateVD->setInitStyle(RHSVD->getInitStyle());
10361     auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
10362     ExprResult ReductionOp;
10363     if (DeclareReductionRef.isUsable()) {
10364       QualType RedTy = DeclareReductionRef.get()->getType();
10365       QualType PtrRedTy = Context.getPointerType(RedTy);
10366       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10367       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
10368       if (!BasePath.empty()) {
10369         LHS = S.DefaultLvalueConversion(LHS.get());
10370         RHS = S.DefaultLvalueConversion(RHS.get());
10371         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10372                                        CK_UncheckedDerivedToBase, LHS.get(),
10373                                        &BasePath, LHS.get()->getValueKind());
10374         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10375                                        CK_UncheckedDerivedToBase, RHS.get(),
10376                                        &BasePath, RHS.get()->getValueKind());
10377       }
10378       FunctionProtoType::ExtProtoInfo EPI;
10379       QualType Params[] = {PtrRedTy, PtrRedTy};
10380       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10381       auto *OVE = new (Context) OpaqueValueExpr(
10382           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
10383           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
10384       Expr *Args[] = {LHS.get(), RHS.get()};
10385       ReductionOp = new (Context)
10386           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10387     } else {
10388       ReductionOp = S.BuildBinOp(
10389           Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
10390       if (ReductionOp.isUsable()) {
10391         if (BOK != BO_LT && BOK != BO_GT) {
10392           ReductionOp =
10393               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10394                            BO_Assign, LHSDRE, ReductionOp.get());
10395         } else {
10396           auto *ConditionalOp = new (Context)
10397               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10398                                   Type, VK_LValue, OK_Ordinary);
10399           ReductionOp =
10400               S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10401                            BO_Assign, LHSDRE, ConditionalOp);
10402         }
10403         if (ReductionOp.isUsable())
10404           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
10405       }
10406       if (!ReductionOp.isUsable())
10407         continue;
10408     }
10409 
10410     // OpenMP [2.15.4.6, Restrictions, p.2]
10411     // A list item that appears in an in_reduction clause of a task construct
10412     // must appear in a task_reduction clause of a construct associated with a
10413     // taskgroup region that includes the participating task in its taskgroup
10414     // set. The construct associated with the innermost region that meets this
10415     // condition must specify the same reduction-identifier as the in_reduction
10416     // clause.
10417     if (ClauseKind == OMPC_in_reduction) {
10418       SourceRange ParentSR;
10419       BinaryOperatorKind ParentBOK;
10420       const Expr *ParentReductionOp;
10421       Expr *ParentBOKTD, *ParentReductionOpTD;
10422       DSAStackTy::DSAVarData ParentBOKDSA =
10423           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10424                                                   ParentBOKTD);
10425       DSAStackTy::DSAVarData ParentReductionOpDSA =
10426           Stack->getTopMostTaskgroupReductionData(
10427               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
10428       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10429       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10430       if (!IsParentBOK && !IsParentReductionOp) {
10431         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10432         continue;
10433       }
10434       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10435           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10436           IsParentReductionOp) {
10437         bool EmitError = true;
10438         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10439           llvm::FoldingSetNodeID RedId, ParentRedId;
10440           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10441           DeclareReductionRef.get()->Profile(RedId, Context,
10442                                              /*Canonical=*/true);
10443           EmitError = RedId != ParentRedId;
10444         }
10445         if (EmitError) {
10446           S.Diag(ReductionId.getLocStart(),
10447                  diag::err_omp_reduction_identifier_mismatch)
10448               << ReductionIdRange << RefExpr->getSourceRange();
10449           S.Diag(ParentSR.getBegin(),
10450                  diag::note_omp_previous_reduction_identifier)
10451               << ParentSR
10452               << (IsParentBOK ? ParentBOKDSA.RefExpr
10453                               : ParentReductionOpDSA.RefExpr)
10454                      ->getSourceRange();
10455           continue;
10456         }
10457       }
10458       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10459       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
10460     }
10461 
10462     DeclRefExpr *Ref = nullptr;
10463     Expr *VarsExpr = RefExpr->IgnoreParens();
10464     if (!VD && !S.CurContext->isDependentContext()) {
10465       if (ASE || OASE) {
10466         TransformExprToCaptures RebuildToCapture(S, D);
10467         VarsExpr =
10468             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10469         Ref = RebuildToCapture.getCapturedExpr();
10470       } else {
10471         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
10472       }
10473       if (!S.IsOpenMPCapturedDecl(D)) {
10474         RD.ExprCaptures.emplace_back(Ref->getDecl());
10475         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10476           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
10477           if (!RefRes.isUsable())
10478             continue;
10479           ExprResult PostUpdateRes =
10480               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10481                            RefRes.get());
10482           if (!PostUpdateRes.isUsable())
10483             continue;
10484           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10485               Stack->getCurrentDirective() == OMPD_taskgroup) {
10486             S.Diag(RefExpr->getExprLoc(),
10487                    diag::err_omp_reduction_non_addressable_expression)
10488                 << RefExpr->getSourceRange();
10489             continue;
10490           }
10491           RD.ExprPostUpdates.emplace_back(
10492               S.IgnoredValueConversions(PostUpdateRes.get()).get());
10493         }
10494       }
10495     }
10496     // All reduction items are still marked as reduction (to do not increase
10497     // code base size).
10498     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
10499     if (CurrDir == OMPD_taskgroup) {
10500       if (DeclareReductionRef.isUsable())
10501         Stack->addTaskgroupReductionData(D, ReductionIdRange,
10502                                          DeclareReductionRef.get());
10503       else
10504         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
10505     }
10506     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10507             TaskgroupDescriptor);
10508   }
10509   return RD.Vars.empty();
10510 }
10511 
10512 OMPClause *Sema::ActOnOpenMPReductionClause(
10513     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10514     SourceLocation ColonLoc, SourceLocation EndLoc,
10515     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10516     ArrayRef<Expr *> UnresolvedReductions) {
10517   ReductionData RD(VarList.size());
10518 
10519   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10520                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10521                                   ReductionIdScopeSpec, ReductionId,
10522                                   UnresolvedReductions, RD))
10523     return nullptr;
10524 
10525   return OMPReductionClause::Create(
10526       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10527       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10528       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10529       buildPreInits(Context, RD.ExprCaptures),
10530       buildPostUpdate(*this, RD.ExprPostUpdates));
10531 }
10532 
10533 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10534     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10535     SourceLocation ColonLoc, SourceLocation EndLoc,
10536     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10537     ArrayRef<Expr *> UnresolvedReductions) {
10538   ReductionData RD(VarList.size());
10539 
10540   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10541                                   VarList, StartLoc, LParenLoc, ColonLoc,
10542                                   EndLoc, ReductionIdScopeSpec, ReductionId,
10543                                   UnresolvedReductions, RD))
10544     return nullptr;
10545 
10546   return OMPTaskReductionClause::Create(
10547       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10548       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10549       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10550       buildPreInits(Context, RD.ExprCaptures),
10551       buildPostUpdate(*this, RD.ExprPostUpdates));
10552 }
10553 
10554 OMPClause *Sema::ActOnOpenMPInReductionClause(
10555     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10556     SourceLocation ColonLoc, SourceLocation EndLoc,
10557     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10558     ArrayRef<Expr *> UnresolvedReductions) {
10559   ReductionData RD(VarList.size());
10560 
10561   if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10562                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
10563                                   ReductionIdScopeSpec, ReductionId,
10564                                   UnresolvedReductions, RD))
10565     return nullptr;
10566 
10567   return OMPInReductionClause::Create(
10568       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10569       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10570       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
10571       buildPreInits(Context, RD.ExprCaptures),
10572       buildPostUpdate(*this, RD.ExprPostUpdates));
10573 }
10574 
10575 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10576                                      SourceLocation LinLoc) {
10577   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10578       LinKind == OMPC_LINEAR_unknown) {
10579     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10580     return true;
10581   }
10582   return false;
10583 }
10584 
10585 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10586                                  OpenMPLinearClauseKind LinKind,
10587                                  QualType Type) {
10588   auto *VD = dyn_cast_or_null<VarDecl>(D);
10589   // A variable must not have an incomplete type or a reference type.
10590   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10591     return true;
10592   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10593       !Type->isReferenceType()) {
10594     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10595         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10596     return true;
10597   }
10598   Type = Type.getNonReferenceType();
10599 
10600   // A list item must not be const-qualified.
10601   if (Type.isConstant(Context)) {
10602     Diag(ELoc, diag::err_omp_const_variable)
10603         << getOpenMPClauseName(OMPC_linear);
10604     if (D) {
10605       bool IsDecl =
10606           !VD ||
10607           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10608       Diag(D->getLocation(),
10609            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10610           << D;
10611     }
10612     return true;
10613   }
10614 
10615   // A list item must be of integral or pointer type.
10616   Type = Type.getUnqualifiedType().getCanonicalType();
10617   const auto *Ty = Type.getTypePtrOrNull();
10618   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10619               !Ty->isPointerType())) {
10620     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10621     if (D) {
10622       bool IsDecl =
10623           !VD ||
10624           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10625       Diag(D->getLocation(),
10626            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10627           << D;
10628     }
10629     return true;
10630   }
10631   return false;
10632 }
10633 
10634 OMPClause *Sema::ActOnOpenMPLinearClause(
10635     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10636     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10637     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10638   SmallVector<Expr *, 8> Vars;
10639   SmallVector<Expr *, 8> Privates;
10640   SmallVector<Expr *, 8> Inits;
10641   SmallVector<Decl *, 4> ExprCaptures;
10642   SmallVector<Expr *, 4> ExprPostUpdates;
10643   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
10644     LinKind = OMPC_LINEAR_val;
10645   for (auto &RefExpr : VarList) {
10646     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10647     SourceLocation ELoc;
10648     SourceRange ERange;
10649     Expr *SimpleRefExpr = RefExpr;
10650     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10651                               /*AllowArraySection=*/false);
10652     if (Res.second) {
10653       // It will be analyzed later.
10654       Vars.push_back(RefExpr);
10655       Privates.push_back(nullptr);
10656       Inits.push_back(nullptr);
10657     }
10658     ValueDecl *D = Res.first;
10659     if (!D)
10660       continue;
10661 
10662     QualType Type = D->getType();
10663     auto *VD = dyn_cast<VarDecl>(D);
10664 
10665     // OpenMP [2.14.3.7, linear clause]
10666     //  A list-item cannot appear in more than one linear clause.
10667     //  A list-item that appears in a linear clause cannot appear in any
10668     //  other data-sharing attribute clause.
10669     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
10670     if (DVar.RefExpr) {
10671       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10672                                           << getOpenMPClauseName(OMPC_linear);
10673       ReportOriginalDSA(*this, DSAStack, D, DVar);
10674       continue;
10675     }
10676 
10677     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
10678       continue;
10679     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
10680 
10681     // Build private copy of original var.
10682     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10683                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
10684     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
10685     // Build var to save initial value.
10686     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
10687     Expr *InitExpr;
10688     DeclRefExpr *Ref = nullptr;
10689     if (!VD && !CurContext->isDependentContext()) {
10690       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10691       if (!IsOpenMPCapturedDecl(D)) {
10692         ExprCaptures.push_back(Ref->getDecl());
10693         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10694           ExprResult RefRes = DefaultLvalueConversion(Ref);
10695           if (!RefRes.isUsable())
10696             continue;
10697           ExprResult PostUpdateRes =
10698               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10699                          SimpleRefExpr, RefRes.get());
10700           if (!PostUpdateRes.isUsable())
10701             continue;
10702           ExprPostUpdates.push_back(
10703               IgnoredValueConversions(PostUpdateRes.get()).get());
10704         }
10705       }
10706     }
10707     if (LinKind == OMPC_LINEAR_uval)
10708       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
10709     else
10710       InitExpr = VD ? SimpleRefExpr : Ref;
10711     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
10712                          /*DirectInit=*/false);
10713     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10714 
10715     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
10716     Vars.push_back((VD || CurContext->isDependentContext())
10717                        ? RefExpr->IgnoreParens()
10718                        : Ref);
10719     Privates.push_back(PrivateRef);
10720     Inits.push_back(InitRef);
10721   }
10722 
10723   if (Vars.empty())
10724     return nullptr;
10725 
10726   Expr *StepExpr = Step;
10727   Expr *CalcStepExpr = nullptr;
10728   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10729       !Step->isInstantiationDependent() &&
10730       !Step->containsUnexpandedParameterPack()) {
10731     SourceLocation StepLoc = Step->getLocStart();
10732     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
10733     if (Val.isInvalid())
10734       return nullptr;
10735     StepExpr = Val.get();
10736 
10737     // Build var to save the step value.
10738     VarDecl *SaveVar =
10739         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
10740     ExprResult SaveRef =
10741         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
10742     ExprResult CalcStep =
10743         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
10744     CalcStep = ActOnFinishFullExpr(CalcStep.get());
10745 
10746     // Warn about zero linear step (it would be probably better specified as
10747     // making corresponding variables 'const').
10748     llvm::APSInt Result;
10749     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10750     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
10751       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10752                                                      << (Vars.size() > 1);
10753     if (!IsConstant && CalcStep.isUsable()) {
10754       // Calculate the step beforehand instead of doing this on each iteration.
10755       // (This is not used if the number of iterations may be kfold-ed).
10756       CalcStepExpr = CalcStep.get();
10757     }
10758   }
10759 
10760   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10761                                  ColonLoc, EndLoc, Vars, Privates, Inits,
10762                                  StepExpr, CalcStepExpr,
10763                                  buildPreInits(Context, ExprCaptures),
10764                                  buildPostUpdate(*this, ExprPostUpdates));
10765 }
10766 
10767 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10768                                      Expr *NumIterations, Sema &SemaRef,
10769                                      Scope *S, DSAStackTy *Stack) {
10770   // Walk the vars and build update/final expressions for the CodeGen.
10771   SmallVector<Expr *, 8> Updates;
10772   SmallVector<Expr *, 8> Finals;
10773   Expr *Step = Clause.getStep();
10774   Expr *CalcStep = Clause.getCalcStep();
10775   // OpenMP [2.14.3.7, linear clause]
10776   // If linear-step is not specified it is assumed to be 1.
10777   if (Step == nullptr)
10778     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
10779   else if (CalcStep) {
10780     Step = cast<BinaryOperator>(CalcStep)->getLHS();
10781   }
10782   bool HasErrors = false;
10783   auto CurInit = Clause.inits().begin();
10784   auto CurPrivate = Clause.privates().begin();
10785   auto LinKind = Clause.getModifier();
10786   for (auto &RefExpr : Clause.varlists()) {
10787     SourceLocation ELoc;
10788     SourceRange ERange;
10789     Expr *SimpleRefExpr = RefExpr;
10790     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10791                               /*AllowArraySection=*/false);
10792     ValueDecl *D = Res.first;
10793     if (Res.second || !D) {
10794       Updates.push_back(nullptr);
10795       Finals.push_back(nullptr);
10796       HasErrors = true;
10797       continue;
10798     }
10799     auto &&Info = Stack->isLoopControlVariable(D);
10800     // OpenMP [2.15.11, distribute simd Construct]
10801     // A list item may not appear in a linear clause, unless it is the loop
10802     // iteration variable.
10803     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
10804         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
10805       SemaRef.Diag(ELoc,
10806                    diag::err_omp_linear_distribute_var_non_loop_iteration);
10807       Updates.push_back(nullptr);
10808       Finals.push_back(nullptr);
10809       HasErrors = true;
10810       continue;
10811     }
10812     Expr *InitExpr = *CurInit;
10813 
10814     // Build privatized reference to the current linear var.
10815     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
10816     Expr *CapturedRef;
10817     if (LinKind == OMPC_LINEAR_uval)
10818       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10819     else
10820       CapturedRef =
10821           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10822                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10823                            /*RefersToCapture=*/true);
10824 
10825     // Build update: Var = InitExpr + IV * Step
10826     ExprResult Update;
10827     if (!Info.first) {
10828       Update =
10829           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10830                              InitExpr, IV, Step, /* Subtract */ false);
10831     } else
10832       Update = *CurPrivate;
10833     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10834                                          /*DiscardedValue=*/true);
10835 
10836     // Build final: Var = InitExpr + NumIterations * Step
10837     ExprResult Final;
10838     if (!Info.first) {
10839       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10840                                  InitExpr, NumIterations, Step,
10841                                  /* Subtract */ false);
10842     } else
10843       Final = *CurPrivate;
10844     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10845                                         /*DiscardedValue=*/true);
10846 
10847     if (!Update.isUsable() || !Final.isUsable()) {
10848       Updates.push_back(nullptr);
10849       Finals.push_back(nullptr);
10850       HasErrors = true;
10851     } else {
10852       Updates.push_back(Update.get());
10853       Finals.push_back(Final.get());
10854     }
10855     ++CurInit;
10856     ++CurPrivate;
10857   }
10858   Clause.setUpdates(Updates);
10859   Clause.setFinals(Finals);
10860   return HasErrors;
10861 }
10862 
10863 OMPClause *Sema::ActOnOpenMPAlignedClause(
10864     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10865     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10866 
10867   SmallVector<Expr *, 8> Vars;
10868   for (auto &RefExpr : VarList) {
10869     assert(RefExpr && "NULL expr in OpenMP linear clause.");
10870     SourceLocation ELoc;
10871     SourceRange ERange;
10872     Expr *SimpleRefExpr = RefExpr;
10873     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10874                               /*AllowArraySection=*/false);
10875     if (Res.second) {
10876       // It will be analyzed later.
10877       Vars.push_back(RefExpr);
10878     }
10879     ValueDecl *D = Res.first;
10880     if (!D)
10881       continue;
10882 
10883     QualType QType = D->getType();
10884     auto *VD = dyn_cast<VarDecl>(D);
10885 
10886     // OpenMP  [2.8.1, simd construct, Restrictions]
10887     // The type of list items appearing in the aligned clause must be
10888     // array, pointer, reference to array, or reference to pointer.
10889     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
10890     const Type *Ty = QType.getTypePtrOrNull();
10891     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
10892       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
10893           << QType << getLangOpts().CPlusPlus << ERange;
10894       bool IsDecl =
10895           !VD ||
10896           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10897       Diag(D->getLocation(),
10898            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10899           << D;
10900       continue;
10901     }
10902 
10903     // OpenMP  [2.8.1, simd construct, Restrictions]
10904     // A list-item cannot appear in more than one aligned clause.
10905     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
10906       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
10907       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10908           << getOpenMPClauseName(OMPC_aligned);
10909       continue;
10910     }
10911 
10912     DeclRefExpr *Ref = nullptr;
10913     if (!VD && IsOpenMPCapturedDecl(D))
10914       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10915     Vars.push_back(DefaultFunctionArrayConversion(
10916                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10917                        .get());
10918   }
10919 
10920   // OpenMP [2.8.1, simd construct, Description]
10921   // The parameter of the aligned clause, alignment, must be a constant
10922   // positive integer expression.
10923   // If no optional parameter is specified, implementation-defined default
10924   // alignments for SIMD instructions on the target platforms are assumed.
10925   if (Alignment != nullptr) {
10926     ExprResult AlignResult =
10927         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10928     if (AlignResult.isInvalid())
10929       return nullptr;
10930     Alignment = AlignResult.get();
10931   }
10932   if (Vars.empty())
10933     return nullptr;
10934 
10935   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10936                                   EndLoc, Vars, Alignment);
10937 }
10938 
10939 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10940                                          SourceLocation StartLoc,
10941                                          SourceLocation LParenLoc,
10942                                          SourceLocation EndLoc) {
10943   SmallVector<Expr *, 8> Vars;
10944   SmallVector<Expr *, 8> SrcExprs;
10945   SmallVector<Expr *, 8> DstExprs;
10946   SmallVector<Expr *, 8> AssignmentOps;
10947   for (auto &RefExpr : VarList) {
10948     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10949     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
10950       // It will be analyzed later.
10951       Vars.push_back(RefExpr);
10952       SrcExprs.push_back(nullptr);
10953       DstExprs.push_back(nullptr);
10954       AssignmentOps.push_back(nullptr);
10955       continue;
10956     }
10957 
10958     SourceLocation ELoc = RefExpr->getExprLoc();
10959     // OpenMP [2.1, C/C++]
10960     //  A list item is a variable name.
10961     // OpenMP  [2.14.4.1, Restrictions, p.1]
10962     //  A list item that appears in a copyin clause must be threadprivate.
10963     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
10964     if (!DE || !isa<VarDecl>(DE->getDecl())) {
10965       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10966           << 0 << RefExpr->getSourceRange();
10967       continue;
10968     }
10969 
10970     Decl *D = DE->getDecl();
10971     VarDecl *VD = cast<VarDecl>(D);
10972 
10973     QualType Type = VD->getType();
10974     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10975       // It will be analyzed later.
10976       Vars.push_back(DE);
10977       SrcExprs.push_back(nullptr);
10978       DstExprs.push_back(nullptr);
10979       AssignmentOps.push_back(nullptr);
10980       continue;
10981     }
10982 
10983     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10984     //  A list item that appears in a copyin clause must be threadprivate.
10985     if (!DSAStack->isThreadPrivate(VD)) {
10986       Diag(ELoc, diag::err_omp_required_access)
10987           << getOpenMPClauseName(OMPC_copyin)
10988           << getOpenMPDirectiveName(OMPD_threadprivate);
10989       continue;
10990     }
10991 
10992     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10993     //  A variable of class type (or array thereof) that appears in a
10994     //  copyin clause requires an accessible, unambiguous copy assignment
10995     //  operator for the class type.
10996     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
10997     auto *SrcVD =
10998         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10999                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11000     auto *PseudoSrcExpr = buildDeclRefExpr(
11001         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11002     auto *DstVD =
11003         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11004                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
11005     auto *PseudoDstExpr =
11006         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
11007     // For arrays generate assignment operation for single element and replace
11008     // it by the original array element in CodeGen.
11009     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11010                                    PseudoDstExpr, PseudoSrcExpr);
11011     if (AssignmentOp.isInvalid())
11012       continue;
11013     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11014                                        /*DiscardedValue=*/true);
11015     if (AssignmentOp.isInvalid())
11016       continue;
11017 
11018     DSAStack->addDSA(VD, DE, OMPC_copyin);
11019     Vars.push_back(DE);
11020     SrcExprs.push_back(PseudoSrcExpr);
11021     DstExprs.push_back(PseudoDstExpr);
11022     AssignmentOps.push_back(AssignmentOp.get());
11023   }
11024 
11025   if (Vars.empty())
11026     return nullptr;
11027 
11028   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11029                                  SrcExprs, DstExprs, AssignmentOps);
11030 }
11031 
11032 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11033                                               SourceLocation StartLoc,
11034                                               SourceLocation LParenLoc,
11035                                               SourceLocation EndLoc) {
11036   SmallVector<Expr *, 8> Vars;
11037   SmallVector<Expr *, 8> SrcExprs;
11038   SmallVector<Expr *, 8> DstExprs;
11039   SmallVector<Expr *, 8> AssignmentOps;
11040   for (auto &RefExpr : VarList) {
11041     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11042     SourceLocation ELoc;
11043     SourceRange ERange;
11044     Expr *SimpleRefExpr = RefExpr;
11045     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11046                               /*AllowArraySection=*/false);
11047     if (Res.second) {
11048       // It will be analyzed later.
11049       Vars.push_back(RefExpr);
11050       SrcExprs.push_back(nullptr);
11051       DstExprs.push_back(nullptr);
11052       AssignmentOps.push_back(nullptr);
11053     }
11054     ValueDecl *D = Res.first;
11055     if (!D)
11056       continue;
11057 
11058     QualType Type = D->getType();
11059     auto *VD = dyn_cast<VarDecl>(D);
11060 
11061     // OpenMP [2.14.4.2, Restrictions, p.2]
11062     //  A list item that appears in a copyprivate clause may not appear in a
11063     //  private or firstprivate clause on the single construct.
11064     if (!VD || !DSAStack->isThreadPrivate(VD)) {
11065       auto DVar = DSAStack->getTopDSA(D, false);
11066       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11067           DVar.RefExpr) {
11068         Diag(ELoc, diag::err_omp_wrong_dsa)
11069             << getOpenMPClauseName(DVar.CKind)
11070             << getOpenMPClauseName(OMPC_copyprivate);
11071         ReportOriginalDSA(*this, DSAStack, D, DVar);
11072         continue;
11073       }
11074 
11075       // OpenMP [2.11.4.2, Restrictions, p.1]
11076       //  All list items that appear in a copyprivate clause must be either
11077       //  threadprivate or private in the enclosing context.
11078       if (DVar.CKind == OMPC_unknown) {
11079         DVar = DSAStack->getImplicitDSA(D, false);
11080         if (DVar.CKind == OMPC_shared) {
11081           Diag(ELoc, diag::err_omp_required_access)
11082               << getOpenMPClauseName(OMPC_copyprivate)
11083               << "threadprivate or private in the enclosing context";
11084           ReportOriginalDSA(*this, DSAStack, D, DVar);
11085           continue;
11086         }
11087       }
11088     }
11089 
11090     // Variably modified types are not supported.
11091     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
11092       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11093           << getOpenMPClauseName(OMPC_copyprivate) << Type
11094           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11095       bool IsDecl =
11096           !VD ||
11097           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11098       Diag(D->getLocation(),
11099            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11100           << D;
11101       continue;
11102     }
11103 
11104     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11105     //  A variable of class type (or array thereof) that appears in a
11106     //  copyin clause requires an accessible, unambiguous copy assignment
11107     //  operator for the class type.
11108     Type = Context.getBaseElementType(Type.getNonReferenceType())
11109                .getUnqualifiedType();
11110     auto *SrcVD =
11111         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11112                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11113     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11114     auto *DstVD =
11115         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11116                      D->hasAttrs() ? &D->getAttrs() : nullptr);
11117     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11118     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11119                                    PseudoDstExpr, PseudoSrcExpr);
11120     if (AssignmentOp.isInvalid())
11121       continue;
11122     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
11123                                        /*DiscardedValue=*/true);
11124     if (AssignmentOp.isInvalid())
11125       continue;
11126 
11127     // No need to mark vars as copyprivate, they are already threadprivate or
11128     // implicitly private.
11129     assert(VD || IsOpenMPCapturedDecl(D));
11130     Vars.push_back(
11131         VD ? RefExpr->IgnoreParens()
11132            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
11133     SrcExprs.push_back(PseudoSrcExpr);
11134     DstExprs.push_back(PseudoDstExpr);
11135     AssignmentOps.push_back(AssignmentOp.get());
11136   }
11137 
11138   if (Vars.empty())
11139     return nullptr;
11140 
11141   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11142                                       Vars, SrcExprs, DstExprs, AssignmentOps);
11143 }
11144 
11145 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11146                                         SourceLocation StartLoc,
11147                                         SourceLocation LParenLoc,
11148                                         SourceLocation EndLoc) {
11149   if (VarList.empty())
11150     return nullptr;
11151 
11152   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11153 }
11154 
11155 OMPClause *
11156 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11157                               SourceLocation DepLoc, SourceLocation ColonLoc,
11158                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11159                               SourceLocation LParenLoc, SourceLocation EndLoc) {
11160   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
11161       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
11162     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11163         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
11164     return nullptr;
11165   }
11166   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
11167       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11168        DepKind == OMPC_DEPEND_sink)) {
11169     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
11170     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
11171         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11172                                    /*Last=*/OMPC_DEPEND_unknown, Except)
11173         << getOpenMPClauseName(OMPC_depend);
11174     return nullptr;
11175   }
11176   SmallVector<Expr *, 8> Vars;
11177   DSAStackTy::OperatorOffsetTy OpsOffs;
11178   llvm::APSInt DepCounter(/*BitWidth=*/32);
11179   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11180   if (DepKind == OMPC_DEPEND_sink) {
11181     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11182       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11183       TotalDepCount.setIsUnsigned(/*Val=*/true);
11184     }
11185   }
11186   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11187       DSAStack->getParentOrderedRegionParam()) {
11188     for (auto &RefExpr : VarList) {
11189       assert(RefExpr && "NULL expr in OpenMP shared clause.");
11190       if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11191         // It will be analyzed later.
11192         Vars.push_back(RefExpr);
11193         continue;
11194       }
11195 
11196       SourceLocation ELoc = RefExpr->getExprLoc();
11197       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11198       if (DepKind == OMPC_DEPEND_sink) {
11199         if (DepCounter >= TotalDepCount) {
11200           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11201           continue;
11202         }
11203         ++DepCounter;
11204         // OpenMP  [2.13.9, Summary]
11205         // depend(dependence-type : vec), where dependence-type is:
11206         // 'sink' and where vec is the iteration vector, which has the form:
11207         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11208         // where n is the value specified by the ordered clause in the loop
11209         // directive, xi denotes the loop iteration variable of the i-th nested
11210         // loop associated with the loop directive, and di is a constant
11211         // non-negative integer.
11212         if (CurContext->isDependentContext()) {
11213           // It will be analyzed later.
11214           Vars.push_back(RefExpr);
11215           continue;
11216         }
11217         SimpleExpr = SimpleExpr->IgnoreImplicit();
11218         OverloadedOperatorKind OOK = OO_None;
11219         SourceLocation OOLoc;
11220         Expr *LHS = SimpleExpr;
11221         Expr *RHS = nullptr;
11222         if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11223           OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11224           OOLoc = BO->getOperatorLoc();
11225           LHS = BO->getLHS()->IgnoreParenImpCasts();
11226           RHS = BO->getRHS()->IgnoreParenImpCasts();
11227         } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11228           OOK = OCE->getOperator();
11229           OOLoc = OCE->getOperatorLoc();
11230           LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11231           RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11232         } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11233           OOK = MCE->getMethodDecl()
11234                     ->getNameInfo()
11235                     .getName()
11236                     .getCXXOverloadedOperator();
11237           OOLoc = MCE->getCallee()->getExprLoc();
11238           LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11239           RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11240         }
11241         SourceLocation ELoc;
11242         SourceRange ERange;
11243         auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11244                                   /*AllowArraySection=*/false);
11245         if (Res.second) {
11246           // It will be analyzed later.
11247           Vars.push_back(RefExpr);
11248         }
11249         ValueDecl *D = Res.first;
11250         if (!D)
11251           continue;
11252 
11253         if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11254           Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11255           continue;
11256         }
11257         if (RHS) {
11258           ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11259               RHS, OMPC_depend, /*StrictlyPositive=*/false);
11260           if (RHSRes.isInvalid())
11261             continue;
11262         }
11263         if (!CurContext->isDependentContext() &&
11264             DSAStack->getParentOrderedRegionParam() &&
11265             DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11266           ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11267               DepCounter.getZExtValue());
11268           if (VD) {
11269             Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11270                 << 1 << VD;
11271           } else {
11272              Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11273           }
11274           continue;
11275         }
11276         OpsOffs.push_back({RHS, OOK});
11277       } else {
11278         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11279         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11280             (ASE &&
11281              !ASE->getBase()
11282                   ->getType()
11283                   .getNonReferenceType()
11284                   ->isPointerType() &&
11285              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11286           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11287               << RefExpr->getSourceRange();
11288           continue;
11289         }
11290         bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11291         getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11292         ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
11293                                               RefExpr->IgnoreParenImpCasts());
11294         getDiagnostics().setSuppressAllDiagnostics(Suppress);
11295         if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11296           Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11297               << RefExpr->getSourceRange();
11298           continue;
11299         }
11300       }
11301       Vars.push_back(RefExpr->IgnoreParenImpCasts());
11302     }
11303 
11304     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11305         TotalDepCount > VarList.size() &&
11306         DSAStack->getParentOrderedRegionParam() &&
11307         DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11308       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
11309           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11310     }
11311     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11312         Vars.empty())
11313       return nullptr;
11314   }
11315   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11316                                     DepKind, DepLoc, ColonLoc, Vars);
11317   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11318     DSAStack->addDoacrossDependClause(C, OpsOffs);
11319   return C;
11320 }
11321 
11322 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11323                                          SourceLocation LParenLoc,
11324                                          SourceLocation EndLoc) {
11325   Expr *ValExpr = Device;
11326   Stmt *HelperValStmt = nullptr;
11327 
11328   // OpenMP [2.9.1, Restrictions]
11329   // The device expression must evaluate to a non-negative integer value.
11330   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11331                                  /*StrictlyPositive=*/false))
11332     return nullptr;
11333 
11334   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11335   OpenMPDirectiveKind CaptureRegion =
11336       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11337   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11338     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11339     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11340     HelperValStmt = buildPreInits(Context, Captures);
11341   }
11342 
11343   return new (Context)
11344       OMPDeviceClause(ValExpr, HelperValStmt, StartLoc, LParenLoc, EndLoc);
11345 }
11346 
11347 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11348                               DSAStackTy *Stack, QualType QTy) {
11349   NamedDecl *ND;
11350   if (QTy->isIncompleteType(&ND)) {
11351     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11352     return false;
11353   }
11354   return true;
11355 }
11356 
11357 /// \brief Return true if it can be proven that the provided array expression
11358 /// (array section or array subscript) does NOT specify the whole size of the
11359 /// array whose base type is \a BaseQTy.
11360 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11361                                                         const Expr *E,
11362                                                         QualType BaseQTy) {
11363   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11364 
11365   // If this is an array subscript, it refers to the whole size if the size of
11366   // the dimension is constant and equals 1. Also, an array section assumes the
11367   // format of an array subscript if no colon is used.
11368   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11369     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11370       return ATy->getSize().getSExtValue() != 1;
11371     // Size can't be evaluated statically.
11372     return false;
11373   }
11374 
11375   assert(OASE && "Expecting array section if not an array subscript.");
11376   auto *LowerBound = OASE->getLowerBound();
11377   auto *Length = OASE->getLength();
11378 
11379   // If there is a lower bound that does not evaluates to zero, we are not
11380   // covering the whole dimension.
11381   if (LowerBound) {
11382     llvm::APSInt ConstLowerBound;
11383     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11384       return false; // Can't get the integer value as a constant.
11385     if (ConstLowerBound.getSExtValue())
11386       return true;
11387   }
11388 
11389   // If we don't have a length we covering the whole dimension.
11390   if (!Length)
11391     return false;
11392 
11393   // If the base is a pointer, we don't have a way to get the size of the
11394   // pointee.
11395   if (BaseQTy->isPointerType())
11396     return false;
11397 
11398   // We can only check if the length is the same as the size of the dimension
11399   // if we have a constant array.
11400   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11401   if (!CATy)
11402     return false;
11403 
11404   llvm::APSInt ConstLength;
11405   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11406     return false; // Can't get the integer value as a constant.
11407 
11408   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11409 }
11410 
11411 // Return true if it can be proven that the provided array expression (array
11412 // section or array subscript) does NOT specify a single element of the array
11413 // whose base type is \a BaseQTy.
11414 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
11415                                                         const Expr *E,
11416                                                         QualType BaseQTy) {
11417   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11418 
11419   // An array subscript always refer to a single element. Also, an array section
11420   // assumes the format of an array subscript if no colon is used.
11421   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11422     return false;
11423 
11424   assert(OASE && "Expecting array section if not an array subscript.");
11425   auto *Length = OASE->getLength();
11426 
11427   // If we don't have a length we have to check if the array has unitary size
11428   // for this dimension. Also, we should always expect a length if the base type
11429   // is pointer.
11430   if (!Length) {
11431     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11432       return ATy->getSize().getSExtValue() != 1;
11433     // We cannot assume anything.
11434     return false;
11435   }
11436 
11437   // Check if the length evaluates to 1.
11438   llvm::APSInt ConstLength;
11439   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11440     return false; // Can't get the integer value as a constant.
11441 
11442   return ConstLength.getSExtValue() != 1;
11443 }
11444 
11445 // Return the expression of the base of the mappable expression or null if it
11446 // cannot be determined and do all the necessary checks to see if the expression
11447 // is valid as a standalone mappable expression. In the process, record all the
11448 // components of the expression.
11449 static Expr *CheckMapClauseExpressionBase(
11450     Sema &SemaRef, Expr *E,
11451     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
11452     OpenMPClauseKind CKind, bool NoDiagnose) {
11453   SourceLocation ELoc = E->getExprLoc();
11454   SourceRange ERange = E->getSourceRange();
11455 
11456   // The base of elements of list in a map clause have to be either:
11457   //  - a reference to variable or field.
11458   //  - a member expression.
11459   //  - an array expression.
11460   //
11461   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11462   // reference to 'r'.
11463   //
11464   // If we have:
11465   //
11466   // struct SS {
11467   //   Bla S;
11468   //   foo() {
11469   //     #pragma omp target map (S.Arr[:12]);
11470   //   }
11471   // }
11472   //
11473   // We want to retrieve the member expression 'this->S';
11474 
11475   Expr *RelevantExpr = nullptr;
11476 
11477   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11478   //  If a list item is an array section, it must specify contiguous storage.
11479   //
11480   // For this restriction it is sufficient that we make sure only references
11481   // to variables or fields and array expressions, and that no array sections
11482   // exist except in the rightmost expression (unless they cover the whole
11483   // dimension of the array). E.g. these would be invalid:
11484   //
11485   //   r.ArrS[3:5].Arr[6:7]
11486   //
11487   //   r.ArrS[3:5].x
11488   //
11489   // but these would be valid:
11490   //   r.ArrS[3].Arr[6:7]
11491   //
11492   //   r.ArrS[3].x
11493 
11494   bool AllowUnitySizeArraySection = true;
11495   bool AllowWholeSizeArraySection = true;
11496 
11497   while (!RelevantExpr) {
11498     E = E->IgnoreParenImpCasts();
11499 
11500     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11501       if (!isa<VarDecl>(CurE->getDecl()))
11502         return nullptr;
11503 
11504       RelevantExpr = CurE;
11505 
11506       // If we got a reference to a declaration, we should not expect any array
11507       // section before that.
11508       AllowUnitySizeArraySection = false;
11509       AllowWholeSizeArraySection = false;
11510 
11511       // Record the component.
11512       CurComponents.emplace_back(CurE, CurE->getDecl());
11513     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
11514       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11515 
11516       if (isa<CXXThisExpr>(BaseE))
11517         // We found a base expression: this->Val.
11518         RelevantExpr = CurE;
11519       else
11520         E = BaseE;
11521 
11522       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
11523         if (!NoDiagnose) {
11524           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11525               << CurE->getSourceRange();
11526           return nullptr;
11527         }
11528         if (RelevantExpr)
11529           return nullptr;
11530         continue;
11531       }
11532 
11533       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11534 
11535       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11536       //  A bit-field cannot appear in a map clause.
11537       //
11538       if (FD->isBitField()) {
11539         if (!NoDiagnose) {
11540           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11541               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11542           return nullptr;
11543         }
11544         if (RelevantExpr)
11545           return nullptr;
11546         continue;
11547       }
11548 
11549       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11550       //  If the type of a list item is a reference to a type T then the type
11551       //  will be considered to be T for all purposes of this clause.
11552       QualType CurType = BaseE->getType().getNonReferenceType();
11553 
11554       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11555       //  A list item cannot be a variable that is a member of a structure with
11556       //  a union type.
11557       //
11558       if (auto *RT = CurType->getAs<RecordType>()) {
11559         if (RT->isUnionType()) {
11560           if (!NoDiagnose) {
11561             SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11562                 << CurE->getSourceRange();
11563             return nullptr;
11564           }
11565           continue;
11566         }
11567       }
11568 
11569       // If we got a member expression, we should not expect any array section
11570       // before that:
11571       //
11572       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11573       //  If a list item is an element of a structure, only the rightmost symbol
11574       //  of the variable reference can be an array section.
11575       //
11576       AllowUnitySizeArraySection = false;
11577       AllowWholeSizeArraySection = false;
11578 
11579       // Record the component.
11580       CurComponents.emplace_back(CurE, FD);
11581     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
11582       E = CurE->getBase()->IgnoreParenImpCasts();
11583 
11584       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
11585         if (!NoDiagnose) {
11586           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11587               << 0 << CurE->getSourceRange();
11588           return nullptr;
11589         }
11590         continue;
11591       }
11592 
11593       // If we got an array subscript that express the whole dimension we
11594       // can have any array expressions before. If it only expressing part of
11595       // the dimension, we can only have unitary-size array expressions.
11596       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11597                                                       E->getType()))
11598         AllowWholeSizeArraySection = false;
11599 
11600       // Record the component - we don't have any declaration associated.
11601       CurComponents.emplace_back(CurE, nullptr);
11602     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
11603       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
11604       E = CurE->getBase()->IgnoreParenImpCasts();
11605 
11606       QualType CurType =
11607           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11608 
11609       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11610       //  If the type of a list item is a reference to a type T then the type
11611       //  will be considered to be T for all purposes of this clause.
11612       if (CurType->isReferenceType())
11613         CurType = CurType->getPointeeType();
11614 
11615       bool IsPointer = CurType->isAnyPointerType();
11616 
11617       if (!IsPointer && !CurType->isArrayType()) {
11618         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11619             << 0 << CurE->getSourceRange();
11620         return nullptr;
11621       }
11622 
11623       bool NotWhole =
11624           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11625       bool NotUnity =
11626           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11627 
11628       if (AllowWholeSizeArraySection) {
11629         // Any array section is currently allowed. Allowing a whole size array
11630         // section implies allowing a unity array section as well.
11631         //
11632         // If this array section refers to the whole dimension we can still
11633         // accept other array sections before this one, except if the base is a
11634         // pointer. Otherwise, only unitary sections are accepted.
11635         if (NotWhole || IsPointer)
11636           AllowWholeSizeArraySection = false;
11637       } else if (AllowUnitySizeArraySection && NotUnity) {
11638         // A unity or whole array section is not allowed and that is not
11639         // compatible with the properties of the current array section.
11640         SemaRef.Diag(
11641             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11642             << CurE->getSourceRange();
11643         return nullptr;
11644       }
11645 
11646       // Record the component - we don't have any declaration associated.
11647       CurComponents.emplace_back(CurE, nullptr);
11648     } else {
11649       if (!NoDiagnose) {
11650         // If nothing else worked, this is not a valid map clause expression.
11651         SemaRef.Diag(
11652             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11653             << ERange;
11654       }
11655       return nullptr;
11656     }
11657   }
11658 
11659   return RelevantExpr;
11660 }
11661 
11662 // Return true if expression E associated with value VD has conflicts with other
11663 // map information.
11664 static bool CheckMapConflicts(
11665     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11666     bool CurrentRegionOnly,
11667     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11668     OpenMPClauseKind CKind) {
11669   assert(VD && E);
11670   SourceLocation ELoc = E->getExprLoc();
11671   SourceRange ERange = E->getSourceRange();
11672 
11673   // In order to easily check the conflicts we need to match each component of
11674   // the expression under test with the components of the expressions that are
11675   // already in the stack.
11676 
11677   assert(!CurComponents.empty() && "Map clause expression with no components!");
11678   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
11679          "Map clause expression with unexpected base!");
11680 
11681   // Variables to help detecting enclosing problems in data environment nests.
11682   bool IsEnclosedByDataEnvironmentExpr = false;
11683   const Expr *EnclosingExpr = nullptr;
11684 
11685   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11686       VD, CurrentRegionOnly,
11687       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
11688               StackComponents,
11689           OpenMPClauseKind) -> bool {
11690 
11691         assert(!StackComponents.empty() &&
11692                "Map clause expression with no components!");
11693         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
11694                "Map clause expression with unexpected base!");
11695 
11696         // The whole expression in the stack.
11697         auto *RE = StackComponents.front().getAssociatedExpression();
11698 
11699         // Expressions must start from the same base. Here we detect at which
11700         // point both expressions diverge from each other and see if we can
11701         // detect if the memory referred to both expressions is contiguous and
11702         // do not overlap.
11703         auto CI = CurComponents.rbegin();
11704         auto CE = CurComponents.rend();
11705         auto SI = StackComponents.rbegin();
11706         auto SE = StackComponents.rend();
11707         for (; CI != CE && SI != SE; ++CI, ++SI) {
11708 
11709           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11710           //  At most one list item can be an array item derived from a given
11711           //  variable in map clauses of the same construct.
11712           if (CurrentRegionOnly &&
11713               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11714                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11715               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11716                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11717             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
11718                          diag::err_omp_multiple_array_items_in_map_clause)
11719                 << CI->getAssociatedExpression()->getSourceRange();
11720             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11721                          diag::note_used_here)
11722                 << SI->getAssociatedExpression()->getSourceRange();
11723             return true;
11724           }
11725 
11726           // Do both expressions have the same kind?
11727           if (CI->getAssociatedExpression()->getStmtClass() !=
11728               SI->getAssociatedExpression()->getStmtClass())
11729             break;
11730 
11731           // Are we dealing with different variables/fields?
11732           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
11733             break;
11734         }
11735         // Check if the extra components of the expressions in the enclosing
11736         // data environment are redundant for the current base declaration.
11737         // If they are, the maps completely overlap, which is legal.
11738         for (; SI != SE; ++SI) {
11739           QualType Type;
11740           if (auto *ASE =
11741                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
11742             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
11743           } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11744                          SI->getAssociatedExpression())) {
11745             auto *E = OASE->getBase()->IgnoreParenImpCasts();
11746             Type =
11747                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11748           }
11749           if (Type.isNull() || Type->isAnyPointerType() ||
11750               CheckArrayExpressionDoesNotReferToWholeSize(
11751                   SemaRef, SI->getAssociatedExpression(), Type))
11752             break;
11753         }
11754 
11755         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11756         //  List items of map clauses in the same construct must not share
11757         //  original storage.
11758         //
11759         // If the expressions are exactly the same or one is a subset of the
11760         // other, it means they are sharing storage.
11761         if (CI == CE && SI == SE) {
11762           if (CurrentRegionOnly) {
11763             if (CKind == OMPC_map)
11764               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11765             else {
11766               assert(CKind == OMPC_to || CKind == OMPC_from);
11767               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11768                   << ERange;
11769             }
11770             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11771                 << RE->getSourceRange();
11772             return true;
11773           } else {
11774             // If we find the same expression in the enclosing data environment,
11775             // that is legal.
11776             IsEnclosedByDataEnvironmentExpr = true;
11777             return false;
11778           }
11779         }
11780 
11781         QualType DerivedType =
11782             std::prev(CI)->getAssociatedDeclaration()->getType();
11783         SourceLocation DerivedLoc =
11784             std::prev(CI)->getAssociatedExpression()->getExprLoc();
11785 
11786         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11787         //  If the type of a list item is a reference to a type T then the type
11788         //  will be considered to be T for all purposes of this clause.
11789         DerivedType = DerivedType.getNonReferenceType();
11790 
11791         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11792         //  A variable for which the type is pointer and an array section
11793         //  derived from that variable must not appear as list items of map
11794         //  clauses of the same construct.
11795         //
11796         // Also, cover one of the cases in:
11797         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11798         //  If any part of the original storage of a list item has corresponding
11799         //  storage in the device data environment, all of the original storage
11800         //  must have corresponding storage in the device data environment.
11801         //
11802         if (DerivedType->isAnyPointerType()) {
11803           if (CI == CE || SI == SE) {
11804             SemaRef.Diag(
11805                 DerivedLoc,
11806                 diag::err_omp_pointer_mapped_along_with_derived_section)
11807                 << DerivedLoc;
11808           } else {
11809             assert(CI != CE && SI != SE);
11810             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11811                 << DerivedLoc;
11812           }
11813           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11814               << RE->getSourceRange();
11815           return true;
11816         }
11817 
11818         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11819         //  List items of map clauses in the same construct must not share
11820         //  original storage.
11821         //
11822         // An expression is a subset of the other.
11823         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
11824           if (CKind == OMPC_map)
11825             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11826           else {
11827             assert(CKind == OMPC_to || CKind == OMPC_from);
11828             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11829                 << ERange;
11830           }
11831           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11832               << RE->getSourceRange();
11833           return true;
11834         }
11835 
11836         // The current expression uses the same base as other expression in the
11837         // data environment but does not contain it completely.
11838         if (!CurrentRegionOnly && SI != SE)
11839           EnclosingExpr = RE;
11840 
11841         // The current expression is a subset of the expression in the data
11842         // environment.
11843         IsEnclosedByDataEnvironmentExpr |=
11844             (!CurrentRegionOnly && CI != CE && SI == SE);
11845 
11846         return false;
11847       });
11848 
11849   if (CurrentRegionOnly)
11850     return FoundError;
11851 
11852   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11853   //  If any part of the original storage of a list item has corresponding
11854   //  storage in the device data environment, all of the original storage must
11855   //  have corresponding storage in the device data environment.
11856   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11857   //  If a list item is an element of a structure, and a different element of
11858   //  the structure has a corresponding list item in the device data environment
11859   //  prior to a task encountering the construct associated with the map clause,
11860   //  then the list item must also have a corresponding list item in the device
11861   //  data environment prior to the task encountering the construct.
11862   //
11863   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11864     SemaRef.Diag(ELoc,
11865                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
11866         << ERange;
11867     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11868         << EnclosingExpr->getSourceRange();
11869     return true;
11870   }
11871 
11872   return FoundError;
11873 }
11874 
11875 namespace {
11876 // Utility struct that gathers all the related lists associated with a mappable
11877 // expression.
11878 struct MappableVarListInfo final {
11879   // The list of expressions.
11880   ArrayRef<Expr *> VarList;
11881   // The list of processed expressions.
11882   SmallVector<Expr *, 16> ProcessedVarList;
11883   // The mappble components for each expression.
11884   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11885   // The base declaration of the variable.
11886   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11887 
11888   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11889     // We have a list of components and base declarations for each entry in the
11890     // variable list.
11891     VarComponents.reserve(VarList.size());
11892     VarBaseDeclarations.reserve(VarList.size());
11893   }
11894 };
11895 }
11896 
11897 // Check the validity of the provided variable list for the provided clause kind
11898 // \a CKind. In the check process the valid expressions, and mappable expression
11899 // components and variables are extracted and used to fill \a Vars,
11900 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11901 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11902 static void
11903 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11904                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11905                             SourceLocation StartLoc,
11906                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11907                             bool IsMapTypeImplicit = false) {
11908   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11909   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
11910          "Unexpected clause kind with mappable expressions!");
11911 
11912   // Keep track of the mappable components and base declarations in this clause.
11913   // Each entry in the list is going to have a list of components associated. We
11914   // record each set of the components so that we can build the clause later on.
11915   // In the end we should have the same amount of declarations and component
11916   // lists.
11917 
11918   for (auto &RE : MVLI.VarList) {
11919     assert(RE && "Null expr in omp to/from/map clause");
11920     SourceLocation ELoc = RE->getExprLoc();
11921 
11922     auto *VE = RE->IgnoreParenLValueCasts();
11923 
11924     if (VE->isValueDependent() || VE->isTypeDependent() ||
11925         VE->isInstantiationDependent() ||
11926         VE->containsUnexpandedParameterPack()) {
11927       // We can only analyze this information once the missing information is
11928       // resolved.
11929       MVLI.ProcessedVarList.push_back(RE);
11930       continue;
11931     }
11932 
11933     auto *SimpleExpr = RE->IgnoreParenCasts();
11934 
11935     if (!RE->IgnoreParenImpCasts()->isLValue()) {
11936       SemaRef.Diag(ELoc,
11937                    diag::err_omp_expected_named_var_member_or_array_expression)
11938           << RE->getSourceRange();
11939       continue;
11940     }
11941 
11942     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11943     ValueDecl *CurDeclaration = nullptr;
11944 
11945     // Obtain the array or member expression bases if required. Also, fill the
11946     // components array with all the components identified in the process.
11947     auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
11948                                             CKind, /*NoDiagnose=*/false);
11949     if (!BE)
11950       continue;
11951 
11952     assert(!CurComponents.empty() &&
11953            "Invalid mappable expression information.");
11954 
11955     // For the following checks, we rely on the base declaration which is
11956     // expected to be associated with the last component. The declaration is
11957     // expected to be a variable or a field (if 'this' is being mapped).
11958     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11959     assert(CurDeclaration && "Null decl on map clause.");
11960     assert(
11961         CurDeclaration->isCanonicalDecl() &&
11962         "Expecting components to have associated only canonical declarations.");
11963 
11964     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11965     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
11966 
11967     assert((VD || FD) && "Only variables or fields are expected here!");
11968     (void)FD;
11969 
11970     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
11971     // threadprivate variables cannot appear in a map clause.
11972     // OpenMP 4.5 [2.10.5, target update Construct]
11973     // threadprivate variables cannot appear in a from clause.
11974     if (VD && DSAS->isThreadPrivate(VD)) {
11975       auto DVar = DSAS->getTopDSA(VD, false);
11976       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11977           << getOpenMPClauseName(CKind);
11978       ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
11979       continue;
11980     }
11981 
11982     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11983     //  A list item cannot appear in both a map clause and a data-sharing
11984     //  attribute clause on the same construct.
11985 
11986     // Check conflicts with other map clause expressions. We check the conflicts
11987     // with the current construct separately from the enclosing data
11988     // environment, because the restrictions are different. We only have to
11989     // check conflicts across regions for the map clauses.
11990     if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11991                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
11992       break;
11993     if (CKind == OMPC_map &&
11994         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11995                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
11996       break;
11997 
11998     // OpenMP 4.5 [2.10.5, target update Construct]
11999     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12000     //  If the type of a list item is a reference to a type T then the type will
12001     //  be considered to be T for all purposes of this clause.
12002     QualType Type = CurDeclaration->getType().getNonReferenceType();
12003 
12004     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12005     // A list item in a to or from clause must have a mappable type.
12006     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12007     //  A list item must have a mappable type.
12008     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12009                            DSAS, Type))
12010       continue;
12011 
12012     if (CKind == OMPC_map) {
12013       // target enter data
12014       // OpenMP [2.10.2, Restrictions, p. 99]
12015       // A map-type must be specified in all map clauses and must be either
12016       // to or alloc.
12017       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12018       if (DKind == OMPD_target_enter_data &&
12019           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12020         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12021             << (IsMapTypeImplicit ? 1 : 0)
12022             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12023             << getOpenMPDirectiveName(DKind);
12024         continue;
12025       }
12026 
12027       // target exit_data
12028       // OpenMP [2.10.3, Restrictions, p. 102]
12029       // A map-type must be specified in all map clauses and must be either
12030       // from, release, or delete.
12031       if (DKind == OMPD_target_exit_data &&
12032           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12033             MapType == OMPC_MAP_delete)) {
12034         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12035             << (IsMapTypeImplicit ? 1 : 0)
12036             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12037             << getOpenMPDirectiveName(DKind);
12038         continue;
12039       }
12040 
12041       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12042       // A list item cannot appear in both a map clause and a data-sharing
12043       // attribute clause on the same construct
12044       if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
12045            DKind == OMPD_target_teams_distribute ||
12046            DKind == OMPD_target_teams_distribute_parallel_for ||
12047            DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12048            DKind == OMPD_target_teams_distribute_simd) && VD) {
12049         auto DVar = DSAS->getTopDSA(VD, false);
12050         if (isOpenMPPrivate(DVar.CKind)) {
12051           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12052               << getOpenMPClauseName(DVar.CKind)
12053               << getOpenMPClauseName(OMPC_map)
12054               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12055           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12056           continue;
12057         }
12058       }
12059     }
12060 
12061     // Save the current expression.
12062     MVLI.ProcessedVarList.push_back(RE);
12063 
12064     // Store the components in the stack so that they can be used to check
12065     // against other clauses later on.
12066     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12067                                           /*WhereFoundClauseKind=*/OMPC_map);
12068 
12069     // Save the components and declaration to create the clause. For purposes of
12070     // the clause creation, any component list that has has base 'this' uses
12071     // null as base declaration.
12072     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12073     MVLI.VarComponents.back().append(CurComponents.begin(),
12074                                      CurComponents.end());
12075     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12076                                                            : CurDeclaration);
12077   }
12078 }
12079 
12080 OMPClause *
12081 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12082                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12083                            SourceLocation MapLoc, SourceLocation ColonLoc,
12084                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12085                            SourceLocation LParenLoc, SourceLocation EndLoc) {
12086   MappableVarListInfo MVLI(VarList);
12087   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12088                               MapType, IsMapTypeImplicit);
12089 
12090   // We need to produce a map clause even if we don't have variables so that
12091   // other diagnostics related with non-existing map clauses are accurate.
12092   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12093                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12094                               MVLI.VarComponents, MapTypeModifier, MapType,
12095                               IsMapTypeImplicit, MapLoc);
12096 }
12097 
12098 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12099                                                TypeResult ParsedType) {
12100   assert(ParsedType.isUsable());
12101 
12102   QualType ReductionType = GetTypeFromParser(ParsedType.get());
12103   if (ReductionType.isNull())
12104     return QualType();
12105 
12106   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12107   // A type name in a declare reduction directive cannot be a function type, an
12108   // array type, a reference type, or a type qualified with const, volatile or
12109   // restrict.
12110   if (ReductionType.hasQualifiers()) {
12111     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12112     return QualType();
12113   }
12114 
12115   if (ReductionType->isFunctionType()) {
12116     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12117     return QualType();
12118   }
12119   if (ReductionType->isReferenceType()) {
12120     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12121     return QualType();
12122   }
12123   if (ReductionType->isArrayType()) {
12124     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12125     return QualType();
12126   }
12127   return ReductionType;
12128 }
12129 
12130 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12131     Scope *S, DeclContext *DC, DeclarationName Name,
12132     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12133     AccessSpecifier AS, Decl *PrevDeclInScope) {
12134   SmallVector<Decl *, 8> Decls;
12135   Decls.reserve(ReductionTypes.size());
12136 
12137   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
12138                       forRedeclarationInCurContext());
12139   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12140   // A reduction-identifier may not be re-declared in the current scope for the
12141   // same type or for a type that is compatible according to the base language
12142   // rules.
12143   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12144   OMPDeclareReductionDecl *PrevDRD = nullptr;
12145   bool InCompoundScope = true;
12146   if (S != nullptr) {
12147     // Find previous declaration with the same name not referenced in other
12148     // declarations.
12149     FunctionScopeInfo *ParentFn = getEnclosingFunction();
12150     InCompoundScope =
12151         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12152     LookupName(Lookup, S);
12153     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12154                          /*AllowInlineNamespace=*/false);
12155     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12156     auto Filter = Lookup.makeFilter();
12157     while (Filter.hasNext()) {
12158       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12159       if (InCompoundScope) {
12160         auto I = UsedAsPrevious.find(PrevDecl);
12161         if (I == UsedAsPrevious.end())
12162           UsedAsPrevious[PrevDecl] = false;
12163         if (auto *D = PrevDecl->getPrevDeclInScope())
12164           UsedAsPrevious[D] = true;
12165       }
12166       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12167           PrevDecl->getLocation();
12168     }
12169     Filter.done();
12170     if (InCompoundScope) {
12171       for (auto &PrevData : UsedAsPrevious) {
12172         if (!PrevData.second) {
12173           PrevDRD = PrevData.first;
12174           break;
12175         }
12176       }
12177     }
12178   } else if (PrevDeclInScope != nullptr) {
12179     auto *PrevDRDInScope = PrevDRD =
12180         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12181     do {
12182       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12183           PrevDRDInScope->getLocation();
12184       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12185     } while (PrevDRDInScope != nullptr);
12186   }
12187   for (auto &TyData : ReductionTypes) {
12188     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12189     bool Invalid = false;
12190     if (I != PreviousRedeclTypes.end()) {
12191       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12192           << TyData.first;
12193       Diag(I->second, diag::note_previous_definition);
12194       Invalid = true;
12195     }
12196     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12197     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12198                                                 Name, TyData.first, PrevDRD);
12199     DC->addDecl(DRD);
12200     DRD->setAccess(AS);
12201     Decls.push_back(DRD);
12202     if (Invalid)
12203       DRD->setInvalidDecl();
12204     else
12205       PrevDRD = DRD;
12206   }
12207 
12208   return DeclGroupPtrTy::make(
12209       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12210 }
12211 
12212 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12213   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12214 
12215   // Enter new function scope.
12216   PushFunctionScope();
12217   getCurFunction()->setHasBranchProtectedScope();
12218   getCurFunction()->setHasOMPDeclareReductionCombiner();
12219 
12220   if (S != nullptr)
12221     PushDeclContext(S, DRD);
12222   else
12223     CurContext = DRD;
12224 
12225   PushExpressionEvaluationContext(
12226       ExpressionEvaluationContext::PotentiallyEvaluated);
12227 
12228   QualType ReductionType = DRD->getType();
12229   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12230   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12231   // uses semantics of argument handles by value, but it should be passed by
12232   // reference. C lang does not support references, so pass all parameters as
12233   // pointers.
12234   // Create 'T omp_in;' variable.
12235   auto *OmpInParm =
12236       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
12237   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12238   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12239   // uses semantics of argument handles by value, but it should be passed by
12240   // reference. C lang does not support references, so pass all parameters as
12241   // pointers.
12242   // Create 'T omp_out;' variable.
12243   auto *OmpOutParm =
12244       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12245   if (S != nullptr) {
12246     PushOnScopeChains(OmpInParm, S);
12247     PushOnScopeChains(OmpOutParm, S);
12248   } else {
12249     DRD->addDecl(OmpInParm);
12250     DRD->addDecl(OmpOutParm);
12251   }
12252 }
12253 
12254 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12255   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12256   DiscardCleanupsInEvaluationContext();
12257   PopExpressionEvaluationContext();
12258 
12259   PopDeclContext();
12260   PopFunctionScopeInfo();
12261 
12262   if (Combiner != nullptr)
12263     DRD->setCombiner(Combiner);
12264   else
12265     DRD->setInvalidDecl();
12266 }
12267 
12268 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
12269   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12270 
12271   // Enter new function scope.
12272   PushFunctionScope();
12273   getCurFunction()->setHasBranchProtectedScope();
12274 
12275   if (S != nullptr)
12276     PushDeclContext(S, DRD);
12277   else
12278     CurContext = DRD;
12279 
12280   PushExpressionEvaluationContext(
12281       ExpressionEvaluationContext::PotentiallyEvaluated);
12282 
12283   QualType ReductionType = DRD->getType();
12284   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12285   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12286   // uses semantics of argument handles by value, but it should be passed by
12287   // reference. C lang does not support references, so pass all parameters as
12288   // pointers.
12289   // Create 'T omp_priv;' variable.
12290   auto *OmpPrivParm =
12291       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
12292   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12293   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12294   // uses semantics of argument handles by value, but it should be passed by
12295   // reference. C lang does not support references, so pass all parameters as
12296   // pointers.
12297   // Create 'T omp_orig;' variable.
12298   auto *OmpOrigParm =
12299       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
12300   if (S != nullptr) {
12301     PushOnScopeChains(OmpPrivParm, S);
12302     PushOnScopeChains(OmpOrigParm, S);
12303   } else {
12304     DRD->addDecl(OmpPrivParm);
12305     DRD->addDecl(OmpOrigParm);
12306   }
12307   return OmpPrivParm;
12308 }
12309 
12310 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12311                                                      VarDecl *OmpPrivParm) {
12312   auto *DRD = cast<OMPDeclareReductionDecl>(D);
12313   DiscardCleanupsInEvaluationContext();
12314   PopExpressionEvaluationContext();
12315 
12316   PopDeclContext();
12317   PopFunctionScopeInfo();
12318 
12319   if (Initializer != nullptr) {
12320     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12321   } else if (OmpPrivParm->hasInit()) {
12322     DRD->setInitializer(OmpPrivParm->getInit(),
12323                         OmpPrivParm->isDirectInit()
12324                             ? OMPDeclareReductionDecl::DirectInit
12325                             : OMPDeclareReductionDecl::CopyInit);
12326   } else {
12327     DRD->setInvalidDecl();
12328   }
12329 }
12330 
12331 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12332     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12333   for (auto *D : DeclReductions.get()) {
12334     if (IsValid) {
12335       auto *DRD = cast<OMPDeclareReductionDecl>(D);
12336       if (S != nullptr)
12337         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12338     } else
12339       D->setInvalidDecl();
12340   }
12341   return DeclReductions;
12342 }
12343 
12344 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
12345                                            SourceLocation StartLoc,
12346                                            SourceLocation LParenLoc,
12347                                            SourceLocation EndLoc) {
12348   Expr *ValExpr = NumTeams;
12349   Stmt *HelperValStmt = nullptr;
12350 
12351   // OpenMP [teams Constrcut, Restrictions]
12352   // The num_teams expression must evaluate to a positive integer value.
12353   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12354                                  /*StrictlyPositive=*/true))
12355     return nullptr;
12356 
12357   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12358   OpenMPDirectiveKind CaptureRegion =
12359       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12360   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12361     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12362     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12363     HelperValStmt = buildPreInits(Context, Captures);
12364   }
12365 
12366   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12367                                          StartLoc, LParenLoc, EndLoc);
12368 }
12369 
12370 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12371                                               SourceLocation StartLoc,
12372                                               SourceLocation LParenLoc,
12373                                               SourceLocation EndLoc) {
12374   Expr *ValExpr = ThreadLimit;
12375   Stmt *HelperValStmt = nullptr;
12376 
12377   // OpenMP [teams Constrcut, Restrictions]
12378   // The thread_limit expression must evaluate to a positive integer value.
12379   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12380                                  /*StrictlyPositive=*/true))
12381     return nullptr;
12382 
12383   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12384   OpenMPDirectiveKind CaptureRegion =
12385       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12386   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12387     llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12388     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12389     HelperValStmt = buildPreInits(Context, Captures);
12390   }
12391 
12392   return new (Context) OMPThreadLimitClause(
12393       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
12394 }
12395 
12396 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12397                                            SourceLocation StartLoc,
12398                                            SourceLocation LParenLoc,
12399                                            SourceLocation EndLoc) {
12400   Expr *ValExpr = Priority;
12401 
12402   // OpenMP [2.9.1, task Constrcut]
12403   // The priority-value is a non-negative numerical scalar expression.
12404   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12405                                  /*StrictlyPositive=*/false))
12406     return nullptr;
12407 
12408   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12409 }
12410 
12411 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12412                                             SourceLocation StartLoc,
12413                                             SourceLocation LParenLoc,
12414                                             SourceLocation EndLoc) {
12415   Expr *ValExpr = Grainsize;
12416 
12417   // OpenMP [2.9.2, taskloop Constrcut]
12418   // The parameter of the grainsize clause must be a positive integer
12419   // expression.
12420   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12421                                  /*StrictlyPositive=*/true))
12422     return nullptr;
12423 
12424   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12425 }
12426 
12427 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12428                                            SourceLocation StartLoc,
12429                                            SourceLocation LParenLoc,
12430                                            SourceLocation EndLoc) {
12431   Expr *ValExpr = NumTasks;
12432 
12433   // OpenMP [2.9.2, taskloop Constrcut]
12434   // The parameter of the num_tasks clause must be a positive integer
12435   // expression.
12436   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12437                                  /*StrictlyPositive=*/true))
12438     return nullptr;
12439 
12440   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12441 }
12442 
12443 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12444                                        SourceLocation LParenLoc,
12445                                        SourceLocation EndLoc) {
12446   // OpenMP [2.13.2, critical construct, Description]
12447   // ... where hint-expression is an integer constant expression that evaluates
12448   // to a valid lock hint.
12449   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12450   if (HintExpr.isInvalid())
12451     return nullptr;
12452   return new (Context)
12453       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12454 }
12455 
12456 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12457     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12458     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12459     SourceLocation EndLoc) {
12460   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12461     std::string Values;
12462     Values += "'";
12463     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12464     Values += "'";
12465     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12466         << Values << getOpenMPClauseName(OMPC_dist_schedule);
12467     return nullptr;
12468   }
12469   Expr *ValExpr = ChunkSize;
12470   Stmt *HelperValStmt = nullptr;
12471   if (ChunkSize) {
12472     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12473         !ChunkSize->isInstantiationDependent() &&
12474         !ChunkSize->containsUnexpandedParameterPack()) {
12475       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12476       ExprResult Val =
12477           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12478       if (Val.isInvalid())
12479         return nullptr;
12480 
12481       ValExpr = Val.get();
12482 
12483       // OpenMP [2.7.1, Restrictions]
12484       //  chunk_size must be a loop invariant integer expression with a positive
12485       //  value.
12486       llvm::APSInt Result;
12487       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12488         if (Result.isSigned() && !Result.isStrictlyPositive()) {
12489           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12490               << "dist_schedule" << ChunkSize->getSourceRange();
12491           return nullptr;
12492         }
12493       } else if (getOpenMPCaptureRegionForClause(
12494                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12495                      OMPD_unknown &&
12496                  !CurContext->isDependentContext()) {
12497         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12498         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12499         HelperValStmt = buildPreInits(Context, Captures);
12500       }
12501     }
12502   }
12503 
12504   return new (Context)
12505       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
12506                             Kind, ValExpr, HelperValStmt);
12507 }
12508 
12509 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12510     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12511     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12512     SourceLocation KindLoc, SourceLocation EndLoc) {
12513   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
12514   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
12515     std::string Value;
12516     SourceLocation Loc;
12517     Value += "'";
12518     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12519       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12520                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
12521       Loc = MLoc;
12522     } else {
12523       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
12524                                              OMPC_DEFAULTMAP_scalar);
12525       Loc = KindLoc;
12526     }
12527     Value += "'";
12528     Diag(Loc, diag::err_omp_unexpected_clause_value)
12529         << Value << getOpenMPClauseName(OMPC_defaultmap);
12530     return nullptr;
12531   }
12532   DSAStack->setDefaultDMAToFromScalar(StartLoc);
12533 
12534   return new (Context)
12535       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12536 }
12537 
12538 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12539   DeclContext *CurLexicalContext = getCurLexicalContext();
12540   if (!CurLexicalContext->isFileContext() &&
12541       !CurLexicalContext->isExternCContext() &&
12542       !CurLexicalContext->isExternCXXContext() &&
12543       !isa<CXXRecordDecl>(CurLexicalContext) &&
12544       !isa<ClassTemplateDecl>(CurLexicalContext) &&
12545       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12546       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
12547     Diag(Loc, diag::err_omp_region_not_file_context);
12548     return false;
12549   }
12550   if (IsInOpenMPDeclareTargetContext) {
12551     Diag(Loc, diag::err_omp_enclosed_declare_target);
12552     return false;
12553   }
12554 
12555   IsInOpenMPDeclareTargetContext = true;
12556   return true;
12557 }
12558 
12559 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12560   assert(IsInOpenMPDeclareTargetContext &&
12561          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12562 
12563   IsInOpenMPDeclareTargetContext = false;
12564 }
12565 
12566 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12567                                         CXXScopeSpec &ScopeSpec,
12568                                         const DeclarationNameInfo &Id,
12569                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
12570                                         NamedDeclSetType &SameDirectiveDecls) {
12571   LookupResult Lookup(*this, Id, LookupOrdinaryName);
12572   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12573 
12574   if (Lookup.isAmbiguous())
12575     return;
12576   Lookup.suppressDiagnostics();
12577 
12578   if (!Lookup.isSingleResult()) {
12579     if (TypoCorrection Corrected =
12580             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12581                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12582                         CTK_ErrorRecovery)) {
12583       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12584                                   << Id.getName());
12585       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12586       return;
12587     }
12588 
12589     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12590     return;
12591   }
12592 
12593   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12594   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12595     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12596       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12597 
12598     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12599       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12600       ND->addAttr(A);
12601       if (ASTMutationListener *ML = Context.getASTMutationListener())
12602         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
12603       checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
12604     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12605       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12606           << Id.getName();
12607     }
12608   } else
12609     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12610 }
12611 
12612 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12613                                      Sema &SemaRef, Decl *D) {
12614   if (!D)
12615     return;
12616   Decl *LD = nullptr;
12617   if (isa<TagDecl>(D)) {
12618     LD = cast<TagDecl>(D)->getDefinition();
12619   } else if (isa<VarDecl>(D)) {
12620     LD = cast<VarDecl>(D)->getDefinition();
12621 
12622     // If this is an implicit variable that is legal and we do not need to do
12623     // anything.
12624     if (cast<VarDecl>(D)->isImplicit()) {
12625       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12626           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12627       D->addAttr(A);
12628       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12629         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12630       return;
12631     }
12632 
12633   } else if (isa<FunctionDecl>(D)) {
12634     const FunctionDecl *FD = nullptr;
12635     if (cast<FunctionDecl>(D)->hasBody(FD))
12636       LD = const_cast<FunctionDecl *>(FD);
12637 
12638     // If the definition is associated with the current declaration in the
12639     // target region (it can be e.g. a lambda) that is legal and we do not need
12640     // to do anything else.
12641     if (LD == D) {
12642       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12643           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12644       D->addAttr(A);
12645       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12646         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12647       return;
12648     }
12649   }
12650   if (!LD)
12651     LD = D;
12652   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12653       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12654     // Outlined declaration is not declared target.
12655     if (LD->isOutOfLine()) {
12656       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12657       SemaRef.Diag(SL, diag::note_used_here) << SR;
12658     } else {
12659       DeclContext *DC = LD->getDeclContext();
12660       while (DC) {
12661         if (isa<FunctionDecl>(DC) &&
12662             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12663           break;
12664         DC = DC->getParent();
12665       }
12666       if (DC)
12667         return;
12668 
12669       // Is not declared in target context.
12670       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12671       SemaRef.Diag(SL, diag::note_used_here) << SR;
12672     }
12673     // Mark decl as declared target to prevent further diagnostic.
12674     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12675         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12676     D->addAttr(A);
12677     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12678       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12679   }
12680 }
12681 
12682 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12683                                    Sema &SemaRef, DSAStackTy *Stack,
12684                                    ValueDecl *VD) {
12685   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12686     return true;
12687   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12688     return false;
12689   return true;
12690 }
12691 
12692 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
12693   if (!D || D->isInvalidDecl())
12694     return;
12695   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12696   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12697   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12698   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12699     if (DSAStack->isThreadPrivate(VD)) {
12700       Diag(SL, diag::err_omp_threadprivate_in_target);
12701       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12702       return;
12703     }
12704   }
12705   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12706     // Problem if any with var declared with incomplete type will be reported
12707     // as normal, so no need to check it here.
12708     if ((E || !VD->getType()->isIncompleteType()) &&
12709         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12710       // Mark decl as declared target to prevent further diagnostic.
12711       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
12712         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12713             Context, OMPDeclareTargetDeclAttr::MT_To);
12714         VD->addAttr(A);
12715         if (ASTMutationListener *ML = Context.getASTMutationListener())
12716           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
12717       }
12718       return;
12719     }
12720   }
12721   if (!E) {
12722     // Checking declaration inside declare target region.
12723     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12724         (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
12725       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12726           Context, OMPDeclareTargetDeclAttr::MT_To);
12727       D->addAttr(A);
12728       if (ASTMutationListener *ML = Context.getASTMutationListener())
12729         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12730     }
12731     return;
12732   }
12733   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12734 }
12735 
12736 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12737                                      SourceLocation StartLoc,
12738                                      SourceLocation LParenLoc,
12739                                      SourceLocation EndLoc) {
12740   MappableVarListInfo MVLI(VarList);
12741   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12742   if (MVLI.ProcessedVarList.empty())
12743     return nullptr;
12744 
12745   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12746                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12747                              MVLI.VarComponents);
12748 }
12749 
12750 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12751                                        SourceLocation StartLoc,
12752                                        SourceLocation LParenLoc,
12753                                        SourceLocation EndLoc) {
12754   MappableVarListInfo MVLI(VarList);
12755   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12756   if (MVLI.ProcessedVarList.empty())
12757     return nullptr;
12758 
12759   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12760                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12761                                MVLI.VarComponents);
12762 }
12763 
12764 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12765                                                SourceLocation StartLoc,
12766                                                SourceLocation LParenLoc,
12767                                                SourceLocation EndLoc) {
12768   MappableVarListInfo MVLI(VarList);
12769   SmallVector<Expr *, 8> PrivateCopies;
12770   SmallVector<Expr *, 8> Inits;
12771 
12772   for (auto &RefExpr : VarList) {
12773     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12774     SourceLocation ELoc;
12775     SourceRange ERange;
12776     Expr *SimpleRefExpr = RefExpr;
12777     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12778     if (Res.second) {
12779       // It will be analyzed later.
12780       MVLI.ProcessedVarList.push_back(RefExpr);
12781       PrivateCopies.push_back(nullptr);
12782       Inits.push_back(nullptr);
12783     }
12784     ValueDecl *D = Res.first;
12785     if (!D)
12786       continue;
12787 
12788     QualType Type = D->getType();
12789     Type = Type.getNonReferenceType().getUnqualifiedType();
12790 
12791     auto *VD = dyn_cast<VarDecl>(D);
12792 
12793     // Item should be a pointer or reference to pointer.
12794     if (!Type->isPointerType()) {
12795       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12796           << 0 << RefExpr->getSourceRange();
12797       continue;
12798     }
12799 
12800     // Build the private variable and the expression that refers to it.
12801     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12802                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
12803     if (VDPrivate->isInvalidDecl())
12804       continue;
12805 
12806     CurContext->addDecl(VDPrivate);
12807     auto VDPrivateRefExpr = buildDeclRefExpr(
12808         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12809 
12810     // Add temporary variable to initialize the private copy of the pointer.
12811     auto *VDInit =
12812         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12813     auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12814                                            RefExpr->getExprLoc());
12815     AddInitializerToDecl(VDPrivate,
12816                          DefaultLvalueConversion(VDInitRefExpr).get(),
12817                          /*DirectInit=*/false);
12818 
12819     // If required, build a capture to implement the privatization initialized
12820     // with the current list item value.
12821     DeclRefExpr *Ref = nullptr;
12822     if (!VD)
12823       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12824     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12825     PrivateCopies.push_back(VDPrivateRefExpr);
12826     Inits.push_back(VDInitRefExpr);
12827 
12828     // We need to add a data sharing attribute for this variable to make sure it
12829     // is correctly captured. A variable that shows up in a use_device_ptr has
12830     // similar properties of a first private variable.
12831     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12832 
12833     // Create a mappable component for the list item. List items in this clause
12834     // only need a component.
12835     MVLI.VarBaseDeclarations.push_back(D);
12836     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12837     MVLI.VarComponents.back().push_back(
12838         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
12839   }
12840 
12841   if (MVLI.ProcessedVarList.empty())
12842     return nullptr;
12843 
12844   return OMPUseDevicePtrClause::Create(
12845       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12846       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
12847 }
12848 
12849 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12850                                               SourceLocation StartLoc,
12851                                               SourceLocation LParenLoc,
12852                                               SourceLocation EndLoc) {
12853   MappableVarListInfo MVLI(VarList);
12854   for (auto &RefExpr : VarList) {
12855     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
12856     SourceLocation ELoc;
12857     SourceRange ERange;
12858     Expr *SimpleRefExpr = RefExpr;
12859     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12860     if (Res.second) {
12861       // It will be analyzed later.
12862       MVLI.ProcessedVarList.push_back(RefExpr);
12863     }
12864     ValueDecl *D = Res.first;
12865     if (!D)
12866       continue;
12867 
12868     QualType Type = D->getType();
12869     // item should be a pointer or array or reference to pointer or array
12870     if (!Type.getNonReferenceType()->isPointerType() &&
12871         !Type.getNonReferenceType()->isArrayType()) {
12872       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12873           << 0 << RefExpr->getSourceRange();
12874       continue;
12875     }
12876 
12877     // Check if the declaration in the clause does not show up in any data
12878     // sharing attribute.
12879     auto DVar = DSAStack->getTopDSA(D, false);
12880     if (isOpenMPPrivate(DVar.CKind)) {
12881       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12882           << getOpenMPClauseName(DVar.CKind)
12883           << getOpenMPClauseName(OMPC_is_device_ptr)
12884           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12885       ReportOriginalDSA(*this, DSAStack, D, DVar);
12886       continue;
12887     }
12888 
12889     Expr *ConflictExpr;
12890     if (DSAStack->checkMappableExprComponentListsForDecl(
12891             D, /*CurrentRegionOnly=*/true,
12892             [&ConflictExpr](
12893                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12894                 OpenMPClauseKind) -> bool {
12895               ConflictExpr = R.front().getAssociatedExpression();
12896               return true;
12897             })) {
12898       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12899       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12900           << ConflictExpr->getSourceRange();
12901       continue;
12902     }
12903 
12904     // Store the components in the stack so that they can be used to check
12905     // against other clauses later on.
12906     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12907     DSAStack->addMappableExpressionComponents(
12908         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12909 
12910     // Record the expression we've just processed.
12911     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12912 
12913     // Create a mappable component for the list item. List items in this clause
12914     // only need a component. We use a null declaration to signal fields in
12915     // 'this'.
12916     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12917             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12918            "Unexpected device pointer expression!");
12919     MVLI.VarBaseDeclarations.push_back(
12920         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12921     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12922     MVLI.VarComponents.back().push_back(MC);
12923   }
12924 
12925   if (MVLI.ProcessedVarList.empty())
12926     return nullptr;
12927 
12928   return OMPIsDevicePtrClause::Create(
12929       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12930       MVLI.VarBaseDeclarations, MVLI.VarComponents);
12931 }
12932