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/AST/TypeOrdering.h"
26 #include "clang/Basic/OpenMPKinds.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/Initialization.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaInternal.h"
34 using namespace clang;
35 
36 //===----------------------------------------------------------------------===//
37 // Stack of data-sharing attributes for variables
38 //===----------------------------------------------------------------------===//
39 
40 namespace {
41 /// \brief Default data sharing attributes, which can be applied to directive.
42 enum DefaultDataSharingAttributes {
43   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
45   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
46 };
47 
48 /// \brief Stack for tracking declarations used in OpenMP directives and
49 /// clauses and their data-sharing attributes.
50 class DSAStackTy final {
51 public:
52   struct DSAVarData final {
53     OpenMPDirectiveKind DKind = OMPD_unknown;
54     OpenMPClauseKind CKind = OMPC_unknown;
55     Expr *RefExpr = nullptr;
56     DeclRefExpr *PrivateCopy = nullptr;
57     SourceLocation ImplicitDSALoc;
58     DSAVarData() {}
59   };
60   typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61       OperatorOffsetTy;
62 
63 private:
64   struct DSAInfo final {
65     OpenMPClauseKind Attributes = OMPC_unknown;
66     /// Pointer to a reference expression and a flag which shows that the
67     /// variable is marked as lastprivate(true) or not (false).
68     llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69     DeclRefExpr *PrivateCopy = nullptr;
70   };
71   typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72   typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
73   typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74   typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
75   typedef llvm::DenseMap<
76       ValueDecl *, OMPClauseMappableExprCommon::MappableExprComponentLists>
77       MappedExprComponentsTy;
78   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
79       CriticalsWithHintsTy;
80   typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
81       DoacrossDependMapTy;
82 
83   struct SharingMapTy final {
84     DeclSAMapTy SharingMap;
85     AlignedMapTy AlignedMap;
86     MappedExprComponentsTy MappedExprComponents;
87     LoopControlVariablesMapTy LCVMap;
88     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
89     SourceLocation DefaultAttrLoc;
90     OpenMPDirectiveKind Directive = OMPD_unknown;
91     DeclarationNameInfo DirectiveName;
92     Scope *CurScope = nullptr;
93     SourceLocation ConstructLoc;
94     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
95     /// get the data (loop counters etc.) about enclosing loop-based construct.
96     /// This data is required during codegen.
97     DoacrossDependMapTy DoacrossDepends;
98     /// \brief first argument (Expr *) contains optional argument of the
99     /// 'ordered' clause, the second one is true if the regions has 'ordered'
100     /// clause, false otherwise.
101     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
102     bool NowaitRegion = false;
103     bool CancelRegion = false;
104     unsigned AssociatedLoops = 1;
105     SourceLocation InnerTeamsRegionLoc;
106     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
107                  Scope *CurScope, SourceLocation Loc)
108         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
109           ConstructLoc(Loc) {}
110     SharingMapTy() {}
111   };
112 
113   typedef SmallVector<SharingMapTy, 4> StackTy;
114 
115   /// \brief Stack of used declaration and their data-sharing attributes.
116   StackTy Stack;
117   /// \brief true, if check for DSA must be from parent directive, false, if
118   /// from current directive.
119   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
120   Sema &SemaRef;
121   bool ForceCapturing = false;
122   CriticalsWithHintsTy Criticals;
123 
124   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
125 
126   DSAVarData getDSA(StackTy::reverse_iterator& Iter, ValueDecl *D);
127 
128   /// \brief Checks if the variable is a local for OpenMP region.
129   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
130 
131 public:
132   explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
133 
134   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
135   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
136 
137   bool isForceVarCapturing() const { return ForceCapturing; }
138   void setForceVarCapturing(bool V) { ForceCapturing = V; }
139 
140   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
141             Scope *CurScope, SourceLocation Loc) {
142     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
143     Stack.back().DefaultAttrLoc = Loc;
144   }
145 
146   void pop() {
147     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
148     Stack.pop_back();
149   }
150 
151   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
152     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
153   }
154   const std::pair<OMPCriticalDirective *, llvm::APSInt>
155   getCriticalWithHint(const DeclarationNameInfo &Name) const {
156     auto I = Criticals.find(Name.getAsString());
157     if (I != Criticals.end())
158       return I->second;
159     return std::make_pair(nullptr, llvm::APSInt());
160   }
161   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
162   /// add it and return NULL; otherwise return previous occurrence's expression
163   /// for diagnostics.
164   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
165 
166   /// \brief Register specified variable as loop control variable.
167   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
168   /// \brief Check if the specified variable is a loop control variable for
169   /// current region.
170   /// \return The index of the loop control variable in the list of associated
171   /// for-loops (from outer to inner).
172   LCDeclInfo isLoopControlVariable(ValueDecl *D);
173   /// \brief Check if the specified variable is a loop control variable for
174   /// parent region.
175   /// \return The index of the loop control variable in the list of associated
176   /// for-loops (from outer to inner).
177   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
178   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
179   /// parent directive.
180   ValueDecl *getParentLoopControlVariable(unsigned I);
181 
182   /// \brief Adds explicit data sharing attribute to the specified declaration.
183   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
184               DeclRefExpr *PrivateCopy = nullptr);
185 
186   /// \brief Returns data sharing attributes from top of the stack for the
187   /// specified declaration.
188   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
189   /// \brief Returns data-sharing attributes for the specified declaration.
190   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
191   /// \brief Checks if the specified variables has data-sharing attributes which
192   /// match specified \a CPred predicate in any directive which matches \a DPred
193   /// predicate.
194   DSAVarData hasDSA(ValueDecl *D,
195                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
196                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
197                     bool FromParent);
198   /// \brief Checks if the specified variables has data-sharing attributes which
199   /// match specified \a CPred predicate in any innermost directive which
200   /// matches \a DPred predicate.
201   DSAVarData
202   hasInnermostDSA(ValueDecl *D,
203                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
204                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
205                   bool FromParent);
206   /// \brief Checks if the specified variables has explicit data-sharing
207   /// attributes which match specified \a CPred predicate at the specified
208   /// OpenMP region.
209   bool hasExplicitDSA(ValueDecl *D,
210                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
211                       unsigned Level, bool NotLastprivate = false);
212 
213   /// \brief Returns true if the directive at level \Level matches in the
214   /// specified \a DPred predicate.
215   bool hasExplicitDirective(
216       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
217       unsigned Level);
218 
219   /// \brief Finds a directive which matches specified \a DPred predicate.
220   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
221                                                   const DeclarationNameInfo &,
222                                                   SourceLocation)> &DPred,
223                     bool FromParent);
224 
225   /// \brief Returns currently analyzed directive.
226   OpenMPDirectiveKind getCurrentDirective() const {
227     return Stack.back().Directive;
228   }
229   /// \brief Returns parent directive.
230   OpenMPDirectiveKind getParentDirective() const {
231     if (Stack.size() > 2)
232       return Stack[Stack.size() - 2].Directive;
233     return OMPD_unknown;
234   }
235 
236   /// \brief Set default data sharing attribute to none.
237   void setDefaultDSANone(SourceLocation Loc) {
238     Stack.back().DefaultAttr = DSA_none;
239     Stack.back().DefaultAttrLoc = Loc;
240   }
241   /// \brief Set default data sharing attribute to shared.
242   void setDefaultDSAShared(SourceLocation Loc) {
243     Stack.back().DefaultAttr = DSA_shared;
244     Stack.back().DefaultAttrLoc = Loc;
245   }
246 
247   DefaultDataSharingAttributes getDefaultDSA() const {
248     return Stack.back().DefaultAttr;
249   }
250   SourceLocation getDefaultDSALocation() const {
251     return Stack.back().DefaultAttrLoc;
252   }
253 
254   /// \brief Checks if the specified variable is a threadprivate.
255   bool isThreadPrivate(VarDecl *D) {
256     DSAVarData DVar = getTopDSA(D, false);
257     return isOpenMPThreadPrivate(DVar.CKind);
258   }
259 
260   /// \brief Marks current region as ordered (it has an 'ordered' clause).
261   void setOrderedRegion(bool IsOrdered, Expr *Param) {
262     Stack.back().OrderedRegion.setInt(IsOrdered);
263     Stack.back().OrderedRegion.setPointer(Param);
264   }
265   /// \brief Returns true, if parent region is ordered (has associated
266   /// 'ordered' clause), false - otherwise.
267   bool isParentOrderedRegion() const {
268     if (Stack.size() > 2)
269       return Stack[Stack.size() - 2].OrderedRegion.getInt();
270     return false;
271   }
272   /// \brief Returns optional parameter for the ordered region.
273   Expr *getParentOrderedRegionParam() const {
274     if (Stack.size() > 2)
275       return Stack[Stack.size() - 2].OrderedRegion.getPointer();
276     return nullptr;
277   }
278   /// \brief Marks current region as nowait (it has a 'nowait' clause).
279   void setNowaitRegion(bool IsNowait = true) {
280     Stack.back().NowaitRegion = IsNowait;
281   }
282   /// \brief Returns true, if parent region is nowait (has associated
283   /// 'nowait' clause), false - otherwise.
284   bool isParentNowaitRegion() const {
285     if (Stack.size() > 2)
286       return Stack[Stack.size() - 2].NowaitRegion;
287     return false;
288   }
289   /// \brief Marks parent region as cancel region.
290   void setParentCancelRegion(bool Cancel = true) {
291     if (Stack.size() > 2)
292       Stack[Stack.size() - 2].CancelRegion =
293           Stack[Stack.size() - 2].CancelRegion || Cancel;
294   }
295   /// \brief Return true if current region has inner cancel construct.
296   bool isCancelRegion() const {
297     return Stack.back().CancelRegion;
298   }
299 
300   /// \brief Set collapse value for the region.
301   void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
302   /// \brief Return collapse value for region.
303   unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
304 
305   /// \brief Marks current target region as one with closely nested teams
306   /// region.
307   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
308     if (Stack.size() > 2)
309       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
310   }
311   /// \brief Returns true, if current region has closely nested teams region.
312   bool hasInnerTeamsRegion() const {
313     return getInnerTeamsRegionLoc().isValid();
314   }
315   /// \brief Returns location of the nested teams region (if any).
316   SourceLocation getInnerTeamsRegionLoc() const {
317     if (Stack.size() > 1)
318       return Stack.back().InnerTeamsRegionLoc;
319     return SourceLocation();
320   }
321 
322   Scope *getCurScope() const { return Stack.back().CurScope; }
323   Scope *getCurScope() { return Stack.back().CurScope; }
324   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
325 
326   // Do the check specified in \a Check to all component lists and return true
327   // if any issue is found.
328   bool checkMappableExprComponentListsForDecl(
329       ValueDecl *VD, bool CurrentRegionOnly,
330       const llvm::function_ref<bool(
331           OMPClauseMappableExprCommon::MappableExprComponentListRef)> &Check) {
332     auto SI = Stack.rbegin();
333     auto SE = Stack.rend();
334 
335     if (SI == SE)
336       return false;
337 
338     if (CurrentRegionOnly) {
339       SE = std::next(SI);
340     } else {
341       ++SI;
342     }
343 
344     for (; SI != SE; ++SI) {
345       auto MI = SI->MappedExprComponents.find(VD);
346       if (MI != SI->MappedExprComponents.end())
347         for (auto &L : MI->second)
348           if (Check(L))
349             return true;
350     }
351     return false;
352   }
353 
354   // Create a new mappable expression component list associated with a given
355   // declaration and initialize it with the provided list of components.
356   void addMappableExpressionComponents(
357       ValueDecl *VD,
358       OMPClauseMappableExprCommon::MappableExprComponentListRef Components) {
359     assert(Stack.size() > 1 &&
360            "Not expecting to retrieve components from a empty stack!");
361     auto &MEC = Stack.back().MappedExprComponents[VD];
362     // Create new entry and append the new components there.
363     MEC.resize(MEC.size() + 1);
364     MEC.back().append(Components.begin(), Components.end());
365   }
366 
367   unsigned getNestingLevel() const {
368     assert(Stack.size() > 1);
369     return Stack.size() - 2;
370   }
371   void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
372     assert(Stack.size() > 2);
373     assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
374     Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
375   }
376   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
377   getDoacrossDependClauses() const {
378     assert(Stack.size() > 1);
379     if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
380       auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
381       return llvm::make_range(Ref.begin(), Ref.end());
382     }
383     return llvm::make_range(Stack[0].DoacrossDepends.end(),
384                             Stack[0].DoacrossDepends.end());
385   }
386 };
387 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
388   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
389          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
390 }
391 } // namespace
392 
393 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
394   auto *VD = dyn_cast<VarDecl>(D);
395   auto *FD = dyn_cast<FieldDecl>(D);
396   if (VD  != nullptr) {
397     VD = VD->getCanonicalDecl();
398     D = VD;
399   } else {
400     assert(FD);
401     FD = FD->getCanonicalDecl();
402     D = FD;
403   }
404   return D;
405 }
406 
407 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator& Iter,
408                                           ValueDecl *D) {
409   D = getCanonicalDecl(D);
410   auto *VD = dyn_cast<VarDecl>(D);
411   auto *FD = dyn_cast<FieldDecl>(D);
412   DSAVarData DVar;
413   if (Iter == std::prev(Stack.rend())) {
414     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
415     // in a region but not in construct]
416     //  File-scope or namespace-scope variables referenced in called routines
417     //  in the region are shared unless they appear in a threadprivate
418     //  directive.
419     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
420       DVar.CKind = OMPC_shared;
421 
422     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
423     // in a region but not in construct]
424     //  Variables with static storage duration that are declared in called
425     //  routines in the region are shared.
426     if (VD && VD->hasGlobalStorage())
427       DVar.CKind = OMPC_shared;
428 
429     // Non-static data members are shared by default.
430     if (FD)
431       DVar.CKind = OMPC_shared;
432 
433     return DVar;
434   }
435 
436   DVar.DKind = Iter->Directive;
437   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
438   // in a Construct, C/C++, predetermined, p.1]
439   // Variables with automatic storage duration that are declared in a scope
440   // inside the construct are private.
441   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
442       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
443     DVar.CKind = OMPC_private;
444     return DVar;
445   }
446 
447   // Explicitly specified attributes and local variables with predetermined
448   // attributes.
449   if (Iter->SharingMap.count(D)) {
450     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
451     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
452     DVar.CKind = Iter->SharingMap[D].Attributes;
453     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
454     return DVar;
455   }
456 
457   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
458   // in a Construct, C/C++, implicitly determined, p.1]
459   //  In a parallel or task construct, the data-sharing attributes of these
460   //  variables are determined by the default clause, if present.
461   switch (Iter->DefaultAttr) {
462   case DSA_shared:
463     DVar.CKind = OMPC_shared;
464     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
465     return DVar;
466   case DSA_none:
467     return DVar;
468   case DSA_unspecified:
469     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
470     // in a Construct, implicitly determined, p.2]
471     //  In a parallel construct, if no default clause is present, these
472     //  variables are shared.
473     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
474     if (isOpenMPParallelDirective(DVar.DKind) ||
475         isOpenMPTeamsDirective(DVar.DKind)) {
476       DVar.CKind = OMPC_shared;
477       return DVar;
478     }
479 
480     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
481     // in a Construct, implicitly determined, p.4]
482     //  In a task construct, if no default clause is present, a variable that in
483     //  the enclosing context is determined to be shared by all implicit tasks
484     //  bound to the current team is shared.
485     if (isOpenMPTaskingDirective(DVar.DKind)) {
486       DSAVarData DVarTemp;
487       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
488            I != EE; ++I) {
489         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
490         // Referenced in a Construct, implicitly determined, p.6]
491         //  In a task construct, if no default clause is present, a variable
492         //  whose data-sharing attribute is not determined by the rules above is
493         //  firstprivate.
494         DVarTemp = getDSA(I, D);
495         if (DVarTemp.CKind != OMPC_shared) {
496           DVar.RefExpr = nullptr;
497           DVar.CKind = OMPC_firstprivate;
498           return DVar;
499         }
500         if (isParallelOrTaskRegion(I->Directive))
501           break;
502       }
503       DVar.CKind =
504           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
505       return DVar;
506     }
507   }
508   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
509   // in a Construct, implicitly determined, p.3]
510   //  For constructs other than task, if no default clause is present, these
511   //  variables inherit their data-sharing attributes from the enclosing
512   //  context.
513   return getDSA(++Iter, D);
514 }
515 
516 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
517   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
518   D = getCanonicalDecl(D);
519   auto It = Stack.back().AlignedMap.find(D);
520   if (It == Stack.back().AlignedMap.end()) {
521     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
522     Stack.back().AlignedMap[D] = NewDE;
523     return nullptr;
524   } else {
525     assert(It->second && "Unexpected nullptr expr in the aligned map");
526     return It->second;
527   }
528   return nullptr;
529 }
530 
531 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
532   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
533   D = getCanonicalDecl(D);
534   Stack.back().LCVMap.insert(
535       std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
536 }
537 
538 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
539   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
540   D = getCanonicalDecl(D);
541   return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
542                                           : LCDeclInfo(0, nullptr);
543 }
544 
545 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
546   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
547   D = getCanonicalDecl(D);
548   return Stack[Stack.size() - 2].LCVMap.count(D) > 0
549              ? Stack[Stack.size() - 2].LCVMap[D]
550              : LCDeclInfo(0, nullptr);
551 }
552 
553 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
554   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
555   if (Stack[Stack.size() - 2].LCVMap.size() < I)
556     return nullptr;
557   for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
558     if (Pair.second.first == I)
559       return Pair.first;
560   }
561   return nullptr;
562 }
563 
564 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
565                         DeclRefExpr *PrivateCopy) {
566   D = getCanonicalDecl(D);
567   if (A == OMPC_threadprivate) {
568     auto &Data = Stack[0].SharingMap[D];
569     Data.Attributes = A;
570     Data.RefExpr.setPointer(E);
571     Data.PrivateCopy = nullptr;
572   } else {
573     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
574     auto &Data = Stack.back().SharingMap[D];
575     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
576            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
577            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
578            (isLoopControlVariable(D).first && A == OMPC_private));
579     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
580       Data.RefExpr.setInt(/*IntVal=*/true);
581       return;
582     }
583     const bool IsLastprivate =
584         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
585     Data.Attributes = A;
586     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
587     Data.PrivateCopy = PrivateCopy;
588     if (PrivateCopy) {
589       auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
590       Data.Attributes = A;
591       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
592       Data.PrivateCopy = nullptr;
593     }
594   }
595 }
596 
597 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
598   D = D->getCanonicalDecl();
599   if (Stack.size() > 2) {
600     reverse_iterator I = Iter, E = std::prev(Stack.rend());
601     Scope *TopScope = nullptr;
602     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
603       ++I;
604     }
605     if (I == E)
606       return false;
607     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
608     Scope *CurScope = getCurScope();
609     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
610       CurScope = CurScope->getParent();
611     }
612     return CurScope != TopScope;
613   }
614   return false;
615 }
616 
617 /// \brief Build a variable declaration for OpenMP loop iteration variable.
618 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
619                              StringRef Name, const AttrVec *Attrs = nullptr) {
620   DeclContext *DC = SemaRef.CurContext;
621   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
622   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
623   VarDecl *Decl =
624       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
625   if (Attrs) {
626     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
627          I != E; ++I)
628       Decl->addAttr(*I);
629   }
630   Decl->setImplicit();
631   return Decl;
632 }
633 
634 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
635                                      SourceLocation Loc,
636                                      bool RefersToCapture = false) {
637   D->setReferenced();
638   D->markUsed(S.Context);
639   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
640                              SourceLocation(), D, RefersToCapture, Loc, Ty,
641                              VK_LValue);
642 }
643 
644 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
645   D = getCanonicalDecl(D);
646   DSAVarData DVar;
647 
648   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
649   // in a Construct, C/C++, predetermined, p.1]
650   //  Variables appearing in threadprivate directives are threadprivate.
651   auto *VD = dyn_cast<VarDecl>(D);
652   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
653        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
654          SemaRef.getLangOpts().OpenMPUseTLS &&
655          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
656       (VD && VD->getStorageClass() == SC_Register &&
657        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
658     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
659                                D->getLocation()),
660            OMPC_threadprivate);
661   }
662   if (Stack[0].SharingMap.count(D)) {
663     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
664     DVar.CKind = OMPC_threadprivate;
665     return DVar;
666   }
667 
668   if (Stack.size() == 1) {
669     // Not in OpenMP execution region and top scope was already checked.
670     return DVar;
671   }
672 
673   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
674   // in a Construct, C/C++, predetermined, p.4]
675   //  Static data members are shared.
676   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
677   // in a Construct, C/C++, predetermined, p.7]
678   //  Variables with static storage duration that are declared in a scope
679   //  inside the construct are shared.
680   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
681   if (VD && VD->isStaticDataMember()) {
682     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
683     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
684       return DVar;
685 
686     DVar.CKind = OMPC_shared;
687     return DVar;
688   }
689 
690   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
691   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
692   Type = SemaRef.getASTContext().getBaseElementType(Type);
693   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
694   // in a Construct, C/C++, predetermined, p.6]
695   //  Variables with const qualified type having no mutable member are
696   //  shared.
697   CXXRecordDecl *RD =
698       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
699   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
700     if (auto *CTD = CTSD->getSpecializedTemplate())
701       RD = CTD->getTemplatedDecl();
702   if (IsConstant &&
703       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
704         RD->hasMutableFields())) {
705     // Variables with const-qualified type having no mutable member may be
706     // listed in a firstprivate clause, even if they are static data members.
707     DSAVarData DVarTemp = hasDSA(
708         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
709         MatchesAlways, FromParent);
710     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
711       return DVar;
712 
713     DVar.CKind = OMPC_shared;
714     return DVar;
715   }
716 
717   // Explicitly specified attributes and local variables with predetermined
718   // attributes.
719   auto StartI = std::next(Stack.rbegin());
720   auto EndI = std::prev(Stack.rend());
721   if (FromParent && StartI != EndI) {
722     StartI = std::next(StartI);
723   }
724   auto I = std::prev(StartI);
725   if (I->SharingMap.count(D)) {
726     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
727     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
728     DVar.CKind = I->SharingMap[D].Attributes;
729     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
730   }
731 
732   return DVar;
733 }
734 
735 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
736                                                   bool FromParent) {
737   D = getCanonicalDecl(D);
738   auto StartI = Stack.rbegin();
739   auto EndI = std::prev(Stack.rend());
740   if (FromParent && StartI != EndI) {
741     StartI = std::next(StartI);
742   }
743   return getDSA(StartI, D);
744 }
745 
746 DSAStackTy::DSAVarData
747 DSAStackTy::hasDSA(ValueDecl *D,
748                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
749                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
750                    bool FromParent) {
751   D = getCanonicalDecl(D);
752   auto StartI = std::next(Stack.rbegin());
753   auto EndI = Stack.rend();
754   if (FromParent && StartI != EndI) {
755     StartI = std::next(StartI);
756   }
757   for (auto I = StartI, EE = EndI; I != EE; ++I) {
758     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
759       continue;
760     DSAVarData DVar = getDSA(I, D);
761     if (CPred(DVar.CKind))
762       return DVar;
763   }
764   return DSAVarData();
765 }
766 
767 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
768     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
769     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
770     bool FromParent) {
771   D = getCanonicalDecl(D);
772   auto StartI = std::next(Stack.rbegin());
773   auto EndI = Stack.rend();
774   if (FromParent && StartI != EndI) {
775     StartI = std::next(StartI);
776   }
777   for (auto I = StartI, EE = EndI; I != EE; ++I) {
778     if (!DPred(I->Directive))
779       break;
780     DSAVarData DVar = getDSA(I, D);
781     if (CPred(DVar.CKind))
782       return DVar;
783     return DSAVarData();
784   }
785   return DSAVarData();
786 }
787 
788 bool DSAStackTy::hasExplicitDSA(
789     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
790     unsigned Level, bool NotLastprivate) {
791   if (CPred(ClauseKindMode))
792     return true;
793   D = getCanonicalDecl(D);
794   auto StartI = std::next(Stack.begin());
795   auto EndI = Stack.end();
796   if (std::distance(StartI, EndI) <= (int)Level)
797     return false;
798   std::advance(StartI, Level);
799   return (StartI->SharingMap.count(D) > 0) &&
800          StartI->SharingMap[D].RefExpr.getPointer() &&
801          CPred(StartI->SharingMap[D].Attributes) &&
802          (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
803 }
804 
805 bool DSAStackTy::hasExplicitDirective(
806     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807     unsigned Level) {
808   auto StartI = std::next(Stack.begin());
809   auto EndI = Stack.end();
810   if (std::distance(StartI, EndI) <= (int)Level)
811     return false;
812   std::advance(StartI, Level);
813   return DPred(StartI->Directive);
814 }
815 
816 bool DSAStackTy::hasDirective(
817     const llvm::function_ref<bool(OpenMPDirectiveKind,
818                                   const DeclarationNameInfo &, SourceLocation)>
819         &DPred,
820     bool FromParent) {
821   // We look only in the enclosing region.
822   if (Stack.size() < 2)
823     return false;
824   auto StartI = std::next(Stack.rbegin());
825   auto EndI = std::prev(Stack.rend());
826   if (FromParent && StartI != EndI) {
827     StartI = std::next(StartI);
828   }
829   for (auto I = StartI, EE = EndI; I != EE; ++I) {
830     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831       return true;
832   }
833   return false;
834 }
835 
836 void Sema::InitDataSharingAttributesStack() {
837   VarDataSharingAttributesStack = new DSAStackTy(*this);
838 }
839 
840 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841 
842 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
843   assert(LangOpts.OpenMP && "OpenMP is not allowed");
844 
845   auto &Ctx = getASTContext();
846   bool IsByRef = true;
847 
848   // Find the directive that is associated with the provided scope.
849   auto Ty = D->getType();
850 
851   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
852     // This table summarizes how a given variable should be passed to the device
853     // given its type and the clauses where it appears. This table is based on
854     // the description in OpenMP 4.5 [2.10.4, target Construct] and
855     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856     //
857     // =========================================================================
858     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
859     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
860     // =========================================================================
861     // | scl  |               |     |       |       -       |          | bycopy|
862     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
863     // | scl  |               |  x  |   -   |       -       |     -    | null  |
864     // | scl  |       x       |     |       |       -       |          | byref |
865     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
866     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
867     // | scl  |               |  -  |   -   |       -       |     x    | byref |
868     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
869     //
870     // | agg  |      n.a.     |     |       |       -       |          | byref |
871     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
872     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
873     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
874     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
875     //
876     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
877     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
878     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
879     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
880     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
881     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
882     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
883     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
884     // =========================================================================
885     // Legend:
886     //  scl - scalar
887     //  ptr - pointer
888     //  agg - aggregate
889     //  x - applies
890     //  - - invalid in this combination
891     //  [] - mapped with an array section
892     //  byref - should be mapped by reference
893     //  byval - should be mapped by value
894     //  null - initialize a local variable to null on the device
895     //
896     // Observations:
897     //  - All scalar declarations that show up in a map clause have to be passed
898     //    by reference, because they may have been mapped in the enclosing data
899     //    environment.
900     //  - If the scalar value does not fit the size of uintptr, it has to be
901     //    passed by reference, regardless the result in the table above.
902     //  - For pointers mapped by value that have either an implicit map or an
903     //    array section, the runtime library may pass the NULL value to the
904     //    device instead of the value passed to it by the compiler.
905 
906 
907     if (Ty->isReferenceType())
908       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
909 
910     // Locate map clauses and see if the variable being captured is referred to
911     // in any of those clauses. Here we only care about variables, not fields,
912     // because fields are part of aggregates.
913     bool IsVariableUsedInMapClause = false;
914     bool IsVariableAssociatedWithSection = false;
915 
916     DSAStack->checkMappableExprComponentListsForDecl(
917         D, /*CurrentRegionOnly=*/true,
918         [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
919                 MapExprComponents) {
920 
921           auto EI = MapExprComponents.rbegin();
922           auto EE = MapExprComponents.rend();
923 
924           assert(EI != EE && "Invalid map expression!");
925 
926           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
927             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
928 
929           ++EI;
930           if (EI == EE)
931             return false;
932 
933           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
934               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
935               isa<MemberExpr>(EI->getAssociatedExpression())) {
936             IsVariableAssociatedWithSection = true;
937             // There is nothing more we need to know about this variable.
938             return true;
939           }
940 
941           // Keep looking for more map info.
942           return false;
943         });
944 
945     if (IsVariableUsedInMapClause) {
946       // If variable is identified in a map clause it is always captured by
947       // reference except if it is a pointer that is dereferenced somehow.
948       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
949     } else {
950       // By default, all the data that has a scalar type is mapped by copy.
951       IsByRef = !Ty->isScalarType();
952     }
953   }
954 
955   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
956     IsByRef = !DSAStack->hasExplicitDSA(
957         D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
958         Level, /*NotLastprivate=*/true);
959   }
960 
961   // When passing data by copy, we need to make sure it fits the uintptr size
962   // and alignment, because the runtime library only deals with uintptr types.
963   // If it does not fit the uintptr size, we need to pass the data by reference
964   // instead.
965   if (!IsByRef &&
966       (Ctx.getTypeSizeInChars(Ty) >
967            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
968        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
969     IsByRef = true;
970   }
971 
972   return IsByRef;
973 }
974 
975 unsigned Sema::getOpenMPNestingLevel() const {
976   assert(getLangOpts().OpenMP);
977   return DSAStack->getNestingLevel();
978 }
979 
980 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
981   assert(LangOpts.OpenMP && "OpenMP is not allowed");
982   D = getCanonicalDecl(D);
983 
984   // If we are attempting to capture a global variable in a directive with
985   // 'target' we return true so that this global is also mapped to the device.
986   //
987   // FIXME: If the declaration is enclosed in a 'declare target' directive,
988   // then it should not be captured. Therefore, an extra check has to be
989   // inserted here once support for 'declare target' is added.
990   //
991   auto *VD = dyn_cast<VarDecl>(D);
992   if (VD && !VD->hasLocalStorage()) {
993     if (DSAStack->getCurrentDirective() == OMPD_target &&
994         !DSAStack->isClauseParsingMode())
995       return VD;
996     if (DSAStack->hasDirective(
997             [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
998                SourceLocation) -> bool {
999               return isOpenMPTargetExecutionDirective(K);
1000             },
1001             false))
1002       return VD;
1003   }
1004 
1005   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1006       (!DSAStack->isClauseParsingMode() ||
1007        DSAStack->getParentDirective() != OMPD_unknown)) {
1008     auto &&Info = DSAStack->isLoopControlVariable(D);
1009     if (Info.first ||
1010         (VD && VD->hasLocalStorage() &&
1011          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1012         (VD && DSAStack->isForceVarCapturing()))
1013       return VD ? VD : Info.second;
1014     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1015     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1016       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1017     DVarPrivate = DSAStack->hasDSA(
1018         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1019         DSAStack->isClauseParsingMode());
1020     if (DVarPrivate.CKind != OMPC_unknown)
1021       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1022   }
1023   return nullptr;
1024 }
1025 
1026 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1027   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1028   return DSAStack->hasExplicitDSA(
1029       D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1030 }
1031 
1032 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1033   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1034   // Return true if the current level is no longer enclosed in a target region.
1035 
1036   auto *VD = dyn_cast<VarDecl>(D);
1037   return VD && !VD->hasLocalStorage() &&
1038          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1039                                         Level);
1040 }
1041 
1042 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1043 
1044 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1045                                const DeclarationNameInfo &DirName,
1046                                Scope *CurScope, SourceLocation Loc) {
1047   DSAStack->push(DKind, DirName, CurScope, Loc);
1048   PushExpressionEvaluationContext(PotentiallyEvaluated);
1049 }
1050 
1051 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1052   DSAStack->setClauseParsingMode(K);
1053 }
1054 
1055 void Sema::EndOpenMPClause() {
1056   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1057 }
1058 
1059 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1060   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1061   //  A variable of class type (or array thereof) that appears in a lastprivate
1062   //  clause requires an accessible, unambiguous default constructor for the
1063   //  class type, unless the list item is also specified in a firstprivate
1064   //  clause.
1065   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1066     for (auto *C : D->clauses()) {
1067       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1068         SmallVector<Expr *, 8> PrivateCopies;
1069         for (auto *DE : Clause->varlists()) {
1070           if (DE->isValueDependent() || DE->isTypeDependent()) {
1071             PrivateCopies.push_back(nullptr);
1072             continue;
1073           }
1074           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1075           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1076           QualType Type = VD->getType().getNonReferenceType();
1077           auto DVar = DSAStack->getTopDSA(VD, false);
1078           if (DVar.CKind == OMPC_lastprivate) {
1079             // Generate helper private variable and initialize it with the
1080             // default value. The address of the original variable is replaced
1081             // by the address of the new private variable in CodeGen. This new
1082             // variable is not added to IdResolver, so the code in the OpenMP
1083             // region uses original variable for proper diagnostics.
1084             auto *VDPrivate = buildVarDecl(
1085                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1086                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1087             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1088             if (VDPrivate->isInvalidDecl())
1089               continue;
1090             PrivateCopies.push_back(buildDeclRefExpr(
1091                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1092           } else {
1093             // The variable is also a firstprivate, so initialization sequence
1094             // for private copy is generated already.
1095             PrivateCopies.push_back(nullptr);
1096           }
1097         }
1098         // Set initializers to private copies if no errors were found.
1099         if (PrivateCopies.size() == Clause->varlist_size())
1100           Clause->setPrivateCopies(PrivateCopies);
1101       }
1102     }
1103   }
1104 
1105   DSAStack->pop();
1106   DiscardCleanupsInEvaluationContext();
1107   PopExpressionEvaluationContext();
1108 }
1109 
1110 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1111                                      Expr *NumIterations, Sema &SemaRef,
1112                                      Scope *S, DSAStackTy *Stack);
1113 
1114 namespace {
1115 
1116 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1117 private:
1118   Sema &SemaRef;
1119 
1120 public:
1121   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1122   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1123     NamedDecl *ND = Candidate.getCorrectionDecl();
1124     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
1125       return VD->hasGlobalStorage() &&
1126              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1127                                    SemaRef.getCurScope());
1128     }
1129     return false;
1130   }
1131 };
1132 
1133 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1134 private:
1135   Sema &SemaRef;
1136 
1137 public:
1138   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1139   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1140     NamedDecl *ND = Candidate.getCorrectionDecl();
1141     if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1142       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1143                                    SemaRef.getCurScope());
1144     }
1145     return false;
1146   }
1147 };
1148 
1149 } // namespace
1150 
1151 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1152                                          CXXScopeSpec &ScopeSpec,
1153                                          const DeclarationNameInfo &Id) {
1154   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1155   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1156 
1157   if (Lookup.isAmbiguous())
1158     return ExprError();
1159 
1160   VarDecl *VD;
1161   if (!Lookup.isSingleResult()) {
1162     if (TypoCorrection Corrected = CorrectTypo(
1163             Id, LookupOrdinaryName, CurScope, nullptr,
1164             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1165       diagnoseTypo(Corrected,
1166                    PDiag(Lookup.empty()
1167                              ? diag::err_undeclared_var_use_suggest
1168                              : diag::err_omp_expected_var_arg_suggest)
1169                        << Id.getName());
1170       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1171     } else {
1172       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1173                                        : diag::err_omp_expected_var_arg)
1174           << Id.getName();
1175       return ExprError();
1176     }
1177   } else {
1178     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1179       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1180       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1181       return ExprError();
1182     }
1183   }
1184   Lookup.suppressDiagnostics();
1185 
1186   // OpenMP [2.9.2, Syntax, C/C++]
1187   //   Variables must be file-scope, namespace-scope, or static block-scope.
1188   if (!VD->hasGlobalStorage()) {
1189     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1190         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1191     bool IsDecl =
1192         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1193     Diag(VD->getLocation(),
1194          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1195         << VD;
1196     return ExprError();
1197   }
1198 
1199   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1200   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1201   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1202   //   A threadprivate directive for file-scope variables must appear outside
1203   //   any definition or declaration.
1204   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1205       !getCurLexicalContext()->isTranslationUnit()) {
1206     Diag(Id.getLoc(), diag::err_omp_var_scope)
1207         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1208     bool IsDecl =
1209         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1210     Diag(VD->getLocation(),
1211          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1212         << VD;
1213     return ExprError();
1214   }
1215   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1216   //   A threadprivate directive for static class member variables must appear
1217   //   in the class definition, in the same scope in which the member
1218   //   variables are declared.
1219   if (CanonicalVD->isStaticDataMember() &&
1220       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1221     Diag(Id.getLoc(), diag::err_omp_var_scope)
1222         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1223     bool IsDecl =
1224         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1225     Diag(VD->getLocation(),
1226          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1227         << VD;
1228     return ExprError();
1229   }
1230   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1231   //   A threadprivate directive for namespace-scope variables must appear
1232   //   outside any definition or declaration other than the namespace
1233   //   definition itself.
1234   if (CanonicalVD->getDeclContext()->isNamespace() &&
1235       (!getCurLexicalContext()->isFileContext() ||
1236        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1237     Diag(Id.getLoc(), diag::err_omp_var_scope)
1238         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1239     bool IsDecl =
1240         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1241     Diag(VD->getLocation(),
1242          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1243         << VD;
1244     return ExprError();
1245   }
1246   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1247   //   A threadprivate directive for static block-scope variables must appear
1248   //   in the scope of the variable and not in a nested scope.
1249   if (CanonicalVD->isStaticLocal() && CurScope &&
1250       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1251     Diag(Id.getLoc(), diag::err_omp_var_scope)
1252         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1253     bool IsDecl =
1254         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1255     Diag(VD->getLocation(),
1256          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1257         << VD;
1258     return ExprError();
1259   }
1260 
1261   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1262   //   A threadprivate directive must lexically precede all references to any
1263   //   of the variables in its list.
1264   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1265     Diag(Id.getLoc(), diag::err_omp_var_used)
1266         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1267     return ExprError();
1268   }
1269 
1270   QualType ExprType = VD->getType().getNonReferenceType();
1271   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1272                              SourceLocation(), VD,
1273                              /*RefersToEnclosingVariableOrCapture=*/false,
1274                              Id.getLoc(), ExprType, VK_LValue);
1275 }
1276 
1277 Sema::DeclGroupPtrTy
1278 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1279                                         ArrayRef<Expr *> VarList) {
1280   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1281     CurContext->addDecl(D);
1282     return DeclGroupPtrTy::make(DeclGroupRef(D));
1283   }
1284   return nullptr;
1285 }
1286 
1287 namespace {
1288 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1289   Sema &SemaRef;
1290 
1291 public:
1292   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1293     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1294       if (VD->hasLocalStorage()) {
1295         SemaRef.Diag(E->getLocStart(),
1296                      diag::err_omp_local_var_in_threadprivate_init)
1297             << E->getSourceRange();
1298         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1299             << VD << VD->getSourceRange();
1300         return true;
1301       }
1302     }
1303     return false;
1304   }
1305   bool VisitStmt(const Stmt *S) {
1306     for (auto Child : S->children()) {
1307       if (Child && Visit(Child))
1308         return true;
1309     }
1310     return false;
1311   }
1312   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1313 };
1314 } // namespace
1315 
1316 OMPThreadPrivateDecl *
1317 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1318   SmallVector<Expr *, 8> Vars;
1319   for (auto &RefExpr : VarList) {
1320     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1321     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1322     SourceLocation ILoc = DE->getExprLoc();
1323 
1324     // Mark variable as used.
1325     VD->setReferenced();
1326     VD->markUsed(Context);
1327 
1328     QualType QType = VD->getType();
1329     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1330       // It will be analyzed later.
1331       Vars.push_back(DE);
1332       continue;
1333     }
1334 
1335     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1336     //   A threadprivate variable must not have an incomplete type.
1337     if (RequireCompleteType(ILoc, VD->getType(),
1338                             diag::err_omp_threadprivate_incomplete_type)) {
1339       continue;
1340     }
1341 
1342     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1343     //   A threadprivate variable must not have a reference type.
1344     if (VD->getType()->isReferenceType()) {
1345       Diag(ILoc, diag::err_omp_ref_type_arg)
1346           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1347       bool IsDecl =
1348           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1349       Diag(VD->getLocation(),
1350            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1351           << VD;
1352       continue;
1353     }
1354 
1355     // Check if this is a TLS variable. If TLS is not being supported, produce
1356     // the corresponding diagnostic.
1357     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1358          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1359            getLangOpts().OpenMPUseTLS &&
1360            getASTContext().getTargetInfo().isTLSSupported())) ||
1361         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1362          !VD->isLocalVarDecl())) {
1363       Diag(ILoc, diag::err_omp_var_thread_local)
1364           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1365       bool IsDecl =
1366           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1367       Diag(VD->getLocation(),
1368            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1369           << VD;
1370       continue;
1371     }
1372 
1373     // Check if initial value of threadprivate variable reference variable with
1374     // local storage (it is not supported by runtime).
1375     if (auto Init = VD->getAnyInitializer()) {
1376       LocalVarRefChecker Checker(*this);
1377       if (Checker.Visit(Init))
1378         continue;
1379     }
1380 
1381     Vars.push_back(RefExpr);
1382     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1383     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1384         Context, SourceRange(Loc, Loc)));
1385     if (auto *ML = Context.getASTMutationListener())
1386       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1387   }
1388   OMPThreadPrivateDecl *D = nullptr;
1389   if (!Vars.empty()) {
1390     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1391                                      Vars);
1392     D->setAccess(AS_public);
1393   }
1394   return D;
1395 }
1396 
1397 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1398                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1399                               bool IsLoopIterVar = false) {
1400   if (DVar.RefExpr) {
1401     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1402         << getOpenMPClauseName(DVar.CKind);
1403     return;
1404   }
1405   enum {
1406     PDSA_StaticMemberShared,
1407     PDSA_StaticLocalVarShared,
1408     PDSA_LoopIterVarPrivate,
1409     PDSA_LoopIterVarLinear,
1410     PDSA_LoopIterVarLastprivate,
1411     PDSA_ConstVarShared,
1412     PDSA_GlobalVarShared,
1413     PDSA_TaskVarFirstprivate,
1414     PDSA_LocalVarPrivate,
1415     PDSA_Implicit
1416   } Reason = PDSA_Implicit;
1417   bool ReportHint = false;
1418   auto ReportLoc = D->getLocation();
1419   auto *VD = dyn_cast<VarDecl>(D);
1420   if (IsLoopIterVar) {
1421     if (DVar.CKind == OMPC_private)
1422       Reason = PDSA_LoopIterVarPrivate;
1423     else if (DVar.CKind == OMPC_lastprivate)
1424       Reason = PDSA_LoopIterVarLastprivate;
1425     else
1426       Reason = PDSA_LoopIterVarLinear;
1427   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1428              DVar.CKind == OMPC_firstprivate) {
1429     Reason = PDSA_TaskVarFirstprivate;
1430     ReportLoc = DVar.ImplicitDSALoc;
1431   } else if (VD && VD->isStaticLocal())
1432     Reason = PDSA_StaticLocalVarShared;
1433   else if (VD && VD->isStaticDataMember())
1434     Reason = PDSA_StaticMemberShared;
1435   else if (VD && VD->isFileVarDecl())
1436     Reason = PDSA_GlobalVarShared;
1437   else if (D->getType().isConstant(SemaRef.getASTContext()))
1438     Reason = PDSA_ConstVarShared;
1439   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1440     ReportHint = true;
1441     Reason = PDSA_LocalVarPrivate;
1442   }
1443   if (Reason != PDSA_Implicit) {
1444     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1445         << Reason << ReportHint
1446         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1447   } else if (DVar.ImplicitDSALoc.isValid()) {
1448     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1449         << getOpenMPClauseName(DVar.CKind);
1450   }
1451 }
1452 
1453 namespace {
1454 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1455   DSAStackTy *Stack;
1456   Sema &SemaRef;
1457   bool ErrorFound;
1458   CapturedStmt *CS;
1459   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1460   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1461 
1462 public:
1463   void VisitDeclRefExpr(DeclRefExpr *E) {
1464     if (E->isTypeDependent() || E->isValueDependent() ||
1465         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1466       return;
1467     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1468       // Skip internally declared variables.
1469       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1470         return;
1471 
1472       auto DVar = Stack->getTopDSA(VD, false);
1473       // Check if the variable has explicit DSA set and stop analysis if it so.
1474       if (DVar.RefExpr) return;
1475 
1476       auto ELoc = E->getExprLoc();
1477       auto DKind = Stack->getCurrentDirective();
1478       // The default(none) clause requires that each variable that is referenced
1479       // in the construct, and does not have a predetermined data-sharing
1480       // attribute, must have its data-sharing attribute explicitly determined
1481       // by being listed in a data-sharing attribute clause.
1482       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1483           isParallelOrTaskRegion(DKind) &&
1484           VarsWithInheritedDSA.count(VD) == 0) {
1485         VarsWithInheritedDSA[VD] = E;
1486         return;
1487       }
1488 
1489       // OpenMP [2.9.3.6, Restrictions, p.2]
1490       //  A list item that appears in a reduction clause of the innermost
1491       //  enclosing worksharing or parallel construct may not be accessed in an
1492       //  explicit task.
1493       DVar = Stack->hasInnermostDSA(
1494           VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1495           [](OpenMPDirectiveKind K) -> bool {
1496             return isOpenMPParallelDirective(K) ||
1497                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1498           },
1499           false);
1500       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1501         ErrorFound = true;
1502         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1503         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1504         return;
1505       }
1506 
1507       // Define implicit data-sharing attributes for task.
1508       DVar = Stack->getImplicitDSA(VD, false);
1509       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1510           !Stack->isLoopControlVariable(VD).first)
1511         ImplicitFirstprivate.push_back(E);
1512     }
1513   }
1514   void VisitMemberExpr(MemberExpr *E) {
1515     if (E->isTypeDependent() || E->isValueDependent() ||
1516         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1517       return;
1518     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1519       if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1520         auto DVar = Stack->getTopDSA(FD, false);
1521         // Check if the variable has explicit DSA set and stop analysis if it
1522         // so.
1523         if (DVar.RefExpr)
1524           return;
1525 
1526         auto ELoc = E->getExprLoc();
1527         auto DKind = Stack->getCurrentDirective();
1528         // OpenMP [2.9.3.6, Restrictions, p.2]
1529         //  A list item that appears in a reduction clause of the innermost
1530         //  enclosing worksharing or parallel construct may not be accessed in
1531         //  an  explicit task.
1532         DVar = Stack->hasInnermostDSA(
1533             FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1534             [](OpenMPDirectiveKind K) -> bool {
1535               return isOpenMPParallelDirective(K) ||
1536                      isOpenMPWorksharingDirective(K) ||
1537                      isOpenMPTeamsDirective(K);
1538             },
1539             false);
1540         if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1541           ErrorFound = true;
1542           SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1543           ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1544           return;
1545         }
1546 
1547         // Define implicit data-sharing attributes for task.
1548         DVar = Stack->getImplicitDSA(FD, false);
1549         if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1550             !Stack->isLoopControlVariable(FD).first)
1551           ImplicitFirstprivate.push_back(E);
1552       }
1553     }
1554   }
1555   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1556     for (auto *C : S->clauses()) {
1557       // Skip analysis of arguments of implicitly defined firstprivate clause
1558       // for task directives.
1559       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1560         for (auto *CC : C->children()) {
1561           if (CC)
1562             Visit(CC);
1563         }
1564     }
1565   }
1566   void VisitStmt(Stmt *S) {
1567     for (auto *C : S->children()) {
1568       if (C && !isa<OMPExecutableDirective>(C))
1569         Visit(C);
1570     }
1571   }
1572 
1573   bool isErrorFound() { return ErrorFound; }
1574   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1575   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1576     return VarsWithInheritedDSA;
1577   }
1578 
1579   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1580       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1581 };
1582 } // namespace
1583 
1584 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1585   switch (DKind) {
1586   case OMPD_parallel: {
1587     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1588     QualType KmpInt32PtrTy =
1589         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1590     Sema::CapturedParamNameType Params[] = {
1591         std::make_pair(".global_tid.", KmpInt32PtrTy),
1592         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1593         std::make_pair(StringRef(), QualType()) // __context with shared vars
1594     };
1595     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1596                              Params);
1597     break;
1598   }
1599   case OMPD_simd: {
1600     Sema::CapturedParamNameType Params[] = {
1601         std::make_pair(StringRef(), QualType()) // __context with shared vars
1602     };
1603     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1604                              Params);
1605     break;
1606   }
1607   case OMPD_for: {
1608     Sema::CapturedParamNameType Params[] = {
1609         std::make_pair(StringRef(), QualType()) // __context with shared vars
1610     };
1611     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1612                              Params);
1613     break;
1614   }
1615   case OMPD_for_simd: {
1616     Sema::CapturedParamNameType Params[] = {
1617         std::make_pair(StringRef(), QualType()) // __context with shared vars
1618     };
1619     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1620                              Params);
1621     break;
1622   }
1623   case OMPD_sections: {
1624     Sema::CapturedParamNameType Params[] = {
1625         std::make_pair(StringRef(), QualType()) // __context with shared vars
1626     };
1627     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1628                              Params);
1629     break;
1630   }
1631   case OMPD_section: {
1632     Sema::CapturedParamNameType Params[] = {
1633         std::make_pair(StringRef(), QualType()) // __context with shared vars
1634     };
1635     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1636                              Params);
1637     break;
1638   }
1639   case OMPD_single: {
1640     Sema::CapturedParamNameType Params[] = {
1641         std::make_pair(StringRef(), QualType()) // __context with shared vars
1642     };
1643     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1644                              Params);
1645     break;
1646   }
1647   case OMPD_master: {
1648     Sema::CapturedParamNameType Params[] = {
1649         std::make_pair(StringRef(), QualType()) // __context with shared vars
1650     };
1651     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652                              Params);
1653     break;
1654   }
1655   case OMPD_critical: {
1656     Sema::CapturedParamNameType Params[] = {
1657         std::make_pair(StringRef(), QualType()) // __context with shared vars
1658     };
1659     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1660                              Params);
1661     break;
1662   }
1663   case OMPD_parallel_for: {
1664     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1665     QualType KmpInt32PtrTy =
1666         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1667     Sema::CapturedParamNameType Params[] = {
1668         std::make_pair(".global_tid.", KmpInt32PtrTy),
1669         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1670         std::make_pair(StringRef(), QualType()) // __context with shared vars
1671     };
1672     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1673                              Params);
1674     break;
1675   }
1676   case OMPD_parallel_for_simd: {
1677     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1678     QualType KmpInt32PtrTy =
1679         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1680     Sema::CapturedParamNameType Params[] = {
1681         std::make_pair(".global_tid.", KmpInt32PtrTy),
1682         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1683         std::make_pair(StringRef(), QualType()) // __context with shared vars
1684     };
1685     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1686                              Params);
1687     break;
1688   }
1689   case OMPD_parallel_sections: {
1690     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1691     QualType KmpInt32PtrTy =
1692         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1693     Sema::CapturedParamNameType Params[] = {
1694         std::make_pair(".global_tid.", KmpInt32PtrTy),
1695         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1696         std::make_pair(StringRef(), QualType()) // __context with shared vars
1697     };
1698     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1699                              Params);
1700     break;
1701   }
1702   case OMPD_task: {
1703     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1704     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1705     FunctionProtoType::ExtProtoInfo EPI;
1706     EPI.Variadic = true;
1707     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1708     Sema::CapturedParamNameType Params[] = {
1709         std::make_pair(".global_tid.", KmpInt32Ty),
1710         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1711         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1712         std::make_pair(".copy_fn.",
1713                        Context.getPointerType(CopyFnType).withConst()),
1714         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1715         std::make_pair(StringRef(), QualType()) // __context with shared vars
1716     };
1717     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1718                              Params);
1719     // Mark this captured region as inlined, because we don't use outlined
1720     // function directly.
1721     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1722         AlwaysInlineAttr::CreateImplicit(
1723             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1724     break;
1725   }
1726   case OMPD_ordered: {
1727     Sema::CapturedParamNameType Params[] = {
1728         std::make_pair(StringRef(), QualType()) // __context with shared vars
1729     };
1730     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1731                              Params);
1732     break;
1733   }
1734   case OMPD_atomic: {
1735     Sema::CapturedParamNameType Params[] = {
1736         std::make_pair(StringRef(), QualType()) // __context with shared vars
1737     };
1738     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1739                              Params);
1740     break;
1741   }
1742   case OMPD_target_data:
1743   case OMPD_target:
1744   case OMPD_target_parallel:
1745   case OMPD_target_parallel_for: {
1746     Sema::CapturedParamNameType Params[] = {
1747         std::make_pair(StringRef(), QualType()) // __context with shared vars
1748     };
1749     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1750                              Params);
1751     break;
1752   }
1753   case OMPD_teams: {
1754     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1755     QualType KmpInt32PtrTy =
1756         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1757     Sema::CapturedParamNameType Params[] = {
1758         std::make_pair(".global_tid.", KmpInt32PtrTy),
1759         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1760         std::make_pair(StringRef(), QualType()) // __context with shared vars
1761     };
1762     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1763                              Params);
1764     break;
1765   }
1766   case OMPD_taskgroup: {
1767     Sema::CapturedParamNameType Params[] = {
1768         std::make_pair(StringRef(), QualType()) // __context with shared vars
1769     };
1770     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1771                              Params);
1772     break;
1773   }
1774   case OMPD_taskloop:
1775   case OMPD_taskloop_simd: {
1776     QualType KmpInt32Ty =
1777         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1778     QualType KmpUInt64Ty =
1779         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1780     QualType KmpInt64Ty =
1781         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1782     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1783     FunctionProtoType::ExtProtoInfo EPI;
1784     EPI.Variadic = true;
1785     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1786     Sema::CapturedParamNameType Params[] = {
1787         std::make_pair(".global_tid.", KmpInt32Ty),
1788         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1789         std::make_pair(".privates.",
1790                        Context.VoidPtrTy.withConst().withRestrict()),
1791         std::make_pair(
1792             ".copy_fn.",
1793             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1794         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1795         std::make_pair(".lb.", KmpUInt64Ty),
1796         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1797         std::make_pair(".liter.", KmpInt32Ty),
1798         std::make_pair(StringRef(), QualType()) // __context with shared vars
1799     };
1800     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1801                              Params);
1802     // Mark this captured region as inlined, because we don't use outlined
1803     // function directly.
1804     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1805         AlwaysInlineAttr::CreateImplicit(
1806             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1807     break;
1808   }
1809   case OMPD_distribute: {
1810     Sema::CapturedParamNameType Params[] = {
1811         std::make_pair(StringRef(), QualType()) // __context with shared vars
1812     };
1813     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1814                              Params);
1815     break;
1816   }
1817   case OMPD_distribute_parallel_for: {
1818     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1819     QualType KmpInt32PtrTy =
1820         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1821     Sema::CapturedParamNameType Params[] = {
1822         std::make_pair(".global_tid.", KmpInt32PtrTy),
1823         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1824         std::make_pair(".previous.lb.", Context.getSizeType()),
1825         std::make_pair(".previous.ub.", Context.getSizeType()),
1826         std::make_pair(StringRef(), QualType()) // __context with shared vars
1827     };
1828     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1829                              Params);
1830     break;
1831   }
1832   case OMPD_threadprivate:
1833   case OMPD_taskyield:
1834   case OMPD_barrier:
1835   case OMPD_taskwait:
1836   case OMPD_cancellation_point:
1837   case OMPD_cancel:
1838   case OMPD_flush:
1839   case OMPD_target_enter_data:
1840   case OMPD_target_exit_data:
1841   case OMPD_declare_reduction:
1842   case OMPD_declare_simd:
1843   case OMPD_declare_target:
1844   case OMPD_end_declare_target:
1845   case OMPD_target_update:
1846     llvm_unreachable("OpenMP Directive is not allowed");
1847   case OMPD_unknown:
1848     llvm_unreachable("Unknown OpenMP directive");
1849   }
1850 }
1851 
1852 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1853                                              Expr *CaptureExpr, bool WithInit,
1854                                              bool AsExpression) {
1855   assert(CaptureExpr);
1856   ASTContext &C = S.getASTContext();
1857   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1858   QualType Ty = Init->getType();
1859   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1860     if (S.getLangOpts().CPlusPlus)
1861       Ty = C.getLValueReferenceType(Ty);
1862     else {
1863       Ty = C.getPointerType(Ty);
1864       ExprResult Res =
1865           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1866       if (!Res.isUsable())
1867         return nullptr;
1868       Init = Res.get();
1869     }
1870     WithInit = true;
1871   }
1872   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
1873   if (!WithInit)
1874     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1875   S.CurContext->addHiddenDecl(CED);
1876   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1877                          /*TypeMayContainAuto=*/true);
1878   return CED;
1879 }
1880 
1881 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1882                                  bool WithInit) {
1883   OMPCapturedExprDecl *CD;
1884   if (auto *VD = S.IsOpenMPCapturedDecl(D))
1885     CD = cast<OMPCapturedExprDecl>(VD);
1886   else
1887     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1888                           /*AsExpression=*/false);
1889   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1890                           CaptureExpr->getExprLoc());
1891 }
1892 
1893 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1894   if (!Ref) {
1895     auto *CD =
1896         buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1897                          CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1898     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1899                            CaptureExpr->getExprLoc());
1900   }
1901   ExprResult Res = Ref;
1902   if (!S.getLangOpts().CPlusPlus &&
1903       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1904       Ref->getType()->isPointerType())
1905     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1906   if (!Res.isUsable())
1907     return ExprError();
1908   return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1909 }
1910 
1911 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1912                                       ArrayRef<OMPClause *> Clauses) {
1913   if (!S.isUsable()) {
1914     ActOnCapturedRegionError();
1915     return StmtError();
1916   }
1917 
1918   OMPOrderedClause *OC = nullptr;
1919   OMPScheduleClause *SC = nullptr;
1920   SmallVector<OMPLinearClause *, 4> LCs;
1921   // This is required for proper codegen.
1922   for (auto *Clause : Clauses) {
1923     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1924         Clause->getClauseKind() == OMPC_copyprivate ||
1925         (getLangOpts().OpenMPUseTLS &&
1926          getASTContext().getTargetInfo().isTLSSupported() &&
1927          Clause->getClauseKind() == OMPC_copyin)) {
1928       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1929       // Mark all variables in private list clauses as used in inner region.
1930       for (auto *VarRef : Clause->children()) {
1931         if (auto *E = cast_or_null<Expr>(VarRef)) {
1932           MarkDeclarationsReferencedInExpr(E);
1933         }
1934       }
1935       DSAStack->setForceVarCapturing(/*V=*/false);
1936     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1937       // Mark all variables in private list clauses as used in inner region.
1938       // Required for proper codegen of combined directives.
1939       // TODO: add processing for other clauses.
1940       if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1941         if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1942           for (auto *D : DS->decls())
1943             MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1944         }
1945       }
1946       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1947         if (auto *E = C->getPostUpdateExpr())
1948           MarkDeclarationsReferencedInExpr(E);
1949       }
1950     }
1951     if (Clause->getClauseKind() == OMPC_schedule)
1952       SC = cast<OMPScheduleClause>(Clause);
1953     else if (Clause->getClauseKind() == OMPC_ordered)
1954       OC = cast<OMPOrderedClause>(Clause);
1955     else if (Clause->getClauseKind() == OMPC_linear)
1956       LCs.push_back(cast<OMPLinearClause>(Clause));
1957   }
1958   bool ErrorFound = false;
1959   // OpenMP, 2.7.1 Loop Construct, Restrictions
1960   // The nonmonotonic modifier cannot be specified if an ordered clause is
1961   // specified.
1962   if (SC &&
1963       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1964        SC->getSecondScheduleModifier() ==
1965            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1966       OC) {
1967     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1968              ? SC->getFirstScheduleModifierLoc()
1969              : SC->getSecondScheduleModifierLoc(),
1970          diag::err_omp_schedule_nonmonotonic_ordered)
1971         << SourceRange(OC->getLocStart(), OC->getLocEnd());
1972     ErrorFound = true;
1973   }
1974   if (!LCs.empty() && OC && OC->getNumForLoops()) {
1975     for (auto *C : LCs) {
1976       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1977           << SourceRange(OC->getLocStart(), OC->getLocEnd());
1978     }
1979     ErrorFound = true;
1980   }
1981   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1982       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1983       OC->getNumForLoops()) {
1984     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1985         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1986     ErrorFound = true;
1987   }
1988   if (ErrorFound) {
1989     ActOnCapturedRegionError();
1990     return StmtError();
1991   }
1992   return ActOnCapturedRegionEnd(S.get());
1993 }
1994 
1995 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1996                                   OpenMPDirectiveKind CurrentRegion,
1997                                   const DeclarationNameInfo &CurrentName,
1998                                   OpenMPDirectiveKind CancelRegion,
1999                                   SourceLocation StartLoc) {
2000   // Allowed nesting of constructs
2001   // +------------------+-----------------+------------------------------------+
2002   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
2003   // +------------------+-----------------+------------------------------------+
2004   // | parallel         | parallel        | *                                  |
2005   // | parallel         | for             | *                                  |
2006   // | parallel         | for simd        | *                                  |
2007   // | parallel         | master          | *                                  |
2008   // | parallel         | critical        | *                                  |
2009   // | parallel         | simd            | *                                  |
2010   // | parallel         | sections        | *                                  |
2011   // | parallel         | section         | +                                  |
2012   // | parallel         | single          | *                                  |
2013   // | parallel         | parallel for    | *                                  |
2014   // | parallel         |parallel for simd| *                                  |
2015   // | parallel         |parallel sections| *                                  |
2016   // | parallel         | task            | *                                  |
2017   // | parallel         | taskyield       | *                                  |
2018   // | parallel         | barrier         | *                                  |
2019   // | parallel         | taskwait        | *                                  |
2020   // | parallel         | taskgroup       | *                                  |
2021   // | parallel         | flush           | *                                  |
2022   // | parallel         | ordered         | +                                  |
2023   // | parallel         | atomic          | *                                  |
2024   // | parallel         | target          | *                                  |
2025   // | parallel         | target parallel | *                                  |
2026   // | parallel         | target parallel | *                                  |
2027   // |                  | for             |                                    |
2028   // | parallel         | target enter    | *                                  |
2029   // |                  | data            |                                    |
2030   // | parallel         | target exit     | *                                  |
2031   // |                  | data            |                                    |
2032   // | parallel         | teams           | +                                  |
2033   // | parallel         | cancellation    |                                    |
2034   // |                  | point           | !                                  |
2035   // | parallel         | cancel          | !                                  |
2036   // | parallel         | taskloop        | *                                  |
2037   // | parallel         | taskloop simd   | *                                  |
2038   // | parallel         | distribute      | +                                  |
2039   // | parallel         | distribute      | +                                  |
2040   // |                  | parallel for    |                                    |
2041   // +------------------+-----------------+------------------------------------+
2042   // | for              | parallel        | *                                  |
2043   // | for              | for             | +                                  |
2044   // | for              | for simd        | +                                  |
2045   // | for              | master          | +                                  |
2046   // | for              | critical        | *                                  |
2047   // | for              | simd            | *                                  |
2048   // | for              | sections        | +                                  |
2049   // | for              | section         | +                                  |
2050   // | for              | single          | +                                  |
2051   // | for              | parallel for    | *                                  |
2052   // | for              |parallel for simd| *                                  |
2053   // | for              |parallel sections| *                                  |
2054   // | for              | task            | *                                  |
2055   // | for              | taskyield       | *                                  |
2056   // | for              | barrier         | +                                  |
2057   // | for              | taskwait        | *                                  |
2058   // | for              | taskgroup       | *                                  |
2059   // | for              | flush           | *                                  |
2060   // | for              | ordered         | * (if construct is ordered)        |
2061   // | for              | atomic          | *                                  |
2062   // | for              | target          | *                                  |
2063   // | for              | target parallel | *                                  |
2064   // | for              | target parallel | *                                  |
2065   // |                  | for             |                                    |
2066   // | for              | target enter    | *                                  |
2067   // |                  | data            |                                    |
2068   // | for              | target exit     | *                                  |
2069   // |                  | data            |                                    |
2070   // | for              | teams           | +                                  |
2071   // | for              | cancellation    |                                    |
2072   // |                  | point           | !                                  |
2073   // | for              | cancel          | !                                  |
2074   // | for              | taskloop        | *                                  |
2075   // | for              | taskloop simd   | *                                  |
2076   // | for              | distribute      | +                                  |
2077   // | for              | distribute      | +                                  |
2078   // |                  | parallel for    |                                    |
2079   // +------------------+-----------------+------------------------------------+
2080   // | master           | parallel        | *                                  |
2081   // | master           | for             | +                                  |
2082   // | master           | for simd        | +                                  |
2083   // | master           | master          | *                                  |
2084   // | master           | critical        | *                                  |
2085   // | master           | simd            | *                                  |
2086   // | master           | sections        | +                                  |
2087   // | master           | section         | +                                  |
2088   // | master           | single          | +                                  |
2089   // | master           | parallel for    | *                                  |
2090   // | master           |parallel for simd| *                                  |
2091   // | master           |parallel sections| *                                  |
2092   // | master           | task            | *                                  |
2093   // | master           | taskyield       | *                                  |
2094   // | master           | barrier         | +                                  |
2095   // | master           | taskwait        | *                                  |
2096   // | master           | taskgroup       | *                                  |
2097   // | master           | flush           | *                                  |
2098   // | master           | ordered         | +                                  |
2099   // | master           | atomic          | *                                  |
2100   // | master           | target          | *                                  |
2101   // | master           | target parallel | *                                  |
2102   // | master           | target parallel | *                                  |
2103   // |                  | for             |                                    |
2104   // | master           | target enter    | *                                  |
2105   // |                  | data            |                                    |
2106   // | master           | target exit     | *                                  |
2107   // |                  | data            |                                    |
2108   // | master           | teams           | +                                  |
2109   // | master           | cancellation    |                                    |
2110   // |                  | point           |                                    |
2111   // | master           | cancel          |                                    |
2112   // | master           | taskloop        | *                                  |
2113   // | master           | taskloop simd   | *                                  |
2114   // | master           | distribute      | +                                  |
2115   // | master           | distribute      | +                                  |
2116   // |                  | parallel for    |                                    |
2117   // +------------------+-----------------+------------------------------------+
2118   // | critical         | parallel        | *                                  |
2119   // | critical         | for             | +                                  |
2120   // | critical         | for simd        | +                                  |
2121   // | critical         | master          | *                                  |
2122   // | critical         | critical        | * (should have different names)    |
2123   // | critical         | simd            | *                                  |
2124   // | critical         | sections        | +                                  |
2125   // | critical         | section         | +                                  |
2126   // | critical         | single          | +                                  |
2127   // | critical         | parallel for    | *                                  |
2128   // | critical         |parallel for simd| *                                  |
2129   // | critical         |parallel sections| *                                  |
2130   // | critical         | task            | *                                  |
2131   // | critical         | taskyield       | *                                  |
2132   // | critical         | barrier         | +                                  |
2133   // | critical         | taskwait        | *                                  |
2134   // | critical         | taskgroup       | *                                  |
2135   // | critical         | ordered         | +                                  |
2136   // | critical         | atomic          | *                                  |
2137   // | critical         | target          | *                                  |
2138   // | critical         | target parallel | *                                  |
2139   // | critical         | target parallel | *                                  |
2140   // |                  | for             |                                    |
2141   // | critical         | target enter    | *                                  |
2142   // |                  | data            |                                    |
2143   // | critical         | target exit     | *                                  |
2144   // |                  | data            |                                    |
2145   // | critical         | teams           | +                                  |
2146   // | critical         | cancellation    |                                    |
2147   // |                  | point           |                                    |
2148   // | critical         | cancel          |                                    |
2149   // | critical         | taskloop        | *                                  |
2150   // | critical         | taskloop simd   | *                                  |
2151   // | critical         | distribute      | +                                  |
2152   // | critical         | distribute      | +                                  |
2153   // |                  | parallel for    |                                    |
2154   // +------------------+-----------------+------------------------------------+
2155   // | simd             | parallel        |                                    |
2156   // | simd             | for             |                                    |
2157   // | simd             | for simd        |                                    |
2158   // | simd             | master          |                                    |
2159   // | simd             | critical        |                                    |
2160   // | simd             | simd            | *                                  |
2161   // | simd             | sections        |                                    |
2162   // | simd             | section         |                                    |
2163   // | simd             | single          |                                    |
2164   // | simd             | parallel for    |                                    |
2165   // | simd             |parallel for simd|                                    |
2166   // | simd             |parallel sections|                                    |
2167   // | simd             | task            |                                    |
2168   // | simd             | taskyield       |                                    |
2169   // | simd             | barrier         |                                    |
2170   // | simd             | taskwait        |                                    |
2171   // | simd             | taskgroup       |                                    |
2172   // | simd             | flush           |                                    |
2173   // | simd             | ordered         | + (with simd clause)               |
2174   // | simd             | atomic          |                                    |
2175   // | simd             | target          |                                    |
2176   // | simd             | target parallel |                                    |
2177   // | simd             | target parallel |                                    |
2178   // |                  | for             |                                    |
2179   // | simd             | target enter    |                                    |
2180   // |                  | data            |                                    |
2181   // | simd             | target exit     |                                    |
2182   // |                  | data            |                                    |
2183   // | simd             | teams           |                                    |
2184   // | simd             | cancellation    |                                    |
2185   // |                  | point           |                                    |
2186   // | simd             | cancel          |                                    |
2187   // | simd             | taskloop        |                                    |
2188   // | simd             | taskloop simd   |                                    |
2189   // | simd             | distribute      |                                    |
2190   // | simd             | distribute      |                                    |
2191   // |                  | parallel for    |                                    |
2192   // +------------------+-----------------+------------------------------------+
2193   // | for simd         | parallel        |                                    |
2194   // | for simd         | for             |                                    |
2195   // | for simd         | for simd        |                                    |
2196   // | for simd         | master          |                                    |
2197   // | for simd         | critical        |                                    |
2198   // | for simd         | simd            | *                                  |
2199   // | for simd         | sections        |                                    |
2200   // | for simd         | section         |                                    |
2201   // | for simd         | single          |                                    |
2202   // | for simd         | parallel for    |                                    |
2203   // | for simd         |parallel for simd|                                    |
2204   // | for simd         |parallel sections|                                    |
2205   // | for simd         | task            |                                    |
2206   // | for simd         | taskyield       |                                    |
2207   // | for simd         | barrier         |                                    |
2208   // | for simd         | taskwait        |                                    |
2209   // | for simd         | taskgroup       |                                    |
2210   // | for simd         | flush           |                                    |
2211   // | for simd         | ordered         | + (with simd clause)               |
2212   // | for simd         | atomic          |                                    |
2213   // | for simd         | target          |                                    |
2214   // | for simd         | target parallel |                                    |
2215   // | for simd         | target parallel |                                    |
2216   // |                  | for             |                                    |
2217   // | for simd         | target enter    |                                    |
2218   // |                  | data            |                                    |
2219   // | for simd         | target exit     |                                    |
2220   // |                  | data            |                                    |
2221   // | for simd         | teams           |                                    |
2222   // | for simd         | cancellation    |                                    |
2223   // |                  | point           |                                    |
2224   // | for simd         | cancel          |                                    |
2225   // | for simd         | taskloop        |                                    |
2226   // | for simd         | taskloop simd   |                                    |
2227   // | for simd         | distribute      |                                    |
2228   // | for simd         | distribute      |                                    |
2229   // |                  | parallel for    |                                    |
2230   // +------------------+-----------------+------------------------------------+
2231   // | parallel for simd| parallel        |                                    |
2232   // | parallel for simd| for             |                                    |
2233   // | parallel for simd| for simd        |                                    |
2234   // | parallel for simd| master          |                                    |
2235   // | parallel for simd| critical        |                                    |
2236   // | parallel for simd| simd            | *                                  |
2237   // | parallel for simd| sections        |                                    |
2238   // | parallel for simd| section         |                                    |
2239   // | parallel for simd| single          |                                    |
2240   // | parallel for simd| parallel for    |                                    |
2241   // | parallel for simd|parallel for simd|                                    |
2242   // | parallel for simd|parallel sections|                                    |
2243   // | parallel for simd| task            |                                    |
2244   // | parallel for simd| taskyield       |                                    |
2245   // | parallel for simd| barrier         |                                    |
2246   // | parallel for simd| taskwait        |                                    |
2247   // | parallel for simd| taskgroup       |                                    |
2248   // | parallel for simd| flush           |                                    |
2249   // | parallel for simd| ordered         | + (with simd clause)               |
2250   // | parallel for simd| atomic          |                                    |
2251   // | parallel for simd| target          |                                    |
2252   // | parallel for simd| target parallel |                                    |
2253   // | parallel for simd| target parallel |                                    |
2254   // |                  | for             |                                    |
2255   // | parallel for simd| target enter    |                                    |
2256   // |                  | data            |                                    |
2257   // | parallel for simd| target exit     |                                    |
2258   // |                  | data            |                                    |
2259   // | parallel for simd| teams           |                                    |
2260   // | parallel for simd| cancellation    |                                    |
2261   // |                  | point           |                                    |
2262   // | parallel for simd| cancel          |                                    |
2263   // | parallel for simd| taskloop        |                                    |
2264   // | parallel for simd| taskloop simd   |                                    |
2265   // | parallel for simd| distribute      |                                    |
2266   // | parallel for simd| distribute      |                                    |
2267   // |                  | parallel for    |                                    |
2268   // +------------------+-----------------+------------------------------------+
2269   // | sections         | parallel        | *                                  |
2270   // | sections         | for             | +                                  |
2271   // | sections         | for simd        | +                                  |
2272   // | sections         | master          | +                                  |
2273   // | sections         | critical        | *                                  |
2274   // | sections         | simd            | *                                  |
2275   // | sections         | sections        | +                                  |
2276   // | sections         | section         | *                                  |
2277   // | sections         | single          | +                                  |
2278   // | sections         | parallel for    | *                                  |
2279   // | sections         |parallel for simd| *                                  |
2280   // | sections         |parallel sections| *                                  |
2281   // | sections         | task            | *                                  |
2282   // | sections         | taskyield       | *                                  |
2283   // | sections         | barrier         | +                                  |
2284   // | sections         | taskwait        | *                                  |
2285   // | sections         | taskgroup       | *                                  |
2286   // | sections         | flush           | *                                  |
2287   // | sections         | ordered         | +                                  |
2288   // | sections         | atomic          | *                                  |
2289   // | sections         | target          | *                                  |
2290   // | sections         | target parallel | *                                  |
2291   // | sections         | target parallel | *                                  |
2292   // |                  | for             |                                    |
2293   // | sections         | target enter    | *                                  |
2294   // |                  | data            |                                    |
2295   // | sections         | target exit     | *                                  |
2296   // |                  | data            |                                    |
2297   // | sections         | teams           | +                                  |
2298   // | sections         | cancellation    |                                    |
2299   // |                  | point           | !                                  |
2300   // | sections         | cancel          | !                                  |
2301   // | sections         | taskloop        | *                                  |
2302   // | sections         | taskloop simd   | *                                  |
2303   // | sections         | distribute      | +                                  |
2304   // | sections         | distribute      | +                                  |
2305   // |                  | parallel for    |                                    |
2306   // +------------------+-----------------+------------------------------------+
2307   // | section          | parallel        | *                                  |
2308   // | section          | for             | +                                  |
2309   // | section          | for simd        | +                                  |
2310   // | section          | master          | +                                  |
2311   // | section          | critical        | *                                  |
2312   // | section          | simd            | *                                  |
2313   // | section          | sections        | +                                  |
2314   // | section          | section         | +                                  |
2315   // | section          | single          | +                                  |
2316   // | section          | parallel for    | *                                  |
2317   // | section          |parallel for simd| *                                  |
2318   // | section          |parallel sections| *                                  |
2319   // | section          | task            | *                                  |
2320   // | section          | taskyield       | *                                  |
2321   // | section          | barrier         | +                                  |
2322   // | section          | taskwait        | *                                  |
2323   // | section          | taskgroup       | *                                  |
2324   // | section          | flush           | *                                  |
2325   // | section          | ordered         | +                                  |
2326   // | section          | atomic          | *                                  |
2327   // | section          | target          | *                                  |
2328   // | section          | target parallel | *                                  |
2329   // | section          | target parallel | *                                  |
2330   // |                  | for             |                                    |
2331   // | section          | target enter    | *                                  |
2332   // |                  | data            |                                    |
2333   // | section          | target exit     | *                                  |
2334   // |                  | data            |                                    |
2335   // | section          | teams           | +                                  |
2336   // | section          | cancellation    |                                    |
2337   // |                  | point           | !                                  |
2338   // | section          | cancel          | !                                  |
2339   // | section          | taskloop        | *                                  |
2340   // | section          | taskloop simd   | *                                  |
2341   // | section          | distribute      | +                                  |
2342   // | section          | distribute      | +                                  |
2343   // |                  | parallel for    |                                    |
2344   // +------------------+-----------------+------------------------------------+
2345   // | single           | parallel        | *                                  |
2346   // | single           | for             | +                                  |
2347   // | single           | for simd        | +                                  |
2348   // | single           | master          | +                                  |
2349   // | single           | critical        | *                                  |
2350   // | single           | simd            | *                                  |
2351   // | single           | sections        | +                                  |
2352   // | single           | section         | +                                  |
2353   // | single           | single          | +                                  |
2354   // | single           | parallel for    | *                                  |
2355   // | single           |parallel for simd| *                                  |
2356   // | single           |parallel sections| *                                  |
2357   // | single           | task            | *                                  |
2358   // | single           | taskyield       | *                                  |
2359   // | single           | barrier         | +                                  |
2360   // | single           | taskwait        | *                                  |
2361   // | single           | taskgroup       | *                                  |
2362   // | single           | flush           | *                                  |
2363   // | single           | ordered         | +                                  |
2364   // | single           | atomic          | *                                  |
2365   // | single           | target          | *                                  |
2366   // | single           | target parallel | *                                  |
2367   // | single           | target parallel | *                                  |
2368   // |                  | for             |                                    |
2369   // | single           | target enter    | *                                  |
2370   // |                  | data            |                                    |
2371   // | single           | target exit     | *                                  |
2372   // |                  | data            |                                    |
2373   // | single           | teams           | +                                  |
2374   // | single           | cancellation    |                                    |
2375   // |                  | point           |                                    |
2376   // | single           | cancel          |                                    |
2377   // | single           | taskloop        | *                                  |
2378   // | single           | taskloop simd   | *                                  |
2379   // | single           | distribute      | +                                  |
2380   // | single           | distribute      | +                                  |
2381   // |                  | parallel for    |                                    |
2382   // +------------------+-----------------+------------------------------------+
2383   // | parallel for     | parallel        | *                                  |
2384   // | parallel for     | for             | +                                  |
2385   // | parallel for     | for simd        | +                                  |
2386   // | parallel for     | master          | +                                  |
2387   // | parallel for     | critical        | *                                  |
2388   // | parallel for     | simd            | *                                  |
2389   // | parallel for     | sections        | +                                  |
2390   // | parallel for     | section         | +                                  |
2391   // | parallel for     | single          | +                                  |
2392   // | parallel for     | parallel for    | *                                  |
2393   // | parallel for     |parallel for simd| *                                  |
2394   // | parallel for     |parallel sections| *                                  |
2395   // | parallel for     | task            | *                                  |
2396   // | parallel for     | taskyield       | *                                  |
2397   // | parallel for     | barrier         | +                                  |
2398   // | parallel for     | taskwait        | *                                  |
2399   // | parallel for     | taskgroup       | *                                  |
2400   // | parallel for     | flush           | *                                  |
2401   // | parallel for     | ordered         | * (if construct is ordered)        |
2402   // | parallel for     | atomic          | *                                  |
2403   // | parallel for     | target          | *                                  |
2404   // | parallel for     | target parallel | *                                  |
2405   // | parallel for     | target parallel | *                                  |
2406   // |                  | for             |                                    |
2407   // | parallel for     | target enter    | *                                  |
2408   // |                  | data            |                                    |
2409   // | parallel for     | target exit     | *                                  |
2410   // |                  | data            |                                    |
2411   // | parallel for     | teams           | +                                  |
2412   // | parallel for     | cancellation    |                                    |
2413   // |                  | point           | !                                  |
2414   // | parallel for     | cancel          | !                                  |
2415   // | parallel for     | taskloop        | *                                  |
2416   // | parallel for     | taskloop simd   | *                                  |
2417   // | parallel for     | distribute      | +                                  |
2418   // | parallel for     | distribute      | +                                  |
2419   // |                  | parallel for    |                                    |
2420   // +------------------+-----------------+------------------------------------+
2421   // | parallel sections| parallel        | *                                  |
2422   // | parallel sections| for             | +                                  |
2423   // | parallel sections| for simd        | +                                  |
2424   // | parallel sections| master          | +                                  |
2425   // | parallel sections| critical        | +                                  |
2426   // | parallel sections| simd            | *                                  |
2427   // | parallel sections| sections        | +                                  |
2428   // | parallel sections| section         | *                                  |
2429   // | parallel sections| single          | +                                  |
2430   // | parallel sections| parallel for    | *                                  |
2431   // | parallel sections|parallel for simd| *                                  |
2432   // | parallel sections|parallel sections| *                                  |
2433   // | parallel sections| task            | *                                  |
2434   // | parallel sections| taskyield       | *                                  |
2435   // | parallel sections| barrier         | +                                  |
2436   // | parallel sections| taskwait        | *                                  |
2437   // | parallel sections| taskgroup       | *                                  |
2438   // | parallel sections| flush           | *                                  |
2439   // | parallel sections| ordered         | +                                  |
2440   // | parallel sections| atomic          | *                                  |
2441   // | parallel sections| target          | *                                  |
2442   // | parallel sections| target parallel | *                                  |
2443   // | parallel sections| target parallel | *                                  |
2444   // |                  | for             |                                    |
2445   // | parallel sections| target enter    | *                                  |
2446   // |                  | data            |                                    |
2447   // | parallel sections| target exit     | *                                  |
2448   // |                  | data            |                                    |
2449   // | parallel sections| teams           | +                                  |
2450   // | parallel sections| cancellation    |                                    |
2451   // |                  | point           | !                                  |
2452   // | parallel sections| cancel          | !                                  |
2453   // | parallel sections| taskloop        | *                                  |
2454   // | parallel sections| taskloop simd   | *                                  |
2455   // | parallel sections| distribute      | +                                  |
2456   // | parallel sections| distribute      | +                                  |
2457   // |                  | parallel for    |                                    |
2458   // +------------------+-----------------+------------------------------------+
2459   // | task             | parallel        | *                                  |
2460   // | task             | for             | +                                  |
2461   // | task             | for simd        | +                                  |
2462   // | task             | master          | +                                  |
2463   // | task             | critical        | *                                  |
2464   // | task             | simd            | *                                  |
2465   // | task             | sections        | +                                  |
2466   // | task             | section         | +                                  |
2467   // | task             | single          | +                                  |
2468   // | task             | parallel for    | *                                  |
2469   // | task             |parallel for simd| *                                  |
2470   // | task             |parallel sections| *                                  |
2471   // | task             | task            | *                                  |
2472   // | task             | taskyield       | *                                  |
2473   // | task             | barrier         | +                                  |
2474   // | task             | taskwait        | *                                  |
2475   // | task             | taskgroup       | *                                  |
2476   // | task             | flush           | *                                  |
2477   // | task             | ordered         | +                                  |
2478   // | task             | atomic          | *                                  |
2479   // | task             | target          | *                                  |
2480   // | task             | target parallel | *                                  |
2481   // | task             | target parallel | *                                  |
2482   // |                  | for             |                                    |
2483   // | task             | target enter    | *                                  |
2484   // |                  | data            |                                    |
2485   // | task             | target exit     | *                                  |
2486   // |                  | data            |                                    |
2487   // | task             | teams           | +                                  |
2488   // | task             | cancellation    |                                    |
2489   // |                  | point           | !                                  |
2490   // | task             | cancel          | !                                  |
2491   // | task             | taskloop        | *                                  |
2492   // | task             | taskloop simd   | *                                  |
2493   // | task             | distribute      | +                                  |
2494   // | task             | distribute      | +                                  |
2495   // |                  | parallel for    |                                    |
2496   // +------------------+-----------------+------------------------------------+
2497   // | ordered          | parallel        | *                                  |
2498   // | ordered          | for             | +                                  |
2499   // | ordered          | for simd        | +                                  |
2500   // | ordered          | master          | *                                  |
2501   // | ordered          | critical        | *                                  |
2502   // | ordered          | simd            | *                                  |
2503   // | ordered          | sections        | +                                  |
2504   // | ordered          | section         | +                                  |
2505   // | ordered          | single          | +                                  |
2506   // | ordered          | parallel for    | *                                  |
2507   // | ordered          |parallel for simd| *                                  |
2508   // | ordered          |parallel sections| *                                  |
2509   // | ordered          | task            | *                                  |
2510   // | ordered          | taskyield       | *                                  |
2511   // | ordered          | barrier         | +                                  |
2512   // | ordered          | taskwait        | *                                  |
2513   // | ordered          | taskgroup       | *                                  |
2514   // | ordered          | flush           | *                                  |
2515   // | ordered          | ordered         | +                                  |
2516   // | ordered          | atomic          | *                                  |
2517   // | ordered          | target          | *                                  |
2518   // | ordered          | target parallel | *                                  |
2519   // | ordered          | target parallel | *                                  |
2520   // |                  | for             |                                    |
2521   // | ordered          | target enter    | *                                  |
2522   // |                  | data            |                                    |
2523   // | ordered          | target exit     | *                                  |
2524   // |                  | data            |                                    |
2525   // | ordered          | teams           | +                                  |
2526   // | ordered          | cancellation    |                                    |
2527   // |                  | point           |                                    |
2528   // | ordered          | cancel          |                                    |
2529   // | ordered          | taskloop        | *                                  |
2530   // | ordered          | taskloop simd   | *                                  |
2531   // | ordered          | distribute      | +                                  |
2532   // | ordered          | distribute      | +                                  |
2533   // |                  | parallel for    |                                    |
2534   // +------------------+-----------------+------------------------------------+
2535   // | atomic           | parallel        |                                    |
2536   // | atomic           | for             |                                    |
2537   // | atomic           | for simd        |                                    |
2538   // | atomic           | master          |                                    |
2539   // | atomic           | critical        |                                    |
2540   // | atomic           | simd            |                                    |
2541   // | atomic           | sections        |                                    |
2542   // | atomic           | section         |                                    |
2543   // | atomic           | single          |                                    |
2544   // | atomic           | parallel for    |                                    |
2545   // | atomic           |parallel for simd|                                    |
2546   // | atomic           |parallel sections|                                    |
2547   // | atomic           | task            |                                    |
2548   // | atomic           | taskyield       |                                    |
2549   // | atomic           | barrier         |                                    |
2550   // | atomic           | taskwait        |                                    |
2551   // | atomic           | taskgroup       |                                    |
2552   // | atomic           | flush           |                                    |
2553   // | atomic           | ordered         |                                    |
2554   // | atomic           | atomic          |                                    |
2555   // | atomic           | target          |                                    |
2556   // | atomic           | target parallel |                                    |
2557   // | atomic           | target parallel |                                    |
2558   // |                  | for             |                                    |
2559   // | atomic           | target enter    |                                    |
2560   // |                  | data            |                                    |
2561   // | atomic           | target exit     |                                    |
2562   // |                  | data            |                                    |
2563   // | atomic           | teams           |                                    |
2564   // | atomic           | cancellation    |                                    |
2565   // |                  | point           |                                    |
2566   // | atomic           | cancel          |                                    |
2567   // | atomic           | taskloop        |                                    |
2568   // | atomic           | taskloop simd   |                                    |
2569   // | atomic           | distribute      |                                    |
2570   // | atomic           | distribute      |                                    |
2571   // |                  | parallel for    |                                    |
2572   // +------------------+-----------------+------------------------------------+
2573   // | target           | parallel        | *                                  |
2574   // | target           | for             | *                                  |
2575   // | target           | for simd        | *                                  |
2576   // | target           | master          | *                                  |
2577   // | target           | critical        | *                                  |
2578   // | target           | simd            | *                                  |
2579   // | target           | sections        | *                                  |
2580   // | target           | section         | *                                  |
2581   // | target           | single          | *                                  |
2582   // | target           | parallel for    | *                                  |
2583   // | target           |parallel for simd| *                                  |
2584   // | target           |parallel sections| *                                  |
2585   // | target           | task            | *                                  |
2586   // | target           | taskyield       | *                                  |
2587   // | target           | barrier         | *                                  |
2588   // | target           | taskwait        | *                                  |
2589   // | target           | taskgroup       | *                                  |
2590   // | target           | flush           | *                                  |
2591   // | target           | ordered         | *                                  |
2592   // | target           | atomic          | *                                  |
2593   // | target           | target          |                                    |
2594   // | target           | target parallel |                                    |
2595   // | target           | target parallel |                                    |
2596   // |                  | for             |                                    |
2597   // | target           | target enter    |                                    |
2598   // |                  | data            |                                    |
2599   // | target           | target exit     |                                    |
2600   // |                  | data            |                                    |
2601   // | target           | teams           | *                                  |
2602   // | target           | cancellation    |                                    |
2603   // |                  | point           |                                    |
2604   // | target           | cancel          |                                    |
2605   // | target           | taskloop        | *                                  |
2606   // | target           | taskloop simd   | *                                  |
2607   // | target           | distribute      | +                                  |
2608   // | target           | distribute      | +                                  |
2609   // |                  | parallel for    |                                    |
2610   // +------------------+-----------------+------------------------------------+
2611   // | target parallel  | parallel        | *                                  |
2612   // | target parallel  | for             | *                                  |
2613   // | target parallel  | for simd        | *                                  |
2614   // | target parallel  | master          | *                                  |
2615   // | target parallel  | critical        | *                                  |
2616   // | target parallel  | simd            | *                                  |
2617   // | target parallel  | sections        | *                                  |
2618   // | target parallel  | section         | *                                  |
2619   // | target parallel  | single          | *                                  |
2620   // | target parallel  | parallel for    | *                                  |
2621   // | target parallel  |parallel for simd| *                                  |
2622   // | target parallel  |parallel sections| *                                  |
2623   // | target parallel  | task            | *                                  |
2624   // | target parallel  | taskyield       | *                                  |
2625   // | target parallel  | barrier         | *                                  |
2626   // | target parallel  | taskwait        | *                                  |
2627   // | target parallel  | taskgroup       | *                                  |
2628   // | target parallel  | flush           | *                                  |
2629   // | target parallel  | ordered         | *                                  |
2630   // | target parallel  | atomic          | *                                  |
2631   // | target parallel  | target          |                                    |
2632   // | target parallel  | target parallel |                                    |
2633   // | target parallel  | target parallel |                                    |
2634   // |                  | for             |                                    |
2635   // | target parallel  | target enter    |                                    |
2636   // |                  | data            |                                    |
2637   // | target parallel  | target exit     |                                    |
2638   // |                  | data            |                                    |
2639   // | target parallel  | teams           |                                    |
2640   // | target parallel  | cancellation    |                                    |
2641   // |                  | point           | !                                  |
2642   // | target parallel  | cancel          | !                                  |
2643   // | target parallel  | taskloop        | *                                  |
2644   // | target parallel  | taskloop simd   | *                                  |
2645   // | target parallel  | distribute      |                                    |
2646   // | target parallel  | distribute      |                                    |
2647   // |                  | parallel for    |                                    |
2648   // +------------------+-----------------+------------------------------------+
2649   // | target parallel  | parallel        | *                                  |
2650   // | for              |                 |                                    |
2651   // | target parallel  | for             | *                                  |
2652   // | for              |                 |                                    |
2653   // | target parallel  | for simd        | *                                  |
2654   // | for              |                 |                                    |
2655   // | target parallel  | master          | *                                  |
2656   // | for              |                 |                                    |
2657   // | target parallel  | critical        | *                                  |
2658   // | for              |                 |                                    |
2659   // | target parallel  | simd            | *                                  |
2660   // | for              |                 |                                    |
2661   // | target parallel  | sections        | *                                  |
2662   // | for              |                 |                                    |
2663   // | target parallel  | section         | *                                  |
2664   // | for              |                 |                                    |
2665   // | target parallel  | single          | *                                  |
2666   // | for              |                 |                                    |
2667   // | target parallel  | parallel for    | *                                  |
2668   // | for              |                 |                                    |
2669   // | target parallel  |parallel for simd| *                                  |
2670   // | for              |                 |                                    |
2671   // | target parallel  |parallel sections| *                                  |
2672   // | for              |                 |                                    |
2673   // | target parallel  | task            | *                                  |
2674   // | for              |                 |                                    |
2675   // | target parallel  | taskyield       | *                                  |
2676   // | for              |                 |                                    |
2677   // | target parallel  | barrier         | *                                  |
2678   // | for              |                 |                                    |
2679   // | target parallel  | taskwait        | *                                  |
2680   // | for              |                 |                                    |
2681   // | target parallel  | taskgroup       | *                                  |
2682   // | for              |                 |                                    |
2683   // | target parallel  | flush           | *                                  |
2684   // | for              |                 |                                    |
2685   // | target parallel  | ordered         | *                                  |
2686   // | for              |                 |                                    |
2687   // | target parallel  | atomic          | *                                  |
2688   // | for              |                 |                                    |
2689   // | target parallel  | target          |                                    |
2690   // | for              |                 |                                    |
2691   // | target parallel  | target parallel |                                    |
2692   // | for              |                 |                                    |
2693   // | target parallel  | target parallel |                                    |
2694   // | for              | for             |                                    |
2695   // | target parallel  | target enter    |                                    |
2696   // | for              | data            |                                    |
2697   // | target parallel  | target exit     |                                    |
2698   // | for              | data            |                                    |
2699   // | target parallel  | teams           |                                    |
2700   // | for              |                 |                                    |
2701   // | target parallel  | cancellation    |                                    |
2702   // | for              | point           | !                                  |
2703   // | target parallel  | cancel          | !                                  |
2704   // | for              |                 |                                    |
2705   // | target parallel  | taskloop        | *                                  |
2706   // | for              |                 |                                    |
2707   // | target parallel  | taskloop simd   | *                                  |
2708   // | for              |                 |                                    |
2709   // | target parallel  | distribute      |                                    |
2710   // | for              |                 |                                    |
2711   // | parallel         | distribute      |                                    |
2712   // | for              | parallel for    |                                    |
2713   // +------------------+-----------------+------------------------------------+
2714   // | teams            | parallel        | *                                  |
2715   // | teams            | for             | +                                  |
2716   // | teams            | for simd        | +                                  |
2717   // | teams            | master          | +                                  |
2718   // | teams            | critical        | +                                  |
2719   // | teams            | simd            | +                                  |
2720   // | teams            | sections        | +                                  |
2721   // | teams            | section         | +                                  |
2722   // | teams            | single          | +                                  |
2723   // | teams            | parallel for    | *                                  |
2724   // | teams            |parallel for simd| *                                  |
2725   // | teams            |parallel sections| *                                  |
2726   // | teams            | task            | +                                  |
2727   // | teams            | taskyield       | +                                  |
2728   // | teams            | barrier         | +                                  |
2729   // | teams            | taskwait        | +                                  |
2730   // | teams            | taskgroup       | +                                  |
2731   // | teams            | flush           | +                                  |
2732   // | teams            | ordered         | +                                  |
2733   // | teams            | atomic          | +                                  |
2734   // | teams            | target          | +                                  |
2735   // | teams            | target parallel | +                                  |
2736   // | teams            | target parallel | +                                  |
2737   // |                  | for             |                                    |
2738   // | teams            | target enter    | +                                  |
2739   // |                  | data            |                                    |
2740   // | teams            | target exit     | +                                  |
2741   // |                  | data            |                                    |
2742   // | teams            | teams           | +                                  |
2743   // | teams            | cancellation    |                                    |
2744   // |                  | point           |                                    |
2745   // | teams            | cancel          |                                    |
2746   // | teams            | taskloop        | +                                  |
2747   // | teams            | taskloop simd   | +                                  |
2748   // | teams            | distribute      | !                                  |
2749   // | teams            | distribute      | !                                  |
2750   // |                  | parallel for    |                                    |
2751   // +------------------+-----------------+------------------------------------+
2752   // | taskloop         | parallel        | *                                  |
2753   // | taskloop         | for             | +                                  |
2754   // | taskloop         | for simd        | +                                  |
2755   // | taskloop         | master          | +                                  |
2756   // | taskloop         | critical        | *                                  |
2757   // | taskloop         | simd            | *                                  |
2758   // | taskloop         | sections        | +                                  |
2759   // | taskloop         | section         | +                                  |
2760   // | taskloop         | single          | +                                  |
2761   // | taskloop         | parallel for    | *                                  |
2762   // | taskloop         |parallel for simd| *                                  |
2763   // | taskloop         |parallel sections| *                                  |
2764   // | taskloop         | task            | *                                  |
2765   // | taskloop         | taskyield       | *                                  |
2766   // | taskloop         | barrier         | +                                  |
2767   // | taskloop         | taskwait        | *                                  |
2768   // | taskloop         | taskgroup       | *                                  |
2769   // | taskloop         | flush           | *                                  |
2770   // | taskloop         | ordered         | +                                  |
2771   // | taskloop         | atomic          | *                                  |
2772   // | taskloop         | target          | *                                  |
2773   // | taskloop         | target parallel | *                                  |
2774   // | taskloop         | target parallel | *                                  |
2775   // |                  | for             |                                    |
2776   // | taskloop         | target enter    | *                                  |
2777   // |                  | data            |                                    |
2778   // | taskloop         | target exit     | *                                  |
2779   // |                  | data            |                                    |
2780   // | taskloop         | teams           | +                                  |
2781   // | taskloop         | cancellation    |                                    |
2782   // |                  | point           |                                    |
2783   // | taskloop         | cancel          |                                    |
2784   // | taskloop         | taskloop        | *                                  |
2785   // | taskloop         | distribute      | +                                  |
2786   // | taskloop         | distribute      | +                                  |
2787   // |                  | parallel for    |                                    |
2788   // +------------------+-----------------+------------------------------------+
2789   // | taskloop simd    | parallel        |                                    |
2790   // | taskloop simd    | for             |                                    |
2791   // | taskloop simd    | for simd        |                                    |
2792   // | taskloop simd    | master          |                                    |
2793   // | taskloop simd    | critical        |                                    |
2794   // | taskloop simd    | simd            | *                                  |
2795   // | taskloop simd    | sections        |                                    |
2796   // | taskloop simd    | section         |                                    |
2797   // | taskloop simd    | single          |                                    |
2798   // | taskloop simd    | parallel for    |                                    |
2799   // | taskloop simd    |parallel for simd|                                    |
2800   // | taskloop simd    |parallel sections|                                    |
2801   // | taskloop simd    | task            |                                    |
2802   // | taskloop simd    | taskyield       |                                    |
2803   // | taskloop simd    | barrier         |                                    |
2804   // | taskloop simd    | taskwait        |                                    |
2805   // | taskloop simd    | taskgroup       |                                    |
2806   // | taskloop simd    | flush           |                                    |
2807   // | taskloop simd    | ordered         | + (with simd clause)               |
2808   // | taskloop simd    | atomic          |                                    |
2809   // | taskloop simd    | target          |                                    |
2810   // | taskloop simd    | target parallel |                                    |
2811   // | taskloop simd    | target parallel |                                    |
2812   // |                  | for             |                                    |
2813   // | taskloop simd    | target enter    |                                    |
2814   // |                  | data            |                                    |
2815   // | taskloop simd    | target exit     |                                    |
2816   // |                  | data            |                                    |
2817   // | taskloop simd    | teams           |                                    |
2818   // | taskloop simd    | cancellation    |                                    |
2819   // |                  | point           |                                    |
2820   // | taskloop simd    | cancel          |                                    |
2821   // | taskloop simd    | taskloop        |                                    |
2822   // | taskloop simd    | taskloop simd   |                                    |
2823   // | taskloop simd    | distribute      |                                    |
2824   // | taskloop simd    | distribute      |                                    |
2825   // |                  | parallel for    |                                    |
2826   // +------------------+-----------------+------------------------------------+
2827   // | distribute       | parallel        | *                                  |
2828   // | distribute       | for             | *                                  |
2829   // | distribute       | for simd        | *                                  |
2830   // | distribute       | master          | *                                  |
2831   // | distribute       | critical        | *                                  |
2832   // | distribute       | simd            | *                                  |
2833   // | distribute       | sections        | *                                  |
2834   // | distribute       | section         | *                                  |
2835   // | distribute       | single          | *                                  |
2836   // | distribute       | parallel for    | *                                  |
2837   // | distribute       |parallel for simd| *                                  |
2838   // | distribute       |parallel sections| *                                  |
2839   // | distribute       | task            | *                                  |
2840   // | distribute       | taskyield       | *                                  |
2841   // | distribute       | barrier         | *                                  |
2842   // | distribute       | taskwait        | *                                  |
2843   // | distribute       | taskgroup       | *                                  |
2844   // | distribute       | flush           | *                                  |
2845   // | distribute       | ordered         | +                                  |
2846   // | distribute       | atomic          | *                                  |
2847   // | distribute       | target          |                                    |
2848   // | distribute       | target parallel |                                    |
2849   // | distribute       | target parallel |                                    |
2850   // |                  | for             |                                    |
2851   // | distribute       | target enter    |                                    |
2852   // |                  | data            |                                    |
2853   // | distribute       | target exit     |                                    |
2854   // |                  | data            |                                    |
2855   // | distribute       | teams           |                                    |
2856   // | distribute       | cancellation    | +                                  |
2857   // |                  | point           |                                    |
2858   // | distribute       | cancel          | +                                  |
2859   // | distribute       | taskloop        | *                                  |
2860   // | distribute       | taskloop simd   | *                                  |
2861   // | distribute       | distribute      |                                    |
2862   // | distribute       | distribute      |                                    |
2863   // |                  | parallel for    |                                    |
2864   // +------------------+-----------------+------------------------------------+
2865   // | distribute       | parallel        | *                                  |
2866   // | parallel for     |                 |                                    |
2867   // | distribute       | for             | *                                  |
2868   // | parallel for     |                 |                                    |
2869   // | distribute       | for simd        | *                                  |
2870   // | parallel for     |                 |                                    |
2871   // | distribute       | master          | *                                  |
2872   // | parallel for     |                 |                                    |
2873   // | distribute       | critical        | *                                  |
2874   // | parallel for     |                 |                                    |
2875   // | distribute       | simd            | *                                  |
2876   // | parallel for     |                 |                                    |
2877   // | distribute       | sections        | *                                  |
2878   // | parallel for     |                 |                                    |
2879   // | distribute       | section         | *                                  |
2880   // | parallel for     |                 |                                    |
2881   // | distribute       | single          | *                                  |
2882   // | parallel for     |                 |                                    |
2883   // | distribute       | parallel for    | *                                  |
2884   // | parallel for     |                 |                                    |
2885   // | distribute       |parallel for simd| *                                  |
2886   // | parallel for     |                 |                                    |
2887   // | distribute       |parallel sections| *                                  |
2888   // | parallel for     |                 |                                    |
2889   // | distribute       | task            | *                                  |
2890   // | parallel for     |                 |                                    |
2891   // | parallel for     |                 |                                    |
2892   // | distribute       | taskyield       | *                                  |
2893   // | parallel for     |                 |                                    |
2894   // | distribute       | barrier         | *                                  |
2895   // | parallel for     |                 |                                    |
2896   // | distribute       | taskwait        | *                                  |
2897   // | parallel for     |                 |                                    |
2898   // | distribute       | taskgroup       | *                                  |
2899   // | parallel for     |                 |                                    |
2900   // | distribute       | flush           | *                                  |
2901   // | parallel for     |                 |                                    |
2902   // | distribute       | ordered         | +                                  |
2903   // | parallel for     |                 |                                    |
2904   // | distribute       | atomic          | *                                  |
2905   // | parallel for     |                 |                                    |
2906   // | distribute       | target          |                                    |
2907   // | parallel for     |                 |                                    |
2908   // | distribute       | target parallel |                                    |
2909   // | parallel for     |                 |                                    |
2910   // | distribute       | target parallel |                                    |
2911   // | parallel for     | for             |                                    |
2912   // | distribute       | target enter    |                                    |
2913   // | parallel for     | data            |                                    |
2914   // | distribute       | target exit     |                                    |
2915   // | parallel for     | data            |                                    |
2916   // | distribute       | teams           |                                    |
2917   // | parallel for     |                 |                                    |
2918   // | distribute       | cancellation    | +                                  |
2919   // | parallel for     | point           |                                    |
2920   // | distribute       | cancel          | +                                  |
2921   // | parallel for     |                 |                                    |
2922   // | distribute       | taskloop        | *                                  |
2923   // | parallel for     |                 |                                    |
2924   // | distribute       | taskloop simd   | *                                  |
2925   // | parallel for     |                 |                                    |
2926   // | distribute       | distribute      |                                    |
2927   // | parallel for     |                 |                                    |
2928   // | distribute       | distribute      |                                    |
2929   // | parallel for     | parallel for    |                                    |
2930   // +------------------+-----------------+------------------------------------+
2931   if (Stack->getCurScope()) {
2932     auto ParentRegion = Stack->getParentDirective();
2933     auto OffendingRegion = ParentRegion;
2934     bool NestingProhibited = false;
2935     bool CloseNesting = true;
2936     enum {
2937       NoRecommend,
2938       ShouldBeInParallelRegion,
2939       ShouldBeInOrderedRegion,
2940       ShouldBeInTargetRegion,
2941       ShouldBeInTeamsRegion
2942     } Recommend = NoRecommend;
2943     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered &&
2944         CurrentRegion != OMPD_simd) {
2945       // OpenMP [2.16, Nesting of Regions]
2946       // OpenMP constructs may not be nested inside a simd region.
2947       // OpenMP [2.8.1,simd Construct, Restrictions]
2948       // An ordered construct with the simd clause is the only OpenMP construct
2949       // that can appear in the simd region.
2950       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2951       return true;
2952     }
2953     if (ParentRegion == OMPD_atomic) {
2954       // OpenMP [2.16, Nesting of Regions]
2955       // OpenMP constructs may not be nested inside an atomic region.
2956       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2957       return true;
2958     }
2959     if (CurrentRegion == OMPD_section) {
2960       // OpenMP [2.7.2, sections Construct, Restrictions]
2961       // Orphaned section directives are prohibited. That is, the section
2962       // directives must appear within the sections construct and must not be
2963       // encountered elsewhere in the sections region.
2964       if (ParentRegion != OMPD_sections &&
2965           ParentRegion != OMPD_parallel_sections) {
2966         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2967             << (ParentRegion != OMPD_unknown)
2968             << getOpenMPDirectiveName(ParentRegion);
2969         return true;
2970       }
2971       return false;
2972     }
2973     // Allow some constructs to be orphaned (they could be used in functions,
2974     // called from OpenMP regions with the required preconditions).
2975     if (ParentRegion == OMPD_unknown)
2976       return false;
2977     if (CurrentRegion == OMPD_cancellation_point ||
2978         CurrentRegion == OMPD_cancel) {
2979       // OpenMP [2.16, Nesting of Regions]
2980       // A cancellation point construct for which construct-type-clause is
2981       // taskgroup must be nested inside a task construct. A cancellation
2982       // point construct for which construct-type-clause is not taskgroup must
2983       // be closely nested inside an OpenMP construct that matches the type
2984       // specified in construct-type-clause.
2985       // A cancel construct for which construct-type-clause is taskgroup must be
2986       // nested inside a task construct. A cancel construct for which
2987       // construct-type-clause is not taskgroup must be closely nested inside an
2988       // OpenMP construct that matches the type specified in
2989       // construct-type-clause.
2990       NestingProhibited =
2991           !((CancelRegion == OMPD_parallel &&
2992              (ParentRegion == OMPD_parallel ||
2993               ParentRegion == OMPD_target_parallel)) ||
2994             (CancelRegion == OMPD_for &&
2995              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2996               ParentRegion == OMPD_target_parallel_for)) ||
2997             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2998             (CancelRegion == OMPD_sections &&
2999              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3000               ParentRegion == OMPD_parallel_sections)));
3001     } else if (CurrentRegion == OMPD_master) {
3002       // OpenMP [2.16, Nesting of Regions]
3003       // A master region may not be closely nested inside a worksharing,
3004       // atomic, or explicit task region.
3005       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3006                           isOpenMPTaskingDirective(ParentRegion);
3007     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3008       // OpenMP [2.16, Nesting of Regions]
3009       // A critical region may not be nested (closely or otherwise) inside a
3010       // critical region with the same name. Note that this restriction is not
3011       // sufficient to prevent deadlock.
3012       SourceLocation PreviousCriticalLoc;
3013       bool DeadLock =
3014           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
3015                                   OpenMPDirectiveKind K,
3016                                   const DeclarationNameInfo &DNI,
3017                                   SourceLocation Loc)
3018                                   ->bool {
3019                                 if (K == OMPD_critical &&
3020                                     DNI.getName() == CurrentName.getName()) {
3021                                   PreviousCriticalLoc = Loc;
3022                                   return true;
3023                                 } else
3024                                   return false;
3025                               },
3026                               false /* skip top directive */);
3027       if (DeadLock) {
3028         SemaRef.Diag(StartLoc,
3029                      diag::err_omp_prohibited_region_critical_same_name)
3030             << CurrentName.getName();
3031         if (PreviousCriticalLoc.isValid())
3032           SemaRef.Diag(PreviousCriticalLoc,
3033                        diag::note_omp_previous_critical_region);
3034         return true;
3035       }
3036     } else if (CurrentRegion == OMPD_barrier) {
3037       // OpenMP [2.16, Nesting of Regions]
3038       // A barrier region may not be closely nested inside a worksharing,
3039       // explicit task, critical, ordered, atomic, or master region.
3040       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3041                           isOpenMPTaskingDirective(ParentRegion) ||
3042                           ParentRegion == OMPD_master ||
3043                           ParentRegion == OMPD_critical ||
3044                           ParentRegion == OMPD_ordered;
3045     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3046                !isOpenMPParallelDirective(CurrentRegion)) {
3047       // OpenMP [2.16, Nesting of Regions]
3048       // A worksharing region may not be closely nested inside a worksharing,
3049       // explicit task, critical, ordered, atomic, or master region.
3050       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3051                           isOpenMPTaskingDirective(ParentRegion) ||
3052                           ParentRegion == OMPD_master ||
3053                           ParentRegion == OMPD_critical ||
3054                           ParentRegion == OMPD_ordered;
3055       Recommend = ShouldBeInParallelRegion;
3056     } else if (CurrentRegion == OMPD_ordered) {
3057       // OpenMP [2.16, Nesting of Regions]
3058       // An ordered region may not be closely nested inside a critical,
3059       // atomic, or explicit task region.
3060       // An ordered region must be closely nested inside a loop region (or
3061       // parallel loop region) with an ordered clause.
3062       // OpenMP [2.8.1,simd Construct, Restrictions]
3063       // An ordered construct with the simd clause is the only OpenMP construct
3064       // that can appear in the simd region.
3065       NestingProhibited = ParentRegion == OMPD_critical ||
3066                           isOpenMPTaskingDirective(ParentRegion) ||
3067                           !(isOpenMPSimdDirective(ParentRegion) ||
3068                             Stack->isParentOrderedRegion());
3069       Recommend = ShouldBeInOrderedRegion;
3070     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
3071       // OpenMP [2.16, Nesting of Regions]
3072       // If specified, a teams construct must be contained within a target
3073       // construct.
3074       NestingProhibited = ParentRegion != OMPD_target;
3075       Recommend = ShouldBeInTargetRegion;
3076       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
3077     }
3078     if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
3079       // OpenMP [2.16, Nesting of Regions]
3080       // distribute, parallel, parallel sections, parallel workshare, and the
3081       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3082       // constructs that can be closely nested in the teams region.
3083       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3084                           !isOpenMPDistributeDirective(CurrentRegion);
3085       Recommend = ShouldBeInParallelRegion;
3086     }
3087     if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
3088       // OpenMP 4.5 [2.17 Nesting of Regions]
3089       // The region associated with the distribute construct must be strictly
3090       // nested inside a teams region
3091       NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
3092       Recommend = ShouldBeInTeamsRegion;
3093     }
3094     if (!NestingProhibited &&
3095         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3096          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3097       // OpenMP 4.5 [2.17 Nesting of Regions]
3098       // If a target, target update, target data, target enter data, or
3099       // target exit data construct is encountered during execution of a
3100       // target region, the behavior is unspecified.
3101       NestingProhibited = Stack->hasDirective(
3102           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3103                              SourceLocation) -> bool {
3104             if (isOpenMPTargetExecutionDirective(K)) {
3105               OffendingRegion = K;
3106               return true;
3107             } else
3108               return false;
3109           },
3110           false /* don't skip top directive */);
3111       CloseNesting = false;
3112     }
3113     if (NestingProhibited) {
3114       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3115           << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3116           << Recommend << getOpenMPDirectiveName(CurrentRegion);
3117       return true;
3118     }
3119   }
3120   return false;
3121 }
3122 
3123 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3124                            ArrayRef<OMPClause *> Clauses,
3125                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3126   bool ErrorFound = false;
3127   unsigned NamedModifiersNumber = 0;
3128   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3129       OMPD_unknown + 1);
3130   SmallVector<SourceLocation, 4> NameModifierLoc;
3131   for (const auto *C : Clauses) {
3132     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3133       // At most one if clause without a directive-name-modifier can appear on
3134       // the directive.
3135       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3136       if (FoundNameModifiers[CurNM]) {
3137         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
3138             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3139             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3140         ErrorFound = true;
3141       } else if (CurNM != OMPD_unknown) {
3142         NameModifierLoc.push_back(IC->getNameModifierLoc());
3143         ++NamedModifiersNumber;
3144       }
3145       FoundNameModifiers[CurNM] = IC;
3146       if (CurNM == OMPD_unknown)
3147         continue;
3148       // Check if the specified name modifier is allowed for the current
3149       // directive.
3150       // At most one if clause with the particular directive-name-modifier can
3151       // appear on the directive.
3152       bool MatchFound = false;
3153       for (auto NM : AllowedNameModifiers) {
3154         if (CurNM == NM) {
3155           MatchFound = true;
3156           break;
3157         }
3158       }
3159       if (!MatchFound) {
3160         S.Diag(IC->getNameModifierLoc(),
3161                diag::err_omp_wrong_if_directive_name_modifier)
3162             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3163         ErrorFound = true;
3164       }
3165     }
3166   }
3167   // If any if clause on the directive includes a directive-name-modifier then
3168   // all if clauses on the directive must include a directive-name-modifier.
3169   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3170     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3171       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
3172              diag::err_omp_no_more_if_clause);
3173     } else {
3174       std::string Values;
3175       std::string Sep(", ");
3176       unsigned AllowedCnt = 0;
3177       unsigned TotalAllowedNum =
3178           AllowedNameModifiers.size() - NamedModifiersNumber;
3179       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3180            ++Cnt) {
3181         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3182         if (!FoundNameModifiers[NM]) {
3183           Values += "'";
3184           Values += getOpenMPDirectiveName(NM);
3185           Values += "'";
3186           if (AllowedCnt + 2 == TotalAllowedNum)
3187             Values += " or ";
3188           else if (AllowedCnt + 1 != TotalAllowedNum)
3189             Values += Sep;
3190           ++AllowedCnt;
3191         }
3192       }
3193       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
3194              diag::err_omp_unnamed_if_clause)
3195           << (TotalAllowedNum > 1) << Values;
3196     }
3197     for (auto Loc : NameModifierLoc) {
3198       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3199     }
3200     ErrorFound = true;
3201   }
3202   return ErrorFound;
3203 }
3204 
3205 StmtResult Sema::ActOnOpenMPExecutableDirective(
3206     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3207     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3208     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3209   StmtResult Res = StmtError();
3210   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3211                             StartLoc))
3212     return StmtError();
3213 
3214   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3215   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
3216   bool ErrorFound = false;
3217   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3218   if (AStmt) {
3219     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3220 
3221     // Check default data sharing attributes for referenced variables.
3222     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3223     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
3224     if (DSAChecker.isErrorFound())
3225       return StmtError();
3226     // Generate list of implicitly defined firstprivate variables.
3227     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3228 
3229     if (!DSAChecker.getImplicitFirstprivate().empty()) {
3230       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3231               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
3232               SourceLocation(), SourceLocation())) {
3233         ClausesWithImplicit.push_back(Implicit);
3234         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3235                      DSAChecker.getImplicitFirstprivate().size();
3236       } else
3237         ErrorFound = true;
3238     }
3239   }
3240 
3241   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3242   switch (Kind) {
3243   case OMPD_parallel:
3244     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3245                                        EndLoc);
3246     AllowedNameModifiers.push_back(OMPD_parallel);
3247     break;
3248   case OMPD_simd:
3249     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3250                                    VarsWithInheritedDSA);
3251     break;
3252   case OMPD_for:
3253     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3254                                   VarsWithInheritedDSA);
3255     break;
3256   case OMPD_for_simd:
3257     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3258                                       EndLoc, VarsWithInheritedDSA);
3259     break;
3260   case OMPD_sections:
3261     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3262                                        EndLoc);
3263     break;
3264   case OMPD_section:
3265     assert(ClausesWithImplicit.empty() &&
3266            "No clauses are allowed for 'omp section' directive");
3267     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3268     break;
3269   case OMPD_single:
3270     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3271                                      EndLoc);
3272     break;
3273   case OMPD_master:
3274     assert(ClausesWithImplicit.empty() &&
3275            "No clauses are allowed for 'omp master' directive");
3276     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3277     break;
3278   case OMPD_critical:
3279     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3280                                        StartLoc, EndLoc);
3281     break;
3282   case OMPD_parallel_for:
3283     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3284                                           EndLoc, VarsWithInheritedDSA);
3285     AllowedNameModifiers.push_back(OMPD_parallel);
3286     break;
3287   case OMPD_parallel_for_simd:
3288     Res = ActOnOpenMPParallelForSimdDirective(
3289         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3290     AllowedNameModifiers.push_back(OMPD_parallel);
3291     break;
3292   case OMPD_parallel_sections:
3293     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3294                                                StartLoc, EndLoc);
3295     AllowedNameModifiers.push_back(OMPD_parallel);
3296     break;
3297   case OMPD_task:
3298     Res =
3299         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3300     AllowedNameModifiers.push_back(OMPD_task);
3301     break;
3302   case OMPD_taskyield:
3303     assert(ClausesWithImplicit.empty() &&
3304            "No clauses are allowed for 'omp taskyield' directive");
3305     assert(AStmt == nullptr &&
3306            "No associated statement allowed for 'omp taskyield' directive");
3307     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3308     break;
3309   case OMPD_barrier:
3310     assert(ClausesWithImplicit.empty() &&
3311            "No clauses are allowed for 'omp barrier' directive");
3312     assert(AStmt == nullptr &&
3313            "No associated statement allowed for 'omp barrier' directive");
3314     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3315     break;
3316   case OMPD_taskwait:
3317     assert(ClausesWithImplicit.empty() &&
3318            "No clauses are allowed for 'omp taskwait' directive");
3319     assert(AStmt == nullptr &&
3320            "No associated statement allowed for 'omp taskwait' directive");
3321     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3322     break;
3323   case OMPD_taskgroup:
3324     assert(ClausesWithImplicit.empty() &&
3325            "No clauses are allowed for 'omp taskgroup' directive");
3326     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
3327     break;
3328   case OMPD_flush:
3329     assert(AStmt == nullptr &&
3330            "No associated statement allowed for 'omp flush' directive");
3331     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3332     break;
3333   case OMPD_ordered:
3334     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3335                                       EndLoc);
3336     break;
3337   case OMPD_atomic:
3338     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3339                                      EndLoc);
3340     break;
3341   case OMPD_teams:
3342     Res =
3343         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3344     break;
3345   case OMPD_target:
3346     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3347                                      EndLoc);
3348     AllowedNameModifiers.push_back(OMPD_target);
3349     break;
3350   case OMPD_target_parallel:
3351     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3352                                              StartLoc, EndLoc);
3353     AllowedNameModifiers.push_back(OMPD_target);
3354     AllowedNameModifiers.push_back(OMPD_parallel);
3355     break;
3356   case OMPD_target_parallel_for:
3357     Res = ActOnOpenMPTargetParallelForDirective(
3358         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3359     AllowedNameModifiers.push_back(OMPD_target);
3360     AllowedNameModifiers.push_back(OMPD_parallel);
3361     break;
3362   case OMPD_cancellation_point:
3363     assert(ClausesWithImplicit.empty() &&
3364            "No clauses are allowed for 'omp cancellation point' directive");
3365     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3366                                "cancellation point' directive");
3367     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3368     break;
3369   case OMPD_cancel:
3370     assert(AStmt == nullptr &&
3371            "No associated statement allowed for 'omp cancel' directive");
3372     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3373                                      CancelRegion);
3374     AllowedNameModifiers.push_back(OMPD_cancel);
3375     break;
3376   case OMPD_target_data:
3377     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3378                                          EndLoc);
3379     AllowedNameModifiers.push_back(OMPD_target_data);
3380     break;
3381   case OMPD_target_enter_data:
3382     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3383                                               EndLoc);
3384     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3385     break;
3386   case OMPD_target_exit_data:
3387     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3388                                              EndLoc);
3389     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3390     break;
3391   case OMPD_taskloop:
3392     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3393                                        EndLoc, VarsWithInheritedDSA);
3394     AllowedNameModifiers.push_back(OMPD_taskloop);
3395     break;
3396   case OMPD_taskloop_simd:
3397     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3398                                            EndLoc, VarsWithInheritedDSA);
3399     AllowedNameModifiers.push_back(OMPD_taskloop);
3400     break;
3401   case OMPD_distribute:
3402     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3403                                          EndLoc, VarsWithInheritedDSA);
3404     break;
3405   case OMPD_target_update:
3406     assert(!AStmt && "Statement is not allowed for target update");
3407     Res =
3408         ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
3409     AllowedNameModifiers.push_back(OMPD_target_update);
3410     break;
3411   case OMPD_distribute_parallel_for:
3412     Res = ActOnOpenMPDistributeParallelForDirective(
3413         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3414     AllowedNameModifiers.push_back(OMPD_parallel);
3415     break;
3416   case OMPD_declare_target:
3417   case OMPD_end_declare_target:
3418   case OMPD_threadprivate:
3419   case OMPD_declare_reduction:
3420   case OMPD_declare_simd:
3421     llvm_unreachable("OpenMP Directive is not allowed");
3422   case OMPD_unknown:
3423     llvm_unreachable("Unknown OpenMP directive");
3424   }
3425 
3426   for (auto P : VarsWithInheritedDSA) {
3427     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3428         << P.first << P.second->getSourceRange();
3429   }
3430   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3431 
3432   if (!AllowedNameModifiers.empty())
3433     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3434                  ErrorFound;
3435 
3436   if (ErrorFound)
3437     return StmtError();
3438   return Res;
3439 }
3440 
3441 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3442     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3443     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3444     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3445     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3446   assert(Aligneds.size() == Alignments.size());
3447   assert(Linears.size() == LinModifiers.size());
3448   assert(Linears.size() == Steps.size());
3449   if (!DG || DG.get().isNull())
3450     return DeclGroupPtrTy();
3451 
3452   if (!DG.get().isSingleDecl()) {
3453     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3454     return DG;
3455   }
3456   auto *ADecl = DG.get().getSingleDecl();
3457   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3458     ADecl = FTD->getTemplatedDecl();
3459 
3460   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3461   if (!FD) {
3462     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3463     return DeclGroupPtrTy();
3464   }
3465 
3466   // OpenMP [2.8.2, declare simd construct, Description]
3467   // The parameter of the simdlen clause must be a constant positive integer
3468   // expression.
3469   ExprResult SL;
3470   if (Simdlen)
3471     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3472   // OpenMP [2.8.2, declare simd construct, Description]
3473   // The special this pointer can be used as if was one of the arguments to the
3474   // function in any of the linear, aligned, or uniform clauses.
3475   // The uniform clause declares one or more arguments to have an invariant
3476   // value for all concurrent invocations of the function in the execution of a
3477   // single SIMD loop.
3478   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3479   Expr *UniformedLinearThis = nullptr;
3480   for (auto *E : Uniforms) {
3481     E = E->IgnoreParenImpCasts();
3482     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3483       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3484         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3485             FD->getParamDecl(PVD->getFunctionScopeIndex())
3486                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3487           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
3488           continue;
3489         }
3490     if (isa<CXXThisExpr>(E)) {
3491       UniformedLinearThis = E;
3492       continue;
3493     }
3494     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3495         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3496   }
3497   // OpenMP [2.8.2, declare simd construct, Description]
3498   // The aligned clause declares that the object to which each list item points
3499   // is aligned to the number of bytes expressed in the optional parameter of
3500   // the aligned clause.
3501   // The special this pointer can be used as if was one of the arguments to the
3502   // function in any of the linear, aligned, or uniform clauses.
3503   // The type of list items appearing in the aligned clause must be array,
3504   // pointer, reference to array, or reference to pointer.
3505   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3506   Expr *AlignedThis = nullptr;
3507   for (auto *E : Aligneds) {
3508     E = E->IgnoreParenImpCasts();
3509     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3510       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3511         auto *CanonPVD = PVD->getCanonicalDecl();
3512         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3513             FD->getParamDecl(PVD->getFunctionScopeIndex())
3514                     ->getCanonicalDecl() == CanonPVD) {
3515           // OpenMP  [2.8.1, simd construct, Restrictions]
3516           // A list-item cannot appear in more than one aligned clause.
3517           if (AlignedArgs.count(CanonPVD) > 0) {
3518             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3519                 << 1 << E->getSourceRange();
3520             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3521                  diag::note_omp_explicit_dsa)
3522                 << getOpenMPClauseName(OMPC_aligned);
3523             continue;
3524           }
3525           AlignedArgs[CanonPVD] = E;
3526           QualType QTy = PVD->getType()
3527                              .getNonReferenceType()
3528                              .getUnqualifiedType()
3529                              .getCanonicalType();
3530           const Type *Ty = QTy.getTypePtrOrNull();
3531           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3532             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3533                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3534             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3535           }
3536           continue;
3537         }
3538       }
3539     if (isa<CXXThisExpr>(E)) {
3540       if (AlignedThis) {
3541         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3542             << 2 << E->getSourceRange();
3543         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3544             << getOpenMPClauseName(OMPC_aligned);
3545       }
3546       AlignedThis = E;
3547       continue;
3548     }
3549     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3550         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3551   }
3552   // The optional parameter of the aligned clause, alignment, must be a constant
3553   // positive integer expression. If no optional parameter is specified,
3554   // implementation-defined default alignments for SIMD instructions on the
3555   // target platforms are assumed.
3556   SmallVector<Expr *, 4> NewAligns;
3557   for (auto *E : Alignments) {
3558     ExprResult Align;
3559     if (E)
3560       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3561     NewAligns.push_back(Align.get());
3562   }
3563   // OpenMP [2.8.2, declare simd construct, Description]
3564   // The linear clause declares one or more list items to be private to a SIMD
3565   // lane and to have a linear relationship with respect to the iteration space
3566   // of a loop.
3567   // The special this pointer can be used as if was one of the arguments to the
3568   // function in any of the linear, aligned, or uniform clauses.
3569   // When a linear-step expression is specified in a linear clause it must be
3570   // either a constant integer expression or an integer-typed parameter that is
3571   // specified in a uniform clause on the directive.
3572   llvm::DenseMap<Decl *, Expr *> LinearArgs;
3573   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3574   auto MI = LinModifiers.begin();
3575   for (auto *E : Linears) {
3576     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3577     ++MI;
3578     E = E->IgnoreParenImpCasts();
3579     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3580       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3581         auto *CanonPVD = PVD->getCanonicalDecl();
3582         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3583             FD->getParamDecl(PVD->getFunctionScopeIndex())
3584                     ->getCanonicalDecl() == CanonPVD) {
3585           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3586           // A list-item cannot appear in more than one linear clause.
3587           if (LinearArgs.count(CanonPVD) > 0) {
3588             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3589                 << getOpenMPClauseName(OMPC_linear)
3590                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3591             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3592                  diag::note_omp_explicit_dsa)
3593                 << getOpenMPClauseName(OMPC_linear);
3594             continue;
3595           }
3596           // Each argument can appear in at most one uniform or linear clause.
3597           if (UniformedArgs.count(CanonPVD) > 0) {
3598             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3599                 << getOpenMPClauseName(OMPC_linear)
3600                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3601             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3602                  diag::note_omp_explicit_dsa)
3603                 << getOpenMPClauseName(OMPC_uniform);
3604             continue;
3605           }
3606           LinearArgs[CanonPVD] = E;
3607           if (E->isValueDependent() || E->isTypeDependent() ||
3608               E->isInstantiationDependent() ||
3609               E->containsUnexpandedParameterPack())
3610             continue;
3611           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3612                                       PVD->getOriginalType());
3613           continue;
3614         }
3615       }
3616     if (isa<CXXThisExpr>(E)) {
3617       if (UniformedLinearThis) {
3618         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3619             << getOpenMPClauseName(OMPC_linear)
3620             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3621             << E->getSourceRange();
3622         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3623             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3624                                                    : OMPC_linear);
3625         continue;
3626       }
3627       UniformedLinearThis = E;
3628       if (E->isValueDependent() || E->isTypeDependent() ||
3629           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3630         continue;
3631       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3632                                   E->getType());
3633       continue;
3634     }
3635     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3636         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3637   }
3638   Expr *Step = nullptr;
3639   Expr *NewStep = nullptr;
3640   SmallVector<Expr *, 4> NewSteps;
3641   for (auto *E : Steps) {
3642     // Skip the same step expression, it was checked already.
3643     if (Step == E || !E) {
3644       NewSteps.push_back(E ? NewStep : nullptr);
3645       continue;
3646     }
3647     Step = E;
3648     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3649       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3650         auto *CanonPVD = PVD->getCanonicalDecl();
3651         if (UniformedArgs.count(CanonPVD) == 0) {
3652           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3653               << Step->getSourceRange();
3654         } else if (E->isValueDependent() || E->isTypeDependent() ||
3655                    E->isInstantiationDependent() ||
3656                    E->containsUnexpandedParameterPack() ||
3657                    CanonPVD->getType()->hasIntegerRepresentation())
3658           NewSteps.push_back(Step);
3659         else {
3660           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3661               << Step->getSourceRange();
3662         }
3663         continue;
3664       }
3665     NewStep = Step;
3666     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3667         !Step->isInstantiationDependent() &&
3668         !Step->containsUnexpandedParameterPack()) {
3669       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3670                     .get();
3671       if (NewStep)
3672         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3673     }
3674     NewSteps.push_back(NewStep);
3675   }
3676   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3677       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3678       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3679       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3680       const_cast<Expr **>(Linears.data()), Linears.size(),
3681       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3682       NewSteps.data(), NewSteps.size(), SR);
3683   ADecl->addAttr(NewAttr);
3684   return ConvertDeclToDeclGroup(ADecl);
3685 }
3686 
3687 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3688                                               Stmt *AStmt,
3689                                               SourceLocation StartLoc,
3690                                               SourceLocation EndLoc) {
3691   if (!AStmt)
3692     return StmtError();
3693 
3694   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3695   // 1.2.2 OpenMP Language Terminology
3696   // Structured block - An executable statement with a single entry at the
3697   // top and a single exit at the bottom.
3698   // The point of exit cannot be a branch out of the structured block.
3699   // longjmp() and throw() must not violate the entry/exit criteria.
3700   CS->getCapturedDecl()->setNothrow();
3701 
3702   getCurFunction()->setHasBranchProtectedScope();
3703 
3704   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3705                                       DSAStack->isCancelRegion());
3706 }
3707 
3708 namespace {
3709 /// \brief Helper class for checking canonical form of the OpenMP loops and
3710 /// extracting iteration space of each loop in the loop nest, that will be used
3711 /// for IR generation.
3712 class OpenMPIterationSpaceChecker {
3713   /// \brief Reference to Sema.
3714   Sema &SemaRef;
3715   /// \brief A location for diagnostics (when there is no some better location).
3716   SourceLocation DefaultLoc;
3717   /// \brief A location for diagnostics (when increment is not compatible).
3718   SourceLocation ConditionLoc;
3719   /// \brief A source location for referring to loop init later.
3720   SourceRange InitSrcRange;
3721   /// \brief A source location for referring to condition later.
3722   SourceRange ConditionSrcRange;
3723   /// \brief A source location for referring to increment later.
3724   SourceRange IncrementSrcRange;
3725   /// \brief Loop variable.
3726   ValueDecl *LCDecl = nullptr;
3727   /// \brief Reference to loop variable.
3728   Expr *LCRef = nullptr;
3729   /// \brief Lower bound (initializer for the var).
3730   Expr *LB = nullptr;
3731   /// \brief Upper bound.
3732   Expr *UB = nullptr;
3733   /// \brief Loop step (increment).
3734   Expr *Step = nullptr;
3735   /// \brief This flag is true when condition is one of:
3736   ///   Var <  UB
3737   ///   Var <= UB
3738   ///   UB  >  Var
3739   ///   UB  >= Var
3740   bool TestIsLessOp = false;
3741   /// \brief This flag is true when condition is strict ( < or > ).
3742   bool TestIsStrictOp = false;
3743   /// \brief This flag is true when step is subtracted on each iteration.
3744   bool SubtractStep = false;
3745 
3746 public:
3747   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3748       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3749   /// \brief Check init-expr for canonical loop form and save loop counter
3750   /// variable - #Var and its initialization value - #LB.
3751   bool CheckInit(Stmt *S, bool EmitDiags = true);
3752   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3753   /// for less/greater and for strict/non-strict comparison.
3754   bool CheckCond(Expr *S);
3755   /// \brief Check incr-expr for canonical loop form and return true if it
3756   /// does not conform, otherwise save loop step (#Step).
3757   bool CheckInc(Expr *S);
3758   /// \brief Return the loop counter variable.
3759   ValueDecl *GetLoopDecl() const { return LCDecl; }
3760   /// \brief Return the reference expression to loop counter variable.
3761   Expr *GetLoopDeclRefExpr() const { return LCRef; }
3762   /// \brief Source range of the loop init.
3763   SourceRange GetInitSrcRange() const { return InitSrcRange; }
3764   /// \brief Source range of the loop condition.
3765   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3766   /// \brief Source range of the loop increment.
3767   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3768   /// \brief True if the step should be subtracted.
3769   bool ShouldSubtractStep() const { return SubtractStep; }
3770   /// \brief Build the expression to calculate the number of iterations.
3771   Expr *
3772   BuildNumIterations(Scope *S, const bool LimitedType,
3773                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3774   /// \brief Build the precondition expression for the loops.
3775   Expr *BuildPreCond(Scope *S, Expr *Cond,
3776                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
3777   /// \brief Build reference expression to the counter be used for codegen.
3778   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3779                                DSAStackTy &DSA) const;
3780   /// \brief Build reference expression to the private counter be used for
3781   /// codegen.
3782   Expr *BuildPrivateCounterVar() const;
3783   /// \brief Build initization of the counter be used for codegen.
3784   Expr *BuildCounterInit() const;
3785   /// \brief Build step of the counter be used for codegen.
3786   Expr *BuildCounterStep() const;
3787   /// \brief Return true if any expression is dependent.
3788   bool Dependent() const;
3789 
3790 private:
3791   /// \brief Check the right-hand side of an assignment in the increment
3792   /// expression.
3793   bool CheckIncRHS(Expr *RHS);
3794   /// \brief Helper to set loop counter variable and its initializer.
3795   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
3796   /// \brief Helper to set upper bound.
3797   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
3798              SourceLocation SL);
3799   /// \brief Helper to set loop increment.
3800   bool SetStep(Expr *NewStep, bool Subtract);
3801 };
3802 
3803 bool OpenMPIterationSpaceChecker::Dependent() const {
3804   if (!LCDecl) {
3805     assert(!LB && !UB && !Step);
3806     return false;
3807   }
3808   return LCDecl->getType()->isDependentType() ||
3809          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3810          (Step && Step->isValueDependent());
3811 }
3812 
3813 static Expr *getExprAsWritten(Expr *E) {
3814   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
3815     E = ExprTemp->getSubExpr();
3816 
3817   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
3818     E = MTE->GetTemporaryExpr();
3819 
3820   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
3821     E = Binder->getSubExpr();
3822 
3823   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
3824     E = ICE->getSubExprAsWritten();
3825   return E->IgnoreParens();
3826 }
3827 
3828 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3829                                                  Expr *NewLCRefExpr,
3830                                                  Expr *NewLB) {
3831   // State consistency checking to ensure correct usage.
3832   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
3833          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3834   if (!NewLCDecl || !NewLB)
3835     return true;
3836   LCDecl = getCanonicalDecl(NewLCDecl);
3837   LCRef = NewLCRefExpr;
3838   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3839     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3840       if ((Ctor->isCopyOrMoveConstructor() ||
3841            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3842           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3843         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
3844   LB = NewLB;
3845   return false;
3846 }
3847 
3848 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
3849                                         SourceRange SR, SourceLocation SL) {
3850   // State consistency checking to ensure correct usage.
3851   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3852          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
3853   if (!NewUB)
3854     return true;
3855   UB = NewUB;
3856   TestIsLessOp = LessOp;
3857   TestIsStrictOp = StrictOp;
3858   ConditionSrcRange = SR;
3859   ConditionLoc = SL;
3860   return false;
3861 }
3862 
3863 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3864   // State consistency checking to ensure correct usage.
3865   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
3866   if (!NewStep)
3867     return true;
3868   if (!NewStep->isValueDependent()) {
3869     // Check that the step is integer expression.
3870     SourceLocation StepLoc = NewStep->getLocStart();
3871     ExprResult Val =
3872         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3873     if (Val.isInvalid())
3874       return true;
3875     NewStep = Val.get();
3876 
3877     // OpenMP [2.6, Canonical Loop Form, Restrictions]
3878     //  If test-expr is of form var relational-op b and relational-op is < or
3879     //  <= then incr-expr must cause var to increase on each iteration of the
3880     //  loop. If test-expr is of form var relational-op b and relational-op is
3881     //  > or >= then incr-expr must cause var to decrease on each iteration of
3882     //  the loop.
3883     //  If test-expr is of form b relational-op var and relational-op is < or
3884     //  <= then incr-expr must cause var to decrease on each iteration of the
3885     //  loop. If test-expr is of form b relational-op var and relational-op is
3886     //  > or >= then incr-expr must cause var to increase on each iteration of
3887     //  the loop.
3888     llvm::APSInt Result;
3889     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3890     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3891     bool IsConstNeg =
3892         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
3893     bool IsConstPos =
3894         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
3895     bool IsConstZero = IsConstant && !Result.getBoolValue();
3896     if (UB && (IsConstZero ||
3897                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
3898                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
3899       SemaRef.Diag(NewStep->getExprLoc(),
3900                    diag::err_omp_loop_incr_not_compatible)
3901           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
3902       SemaRef.Diag(ConditionLoc,
3903                    diag::note_omp_loop_cond_requres_compatible_incr)
3904           << TestIsLessOp << ConditionSrcRange;
3905       return true;
3906     }
3907     if (TestIsLessOp == Subtract) {
3908       NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
3909                                              NewStep).get();
3910       Subtract = !Subtract;
3911     }
3912   }
3913 
3914   Step = NewStep;
3915   SubtractStep = Subtract;
3916   return false;
3917 }
3918 
3919 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
3920   // Check init-expr for canonical loop form and save loop counter
3921   // variable - #Var and its initialization value - #LB.
3922   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3923   //   var = lb
3924   //   integer-type var = lb
3925   //   random-access-iterator-type var = lb
3926   //   pointer-type var = lb
3927   //
3928   if (!S) {
3929     if (EmitDiags) {
3930       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3931     }
3932     return true;
3933   }
3934   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3935     if (!ExprTemp->cleanupsHaveSideEffects())
3936       S = ExprTemp->getSubExpr();
3937 
3938   InitSrcRange = S->getSourceRange();
3939   if (Expr *E = dyn_cast<Expr>(S))
3940     S = E->IgnoreParens();
3941   if (auto BO = dyn_cast<BinaryOperator>(S)) {
3942     if (BO->getOpcode() == BO_Assign) {
3943       auto *LHS = BO->getLHS()->IgnoreParens();
3944       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3945         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3946           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3947             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3948         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3949       }
3950       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3951         if (ME->isArrow() &&
3952             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3953           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3954       }
3955     }
3956   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
3957     if (DS->isSingleDecl()) {
3958       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
3959         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
3960           // Accept non-canonical init form here but emit ext. warning.
3961           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
3962             SemaRef.Diag(S->getLocStart(),
3963                          diag::ext_omp_loop_not_canonical_init)
3964                 << S->getSourceRange();
3965           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
3966         }
3967       }
3968     }
3969   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3970     if (CE->getOperator() == OO_Equal) {
3971       auto *LHS = CE->getArg(0);
3972       if (auto DRE = dyn_cast<DeclRefExpr>(LHS)) {
3973         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3974           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3975             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3976         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3977       }
3978       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3979         if (ME->isArrow() &&
3980             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3981           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3982       }
3983     }
3984   }
3985 
3986   if (Dependent() || SemaRef.CurContext->isDependentContext())
3987     return false;
3988   if (EmitDiags) {
3989     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3990         << S->getSourceRange();
3991   }
3992   return true;
3993 }
3994 
3995 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3996 /// variable (which may be the loop variable) if possible.
3997 static const ValueDecl *GetInitLCDecl(Expr *E) {
3998   if (!E)
3999     return nullptr;
4000   E = getExprAsWritten(E);
4001   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4002     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4003       if ((Ctor->isCopyOrMoveConstructor() ||
4004            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4005           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4006         E = CE->getArg(0)->IgnoreParenImpCasts();
4007   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4008     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
4009       if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
4010         if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4011           return getCanonicalDecl(ME->getMemberDecl());
4012       return getCanonicalDecl(VD);
4013     }
4014   }
4015   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
4016     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4017       return getCanonicalDecl(ME->getMemberDecl());
4018   return nullptr;
4019 }
4020 
4021 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
4022   // Check test-expr for canonical form, save upper-bound UB, flags for
4023   // less/greater and for strict/non-strict comparison.
4024   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4025   //   var relational-op b
4026   //   b relational-op var
4027   //
4028   if (!S) {
4029     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4030     return true;
4031   }
4032   S = getExprAsWritten(S);
4033   SourceLocation CondLoc = S->getLocStart();
4034   if (auto BO = dyn_cast<BinaryOperator>(S)) {
4035     if (BO->isRelationalOp()) {
4036       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
4037         return SetUB(BO->getRHS(),
4038                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4039                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4040                      BO->getSourceRange(), BO->getOperatorLoc());
4041       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
4042         return SetUB(BO->getLHS(),
4043                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4044                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4045                      BO->getSourceRange(), BO->getOperatorLoc());
4046     }
4047   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4048     if (CE->getNumArgs() == 2) {
4049       auto Op = CE->getOperator();
4050       switch (Op) {
4051       case OO_Greater:
4052       case OO_GreaterEqual:
4053       case OO_Less:
4054       case OO_LessEqual:
4055         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4056           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4057                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4058                        CE->getOperatorLoc());
4059         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
4060           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4061                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4062                        CE->getOperatorLoc());
4063         break;
4064       default:
4065         break;
4066       }
4067     }
4068   }
4069   if (Dependent() || SemaRef.CurContext->isDependentContext())
4070     return false;
4071   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4072       << S->getSourceRange() << LCDecl;
4073   return true;
4074 }
4075 
4076 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
4077   // RHS of canonical loop form increment can be:
4078   //   var + incr
4079   //   incr + var
4080   //   var - incr
4081   //
4082   RHS = RHS->IgnoreParenImpCasts();
4083   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
4084     if (BO->isAdditiveOp()) {
4085       bool IsAdd = BO->getOpcode() == BO_Add;
4086       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
4087         return SetStep(BO->getRHS(), !IsAdd);
4088       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
4089         return SetStep(BO->getLHS(), false);
4090     }
4091   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4092     bool IsAdd = CE->getOperator() == OO_Plus;
4093     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4094       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4095         return SetStep(CE->getArg(1), !IsAdd);
4096       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
4097         return SetStep(CE->getArg(0), false);
4098     }
4099   }
4100   if (Dependent() || SemaRef.CurContext->isDependentContext())
4101     return false;
4102   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
4103       << RHS->getSourceRange() << LCDecl;
4104   return true;
4105 }
4106 
4107 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
4108   // Check incr-expr for canonical loop form and return true if it
4109   // does not conform.
4110   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4111   //   ++var
4112   //   var++
4113   //   --var
4114   //   var--
4115   //   var += incr
4116   //   var -= incr
4117   //   var = var + incr
4118   //   var = incr + var
4119   //   var = var - incr
4120   //
4121   if (!S) {
4122     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4123     return true;
4124   }
4125   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4126     if (!ExprTemp->cleanupsHaveSideEffects())
4127       S = ExprTemp->getSubExpr();
4128 
4129   IncrementSrcRange = S->getSourceRange();
4130   S = S->IgnoreParens();
4131   if (auto UO = dyn_cast<UnaryOperator>(S)) {
4132     if (UO->isIncrementDecrementOp() &&
4133         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
4134       return SetStep(
4135           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
4136                                        (UO->isDecrementOp() ? -1 : 1)).get(),
4137           false);
4138   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
4139     switch (BO->getOpcode()) {
4140     case BO_AddAssign:
4141     case BO_SubAssign:
4142       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
4143         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4144       break;
4145     case BO_Assign:
4146       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
4147         return CheckIncRHS(BO->getRHS());
4148       break;
4149     default:
4150       break;
4151     }
4152   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4153     switch (CE->getOperator()) {
4154     case OO_PlusPlus:
4155     case OO_MinusMinus:
4156       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4157         return SetStep(
4158             SemaRef.ActOnIntegerConstant(
4159                         CE->getLocStart(),
4160                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
4161             false);
4162       break;
4163     case OO_PlusEqual:
4164     case OO_MinusEqual:
4165       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4166         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4167       break;
4168     case OO_Equal:
4169       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
4170         return CheckIncRHS(CE->getArg(1));
4171       break;
4172     default:
4173       break;
4174     }
4175   }
4176   if (Dependent() || SemaRef.CurContext->isDependentContext())
4177     return false;
4178   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
4179       << S->getSourceRange() << LCDecl;
4180   return true;
4181 }
4182 
4183 static ExprResult
4184 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4185                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4186   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4187     return SemaRef.PerformImplicitConversion(
4188         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4189         /*AllowExplicit=*/true);
4190   auto I = Captures.find(Capture);
4191   if (I != Captures.end())
4192     return buildCapture(SemaRef, Capture, I->second);
4193   DeclRefExpr *Ref = nullptr;
4194   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4195   Captures[Capture] = Ref;
4196   return Res;
4197 }
4198 
4199 /// \brief Build the expression to calculate the number of iterations.
4200 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4201     Scope *S, const bool LimitedType,
4202     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4203   ExprResult Diff;
4204   auto VarType = LCDecl->getType().getNonReferenceType();
4205   if (VarType->isIntegerType() || VarType->isPointerType() ||
4206       SemaRef.getLangOpts().CPlusPlus) {
4207     // Upper - Lower
4208     auto *UBExpr = TestIsLessOp ? UB : LB;
4209     auto *LBExpr = TestIsLessOp ? LB : UB;
4210     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4211     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4212     if (!Upper || !Lower)
4213       return nullptr;
4214 
4215     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4216 
4217     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4218       // BuildBinOp already emitted error, this one is to point user to upper
4219       // and lower bound, and to tell what is passed to 'operator-'.
4220       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4221           << Upper->getSourceRange() << Lower->getSourceRange();
4222       return nullptr;
4223     }
4224   }
4225 
4226   if (!Diff.isUsable())
4227     return nullptr;
4228 
4229   // Upper - Lower [- 1]
4230   if (TestIsStrictOp)
4231     Diff = SemaRef.BuildBinOp(
4232         S, DefaultLoc, BO_Sub, Diff.get(),
4233         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4234   if (!Diff.isUsable())
4235     return nullptr;
4236 
4237   // Upper - Lower [- 1] + Step
4238   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4239   if (!NewStep.isUsable())
4240     return nullptr;
4241   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4242   if (!Diff.isUsable())
4243     return nullptr;
4244 
4245   // Parentheses (for dumping/debugging purposes only).
4246   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4247   if (!Diff.isUsable())
4248     return nullptr;
4249 
4250   // (Upper - Lower [- 1] + Step) / Step
4251   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4252   if (!Diff.isUsable())
4253     return nullptr;
4254 
4255   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4256   QualType Type = Diff.get()->getType();
4257   auto &C = SemaRef.Context;
4258   bool UseVarType = VarType->hasIntegerRepresentation() &&
4259                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4260   if (!Type->isIntegerType() || UseVarType) {
4261     unsigned NewSize =
4262         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4263     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4264                                : Type->hasSignedIntegerRepresentation();
4265     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4266     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4267       Diff = SemaRef.PerformImplicitConversion(
4268           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4269       if (!Diff.isUsable())
4270         return nullptr;
4271     }
4272   }
4273   if (LimitedType) {
4274     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4275     if (NewSize != C.getTypeSize(Type)) {
4276       if (NewSize < C.getTypeSize(Type)) {
4277         assert(NewSize == 64 && "incorrect loop var size");
4278         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4279             << InitSrcRange << ConditionSrcRange;
4280       }
4281       QualType NewType = C.getIntTypeForBitwidth(
4282           NewSize, Type->hasSignedIntegerRepresentation() ||
4283                        C.getTypeSize(Type) < NewSize);
4284       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4285         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4286                                                  Sema::AA_Converting, true);
4287         if (!Diff.isUsable())
4288           return nullptr;
4289       }
4290     }
4291   }
4292 
4293   return Diff.get();
4294 }
4295 
4296 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4297     Scope *S, Expr *Cond,
4298     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
4299   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4300   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4301   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4302 
4303   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4304   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4305   if (!NewLB.isUsable() || !NewUB.isUsable())
4306     return nullptr;
4307 
4308   auto CondExpr = SemaRef.BuildBinOp(
4309       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4310                                   : (TestIsStrictOp ? BO_GT : BO_GE),
4311       NewLB.get(), NewUB.get());
4312   if (CondExpr.isUsable()) {
4313     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4314                                                 SemaRef.Context.BoolTy))
4315       CondExpr = SemaRef.PerformImplicitConversion(
4316           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4317           /*AllowExplicit=*/true);
4318   }
4319   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4320   // Otherwise use original loop conditon and evaluate it in runtime.
4321   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4322 }
4323 
4324 /// \brief Build reference expression to the counter be used for codegen.
4325 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
4326     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
4327   auto *VD = dyn_cast<VarDecl>(LCDecl);
4328   if (!VD) {
4329     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4330     auto *Ref = buildDeclRefExpr(
4331         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4332     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4333     // If the loop control decl is explicitly marked as private, do not mark it
4334     // as captured again.
4335     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4336       Captures.insert(std::make_pair(LCRef, Ref));
4337     return Ref;
4338   }
4339   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4340                           DefaultLoc);
4341 }
4342 
4343 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
4344   if (LCDecl && !LCDecl->isInvalidDecl()) {
4345     auto Type = LCDecl->getType().getNonReferenceType();
4346     auto *PrivateVar =
4347         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4348                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
4349     if (PrivateVar->isInvalidDecl())
4350       return nullptr;
4351     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4352   }
4353   return nullptr;
4354 }
4355 
4356 /// \brief Build initization of the counter be used for codegen.
4357 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4358 
4359 /// \brief Build step of the counter be used for codegen.
4360 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4361 
4362 /// \brief Iteration space of a single for loop.
4363 struct LoopIterationSpace final {
4364   /// \brief Condition of the loop.
4365   Expr *PreCond = nullptr;
4366   /// \brief This expression calculates the number of iterations in the loop.
4367   /// It is always possible to calculate it before starting the loop.
4368   Expr *NumIterations = nullptr;
4369   /// \brief The loop counter variable.
4370   Expr *CounterVar = nullptr;
4371   /// \brief Private loop counter variable.
4372   Expr *PrivateCounterVar = nullptr;
4373   /// \brief This is initializer for the initial value of #CounterVar.
4374   Expr *CounterInit = nullptr;
4375   /// \brief This is step for the #CounterVar used to generate its update:
4376   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4377   Expr *CounterStep = nullptr;
4378   /// \brief Should step be subtracted?
4379   bool Subtract = false;
4380   /// \brief Source range of the loop init.
4381   SourceRange InitSrcRange;
4382   /// \brief Source range of the loop condition.
4383   SourceRange CondSrcRange;
4384   /// \brief Source range of the loop increment.
4385   SourceRange IncSrcRange;
4386 };
4387 
4388 } // namespace
4389 
4390 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4391   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4392   assert(Init && "Expected loop in canonical form.");
4393   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4394   if (AssociatedLoops > 0 &&
4395       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4396     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4397     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4398       if (auto *D = ISC.GetLoopDecl()) {
4399         auto *VD = dyn_cast<VarDecl>(D);
4400         if (!VD) {
4401           if (auto *Private = IsOpenMPCapturedDecl(D))
4402             VD = Private;
4403           else {
4404             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4405                                      /*WithInit=*/false);
4406             VD = cast<VarDecl>(Ref->getDecl());
4407           }
4408         }
4409         DSAStack->addLoopControlVariable(D, VD);
4410       }
4411     }
4412     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4413   }
4414 }
4415 
4416 /// \brief Called on a for stmt to check and extract its iteration space
4417 /// for further processing (such as collapsing).
4418 static bool CheckOpenMPIterationSpace(
4419     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4420     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4421     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
4422     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4423     LoopIterationSpace &ResultIterSpace,
4424     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4425   // OpenMP [2.6, Canonical Loop Form]
4426   //   for (init-expr; test-expr; incr-expr) structured-block
4427   auto For = dyn_cast_or_null<ForStmt>(S);
4428   if (!For) {
4429     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
4430         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4431         << getOpenMPDirectiveName(DKind) << NestedLoopCount
4432         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4433     if (NestedLoopCount > 1) {
4434       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4435         SemaRef.Diag(DSA.getConstructLoc(),
4436                      diag::note_omp_collapse_ordered_expr)
4437             << 2 << CollapseLoopCountExpr->getSourceRange()
4438             << OrderedLoopCountExpr->getSourceRange();
4439       else if (CollapseLoopCountExpr)
4440         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4441                      diag::note_omp_collapse_ordered_expr)
4442             << 0 << CollapseLoopCountExpr->getSourceRange();
4443       else
4444         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4445                      diag::note_omp_collapse_ordered_expr)
4446             << 1 << OrderedLoopCountExpr->getSourceRange();
4447     }
4448     return true;
4449   }
4450   assert(For->getBody());
4451 
4452   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4453 
4454   // Check init.
4455   auto Init = For->getInit();
4456   if (ISC.CheckInit(Init))
4457     return true;
4458 
4459   bool HasErrors = false;
4460 
4461   // Check loop variable's type.
4462   if (auto *LCDecl = ISC.GetLoopDecl()) {
4463     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
4464 
4465     // OpenMP [2.6, Canonical Loop Form]
4466     // Var is one of the following:
4467     //   A variable of signed or unsigned integer type.
4468     //   For C++, a variable of a random access iterator type.
4469     //   For C, a variable of a pointer type.
4470     auto VarType = LCDecl->getType().getNonReferenceType();
4471     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4472         !VarType->isPointerType() &&
4473         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4474       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4475           << SemaRef.getLangOpts().CPlusPlus;
4476       HasErrors = true;
4477     }
4478 
4479     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4480     // a Construct
4481     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4482     // parallel for construct is (are) private.
4483     // The loop iteration variable in the associated for-loop of a simd
4484     // construct with just one associated for-loop is linear with a
4485     // constant-linear-step that is the increment of the associated for-loop.
4486     // Exclude loop var from the list of variables with implicitly defined data
4487     // sharing attributes.
4488     VarsWithImplicitDSA.erase(LCDecl);
4489 
4490     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4491     // in a Construct, C/C++].
4492     // The loop iteration variable in the associated for-loop of a simd
4493     // construct with just one associated for-loop may be listed in a linear
4494     // clause with a constant-linear-step that is the increment of the
4495     // associated for-loop.
4496     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4497     // parallel for construct may be listed in a private or lastprivate clause.
4498     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4499     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4500     // declared in the loop and it is predetermined as a private.
4501     auto PredeterminedCKind =
4502         isOpenMPSimdDirective(DKind)
4503             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4504             : OMPC_private;
4505     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4506           DVar.CKind != PredeterminedCKind) ||
4507          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4508            isOpenMPDistributeDirective(DKind)) &&
4509           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4510           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4511         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4512       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4513           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4514           << getOpenMPClauseName(PredeterminedCKind);
4515       if (DVar.RefExpr == nullptr)
4516         DVar.CKind = PredeterminedCKind;
4517       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4518       HasErrors = true;
4519     } else if (LoopDeclRefExpr != nullptr) {
4520       // Make the loop iteration variable private (for worksharing constructs),
4521       // linear (for simd directives with the only one associated loop) or
4522       // lastprivate (for simd directives with several collapsed or ordered
4523       // loops).
4524       if (DVar.CKind == OMPC_unknown)
4525         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4526                           [](OpenMPDirectiveKind) -> bool { return true; },
4527                           /*FromParent=*/false);
4528       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4529     }
4530 
4531     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4532 
4533     // Check test-expr.
4534     HasErrors |= ISC.CheckCond(For->getCond());
4535 
4536     // Check incr-expr.
4537     HasErrors |= ISC.CheckInc(For->getInc());
4538   }
4539 
4540   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4541     return HasErrors;
4542 
4543   // Build the loop's iteration space representation.
4544   ResultIterSpace.PreCond =
4545       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4546   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
4547       DSA.getCurScope(),
4548       (isOpenMPWorksharingDirective(DKind) ||
4549        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4550       Captures);
4551   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
4552   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
4553   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4554   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4555   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4556   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4557   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4558   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4559 
4560   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4561                 ResultIterSpace.NumIterations == nullptr ||
4562                 ResultIterSpace.CounterVar == nullptr ||
4563                 ResultIterSpace.PrivateCounterVar == nullptr ||
4564                 ResultIterSpace.CounterInit == nullptr ||
4565                 ResultIterSpace.CounterStep == nullptr);
4566 
4567   return HasErrors;
4568 }
4569 
4570 /// \brief Build 'VarRef = Start.
4571 static ExprResult
4572 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4573                  ExprResult Start,
4574                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4575   // Build 'VarRef = Start.
4576   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4577   if (!NewStart.isUsable())
4578     return ExprError();
4579   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4580                                    VarRef.get()->getType())) {
4581     NewStart = SemaRef.PerformImplicitConversion(
4582         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4583         /*AllowExplicit=*/true);
4584     if (!NewStart.isUsable())
4585       return ExprError();
4586   }
4587 
4588   auto Init =
4589       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4590   return Init;
4591 }
4592 
4593 /// \brief Build 'VarRef = Start + Iter * Step'.
4594 static ExprResult
4595 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4596                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
4597                    ExprResult Step, bool Subtract,
4598                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
4599   // Add parentheses (for debugging purposes only).
4600   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4601   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4602       !Step.isUsable())
4603     return ExprError();
4604 
4605   ExprResult NewStep = Step;
4606   if (Captures)
4607     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4608   if (NewStep.isInvalid())
4609     return ExprError();
4610   ExprResult Update =
4611       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4612   if (!Update.isUsable())
4613     return ExprError();
4614 
4615   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4616   // 'VarRef = Start (+|-) Iter * Step'.
4617   ExprResult NewStart = Start;
4618   if (Captures)
4619     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4620   if (NewStart.isInvalid())
4621     return ExprError();
4622 
4623   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4624   ExprResult SavedUpdate = Update;
4625   ExprResult UpdateVal;
4626   if (VarRef.get()->getType()->isOverloadableType() ||
4627       NewStart.get()->getType()->isOverloadableType() ||
4628       Update.get()->getType()->isOverloadableType()) {
4629     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4630     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4631     Update =
4632         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4633     if (Update.isUsable()) {
4634       UpdateVal =
4635           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4636                              VarRef.get(), SavedUpdate.get());
4637       if (UpdateVal.isUsable()) {
4638         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4639                                             UpdateVal.get());
4640       }
4641     }
4642     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4643   }
4644 
4645   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4646   if (!Update.isUsable() || !UpdateVal.isUsable()) {
4647     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4648                                 NewStart.get(), SavedUpdate.get());
4649     if (!Update.isUsable())
4650       return ExprError();
4651 
4652     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4653                                      VarRef.get()->getType())) {
4654       Update = SemaRef.PerformImplicitConversion(
4655           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4656       if (!Update.isUsable())
4657         return ExprError();
4658     }
4659 
4660     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4661   }
4662   return Update;
4663 }
4664 
4665 /// \brief Convert integer expression \a E to make it have at least \a Bits
4666 /// bits.
4667 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
4668                                       Sema &SemaRef) {
4669   if (E == nullptr)
4670     return ExprError();
4671   auto &C = SemaRef.Context;
4672   QualType OldType = E->getType();
4673   unsigned HasBits = C.getTypeSize(OldType);
4674   if (HasBits >= Bits)
4675     return ExprResult(E);
4676   // OK to convert to signed, because new type has more bits than old.
4677   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4678   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4679                                            true);
4680 }
4681 
4682 /// \brief Check if the given expression \a E is a constant integer that fits
4683 /// into \a Bits bits.
4684 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4685   if (E == nullptr)
4686     return false;
4687   llvm::APSInt Result;
4688   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4689     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4690   return false;
4691 }
4692 
4693 /// Build preinits statement for the given declarations.
4694 static Stmt *buildPreInits(ASTContext &Context,
4695                            SmallVectorImpl<Decl *> &PreInits) {
4696   if (!PreInits.empty()) {
4697     return new (Context) DeclStmt(
4698         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4699         SourceLocation(), SourceLocation());
4700   }
4701   return nullptr;
4702 }
4703 
4704 /// Build preinits statement for the given declarations.
4705 static Stmt *buildPreInits(ASTContext &Context,
4706                            llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4707   if (!Captures.empty()) {
4708     SmallVector<Decl *, 16> PreInits;
4709     for (auto &Pair : Captures)
4710       PreInits.push_back(Pair.second->getDecl());
4711     return buildPreInits(Context, PreInits);
4712   }
4713   return nullptr;
4714 }
4715 
4716 /// Build postupdate expression for the given list of postupdates expressions.
4717 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4718   Expr *PostUpdate = nullptr;
4719   if (!PostUpdates.empty()) {
4720     for (auto *E : PostUpdates) {
4721       Expr *ConvE = S.BuildCStyleCastExpr(
4722                          E->getExprLoc(),
4723                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4724                          E->getExprLoc(), E)
4725                         .get();
4726       PostUpdate = PostUpdate
4727                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4728                                               PostUpdate, ConvE)
4729                              .get()
4730                        : ConvE;
4731     }
4732   }
4733   return PostUpdate;
4734 }
4735 
4736 /// \brief Called on a for stmt to check itself and nested loops (if any).
4737 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4738 /// number of collapsed loops otherwise.
4739 static unsigned
4740 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4741                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4742                 DSAStackTy &DSA,
4743                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
4744                 OMPLoopDirective::HelperExprs &Built) {
4745   unsigned NestedLoopCount = 1;
4746   if (CollapseLoopCountExpr) {
4747     // Found 'collapse' clause - calculate collapse number.
4748     llvm::APSInt Result;
4749     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
4750       NestedLoopCount = Result.getLimitedValue();
4751   }
4752   if (OrderedLoopCountExpr) {
4753     // Found 'ordered' clause - calculate collapse number.
4754     llvm::APSInt Result;
4755     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4756       if (Result.getLimitedValue() < NestedLoopCount) {
4757         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4758                      diag::err_omp_wrong_ordered_loop_count)
4759             << OrderedLoopCountExpr->getSourceRange();
4760         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4761                      diag::note_collapse_loop_count)
4762             << CollapseLoopCountExpr->getSourceRange();
4763       }
4764       NestedLoopCount = Result.getLimitedValue();
4765     }
4766   }
4767   // This is helper routine for loop directives (e.g., 'for', 'simd',
4768   // 'for simd', etc.).
4769   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
4770   SmallVector<LoopIterationSpace, 4> IterSpaces;
4771   IterSpaces.resize(NestedLoopCount);
4772   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
4773   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
4774     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
4775                                   NestedLoopCount, CollapseLoopCountExpr,
4776                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
4777                                   IterSpaces[Cnt], Captures))
4778       return 0;
4779     // Move on to the next nested for loop, or to the loop body.
4780     // OpenMP [2.8.1, simd construct, Restrictions]
4781     // All loops associated with the construct must be perfectly nested; that
4782     // is, there must be no intervening code nor any OpenMP directive between
4783     // any two loops.
4784     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
4785   }
4786 
4787   Built.clear(/* size */ NestedLoopCount);
4788 
4789   if (SemaRef.CurContext->isDependentContext())
4790     return NestedLoopCount;
4791 
4792   // An example of what is generated for the following code:
4793   //
4794   //   #pragma omp simd collapse(2) ordered(2)
4795   //   for (i = 0; i < NI; ++i)
4796   //     for (k = 0; k < NK; ++k)
4797   //       for (j = J0; j < NJ; j+=2) {
4798   //         <loop body>
4799   //       }
4800   //
4801   // We generate the code below.
4802   // Note: the loop body may be outlined in CodeGen.
4803   // Note: some counters may be C++ classes, operator- is used to find number of
4804   // iterations and operator+= to calculate counter value.
4805   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4806   // or i64 is currently supported).
4807   //
4808   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4809   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4810   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4811   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4812   //     // similar updates for vars in clauses (e.g. 'linear')
4813   //     <loop body (using local i and j)>
4814   //   }
4815   //   i = NI; // assign final values of counters
4816   //   j = NJ;
4817   //
4818 
4819   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4820   // the iteration counts of the collapsed for loops.
4821   // Precondition tests if there is at least one iteration (all conditions are
4822   // true).
4823   auto PreCond = ExprResult(IterSpaces[0].PreCond);
4824   auto N0 = IterSpaces[0].NumIterations;
4825   ExprResult LastIteration32 = WidenIterationCount(
4826       32 /* Bits */, SemaRef.PerformImplicitConversion(
4827                                 N0->IgnoreImpCasts(), N0->getType(),
4828                                 Sema::AA_Converting, /*AllowExplicit=*/true)
4829                          .get(),
4830       SemaRef);
4831   ExprResult LastIteration64 = WidenIterationCount(
4832       64 /* Bits */, SemaRef.PerformImplicitConversion(
4833                                 N0->IgnoreImpCasts(), N0->getType(),
4834                                 Sema::AA_Converting, /*AllowExplicit=*/true)
4835                          .get(),
4836       SemaRef);
4837 
4838   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4839     return NestedLoopCount;
4840 
4841   auto &C = SemaRef.Context;
4842   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4843 
4844   Scope *CurScope = DSA.getCurScope();
4845   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
4846     if (PreCond.isUsable()) {
4847       PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
4848                                    PreCond.get(), IterSpaces[Cnt].PreCond);
4849     }
4850     auto N = IterSpaces[Cnt].NumIterations;
4851     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4852     if (LastIteration32.isUsable())
4853       LastIteration32 = SemaRef.BuildBinOp(
4854           CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
4855           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4856                                             Sema::AA_Converting,
4857                                             /*AllowExplicit=*/true)
4858               .get());
4859     if (LastIteration64.isUsable())
4860       LastIteration64 = SemaRef.BuildBinOp(
4861           CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
4862           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4863                                             Sema::AA_Converting,
4864                                             /*AllowExplicit=*/true)
4865               .get());
4866   }
4867 
4868   // Choose either the 32-bit or 64-bit version.
4869   ExprResult LastIteration = LastIteration64;
4870   if (LastIteration32.isUsable() &&
4871       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4872       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4873        FitsInto(
4874            32 /* Bits */,
4875            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4876            LastIteration64.get(), SemaRef)))
4877     LastIteration = LastIteration32;
4878   QualType VType = LastIteration.get()->getType();
4879   QualType RealVType = VType;
4880   QualType StrideVType = VType;
4881   if (isOpenMPTaskLoopDirective(DKind)) {
4882     VType =
4883         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4884     StrideVType =
4885         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4886   }
4887 
4888   if (!LastIteration.isUsable())
4889     return 0;
4890 
4891   // Save the number of iterations.
4892   ExprResult NumIterations = LastIteration;
4893   {
4894     LastIteration = SemaRef.BuildBinOp(
4895         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
4896         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4897     if (!LastIteration.isUsable())
4898       return 0;
4899   }
4900 
4901   // Calculate the last iteration number beforehand instead of doing this on
4902   // each iteration. Do not do this if the number of iterations may be kfold-ed.
4903   llvm::APSInt Result;
4904   bool IsConstant =
4905       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4906   ExprResult CalcLastIteration;
4907   if (!IsConstant) {
4908     ExprResult SaveRef =
4909         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
4910     LastIteration = SaveRef;
4911 
4912     // Prepare SaveRef + 1.
4913     NumIterations = SemaRef.BuildBinOp(
4914         CurScope, SourceLocation(), BO_Add, SaveRef.get(),
4915         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4916     if (!NumIterations.isUsable())
4917       return 0;
4918   }
4919 
4920   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4921 
4922   // Build variables passed into runtime, nesessary for worksharing directives.
4923   ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
4924   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4925       isOpenMPDistributeDirective(DKind)) {
4926     // Lower bound variable, initialized with zero.
4927     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4928     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
4929     SemaRef.AddInitializerToDecl(
4930         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4931         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4932 
4933     // Upper bound variable, initialized with last iteration number.
4934     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4935     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
4936     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
4937                                  /*DirectInit*/ false,
4938                                  /*TypeMayContainAuto*/ false);
4939 
4940     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4941     // This will be used to implement clause 'lastprivate'.
4942     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
4943     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4944     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
4945     SemaRef.AddInitializerToDecl(
4946         ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4947         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4948 
4949     // Stride variable returned by runtime (we initialize it to 1 by default).
4950     VarDecl *STDecl =
4951         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4952     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
4953     SemaRef.AddInitializerToDecl(
4954         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4955         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
4956 
4957     // Build expression: UB = min(UB, LastIteration)
4958     // It is nesessary for CodeGen of directives with static scheduling.
4959     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4960                                                 UB.get(), LastIteration.get());
4961     ExprResult CondOp = SemaRef.ActOnConditionalOp(
4962         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4963     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4964                              CondOp.get());
4965     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
4966 
4967     // If we have a combined directive that combines 'distribute', 'for' or
4968     // 'simd' we need to be able to access the bounds of the schedule of the
4969     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4970     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4971     if (isOpenMPLoopBoundSharingDirective(DKind)) {
4972       auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4973 
4974       // We expect to have at least 2 more parameters than the 'parallel'
4975       // directive does - the lower and upper bounds of the previous schedule.
4976       assert(CD->getNumParams() >= 4 &&
4977              "Unexpected number of parameters in loop combined directive");
4978 
4979       // Set the proper type for the bounds given what we learned from the
4980       // enclosed loops.
4981       auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4982       auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4983 
4984       // Previous lower and upper bounds are obtained from the region
4985       // parameters.
4986       PrevLB =
4987           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4988       PrevUB =
4989           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4990     }
4991   }
4992 
4993   // Build the iteration variable and its initialization before loop.
4994   ExprResult IV;
4995   ExprResult Init;
4996   {
4997     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4998     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
4999     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
5000                  isOpenMPTaskLoopDirective(DKind) ||
5001                  isOpenMPDistributeDirective(DKind))
5002                     ? LB.get()
5003                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5004     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5005     Init = SemaRef.ActOnFinishFullExpr(Init.get());
5006   }
5007 
5008   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
5009   SourceLocation CondLoc;
5010   ExprResult Cond =
5011       (isOpenMPWorksharingDirective(DKind) ||
5012        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5013           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
5014           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5015                                NumIterations.get());
5016 
5017   // Loop increment (IV = IV + 1)
5018   SourceLocation IncLoc;
5019   ExprResult Inc =
5020       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5021                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5022   if (!Inc.isUsable())
5023     return 0;
5024   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5025   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
5026   if (!Inc.isUsable())
5027     return 0;
5028 
5029   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5030   // Used for directives with static scheduling.
5031   ExprResult NextLB, NextUB;
5032   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5033       isOpenMPDistributeDirective(DKind)) {
5034     // LB + ST
5035     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5036     if (!NextLB.isUsable())
5037       return 0;
5038     // LB = LB + ST
5039     NextLB =
5040         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5041     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
5042     if (!NextLB.isUsable())
5043       return 0;
5044     // UB + ST
5045     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5046     if (!NextUB.isUsable())
5047       return 0;
5048     // UB = UB + ST
5049     NextUB =
5050         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5051     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
5052     if (!NextUB.isUsable())
5053       return 0;
5054   }
5055 
5056   // Build updates and final values of the loop counters.
5057   bool HasErrors = false;
5058   Built.Counters.resize(NestedLoopCount);
5059   Built.Inits.resize(NestedLoopCount);
5060   Built.Updates.resize(NestedLoopCount);
5061   Built.Finals.resize(NestedLoopCount);
5062   SmallVector<Expr *, 4> LoopMultipliers;
5063   {
5064     ExprResult Div;
5065     // Go from inner nested loop to outer.
5066     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5067       LoopIterationSpace &IS = IterSpaces[Cnt];
5068       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5069       // Build: Iter = (IV / Div) % IS.NumIters
5070       // where Div is product of previous iterations' IS.NumIters.
5071       ExprResult Iter;
5072       if (Div.isUsable()) {
5073         Iter =
5074             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5075       } else {
5076         Iter = IV;
5077         assert((Cnt == (int)NestedLoopCount - 1) &&
5078                "unusable div expected on first iteration only");
5079       }
5080 
5081       if (Cnt != 0 && Iter.isUsable())
5082         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5083                                   IS.NumIterations);
5084       if (!Iter.isUsable()) {
5085         HasErrors = true;
5086         break;
5087       }
5088 
5089       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5090       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5091       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5092                                           IS.CounterVar->getExprLoc(),
5093                                           /*RefersToCapture=*/true);
5094       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5095                                          IS.CounterInit, Captures);
5096       if (!Init.isUsable()) {
5097         HasErrors = true;
5098         break;
5099       }
5100       ExprResult Update = BuildCounterUpdate(
5101           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5102           IS.CounterStep, IS.Subtract, &Captures);
5103       if (!Update.isUsable()) {
5104         HasErrors = true;
5105         break;
5106       }
5107 
5108       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5109       ExprResult Final = BuildCounterUpdate(
5110           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5111           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5112       if (!Final.isUsable()) {
5113         HasErrors = true;
5114         break;
5115       }
5116 
5117       // Build Div for the next iteration: Div <- Div * IS.NumIters
5118       if (Cnt != 0) {
5119         if (Div.isUnset())
5120           Div = IS.NumIterations;
5121         else
5122           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5123                                    IS.NumIterations);
5124 
5125         // Add parentheses (for debugging purposes only).
5126         if (Div.isUsable())
5127           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
5128         if (!Div.isUsable()) {
5129           HasErrors = true;
5130           break;
5131         }
5132         LoopMultipliers.push_back(Div.get());
5133       }
5134       if (!Update.isUsable() || !Final.isUsable()) {
5135         HasErrors = true;
5136         break;
5137       }
5138       // Save results
5139       Built.Counters[Cnt] = IS.CounterVar;
5140       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5141       Built.Inits[Cnt] = Init.get();
5142       Built.Updates[Cnt] = Update.get();
5143       Built.Finals[Cnt] = Final.get();
5144     }
5145   }
5146 
5147   if (HasErrors)
5148     return 0;
5149 
5150   // Save results
5151   Built.IterationVarRef = IV.get();
5152   Built.LastIteration = LastIteration.get();
5153   Built.NumIterations = NumIterations.get();
5154   Built.CalcLastIteration =
5155       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
5156   Built.PreCond = PreCond.get();
5157   Built.PreInits = buildPreInits(C, Captures);
5158   Built.Cond = Cond.get();
5159   Built.Init = Init.get();
5160   Built.Inc = Inc.get();
5161   Built.LB = LB.get();
5162   Built.UB = UB.get();
5163   Built.IL = IL.get();
5164   Built.ST = ST.get();
5165   Built.EUB = EUB.get();
5166   Built.NLB = NextLB.get();
5167   Built.NUB = NextUB.get();
5168   Built.PrevLB = PrevLB.get();
5169   Built.PrevUB = PrevUB.get();
5170 
5171   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5172   // Fill data for doacross depend clauses.
5173   for (auto Pair : DSA.getDoacrossDependClauses()) {
5174     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5175       Pair.first->setCounterValue(CounterVal);
5176     else {
5177       if (NestedLoopCount != Pair.second.size() ||
5178           NestedLoopCount != LoopMultipliers.size() + 1) {
5179         // Erroneous case - clause has some problems.
5180         Pair.first->setCounterValue(CounterVal);
5181         continue;
5182       }
5183       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5184       auto I = Pair.second.rbegin();
5185       auto IS = IterSpaces.rbegin();
5186       auto ILM = LoopMultipliers.rbegin();
5187       Expr *UpCounterVal = CounterVal;
5188       Expr *Multiplier = nullptr;
5189       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5190         if (I->first) {
5191           assert(IS->CounterStep);
5192           Expr *NormalizedOffset =
5193               SemaRef
5194                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5195                               I->first, IS->CounterStep)
5196                   .get();
5197           if (Multiplier) {
5198             NormalizedOffset =
5199                 SemaRef
5200                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5201                                 NormalizedOffset, Multiplier)
5202                     .get();
5203           }
5204           assert(I->second == OO_Plus || I->second == OO_Minus);
5205           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
5206           UpCounterVal =
5207               SemaRef.BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5208                                  UpCounterVal, NormalizedOffset).get();
5209         }
5210         Multiplier = *ILM;
5211         ++I;
5212         ++IS;
5213         ++ILM;
5214       }
5215       Pair.first->setCounterValue(UpCounterVal);
5216     }
5217   }
5218 
5219   return NestedLoopCount;
5220 }
5221 
5222 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5223   auto CollapseClauses =
5224       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5225   if (CollapseClauses.begin() != CollapseClauses.end())
5226     return (*CollapseClauses.begin())->getNumForLoops();
5227   return nullptr;
5228 }
5229 
5230 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5231   auto OrderedClauses =
5232       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5233   if (OrderedClauses.begin() != OrderedClauses.end())
5234     return (*OrderedClauses.begin())->getNumForLoops();
5235   return nullptr;
5236 }
5237 
5238 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
5239                                       const Expr *Safelen) {
5240   llvm::APSInt SimdlenRes, SafelenRes;
5241   if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
5242       Simdlen->isInstantiationDependent() ||
5243       Simdlen->containsUnexpandedParameterPack())
5244     return false;
5245   if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
5246       Safelen->isInstantiationDependent() ||
5247       Safelen->containsUnexpandedParameterPack())
5248     return false;
5249   Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
5250   Safelen->EvaluateAsInt(SafelenRes, S.Context);
5251   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5252   // If both simdlen and safelen clauses are specified, the value of the simdlen
5253   // parameter must be less than or equal to the value of the safelen parameter.
5254   if (SimdlenRes > SafelenRes) {
5255     S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
5256         << Simdlen->getSourceRange() << Safelen->getSourceRange();
5257     return true;
5258   }
5259   return false;
5260 }
5261 
5262 StmtResult Sema::ActOnOpenMPSimdDirective(
5263     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5264     SourceLocation EndLoc,
5265     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5266   if (!AStmt)
5267     return StmtError();
5268 
5269   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5270   OMPLoopDirective::HelperExprs B;
5271   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5272   // define the nested loops number.
5273   unsigned NestedLoopCount = CheckOpenMPLoop(
5274       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5275       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5276   if (NestedLoopCount == 0)
5277     return StmtError();
5278 
5279   assert((CurContext->isDependentContext() || B.builtAll()) &&
5280          "omp simd loop exprs were not built");
5281 
5282   if (!CurContext->isDependentContext()) {
5283     // Finalize the clauses that need pre-built expressions for CodeGen.
5284     for (auto C : Clauses) {
5285       if (auto LC = dyn_cast<OMPLinearClause>(C))
5286         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5287                                      B.NumIterations, *this, CurScope,
5288                                      DSAStack))
5289           return StmtError();
5290     }
5291   }
5292 
5293   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5294   // If both simdlen and safelen clauses are specified, the value of the simdlen
5295   // parameter must be less than or equal to the value of the safelen parameter.
5296   OMPSafelenClause *Safelen = nullptr;
5297   OMPSimdlenClause *Simdlen = nullptr;
5298   for (auto *Clause : Clauses) {
5299     if (Clause->getClauseKind() == OMPC_safelen)
5300       Safelen = cast<OMPSafelenClause>(Clause);
5301     else if (Clause->getClauseKind() == OMPC_simdlen)
5302       Simdlen = cast<OMPSimdlenClause>(Clause);
5303     if (Safelen && Simdlen)
5304       break;
5305   }
5306   if (Simdlen && Safelen &&
5307       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5308                                 Safelen->getSafelen()))
5309     return StmtError();
5310 
5311   getCurFunction()->setHasBranchProtectedScope();
5312   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5313                                   Clauses, AStmt, B);
5314 }
5315 
5316 StmtResult Sema::ActOnOpenMPForDirective(
5317     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5318     SourceLocation EndLoc,
5319     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5320   if (!AStmt)
5321     return StmtError();
5322 
5323   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5324   OMPLoopDirective::HelperExprs B;
5325   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5326   // define the nested loops number.
5327   unsigned NestedLoopCount = CheckOpenMPLoop(
5328       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5329       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5330   if (NestedLoopCount == 0)
5331     return StmtError();
5332 
5333   assert((CurContext->isDependentContext() || B.builtAll()) &&
5334          "omp for loop exprs were not built");
5335 
5336   if (!CurContext->isDependentContext()) {
5337     // Finalize the clauses that need pre-built expressions for CodeGen.
5338     for (auto C : Clauses) {
5339       if (auto LC = dyn_cast<OMPLinearClause>(C))
5340         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5341                                      B.NumIterations, *this, CurScope,
5342                                      DSAStack))
5343           return StmtError();
5344     }
5345   }
5346 
5347   getCurFunction()->setHasBranchProtectedScope();
5348   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5349                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5350 }
5351 
5352 StmtResult Sema::ActOnOpenMPForSimdDirective(
5353     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5354     SourceLocation EndLoc,
5355     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5356   if (!AStmt)
5357     return StmtError();
5358 
5359   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5360   OMPLoopDirective::HelperExprs B;
5361   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5362   // define the nested loops number.
5363   unsigned NestedLoopCount =
5364       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5365                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5366                       VarsWithImplicitDSA, B);
5367   if (NestedLoopCount == 0)
5368     return StmtError();
5369 
5370   assert((CurContext->isDependentContext() || B.builtAll()) &&
5371          "omp for simd loop exprs were not built");
5372 
5373   if (!CurContext->isDependentContext()) {
5374     // Finalize the clauses that need pre-built expressions for CodeGen.
5375     for (auto C : Clauses) {
5376       if (auto LC = dyn_cast<OMPLinearClause>(C))
5377         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5378                                      B.NumIterations, *this, CurScope,
5379                                      DSAStack))
5380           return StmtError();
5381     }
5382   }
5383 
5384   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5385   // If both simdlen and safelen clauses are specified, the value of the simdlen
5386   // parameter must be less than or equal to the value of the safelen parameter.
5387   OMPSafelenClause *Safelen = nullptr;
5388   OMPSimdlenClause *Simdlen = nullptr;
5389   for (auto *Clause : Clauses) {
5390     if (Clause->getClauseKind() == OMPC_safelen)
5391       Safelen = cast<OMPSafelenClause>(Clause);
5392     else if (Clause->getClauseKind() == OMPC_simdlen)
5393       Simdlen = cast<OMPSimdlenClause>(Clause);
5394     if (Safelen && Simdlen)
5395       break;
5396   }
5397   if (Simdlen && Safelen &&
5398       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5399                                 Safelen->getSafelen()))
5400     return StmtError();
5401 
5402   getCurFunction()->setHasBranchProtectedScope();
5403   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5404                                      Clauses, AStmt, B);
5405 }
5406 
5407 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5408                                               Stmt *AStmt,
5409                                               SourceLocation StartLoc,
5410                                               SourceLocation EndLoc) {
5411   if (!AStmt)
5412     return StmtError();
5413 
5414   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5415   auto BaseStmt = AStmt;
5416   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5417     BaseStmt = CS->getCapturedStmt();
5418   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5419     auto S = C->children();
5420     if (S.begin() == S.end())
5421       return StmtError();
5422     // All associated statements must be '#pragma omp section' except for
5423     // the first one.
5424     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5425       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5426         if (SectionStmt)
5427           Diag(SectionStmt->getLocStart(),
5428                diag::err_omp_sections_substmt_not_section);
5429         return StmtError();
5430       }
5431       cast<OMPSectionDirective>(SectionStmt)
5432           ->setHasCancel(DSAStack->isCancelRegion());
5433     }
5434   } else {
5435     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5436     return StmtError();
5437   }
5438 
5439   getCurFunction()->setHasBranchProtectedScope();
5440 
5441   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5442                                       DSAStack->isCancelRegion());
5443 }
5444 
5445 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5446                                              SourceLocation StartLoc,
5447                                              SourceLocation EndLoc) {
5448   if (!AStmt)
5449     return StmtError();
5450 
5451   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5452 
5453   getCurFunction()->setHasBranchProtectedScope();
5454   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5455 
5456   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5457                                      DSAStack->isCancelRegion());
5458 }
5459 
5460 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5461                                             Stmt *AStmt,
5462                                             SourceLocation StartLoc,
5463                                             SourceLocation EndLoc) {
5464   if (!AStmt)
5465     return StmtError();
5466 
5467   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5468 
5469   getCurFunction()->setHasBranchProtectedScope();
5470 
5471   // OpenMP [2.7.3, single Construct, Restrictions]
5472   // The copyprivate clause must not be used with the nowait clause.
5473   OMPClause *Nowait = nullptr;
5474   OMPClause *Copyprivate = nullptr;
5475   for (auto *Clause : Clauses) {
5476     if (Clause->getClauseKind() == OMPC_nowait)
5477       Nowait = Clause;
5478     else if (Clause->getClauseKind() == OMPC_copyprivate)
5479       Copyprivate = Clause;
5480     if (Copyprivate && Nowait) {
5481       Diag(Copyprivate->getLocStart(),
5482            diag::err_omp_single_copyprivate_with_nowait);
5483       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5484       return StmtError();
5485     }
5486   }
5487 
5488   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5489 }
5490 
5491 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5492                                             SourceLocation StartLoc,
5493                                             SourceLocation EndLoc) {
5494   if (!AStmt)
5495     return StmtError();
5496 
5497   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5498 
5499   getCurFunction()->setHasBranchProtectedScope();
5500 
5501   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5502 }
5503 
5504 StmtResult Sema::ActOnOpenMPCriticalDirective(
5505     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5506     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
5507   if (!AStmt)
5508     return StmtError();
5509 
5510   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5511 
5512   bool ErrorFound = false;
5513   llvm::APSInt Hint;
5514   SourceLocation HintLoc;
5515   bool DependentHint = false;
5516   for (auto *C : Clauses) {
5517     if (C->getClauseKind() == OMPC_hint) {
5518       if (!DirName.getName()) {
5519         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5520         ErrorFound = true;
5521       }
5522       Expr *E = cast<OMPHintClause>(C)->getHint();
5523       if (E->isTypeDependent() || E->isValueDependent() ||
5524           E->isInstantiationDependent())
5525         DependentHint = true;
5526       else {
5527         Hint = E->EvaluateKnownConstInt(Context);
5528         HintLoc = C->getLocStart();
5529       }
5530     }
5531   }
5532   if (ErrorFound)
5533     return StmtError();
5534   auto Pair = DSAStack->getCriticalWithHint(DirName);
5535   if (Pair.first && DirName.getName() && !DependentHint) {
5536     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5537       Diag(StartLoc, diag::err_omp_critical_with_hint);
5538       if (HintLoc.isValid()) {
5539         Diag(HintLoc, diag::note_omp_critical_hint_here)
5540             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5541       } else
5542         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5543       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5544         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5545             << 1
5546             << C->getHint()->EvaluateKnownConstInt(Context).toString(
5547                    /*Radix=*/10, /*Signed=*/false);
5548       } else
5549         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5550     }
5551   }
5552 
5553   getCurFunction()->setHasBranchProtectedScope();
5554 
5555   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5556                                            Clauses, AStmt);
5557   if (!Pair.first && DirName.getName() && !DependentHint)
5558     DSAStack->addCriticalWithHint(Dir, Hint);
5559   return Dir;
5560 }
5561 
5562 StmtResult Sema::ActOnOpenMPParallelForDirective(
5563     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5564     SourceLocation EndLoc,
5565     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5566   if (!AStmt)
5567     return StmtError();
5568 
5569   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5570   // 1.2.2 OpenMP Language Terminology
5571   // Structured block - An executable statement with a single entry at the
5572   // top and a single exit at the bottom.
5573   // The point of exit cannot be a branch out of the structured block.
5574   // longjmp() and throw() must not violate the entry/exit criteria.
5575   CS->getCapturedDecl()->setNothrow();
5576 
5577   OMPLoopDirective::HelperExprs B;
5578   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5579   // define the nested loops number.
5580   unsigned NestedLoopCount =
5581       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5582                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5583                       VarsWithImplicitDSA, B);
5584   if (NestedLoopCount == 0)
5585     return StmtError();
5586 
5587   assert((CurContext->isDependentContext() || B.builtAll()) &&
5588          "omp parallel for loop exprs were not built");
5589 
5590   if (!CurContext->isDependentContext()) {
5591     // Finalize the clauses that need pre-built expressions for CodeGen.
5592     for (auto C : Clauses) {
5593       if (auto LC = dyn_cast<OMPLinearClause>(C))
5594         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5595                                      B.NumIterations, *this, CurScope,
5596                                      DSAStack))
5597           return StmtError();
5598     }
5599   }
5600 
5601   getCurFunction()->setHasBranchProtectedScope();
5602   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
5603                                          NestedLoopCount, Clauses, AStmt, B,
5604                                          DSAStack->isCancelRegion());
5605 }
5606 
5607 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5608     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5609     SourceLocation EndLoc,
5610     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5611   if (!AStmt)
5612     return StmtError();
5613 
5614   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5615   // 1.2.2 OpenMP Language Terminology
5616   // Structured block - An executable statement with a single entry at the
5617   // top and a single exit at the bottom.
5618   // The point of exit cannot be a branch out of the structured block.
5619   // longjmp() and throw() must not violate the entry/exit criteria.
5620   CS->getCapturedDecl()->setNothrow();
5621 
5622   OMPLoopDirective::HelperExprs B;
5623   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5624   // define the nested loops number.
5625   unsigned NestedLoopCount =
5626       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5627                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5628                       VarsWithImplicitDSA, B);
5629   if (NestedLoopCount == 0)
5630     return StmtError();
5631 
5632   if (!CurContext->isDependentContext()) {
5633     // Finalize the clauses that need pre-built expressions for CodeGen.
5634     for (auto C : Clauses) {
5635       if (auto LC = dyn_cast<OMPLinearClause>(C))
5636         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5637                                      B.NumIterations, *this, CurScope,
5638                                      DSAStack))
5639           return StmtError();
5640     }
5641   }
5642 
5643   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
5644   // If both simdlen and safelen clauses are specified, the value of the simdlen
5645   // parameter must be less than or equal to the value of the safelen parameter.
5646   OMPSafelenClause *Safelen = nullptr;
5647   OMPSimdlenClause *Simdlen = nullptr;
5648   for (auto *Clause : Clauses) {
5649     if (Clause->getClauseKind() == OMPC_safelen)
5650       Safelen = cast<OMPSafelenClause>(Clause);
5651     else if (Clause->getClauseKind() == OMPC_simdlen)
5652       Simdlen = cast<OMPSimdlenClause>(Clause);
5653     if (Safelen && Simdlen)
5654       break;
5655   }
5656   if (Simdlen && Safelen &&
5657       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
5658                                 Safelen->getSafelen()))
5659     return StmtError();
5660 
5661   getCurFunction()->setHasBranchProtectedScope();
5662   return OMPParallelForSimdDirective::Create(
5663       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5664 }
5665 
5666 StmtResult
5667 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5668                                            Stmt *AStmt, SourceLocation StartLoc,
5669                                            SourceLocation EndLoc) {
5670   if (!AStmt)
5671     return StmtError();
5672 
5673   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5674   auto BaseStmt = AStmt;
5675   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5676     BaseStmt = CS->getCapturedStmt();
5677   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5678     auto S = C->children();
5679     if (S.begin() == S.end())
5680       return StmtError();
5681     // All associated statements must be '#pragma omp section' except for
5682     // the first one.
5683     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5684       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5685         if (SectionStmt)
5686           Diag(SectionStmt->getLocStart(),
5687                diag::err_omp_parallel_sections_substmt_not_section);
5688         return StmtError();
5689       }
5690       cast<OMPSectionDirective>(SectionStmt)
5691           ->setHasCancel(DSAStack->isCancelRegion());
5692     }
5693   } else {
5694     Diag(AStmt->getLocStart(),
5695          diag::err_omp_parallel_sections_not_compound_stmt);
5696     return StmtError();
5697   }
5698 
5699   getCurFunction()->setHasBranchProtectedScope();
5700 
5701   return OMPParallelSectionsDirective::Create(
5702       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
5703 }
5704 
5705 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5706                                           Stmt *AStmt, SourceLocation StartLoc,
5707                                           SourceLocation EndLoc) {
5708   if (!AStmt)
5709     return StmtError();
5710 
5711   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5712   // 1.2.2 OpenMP Language Terminology
5713   // Structured block - An executable statement with a single entry at the
5714   // top and a single exit at the bottom.
5715   // The point of exit cannot be a branch out of the structured block.
5716   // longjmp() and throw() must not violate the entry/exit criteria.
5717   CS->getCapturedDecl()->setNothrow();
5718 
5719   getCurFunction()->setHasBranchProtectedScope();
5720 
5721   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5722                                   DSAStack->isCancelRegion());
5723 }
5724 
5725 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5726                                                SourceLocation EndLoc) {
5727   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5728 }
5729 
5730 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5731                                              SourceLocation EndLoc) {
5732   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5733 }
5734 
5735 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5736                                               SourceLocation EndLoc) {
5737   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5738 }
5739 
5740 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
5741                                                SourceLocation StartLoc,
5742                                                SourceLocation EndLoc) {
5743   if (!AStmt)
5744     return StmtError();
5745 
5746   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5747 
5748   getCurFunction()->setHasBranchProtectedScope();
5749 
5750   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
5751 }
5752 
5753 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5754                                            SourceLocation StartLoc,
5755                                            SourceLocation EndLoc) {
5756   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5757   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5758 }
5759 
5760 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5761                                              Stmt *AStmt,
5762                                              SourceLocation StartLoc,
5763                                              SourceLocation EndLoc) {
5764   OMPClause *DependFound = nullptr;
5765   OMPClause *DependSourceClause = nullptr;
5766   OMPClause *DependSinkClause = nullptr;
5767   bool ErrorFound = false;
5768   OMPThreadsClause *TC = nullptr;
5769   OMPSIMDClause *SC = nullptr;
5770   for (auto *C : Clauses) {
5771     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5772       DependFound = C;
5773       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5774         if (DependSourceClause) {
5775           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5776               << getOpenMPDirectiveName(OMPD_ordered)
5777               << getOpenMPClauseName(OMPC_depend) << 2;
5778           ErrorFound = true;
5779         } else
5780           DependSourceClause = C;
5781         if (DependSinkClause) {
5782           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5783               << 0;
5784           ErrorFound = true;
5785         }
5786       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5787         if (DependSourceClause) {
5788           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5789               << 1;
5790           ErrorFound = true;
5791         }
5792         DependSinkClause = C;
5793       }
5794     } else if (C->getClauseKind() == OMPC_threads)
5795       TC = cast<OMPThreadsClause>(C);
5796     else if (C->getClauseKind() == OMPC_simd)
5797       SC = cast<OMPSIMDClause>(C);
5798   }
5799   if (!ErrorFound && !SC &&
5800       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
5801     // OpenMP [2.8.1,simd Construct, Restrictions]
5802     // An ordered construct with the simd clause is the only OpenMP construct
5803     // that can appear in the simd region.
5804     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
5805     ErrorFound = true;
5806   } else if (DependFound && (TC || SC)) {
5807     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5808         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5809     ErrorFound = true;
5810   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5811     Diag(DependFound->getLocStart(),
5812          diag::err_omp_ordered_directive_without_param);
5813     ErrorFound = true;
5814   } else if (TC || Clauses.empty()) {
5815     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5816       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5817       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5818           << (TC != nullptr);
5819       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5820       ErrorFound = true;
5821     }
5822   }
5823   if ((!AStmt && !DependFound) || ErrorFound)
5824     return StmtError();
5825 
5826   if (AStmt) {
5827     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5828 
5829     getCurFunction()->setHasBranchProtectedScope();
5830   }
5831 
5832   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5833 }
5834 
5835 namespace {
5836 /// \brief Helper class for checking expression in 'omp atomic [update]'
5837 /// construct.
5838 class OpenMPAtomicUpdateChecker {
5839   /// \brief Error results for atomic update expressions.
5840   enum ExprAnalysisErrorCode {
5841     /// \brief A statement is not an expression statement.
5842     NotAnExpression,
5843     /// \brief Expression is not builtin binary or unary operation.
5844     NotABinaryOrUnaryExpression,
5845     /// \brief Unary operation is not post-/pre- increment/decrement operation.
5846     NotAnUnaryIncDecExpression,
5847     /// \brief An expression is not of scalar type.
5848     NotAScalarType,
5849     /// \brief A binary operation is not an assignment operation.
5850     NotAnAssignmentOp,
5851     /// \brief RHS part of the binary operation is not a binary expression.
5852     NotABinaryExpression,
5853     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5854     /// expression.
5855     NotABinaryOperator,
5856     /// \brief RHS binary operation does not have reference to the updated LHS
5857     /// part.
5858     NotAnUpdateExpression,
5859     /// \brief No errors is found.
5860     NoError
5861   };
5862   /// \brief Reference to Sema.
5863   Sema &SemaRef;
5864   /// \brief A location for note diagnostics (when error is found).
5865   SourceLocation NoteLoc;
5866   /// \brief 'x' lvalue part of the source atomic expression.
5867   Expr *X;
5868   /// \brief 'expr' rvalue part of the source atomic expression.
5869   Expr *E;
5870   /// \brief Helper expression of the form
5871   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5872   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5873   Expr *UpdateExpr;
5874   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5875   /// important for non-associative operations.
5876   bool IsXLHSInRHSPart;
5877   BinaryOperatorKind Op;
5878   SourceLocation OpLoc;
5879   /// \brief true if the source expression is a postfix unary operation, false
5880   /// if it is a prefix unary operation.
5881   bool IsPostfixUpdate;
5882 
5883 public:
5884   OpenMPAtomicUpdateChecker(Sema &SemaRef)
5885       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
5886         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
5887   /// \brief Check specified statement that it is suitable for 'atomic update'
5888   /// constructs and extract 'x', 'expr' and Operation from the original
5889   /// expression. If DiagId and NoteId == 0, then only check is performed
5890   /// without error notification.
5891   /// \param DiagId Diagnostic which should be emitted if error is found.
5892   /// \param NoteId Diagnostic note for the main error message.
5893   /// \return true if statement is not an update expression, false otherwise.
5894   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
5895   /// \brief Return the 'x' lvalue part of the source atomic expression.
5896   Expr *getX() const { return X; }
5897   /// \brief Return the 'expr' rvalue part of the source atomic expression.
5898   Expr *getExpr() const { return E; }
5899   /// \brief Return the update expression used in calculation of the updated
5900   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5901   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5902   Expr *getUpdateExpr() const { return UpdateExpr; }
5903   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5904   /// false otherwise.
5905   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5906 
5907   /// \brief true if the source expression is a postfix unary operation, false
5908   /// if it is a prefix unary operation.
5909   bool isPostfixUpdate() const { return IsPostfixUpdate; }
5910 
5911 private:
5912   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5913                             unsigned NoteId = 0);
5914 };
5915 } // namespace
5916 
5917 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5918     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5919   ExprAnalysisErrorCode ErrorFound = NoError;
5920   SourceLocation ErrorLoc, NoteLoc;
5921   SourceRange ErrorRange, NoteRange;
5922   // Allowed constructs are:
5923   //  x = x binop expr;
5924   //  x = expr binop x;
5925   if (AtomicBinOp->getOpcode() == BO_Assign) {
5926     X = AtomicBinOp->getLHS();
5927     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5928             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5929       if (AtomicInnerBinOp->isMultiplicativeOp() ||
5930           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5931           AtomicInnerBinOp->isBitwiseOp()) {
5932         Op = AtomicInnerBinOp->getOpcode();
5933         OpLoc = AtomicInnerBinOp->getOperatorLoc();
5934         auto *LHS = AtomicInnerBinOp->getLHS();
5935         auto *RHS = AtomicInnerBinOp->getRHS();
5936         llvm::FoldingSetNodeID XId, LHSId, RHSId;
5937         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5938                                           /*Canonical=*/true);
5939         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5940                                             /*Canonical=*/true);
5941         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5942                                             /*Canonical=*/true);
5943         if (XId == LHSId) {
5944           E = RHS;
5945           IsXLHSInRHSPart = true;
5946         } else if (XId == RHSId) {
5947           E = LHS;
5948           IsXLHSInRHSPart = false;
5949         } else {
5950           ErrorLoc = AtomicInnerBinOp->getExprLoc();
5951           ErrorRange = AtomicInnerBinOp->getSourceRange();
5952           NoteLoc = X->getExprLoc();
5953           NoteRange = X->getSourceRange();
5954           ErrorFound = NotAnUpdateExpression;
5955         }
5956       } else {
5957         ErrorLoc = AtomicInnerBinOp->getExprLoc();
5958         ErrorRange = AtomicInnerBinOp->getSourceRange();
5959         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5960         NoteRange = SourceRange(NoteLoc, NoteLoc);
5961         ErrorFound = NotABinaryOperator;
5962       }
5963     } else {
5964       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5965       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5966       ErrorFound = NotABinaryExpression;
5967     }
5968   } else {
5969     ErrorLoc = AtomicBinOp->getExprLoc();
5970     ErrorRange = AtomicBinOp->getSourceRange();
5971     NoteLoc = AtomicBinOp->getOperatorLoc();
5972     NoteRange = SourceRange(NoteLoc, NoteLoc);
5973     ErrorFound = NotAnAssignmentOp;
5974   }
5975   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5976     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5977     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5978     return true;
5979   } else if (SemaRef.CurContext->isDependentContext())
5980     E = X = UpdateExpr = nullptr;
5981   return ErrorFound != NoError;
5982 }
5983 
5984 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5985                                                unsigned NoteId) {
5986   ExprAnalysisErrorCode ErrorFound = NoError;
5987   SourceLocation ErrorLoc, NoteLoc;
5988   SourceRange ErrorRange, NoteRange;
5989   // Allowed constructs are:
5990   //  x++;
5991   //  x--;
5992   //  ++x;
5993   //  --x;
5994   //  x binop= expr;
5995   //  x = x binop expr;
5996   //  x = expr binop x;
5997   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5998     AtomicBody = AtomicBody->IgnoreParenImpCasts();
5999     if (AtomicBody->getType()->isScalarType() ||
6000         AtomicBody->isInstantiationDependent()) {
6001       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6002               AtomicBody->IgnoreParenImpCasts())) {
6003         // Check for Compound Assignment Operation
6004         Op = BinaryOperator::getOpForCompoundAssignment(
6005             AtomicCompAssignOp->getOpcode());
6006         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6007         E = AtomicCompAssignOp->getRHS();
6008         X = AtomicCompAssignOp->getLHS();
6009         IsXLHSInRHSPart = true;
6010       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6011                      AtomicBody->IgnoreParenImpCasts())) {
6012         // Check for Binary Operation
6013         if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6014           return true;
6015       } else if (auto *AtomicUnaryOp =
6016                  dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
6017         // Check for Unary Operation
6018         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6019           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6020           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6021           OpLoc = AtomicUnaryOp->getOperatorLoc();
6022           X = AtomicUnaryOp->getSubExpr();
6023           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6024           IsXLHSInRHSPart = true;
6025         } else {
6026           ErrorFound = NotAnUnaryIncDecExpression;
6027           ErrorLoc = AtomicUnaryOp->getExprLoc();
6028           ErrorRange = AtomicUnaryOp->getSourceRange();
6029           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6030           NoteRange = SourceRange(NoteLoc, NoteLoc);
6031         }
6032       } else if (!AtomicBody->isInstantiationDependent()) {
6033         ErrorFound = NotABinaryOrUnaryExpression;
6034         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6035         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6036       }
6037     } else {
6038       ErrorFound = NotAScalarType;
6039       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
6040       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6041     }
6042   } else {
6043     ErrorFound = NotAnExpression;
6044     NoteLoc = ErrorLoc = S->getLocStart();
6045     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6046   }
6047   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6048     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6049     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6050     return true;
6051   } else if (SemaRef.CurContext->isDependentContext())
6052     E = X = UpdateExpr = nullptr;
6053   if (ErrorFound == NoError && E && X) {
6054     // Build an update expression of form 'OpaqueValueExpr(x) binop
6055     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6056     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6057     auto *OVEX = new (SemaRef.getASTContext())
6058         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6059     auto *OVEExpr = new (SemaRef.getASTContext())
6060         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6061     auto Update =
6062         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6063                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6064     if (Update.isInvalid())
6065       return true;
6066     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6067                                                Sema::AA_Casting);
6068     if (Update.isInvalid())
6069       return true;
6070     UpdateExpr = Update.get();
6071   }
6072   return ErrorFound != NoError;
6073 }
6074 
6075 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6076                                             Stmt *AStmt,
6077                                             SourceLocation StartLoc,
6078                                             SourceLocation EndLoc) {
6079   if (!AStmt)
6080     return StmtError();
6081 
6082   auto CS = cast<CapturedStmt>(AStmt);
6083   // 1.2.2 OpenMP Language Terminology
6084   // Structured block - An executable statement with a single entry at the
6085   // top and a single exit at the bottom.
6086   // The point of exit cannot be a branch out of the structured block.
6087   // longjmp() and throw() must not violate the entry/exit criteria.
6088   OpenMPClauseKind AtomicKind = OMPC_unknown;
6089   SourceLocation AtomicKindLoc;
6090   for (auto *C : Clauses) {
6091     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6092         C->getClauseKind() == OMPC_update ||
6093         C->getClauseKind() == OMPC_capture) {
6094       if (AtomicKind != OMPC_unknown) {
6095         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6096             << SourceRange(C->getLocStart(), C->getLocEnd());
6097         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6098             << getOpenMPClauseName(AtomicKind);
6099       } else {
6100         AtomicKind = C->getClauseKind();
6101         AtomicKindLoc = C->getLocStart();
6102       }
6103     }
6104   }
6105 
6106   auto Body = CS->getCapturedStmt();
6107   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6108     Body = EWC->getSubExpr();
6109 
6110   Expr *X = nullptr;
6111   Expr *V = nullptr;
6112   Expr *E = nullptr;
6113   Expr *UE = nullptr;
6114   bool IsXLHSInRHSPart = false;
6115   bool IsPostfixUpdate = false;
6116   // OpenMP [2.12.6, atomic Construct]
6117   // In the next expressions:
6118   // * x and v (as applicable) are both l-value expressions with scalar type.
6119   // * During the execution of an atomic region, multiple syntactic
6120   // occurrences of x must designate the same storage location.
6121   // * Neither of v and expr (as applicable) may access the storage location
6122   // designated by x.
6123   // * Neither of x and expr (as applicable) may access the storage location
6124   // designated by v.
6125   // * expr is an expression with scalar type.
6126   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6127   // * binop, binop=, ++, and -- are not overloaded operators.
6128   // * The expression x binop expr must be numerically equivalent to x binop
6129   // (expr). This requirement is satisfied if the operators in expr have
6130   // precedence greater than binop, or by using parentheses around expr or
6131   // subexpressions of expr.
6132   // * The expression expr binop x must be numerically equivalent to (expr)
6133   // binop x. This requirement is satisfied if the operators in expr have
6134   // precedence equal to or greater than binop, or by using parentheses around
6135   // expr or subexpressions of expr.
6136   // * For forms that allow multiple occurrences of x, the number of times
6137   // that x is evaluated is unspecified.
6138   if (AtomicKind == OMPC_read) {
6139     enum {
6140       NotAnExpression,
6141       NotAnAssignmentOp,
6142       NotAScalarType,
6143       NotAnLValue,
6144       NoError
6145     } ErrorFound = NoError;
6146     SourceLocation ErrorLoc, NoteLoc;
6147     SourceRange ErrorRange, NoteRange;
6148     // If clause is read:
6149     //  v = x;
6150     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
6151       auto AtomicBinOp =
6152           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6153       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6154         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6155         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6156         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6157             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6158           if (!X->isLValue() || !V->isLValue()) {
6159             auto NotLValueExpr = X->isLValue() ? V : X;
6160             ErrorFound = NotAnLValue;
6161             ErrorLoc = AtomicBinOp->getExprLoc();
6162             ErrorRange = AtomicBinOp->getSourceRange();
6163             NoteLoc = NotLValueExpr->getExprLoc();
6164             NoteRange = NotLValueExpr->getSourceRange();
6165           }
6166         } else if (!X->isInstantiationDependent() ||
6167                    !V->isInstantiationDependent()) {
6168           auto NotScalarExpr =
6169               (X->isInstantiationDependent() || X->getType()->isScalarType())
6170                   ? V
6171                   : X;
6172           ErrorFound = NotAScalarType;
6173           ErrorLoc = AtomicBinOp->getExprLoc();
6174           ErrorRange = AtomicBinOp->getSourceRange();
6175           NoteLoc = NotScalarExpr->getExprLoc();
6176           NoteRange = NotScalarExpr->getSourceRange();
6177         }
6178       } else if (!AtomicBody->isInstantiationDependent()) {
6179         ErrorFound = NotAnAssignmentOp;
6180         ErrorLoc = AtomicBody->getExprLoc();
6181         ErrorRange = AtomicBody->getSourceRange();
6182         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6183                               : AtomicBody->getExprLoc();
6184         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6185                                 : AtomicBody->getSourceRange();
6186       }
6187     } else {
6188       ErrorFound = NotAnExpression;
6189       NoteLoc = ErrorLoc = Body->getLocStart();
6190       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6191     }
6192     if (ErrorFound != NoError) {
6193       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6194           << ErrorRange;
6195       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6196                                                       << NoteRange;
6197       return StmtError();
6198     } else if (CurContext->isDependentContext())
6199       V = X = nullptr;
6200   } else if (AtomicKind == OMPC_write) {
6201     enum {
6202       NotAnExpression,
6203       NotAnAssignmentOp,
6204       NotAScalarType,
6205       NotAnLValue,
6206       NoError
6207     } ErrorFound = NoError;
6208     SourceLocation ErrorLoc, NoteLoc;
6209     SourceRange ErrorRange, NoteRange;
6210     // If clause is write:
6211     //  x = expr;
6212     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
6213       auto AtomicBinOp =
6214           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6215       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6216         X = AtomicBinOp->getLHS();
6217         E = AtomicBinOp->getRHS();
6218         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6219             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6220           if (!X->isLValue()) {
6221             ErrorFound = NotAnLValue;
6222             ErrorLoc = AtomicBinOp->getExprLoc();
6223             ErrorRange = AtomicBinOp->getSourceRange();
6224             NoteLoc = X->getExprLoc();
6225             NoteRange = X->getSourceRange();
6226           }
6227         } else if (!X->isInstantiationDependent() ||
6228                    !E->isInstantiationDependent()) {
6229           auto NotScalarExpr =
6230               (X->isInstantiationDependent() || X->getType()->isScalarType())
6231                   ? E
6232                   : X;
6233           ErrorFound = NotAScalarType;
6234           ErrorLoc = AtomicBinOp->getExprLoc();
6235           ErrorRange = AtomicBinOp->getSourceRange();
6236           NoteLoc = NotScalarExpr->getExprLoc();
6237           NoteRange = NotScalarExpr->getSourceRange();
6238         }
6239       } else if (!AtomicBody->isInstantiationDependent()) {
6240         ErrorFound = NotAnAssignmentOp;
6241         ErrorLoc = AtomicBody->getExprLoc();
6242         ErrorRange = AtomicBody->getSourceRange();
6243         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6244                               : AtomicBody->getExprLoc();
6245         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6246                                 : AtomicBody->getSourceRange();
6247       }
6248     } else {
6249       ErrorFound = NotAnExpression;
6250       NoteLoc = ErrorLoc = Body->getLocStart();
6251       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6252     }
6253     if (ErrorFound != NoError) {
6254       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6255           << ErrorRange;
6256       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6257                                                       << NoteRange;
6258       return StmtError();
6259     } else if (CurContext->isDependentContext())
6260       E = X = nullptr;
6261   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6262     // If clause is update:
6263     //  x++;
6264     //  x--;
6265     //  ++x;
6266     //  --x;
6267     //  x binop= expr;
6268     //  x = x binop expr;
6269     //  x = expr binop x;
6270     OpenMPAtomicUpdateChecker Checker(*this);
6271     if (Checker.checkStatement(
6272             Body, (AtomicKind == OMPC_update)
6273                       ? diag::err_omp_atomic_update_not_expression_statement
6274                       : diag::err_omp_atomic_not_expression_statement,
6275             diag::note_omp_atomic_update))
6276       return StmtError();
6277     if (!CurContext->isDependentContext()) {
6278       E = Checker.getExpr();
6279       X = Checker.getX();
6280       UE = Checker.getUpdateExpr();
6281       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6282     }
6283   } else if (AtomicKind == OMPC_capture) {
6284     enum {
6285       NotAnAssignmentOp,
6286       NotACompoundStatement,
6287       NotTwoSubstatements,
6288       NotASpecificExpression,
6289       NoError
6290     } ErrorFound = NoError;
6291     SourceLocation ErrorLoc, NoteLoc;
6292     SourceRange ErrorRange, NoteRange;
6293     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6294       // If clause is a capture:
6295       //  v = x++;
6296       //  v = x--;
6297       //  v = ++x;
6298       //  v = --x;
6299       //  v = x binop= expr;
6300       //  v = x = x binop expr;
6301       //  v = x = expr binop x;
6302       auto *AtomicBinOp =
6303           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6304       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6305         V = AtomicBinOp->getLHS();
6306         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6307         OpenMPAtomicUpdateChecker Checker(*this);
6308         if (Checker.checkStatement(
6309                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6310                 diag::note_omp_atomic_update))
6311           return StmtError();
6312         E = Checker.getExpr();
6313         X = Checker.getX();
6314         UE = Checker.getUpdateExpr();
6315         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6316         IsPostfixUpdate = Checker.isPostfixUpdate();
6317       } else if (!AtomicBody->isInstantiationDependent()) {
6318         ErrorLoc = AtomicBody->getExprLoc();
6319         ErrorRange = AtomicBody->getSourceRange();
6320         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6321                               : AtomicBody->getExprLoc();
6322         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6323                                 : AtomicBody->getSourceRange();
6324         ErrorFound = NotAnAssignmentOp;
6325       }
6326       if (ErrorFound != NoError) {
6327         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6328             << ErrorRange;
6329         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6330         return StmtError();
6331       } else if (CurContext->isDependentContext()) {
6332         UE = V = E = X = nullptr;
6333       }
6334     } else {
6335       // If clause is a capture:
6336       //  { v = x; x = expr; }
6337       //  { v = x; x++; }
6338       //  { v = x; x--; }
6339       //  { v = x; ++x; }
6340       //  { v = x; --x; }
6341       //  { v = x; x binop= expr; }
6342       //  { v = x; x = x binop expr; }
6343       //  { v = x; x = expr binop x; }
6344       //  { x++; v = x; }
6345       //  { x--; v = x; }
6346       //  { ++x; v = x; }
6347       //  { --x; v = x; }
6348       //  { x binop= expr; v = x; }
6349       //  { x = x binop expr; v = x; }
6350       //  { x = expr binop x; v = x; }
6351       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6352         // Check that this is { expr1; expr2; }
6353         if (CS->size() == 2) {
6354           auto *First = CS->body_front();
6355           auto *Second = CS->body_back();
6356           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6357             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6358           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6359             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6360           // Need to find what subexpression is 'v' and what is 'x'.
6361           OpenMPAtomicUpdateChecker Checker(*this);
6362           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6363           BinaryOperator *BinOp = nullptr;
6364           if (IsUpdateExprFound) {
6365             BinOp = dyn_cast<BinaryOperator>(First);
6366             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6367           }
6368           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6369             //  { v = x; x++; }
6370             //  { v = x; x--; }
6371             //  { v = x; ++x; }
6372             //  { v = x; --x; }
6373             //  { v = x; x binop= expr; }
6374             //  { v = x; x = x binop expr; }
6375             //  { v = x; x = expr binop x; }
6376             // Check that the first expression has form v = x.
6377             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6378             llvm::FoldingSetNodeID XId, PossibleXId;
6379             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6380             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6381             IsUpdateExprFound = XId == PossibleXId;
6382             if (IsUpdateExprFound) {
6383               V = BinOp->getLHS();
6384               X = Checker.getX();
6385               E = Checker.getExpr();
6386               UE = Checker.getUpdateExpr();
6387               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6388               IsPostfixUpdate = true;
6389             }
6390           }
6391           if (!IsUpdateExprFound) {
6392             IsUpdateExprFound = !Checker.checkStatement(First);
6393             BinOp = nullptr;
6394             if (IsUpdateExprFound) {
6395               BinOp = dyn_cast<BinaryOperator>(Second);
6396               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6397             }
6398             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6399               //  { x++; v = x; }
6400               //  { x--; v = x; }
6401               //  { ++x; v = x; }
6402               //  { --x; v = x; }
6403               //  { x binop= expr; v = x; }
6404               //  { x = x binop expr; v = x; }
6405               //  { x = expr binop x; v = x; }
6406               // Check that the second expression has form v = x.
6407               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6408               llvm::FoldingSetNodeID XId, PossibleXId;
6409               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6410               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6411               IsUpdateExprFound = XId == PossibleXId;
6412               if (IsUpdateExprFound) {
6413                 V = BinOp->getLHS();
6414                 X = Checker.getX();
6415                 E = Checker.getExpr();
6416                 UE = Checker.getUpdateExpr();
6417                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6418                 IsPostfixUpdate = false;
6419               }
6420             }
6421           }
6422           if (!IsUpdateExprFound) {
6423             //  { v = x; x = expr; }
6424             auto *FirstExpr = dyn_cast<Expr>(First);
6425             auto *SecondExpr = dyn_cast<Expr>(Second);
6426             if (!FirstExpr || !SecondExpr ||
6427                 !(FirstExpr->isInstantiationDependent() ||
6428                   SecondExpr->isInstantiationDependent())) {
6429               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6430               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6431                 ErrorFound = NotAnAssignmentOp;
6432                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6433                                                 : First->getLocStart();
6434                 NoteRange = ErrorRange = FirstBinOp
6435                                              ? FirstBinOp->getSourceRange()
6436                                              : SourceRange(ErrorLoc, ErrorLoc);
6437               } else {
6438                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6439                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6440                   ErrorFound = NotAnAssignmentOp;
6441                   NoteLoc = ErrorLoc = SecondBinOp
6442                                            ? SecondBinOp->getOperatorLoc()
6443                                            : Second->getLocStart();
6444                   NoteRange = ErrorRange =
6445                       SecondBinOp ? SecondBinOp->getSourceRange()
6446                                   : SourceRange(ErrorLoc, ErrorLoc);
6447                 } else {
6448                   auto *PossibleXRHSInFirst =
6449                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6450                   auto *PossibleXLHSInSecond =
6451                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6452                   llvm::FoldingSetNodeID X1Id, X2Id;
6453                   PossibleXRHSInFirst->Profile(X1Id, Context,
6454                                                /*Canonical=*/true);
6455                   PossibleXLHSInSecond->Profile(X2Id, Context,
6456                                                 /*Canonical=*/true);
6457                   IsUpdateExprFound = X1Id == X2Id;
6458                   if (IsUpdateExprFound) {
6459                     V = FirstBinOp->getLHS();
6460                     X = SecondBinOp->getLHS();
6461                     E = SecondBinOp->getRHS();
6462                     UE = nullptr;
6463                     IsXLHSInRHSPart = false;
6464                     IsPostfixUpdate = true;
6465                   } else {
6466                     ErrorFound = NotASpecificExpression;
6467                     ErrorLoc = FirstBinOp->getExprLoc();
6468                     ErrorRange = FirstBinOp->getSourceRange();
6469                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6470                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6471                   }
6472                 }
6473               }
6474             }
6475           }
6476         } else {
6477           NoteLoc = ErrorLoc = Body->getLocStart();
6478           NoteRange = ErrorRange =
6479               SourceRange(Body->getLocStart(), Body->getLocStart());
6480           ErrorFound = NotTwoSubstatements;
6481         }
6482       } else {
6483         NoteLoc = ErrorLoc = Body->getLocStart();
6484         NoteRange = ErrorRange =
6485             SourceRange(Body->getLocStart(), Body->getLocStart());
6486         ErrorFound = NotACompoundStatement;
6487       }
6488       if (ErrorFound != NoError) {
6489         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6490             << ErrorRange;
6491         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6492         return StmtError();
6493       } else if (CurContext->isDependentContext()) {
6494         UE = V = E = X = nullptr;
6495       }
6496     }
6497   }
6498 
6499   getCurFunction()->setHasBranchProtectedScope();
6500 
6501   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6502                                     X, V, E, UE, IsXLHSInRHSPart,
6503                                     IsPostfixUpdate);
6504 }
6505 
6506 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6507                                             Stmt *AStmt,
6508                                             SourceLocation StartLoc,
6509                                             SourceLocation EndLoc) {
6510   if (!AStmt)
6511     return StmtError();
6512 
6513   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6514   // 1.2.2 OpenMP Language Terminology
6515   // Structured block - An executable statement with a single entry at the
6516   // top and a single exit at the bottom.
6517   // The point of exit cannot be a branch out of the structured block.
6518   // longjmp() and throw() must not violate the entry/exit criteria.
6519   CS->getCapturedDecl()->setNothrow();
6520 
6521   // OpenMP [2.16, Nesting of Regions]
6522   // If specified, a teams construct must be contained within a target
6523   // construct. That target construct must contain no statements or directives
6524   // outside of the teams construct.
6525   if (DSAStack->hasInnerTeamsRegion()) {
6526     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6527     bool OMPTeamsFound = true;
6528     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6529       auto I = CS->body_begin();
6530       while (I != CS->body_end()) {
6531         auto OED = dyn_cast<OMPExecutableDirective>(*I);
6532         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6533           OMPTeamsFound = false;
6534           break;
6535         }
6536         ++I;
6537       }
6538       assert(I != CS->body_end() && "Not found statement");
6539       S = *I;
6540     } else {
6541       auto *OED = dyn_cast<OMPExecutableDirective>(S);
6542       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
6543     }
6544     if (!OMPTeamsFound) {
6545       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6546       Diag(DSAStack->getInnerTeamsRegionLoc(),
6547            diag::note_omp_nested_teams_construct_here);
6548       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6549           << isa<OMPExecutableDirective>(S);
6550       return StmtError();
6551     }
6552   }
6553 
6554   getCurFunction()->setHasBranchProtectedScope();
6555 
6556   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6557 }
6558 
6559 StmtResult
6560 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6561                                          Stmt *AStmt, SourceLocation StartLoc,
6562                                          SourceLocation EndLoc) {
6563   if (!AStmt)
6564     return StmtError();
6565 
6566   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6567   // 1.2.2 OpenMP Language Terminology
6568   // Structured block - An executable statement with a single entry at the
6569   // top and a single exit at the bottom.
6570   // The point of exit cannot be a branch out of the structured block.
6571   // longjmp() and throw() must not violate the entry/exit criteria.
6572   CS->getCapturedDecl()->setNothrow();
6573 
6574   getCurFunction()->setHasBranchProtectedScope();
6575 
6576   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6577                                             AStmt);
6578 }
6579 
6580 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6581     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6582     SourceLocation EndLoc,
6583     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6584   if (!AStmt)
6585     return StmtError();
6586 
6587   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6588   // 1.2.2 OpenMP Language Terminology
6589   // Structured block - An executable statement with a single entry at the
6590   // top and a single exit at the bottom.
6591   // The point of exit cannot be a branch out of the structured block.
6592   // longjmp() and throw() must not violate the entry/exit criteria.
6593   CS->getCapturedDecl()->setNothrow();
6594 
6595   OMPLoopDirective::HelperExprs B;
6596   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6597   // define the nested loops number.
6598   unsigned NestedLoopCount =
6599       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6600                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6601                       VarsWithImplicitDSA, B);
6602   if (NestedLoopCount == 0)
6603     return StmtError();
6604 
6605   assert((CurContext->isDependentContext() || B.builtAll()) &&
6606          "omp target parallel for loop exprs were not built");
6607 
6608   if (!CurContext->isDependentContext()) {
6609     // Finalize the clauses that need pre-built expressions for CodeGen.
6610     for (auto C : Clauses) {
6611       if (auto LC = dyn_cast<OMPLinearClause>(C))
6612         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6613                                      B.NumIterations, *this, CurScope,
6614                                      DSAStack))
6615           return StmtError();
6616     }
6617   }
6618 
6619   getCurFunction()->setHasBranchProtectedScope();
6620   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6621                                                NestedLoopCount, Clauses, AStmt,
6622                                                B, DSAStack->isCancelRegion());
6623 }
6624 
6625 /// \brief Check for existence of a map clause in the list of clauses.
6626 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
6627   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
6628        I != E; ++I) {
6629     if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
6630       return true;
6631     }
6632   }
6633 
6634   return false;
6635 }
6636 
6637 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6638                                                 Stmt *AStmt,
6639                                                 SourceLocation StartLoc,
6640                                                 SourceLocation EndLoc) {
6641   if (!AStmt)
6642     return StmtError();
6643 
6644   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6645 
6646   // OpenMP [2.10.1, Restrictions, p. 97]
6647   // At least one map clause must appear on the directive.
6648   if (!HasMapClause(Clauses)) {
6649     Diag(StartLoc, diag::err_omp_no_map_for_directive) <<
6650         getOpenMPDirectiveName(OMPD_target_data);
6651     return StmtError();
6652   }
6653 
6654   getCurFunction()->setHasBranchProtectedScope();
6655 
6656   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6657                                         AStmt);
6658 }
6659 
6660 StmtResult
6661 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6662                                           SourceLocation StartLoc,
6663                                           SourceLocation EndLoc) {
6664   // OpenMP [2.10.2, Restrictions, p. 99]
6665   // At least one map clause must appear on the directive.
6666   if (!HasMapClause(Clauses)) {
6667     Diag(StartLoc, diag::err_omp_no_map_for_directive)
6668         << getOpenMPDirectiveName(OMPD_target_enter_data);
6669     return StmtError();
6670   }
6671 
6672   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6673                                              Clauses);
6674 }
6675 
6676 StmtResult
6677 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6678                                          SourceLocation StartLoc,
6679                                          SourceLocation EndLoc) {
6680   // OpenMP [2.10.3, Restrictions, p. 102]
6681   // At least one map clause must appear on the directive.
6682   if (!HasMapClause(Clauses)) {
6683     Diag(StartLoc, diag::err_omp_no_map_for_directive)
6684         << getOpenMPDirectiveName(OMPD_target_exit_data);
6685     return StmtError();
6686   }
6687 
6688   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6689 }
6690 
6691 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6692                                                   SourceLocation StartLoc,
6693                                                   SourceLocation EndLoc) {
6694   bool seenMotionClause = false;
6695   for (auto *C : Clauses) {
6696     if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
6697       seenMotionClause = true;
6698   }
6699   if (!seenMotionClause) {
6700     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6701     return StmtError();
6702   }
6703   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6704 }
6705 
6706 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6707                                            Stmt *AStmt, SourceLocation StartLoc,
6708                                            SourceLocation EndLoc) {
6709   if (!AStmt)
6710     return StmtError();
6711 
6712   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6713   // 1.2.2 OpenMP Language Terminology
6714   // Structured block - An executable statement with a single entry at the
6715   // top and a single exit at the bottom.
6716   // The point of exit cannot be a branch out of the structured block.
6717   // longjmp() and throw() must not violate the entry/exit criteria.
6718   CS->getCapturedDecl()->setNothrow();
6719 
6720   getCurFunction()->setHasBranchProtectedScope();
6721 
6722   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6723 }
6724 
6725 StmtResult
6726 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6727                                             SourceLocation EndLoc,
6728                                             OpenMPDirectiveKind CancelRegion) {
6729   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6730       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6731     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6732         << getOpenMPDirectiveName(CancelRegion);
6733     return StmtError();
6734   }
6735   if (DSAStack->isParentNowaitRegion()) {
6736     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6737     return StmtError();
6738   }
6739   if (DSAStack->isParentOrderedRegion()) {
6740     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6741     return StmtError();
6742   }
6743   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6744                                                CancelRegion);
6745 }
6746 
6747 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6748                                             SourceLocation StartLoc,
6749                                             SourceLocation EndLoc,
6750                                             OpenMPDirectiveKind CancelRegion) {
6751   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
6752       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
6753     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
6754         << getOpenMPDirectiveName(CancelRegion);
6755     return StmtError();
6756   }
6757   if (DSAStack->isParentNowaitRegion()) {
6758     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6759     return StmtError();
6760   }
6761   if (DSAStack->isParentOrderedRegion()) {
6762     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6763     return StmtError();
6764   }
6765   DSAStack->setParentCancelRegion(/*Cancel=*/true);
6766   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6767                                     CancelRegion);
6768 }
6769 
6770 static bool checkGrainsizeNumTasksClauses(Sema &S,
6771                                           ArrayRef<OMPClause *> Clauses) {
6772   OMPClause *PrevClause = nullptr;
6773   bool ErrorFound = false;
6774   for (auto *C : Clauses) {
6775     if (C->getClauseKind() == OMPC_grainsize ||
6776         C->getClauseKind() == OMPC_num_tasks) {
6777       if (!PrevClause)
6778         PrevClause = C;
6779       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6780         S.Diag(C->getLocStart(),
6781                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6782             << getOpenMPClauseName(C->getClauseKind())
6783             << getOpenMPClauseName(PrevClause->getClauseKind());
6784         S.Diag(PrevClause->getLocStart(),
6785                diag::note_omp_previous_grainsize_num_tasks)
6786             << getOpenMPClauseName(PrevClause->getClauseKind());
6787         ErrorFound = true;
6788       }
6789     }
6790   }
6791   return ErrorFound;
6792 }
6793 
6794 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6795     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6796     SourceLocation EndLoc,
6797     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6798   if (!AStmt)
6799     return StmtError();
6800 
6801   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6802   OMPLoopDirective::HelperExprs B;
6803   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6804   // define the nested loops number.
6805   unsigned NestedLoopCount =
6806       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
6807                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6808                       VarsWithImplicitDSA, B);
6809   if (NestedLoopCount == 0)
6810     return StmtError();
6811 
6812   assert((CurContext->isDependentContext() || B.builtAll()) &&
6813          "omp for loop exprs were not built");
6814 
6815   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6816   // The grainsize clause and num_tasks clause are mutually exclusive and may
6817   // not appear on the same taskloop directive.
6818   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6819     return StmtError();
6820 
6821   getCurFunction()->setHasBranchProtectedScope();
6822   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6823                                       NestedLoopCount, Clauses, AStmt, B);
6824 }
6825 
6826 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6827     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6828     SourceLocation EndLoc,
6829     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6830   if (!AStmt)
6831     return StmtError();
6832 
6833   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6834   OMPLoopDirective::HelperExprs B;
6835   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6836   // define the nested loops number.
6837   unsigned NestedLoopCount =
6838       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6839                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6840                       VarsWithImplicitDSA, B);
6841   if (NestedLoopCount == 0)
6842     return StmtError();
6843 
6844   assert((CurContext->isDependentContext() || B.builtAll()) &&
6845          "omp for loop exprs were not built");
6846 
6847   if (!CurContext->isDependentContext()) {
6848     // Finalize the clauses that need pre-built expressions for CodeGen.
6849     for (auto C : Clauses) {
6850       if (auto LC = dyn_cast<OMPLinearClause>(C))
6851         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6852                                      B.NumIterations, *this, CurScope,
6853                                      DSAStack))
6854           return StmtError();
6855     }
6856   }
6857 
6858   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6859   // The grainsize clause and num_tasks clause are mutually exclusive and may
6860   // not appear on the same taskloop directive.
6861   if (checkGrainsizeNumTasksClauses(*this, Clauses))
6862     return StmtError();
6863 
6864   getCurFunction()->setHasBranchProtectedScope();
6865   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6866                                           NestedLoopCount, Clauses, AStmt, B);
6867 }
6868 
6869 StmtResult Sema::ActOnOpenMPDistributeDirective(
6870     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6871     SourceLocation EndLoc,
6872     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6873   if (!AStmt)
6874     return StmtError();
6875 
6876   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6877   OMPLoopDirective::HelperExprs B;
6878   // In presence of clause 'collapse' with number of loops, it will
6879   // define the nested loops number.
6880   unsigned NestedLoopCount =
6881       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6882                       nullptr /*ordered not a clause on distribute*/, AStmt,
6883                       *this, *DSAStack, VarsWithImplicitDSA, B);
6884   if (NestedLoopCount == 0)
6885     return StmtError();
6886 
6887   assert((CurContext->isDependentContext() || B.builtAll()) &&
6888          "omp for loop exprs were not built");
6889 
6890   getCurFunction()->setHasBranchProtectedScope();
6891   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6892                                         NestedLoopCount, Clauses, AStmt, B);
6893 }
6894 
6895 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6896     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6897     SourceLocation EndLoc,
6898     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6899   if (!AStmt)
6900     return StmtError();
6901 
6902   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
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   OMPLoopDirective::HelperExprs B;
6911   // In presence of clause 'collapse' with number of loops, it will
6912   // define the nested loops number.
6913   unsigned NestedLoopCount = CheckOpenMPLoop(
6914       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6915       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6916       VarsWithImplicitDSA, B);
6917   if (NestedLoopCount == 0)
6918     return StmtError();
6919 
6920   assert((CurContext->isDependentContext() || B.builtAll()) &&
6921          "omp for loop exprs were not built");
6922 
6923   getCurFunction()->setHasBranchProtectedScope();
6924   return OMPDistributeParallelForDirective::Create(
6925       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6926 }
6927 
6928 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6929                                              SourceLocation StartLoc,
6930                                              SourceLocation LParenLoc,
6931                                              SourceLocation EndLoc) {
6932   OMPClause *Res = nullptr;
6933   switch (Kind) {
6934   case OMPC_final:
6935     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6936     break;
6937   case OMPC_num_threads:
6938     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6939     break;
6940   case OMPC_safelen:
6941     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6942     break;
6943   case OMPC_simdlen:
6944     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6945     break;
6946   case OMPC_collapse:
6947     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6948     break;
6949   case OMPC_ordered:
6950     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6951     break;
6952   case OMPC_device:
6953     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6954     break;
6955   case OMPC_num_teams:
6956     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6957     break;
6958   case OMPC_thread_limit:
6959     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6960     break;
6961   case OMPC_priority:
6962     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6963     break;
6964   case OMPC_grainsize:
6965     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6966     break;
6967   case OMPC_num_tasks:
6968     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6969     break;
6970   case OMPC_hint:
6971     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6972     break;
6973   case OMPC_if:
6974   case OMPC_default:
6975   case OMPC_proc_bind:
6976   case OMPC_schedule:
6977   case OMPC_private:
6978   case OMPC_firstprivate:
6979   case OMPC_lastprivate:
6980   case OMPC_shared:
6981   case OMPC_reduction:
6982   case OMPC_linear:
6983   case OMPC_aligned:
6984   case OMPC_copyin:
6985   case OMPC_copyprivate:
6986   case OMPC_nowait:
6987   case OMPC_untied:
6988   case OMPC_mergeable:
6989   case OMPC_threadprivate:
6990   case OMPC_flush:
6991   case OMPC_read:
6992   case OMPC_write:
6993   case OMPC_update:
6994   case OMPC_capture:
6995   case OMPC_seq_cst:
6996   case OMPC_depend:
6997   case OMPC_threads:
6998   case OMPC_simd:
6999   case OMPC_map:
7000   case OMPC_nogroup:
7001   case OMPC_dist_schedule:
7002   case OMPC_defaultmap:
7003   case OMPC_unknown:
7004   case OMPC_uniform:
7005   case OMPC_to:
7006   case OMPC_from:
7007     llvm_unreachable("Clause is not allowed.");
7008   }
7009   return Res;
7010 }
7011 
7012 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7013                                      Expr *Condition, SourceLocation StartLoc,
7014                                      SourceLocation LParenLoc,
7015                                      SourceLocation NameModifierLoc,
7016                                      SourceLocation ColonLoc,
7017                                      SourceLocation EndLoc) {
7018   Expr *ValExpr = Condition;
7019   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7020       !Condition->isInstantiationDependent() &&
7021       !Condition->containsUnexpandedParameterPack()) {
7022     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7023     if (Val.isInvalid())
7024       return nullptr;
7025 
7026     ValExpr = MakeFullExpr(Val.get()).get();
7027   }
7028 
7029   return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
7030                                    NameModifierLoc, ColonLoc, EndLoc);
7031 }
7032 
7033 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7034                                         SourceLocation StartLoc,
7035                                         SourceLocation LParenLoc,
7036                                         SourceLocation EndLoc) {
7037   Expr *ValExpr = Condition;
7038   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7039       !Condition->isInstantiationDependent() &&
7040       !Condition->containsUnexpandedParameterPack()) {
7041     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
7042     if (Val.isInvalid())
7043       return nullptr;
7044 
7045     ValExpr = MakeFullExpr(Val.get()).get();
7046   }
7047 
7048   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7049 }
7050 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7051                                                         Expr *Op) {
7052   if (!Op)
7053     return ExprError();
7054 
7055   class IntConvertDiagnoser : public ICEConvertDiagnoser {
7056   public:
7057     IntConvertDiagnoser()
7058         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
7059     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7060                                          QualType T) override {
7061       return S.Diag(Loc, diag::err_omp_not_integral) << T;
7062     }
7063     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7064                                              QualType T) override {
7065       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7066     }
7067     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7068                                                QualType T,
7069                                                QualType ConvTy) override {
7070       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7071     }
7072     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7073                                            QualType ConvTy) override {
7074       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7075              << ConvTy->isEnumeralType() << ConvTy;
7076     }
7077     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7078                                             QualType T) override {
7079       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7080     }
7081     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7082                                         QualType ConvTy) override {
7083       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
7084              << ConvTy->isEnumeralType() << ConvTy;
7085     }
7086     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7087                                              QualType) override {
7088       llvm_unreachable("conversion functions are permitted");
7089     }
7090   } ConvertDiagnoser;
7091   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7092 }
7093 
7094 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
7095                                       OpenMPClauseKind CKind,
7096                                       bool StrictlyPositive) {
7097   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7098       !ValExpr->isInstantiationDependent()) {
7099     SourceLocation Loc = ValExpr->getExprLoc();
7100     ExprResult Value =
7101         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7102     if (Value.isInvalid())
7103       return false;
7104 
7105     ValExpr = Value.get();
7106     // The expression must evaluate to a non-negative integer value.
7107     llvm::APSInt Result;
7108     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
7109         Result.isSigned() &&
7110         !((!StrictlyPositive && Result.isNonNegative()) ||
7111           (StrictlyPositive && Result.isStrictlyPositive()))) {
7112       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
7113           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7114           << ValExpr->getSourceRange();
7115       return false;
7116     }
7117   }
7118   return true;
7119 }
7120 
7121 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7122                                              SourceLocation StartLoc,
7123                                              SourceLocation LParenLoc,
7124                                              SourceLocation EndLoc) {
7125   Expr *ValExpr = NumThreads;
7126 
7127   // OpenMP [2.5, Restrictions]
7128   //  The num_threads expression must evaluate to a positive integer value.
7129   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7130                                  /*StrictlyPositive=*/true))
7131     return nullptr;
7132 
7133   return new (Context)
7134       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7135 }
7136 
7137 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
7138                                                        OpenMPClauseKind CKind,
7139                                                        bool StrictlyPositive) {
7140   if (!E)
7141     return ExprError();
7142   if (E->isValueDependent() || E->isTypeDependent() ||
7143       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
7144     return E;
7145   llvm::APSInt Result;
7146   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7147   if (ICE.isInvalid())
7148     return ExprError();
7149   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7150       (!StrictlyPositive && !Result.isNonNegative())) {
7151     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
7152         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7153         << E->getSourceRange();
7154     return ExprError();
7155   }
7156   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7157     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7158         << E->getSourceRange();
7159     return ExprError();
7160   }
7161   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7162     DSAStack->setAssociatedLoops(Result.getExtValue());
7163   else if (CKind == OMPC_ordered)
7164     DSAStack->setAssociatedLoops(Result.getExtValue());
7165   return ICE;
7166 }
7167 
7168 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7169                                           SourceLocation LParenLoc,
7170                                           SourceLocation EndLoc) {
7171   // OpenMP [2.8.1, simd construct, Description]
7172   // The parameter of the safelen clause must be a constant
7173   // positive integer expression.
7174   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7175   if (Safelen.isInvalid())
7176     return nullptr;
7177   return new (Context)
7178       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
7179 }
7180 
7181 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7182                                           SourceLocation LParenLoc,
7183                                           SourceLocation EndLoc) {
7184   // OpenMP [2.8.1, simd construct, Description]
7185   // The parameter of the simdlen clause must be a constant
7186   // positive integer expression.
7187   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7188   if (Simdlen.isInvalid())
7189     return nullptr;
7190   return new (Context)
7191       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7192 }
7193 
7194 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7195                                            SourceLocation StartLoc,
7196                                            SourceLocation LParenLoc,
7197                                            SourceLocation EndLoc) {
7198   // OpenMP [2.7.1, loop construct, Description]
7199   // OpenMP [2.8.1, simd construct, Description]
7200   // OpenMP [2.9.6, distribute construct, Description]
7201   // The parameter of the collapse clause must be a constant
7202   // positive integer expression.
7203   ExprResult NumForLoopsResult =
7204       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7205   if (NumForLoopsResult.isInvalid())
7206     return nullptr;
7207   return new (Context)
7208       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
7209 }
7210 
7211 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7212                                           SourceLocation EndLoc,
7213                                           SourceLocation LParenLoc,
7214                                           Expr *NumForLoops) {
7215   // OpenMP [2.7.1, loop construct, Description]
7216   // OpenMP [2.8.1, simd construct, Description]
7217   // OpenMP [2.9.6, distribute construct, Description]
7218   // The parameter of the ordered clause must be a constant
7219   // positive integer expression if any.
7220   if (NumForLoops && LParenLoc.isValid()) {
7221     ExprResult NumForLoopsResult =
7222         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7223     if (NumForLoopsResult.isInvalid())
7224       return nullptr;
7225     NumForLoops = NumForLoopsResult.get();
7226   } else
7227     NumForLoops = nullptr;
7228   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
7229   return new (Context)
7230       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7231 }
7232 
7233 OMPClause *Sema::ActOnOpenMPSimpleClause(
7234     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7235     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
7236   OMPClause *Res = nullptr;
7237   switch (Kind) {
7238   case OMPC_default:
7239     Res =
7240         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7241                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
7242     break;
7243   case OMPC_proc_bind:
7244     Res = ActOnOpenMPProcBindClause(
7245         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7246         LParenLoc, EndLoc);
7247     break;
7248   case OMPC_if:
7249   case OMPC_final:
7250   case OMPC_num_threads:
7251   case OMPC_safelen:
7252   case OMPC_simdlen:
7253   case OMPC_collapse:
7254   case OMPC_schedule:
7255   case OMPC_private:
7256   case OMPC_firstprivate:
7257   case OMPC_lastprivate:
7258   case OMPC_shared:
7259   case OMPC_reduction:
7260   case OMPC_linear:
7261   case OMPC_aligned:
7262   case OMPC_copyin:
7263   case OMPC_copyprivate:
7264   case OMPC_ordered:
7265   case OMPC_nowait:
7266   case OMPC_untied:
7267   case OMPC_mergeable:
7268   case OMPC_threadprivate:
7269   case OMPC_flush:
7270   case OMPC_read:
7271   case OMPC_write:
7272   case OMPC_update:
7273   case OMPC_capture:
7274   case OMPC_seq_cst:
7275   case OMPC_depend:
7276   case OMPC_device:
7277   case OMPC_threads:
7278   case OMPC_simd:
7279   case OMPC_map:
7280   case OMPC_num_teams:
7281   case OMPC_thread_limit:
7282   case OMPC_priority:
7283   case OMPC_grainsize:
7284   case OMPC_nogroup:
7285   case OMPC_num_tasks:
7286   case OMPC_hint:
7287   case OMPC_dist_schedule:
7288   case OMPC_defaultmap:
7289   case OMPC_unknown:
7290   case OMPC_uniform:
7291   case OMPC_to:
7292   case OMPC_from:
7293     llvm_unreachable("Clause is not allowed.");
7294   }
7295   return Res;
7296 }
7297 
7298 static std::string
7299 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7300                         ArrayRef<unsigned> Exclude = llvm::None) {
7301   std::string Values;
7302   unsigned Bound = Last >= 2 ? Last - 2 : 0;
7303   unsigned Skipped = Exclude.size();
7304   auto S = Exclude.begin(), E = Exclude.end();
7305   for (unsigned i = First; i < Last; ++i) {
7306     if (std::find(S, E, i) != E) {
7307       --Skipped;
7308       continue;
7309     }
7310     Values += "'";
7311     Values += getOpenMPSimpleClauseTypeName(K, i);
7312     Values += "'";
7313     if (i == Bound - Skipped)
7314       Values += " or ";
7315     else if (i != Bound + 1 - Skipped)
7316       Values += ", ";
7317   }
7318   return Values;
7319 }
7320 
7321 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7322                                           SourceLocation KindKwLoc,
7323                                           SourceLocation StartLoc,
7324                                           SourceLocation LParenLoc,
7325                                           SourceLocation EndLoc) {
7326   if (Kind == OMPC_DEFAULT_unknown) {
7327     static_assert(OMPC_DEFAULT_unknown > 0,
7328                   "OMPC_DEFAULT_unknown not greater than 0");
7329     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7330         << getListOfPossibleValues(OMPC_default, /*First=*/0,
7331                                    /*Last=*/OMPC_DEFAULT_unknown)
7332         << getOpenMPClauseName(OMPC_default);
7333     return nullptr;
7334   }
7335   switch (Kind) {
7336   case OMPC_DEFAULT_none:
7337     DSAStack->setDefaultDSANone(KindKwLoc);
7338     break;
7339   case OMPC_DEFAULT_shared:
7340     DSAStack->setDefaultDSAShared(KindKwLoc);
7341     break;
7342   case OMPC_DEFAULT_unknown:
7343     llvm_unreachable("Clause kind is not allowed.");
7344     break;
7345   }
7346   return new (Context)
7347       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7348 }
7349 
7350 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7351                                            SourceLocation KindKwLoc,
7352                                            SourceLocation StartLoc,
7353                                            SourceLocation LParenLoc,
7354                                            SourceLocation EndLoc) {
7355   if (Kind == OMPC_PROC_BIND_unknown) {
7356     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
7357         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7358                                    /*Last=*/OMPC_PROC_BIND_unknown)
7359         << getOpenMPClauseName(OMPC_proc_bind);
7360     return nullptr;
7361   }
7362   return new (Context)
7363       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
7364 }
7365 
7366 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
7367     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
7368     SourceLocation StartLoc, SourceLocation LParenLoc,
7369     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
7370     SourceLocation EndLoc) {
7371   OMPClause *Res = nullptr;
7372   switch (Kind) {
7373   case OMPC_schedule:
7374     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7375     assert(Argument.size() == NumberOfElements &&
7376            ArgumentLoc.size() == NumberOfElements);
7377     Res = ActOnOpenMPScheduleClause(
7378         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7379         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7380         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7381         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7382         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
7383     break;
7384   case OMPC_if:
7385     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7386     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7387                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7388                               DelimLoc, EndLoc);
7389     break;
7390   case OMPC_dist_schedule:
7391     Res = ActOnOpenMPDistScheduleClause(
7392         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7393         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7394     break;
7395   case OMPC_defaultmap:
7396     enum { Modifier, DefaultmapKind };
7397     Res = ActOnOpenMPDefaultmapClause(
7398         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7399         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
7400         StartLoc, LParenLoc, ArgumentLoc[Modifier],
7401         ArgumentLoc[DefaultmapKind], EndLoc);
7402     break;
7403   case OMPC_final:
7404   case OMPC_num_threads:
7405   case OMPC_safelen:
7406   case OMPC_simdlen:
7407   case OMPC_collapse:
7408   case OMPC_default:
7409   case OMPC_proc_bind:
7410   case OMPC_private:
7411   case OMPC_firstprivate:
7412   case OMPC_lastprivate:
7413   case OMPC_shared:
7414   case OMPC_reduction:
7415   case OMPC_linear:
7416   case OMPC_aligned:
7417   case OMPC_copyin:
7418   case OMPC_copyprivate:
7419   case OMPC_ordered:
7420   case OMPC_nowait:
7421   case OMPC_untied:
7422   case OMPC_mergeable:
7423   case OMPC_threadprivate:
7424   case OMPC_flush:
7425   case OMPC_read:
7426   case OMPC_write:
7427   case OMPC_update:
7428   case OMPC_capture:
7429   case OMPC_seq_cst:
7430   case OMPC_depend:
7431   case OMPC_device:
7432   case OMPC_threads:
7433   case OMPC_simd:
7434   case OMPC_map:
7435   case OMPC_num_teams:
7436   case OMPC_thread_limit:
7437   case OMPC_priority:
7438   case OMPC_grainsize:
7439   case OMPC_nogroup:
7440   case OMPC_num_tasks:
7441   case OMPC_hint:
7442   case OMPC_unknown:
7443   case OMPC_uniform:
7444   case OMPC_to:
7445   case OMPC_from:
7446     llvm_unreachable("Clause is not allowed.");
7447   }
7448   return Res;
7449 }
7450 
7451 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7452                                    OpenMPScheduleClauseModifier M2,
7453                                    SourceLocation M1Loc, SourceLocation M2Loc) {
7454   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7455     SmallVector<unsigned, 2> Excluded;
7456     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7457       Excluded.push_back(M2);
7458     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7459       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7460     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7461       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7462     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7463         << getListOfPossibleValues(OMPC_schedule,
7464                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7465                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7466                                    Excluded)
7467         << getOpenMPClauseName(OMPC_schedule);
7468     return true;
7469   }
7470   return false;
7471 }
7472 
7473 OMPClause *Sema::ActOnOpenMPScheduleClause(
7474     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
7475     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
7476     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7477     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7478   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7479       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7480     return nullptr;
7481   // OpenMP, 2.7.1, Loop Construct, Restrictions
7482   // Either the monotonic modifier or the nonmonotonic modifier can be specified
7483   // but not both.
7484   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7485       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7486        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7487       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7488        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7489     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7490         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7491         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7492     return nullptr;
7493   }
7494   if (Kind == OMPC_SCHEDULE_unknown) {
7495     std::string Values;
7496     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7497       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7498       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7499                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7500                                        Exclude);
7501     } else {
7502       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7503                                        /*Last=*/OMPC_SCHEDULE_unknown);
7504     }
7505     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7506         << Values << getOpenMPClauseName(OMPC_schedule);
7507     return nullptr;
7508   }
7509   // OpenMP, 2.7.1, Loop Construct, Restrictions
7510   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7511   // schedule(guided).
7512   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7513        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7514       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7515     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7516          diag::err_omp_schedule_nonmonotonic_static);
7517     return nullptr;
7518   }
7519   Expr *ValExpr = ChunkSize;
7520   Stmt *HelperValStmt = nullptr;
7521   if (ChunkSize) {
7522     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7523         !ChunkSize->isInstantiationDependent() &&
7524         !ChunkSize->containsUnexpandedParameterPack()) {
7525       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7526       ExprResult Val =
7527           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7528       if (Val.isInvalid())
7529         return nullptr;
7530 
7531       ValExpr = Val.get();
7532 
7533       // OpenMP [2.7.1, Restrictions]
7534       //  chunk_size must be a loop invariant integer expression with a positive
7535       //  value.
7536       llvm::APSInt Result;
7537       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7538         if (Result.isSigned() && !Result.isStrictlyPositive()) {
7539           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
7540               << "schedule" << 1 << ChunkSize->getSourceRange();
7541           return nullptr;
7542         }
7543       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7544                  !CurContext->isDependentContext()) {
7545         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7546         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7547         HelperValStmt = buildPreInits(Context, Captures);
7548       }
7549     }
7550   }
7551 
7552   return new (Context)
7553       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
7554                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
7555 }
7556 
7557 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7558                                    SourceLocation StartLoc,
7559                                    SourceLocation EndLoc) {
7560   OMPClause *Res = nullptr;
7561   switch (Kind) {
7562   case OMPC_ordered:
7563     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7564     break;
7565   case OMPC_nowait:
7566     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7567     break;
7568   case OMPC_untied:
7569     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7570     break;
7571   case OMPC_mergeable:
7572     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7573     break;
7574   case OMPC_read:
7575     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7576     break;
7577   case OMPC_write:
7578     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7579     break;
7580   case OMPC_update:
7581     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7582     break;
7583   case OMPC_capture:
7584     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7585     break;
7586   case OMPC_seq_cst:
7587     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7588     break;
7589   case OMPC_threads:
7590     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7591     break;
7592   case OMPC_simd:
7593     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7594     break;
7595   case OMPC_nogroup:
7596     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7597     break;
7598   case OMPC_if:
7599   case OMPC_final:
7600   case OMPC_num_threads:
7601   case OMPC_safelen:
7602   case OMPC_simdlen:
7603   case OMPC_collapse:
7604   case OMPC_schedule:
7605   case OMPC_private:
7606   case OMPC_firstprivate:
7607   case OMPC_lastprivate:
7608   case OMPC_shared:
7609   case OMPC_reduction:
7610   case OMPC_linear:
7611   case OMPC_aligned:
7612   case OMPC_copyin:
7613   case OMPC_copyprivate:
7614   case OMPC_default:
7615   case OMPC_proc_bind:
7616   case OMPC_threadprivate:
7617   case OMPC_flush:
7618   case OMPC_depend:
7619   case OMPC_device:
7620   case OMPC_map:
7621   case OMPC_num_teams:
7622   case OMPC_thread_limit:
7623   case OMPC_priority:
7624   case OMPC_grainsize:
7625   case OMPC_num_tasks:
7626   case OMPC_hint:
7627   case OMPC_dist_schedule:
7628   case OMPC_defaultmap:
7629   case OMPC_unknown:
7630   case OMPC_uniform:
7631   case OMPC_to:
7632   case OMPC_from:
7633     llvm_unreachable("Clause is not allowed.");
7634   }
7635   return Res;
7636 }
7637 
7638 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7639                                          SourceLocation EndLoc) {
7640   DSAStack->setNowaitRegion();
7641   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7642 }
7643 
7644 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7645                                          SourceLocation EndLoc) {
7646   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7647 }
7648 
7649 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7650                                             SourceLocation EndLoc) {
7651   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7652 }
7653 
7654 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7655                                        SourceLocation EndLoc) {
7656   return new (Context) OMPReadClause(StartLoc, EndLoc);
7657 }
7658 
7659 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7660                                         SourceLocation EndLoc) {
7661   return new (Context) OMPWriteClause(StartLoc, EndLoc);
7662 }
7663 
7664 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7665                                          SourceLocation EndLoc) {
7666   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7667 }
7668 
7669 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7670                                           SourceLocation EndLoc) {
7671   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7672 }
7673 
7674 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7675                                          SourceLocation EndLoc) {
7676   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7677 }
7678 
7679 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7680                                           SourceLocation EndLoc) {
7681   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7682 }
7683 
7684 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7685                                        SourceLocation EndLoc) {
7686   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7687 }
7688 
7689 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7690                                           SourceLocation EndLoc) {
7691   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7692 }
7693 
7694 OMPClause *Sema::ActOnOpenMPVarListClause(
7695     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7696     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7697     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
7698     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
7699     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7700     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7701     SourceLocation DepLinMapLoc) {
7702   OMPClause *Res = nullptr;
7703   switch (Kind) {
7704   case OMPC_private:
7705     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7706     break;
7707   case OMPC_firstprivate:
7708     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7709     break;
7710   case OMPC_lastprivate:
7711     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7712     break;
7713   case OMPC_shared:
7714     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7715     break;
7716   case OMPC_reduction:
7717     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7718                                      EndLoc, ReductionIdScopeSpec, ReductionId);
7719     break;
7720   case OMPC_linear:
7721     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
7722                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
7723     break;
7724   case OMPC_aligned:
7725     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7726                                    ColonLoc, EndLoc);
7727     break;
7728   case OMPC_copyin:
7729     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7730     break;
7731   case OMPC_copyprivate:
7732     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7733     break;
7734   case OMPC_flush:
7735     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7736     break;
7737   case OMPC_depend:
7738     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
7739                                   StartLoc, LParenLoc, EndLoc);
7740     break;
7741   case OMPC_map:
7742     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7743                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
7744                                LParenLoc, EndLoc);
7745     break;
7746   case OMPC_to:
7747     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7748     break;
7749   case OMPC_from:
7750     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7751     break;
7752   case OMPC_if:
7753   case OMPC_final:
7754   case OMPC_num_threads:
7755   case OMPC_safelen:
7756   case OMPC_simdlen:
7757   case OMPC_collapse:
7758   case OMPC_default:
7759   case OMPC_proc_bind:
7760   case OMPC_schedule:
7761   case OMPC_ordered:
7762   case OMPC_nowait:
7763   case OMPC_untied:
7764   case OMPC_mergeable:
7765   case OMPC_threadprivate:
7766   case OMPC_read:
7767   case OMPC_write:
7768   case OMPC_update:
7769   case OMPC_capture:
7770   case OMPC_seq_cst:
7771   case OMPC_device:
7772   case OMPC_threads:
7773   case OMPC_simd:
7774   case OMPC_num_teams:
7775   case OMPC_thread_limit:
7776   case OMPC_priority:
7777   case OMPC_grainsize:
7778   case OMPC_nogroup:
7779   case OMPC_num_tasks:
7780   case OMPC_hint:
7781   case OMPC_dist_schedule:
7782   case OMPC_defaultmap:
7783   case OMPC_unknown:
7784   case OMPC_uniform:
7785     llvm_unreachable("Clause is not allowed.");
7786   }
7787   return Res;
7788 }
7789 
7790 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7791                                        ExprObjectKind OK, SourceLocation Loc) {
7792   ExprResult Res = BuildDeclRefExpr(
7793       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7794   if (!Res.isUsable())
7795     return ExprError();
7796   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7797     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7798     if (!Res.isUsable())
7799       return ExprError();
7800   }
7801   if (VK != VK_LValue && Res.get()->isGLValue()) {
7802     Res = DefaultLvalueConversion(Res.get());
7803     if (!Res.isUsable())
7804       return ExprError();
7805   }
7806   return Res;
7807 }
7808 
7809 static std::pair<ValueDecl *, bool>
7810 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7811                SourceRange &ERange, bool AllowArraySection = false) {
7812   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7813       RefExpr->containsUnexpandedParameterPack())
7814     return std::make_pair(nullptr, true);
7815 
7816   // OpenMP [3.1, C/C++]
7817   //  A list item is a variable name.
7818   // OpenMP  [2.9.3.3, Restrictions, p.1]
7819   //  A variable that is part of another variable (as an array or
7820   //  structure element) cannot appear in a private clause.
7821   RefExpr = RefExpr->IgnoreParens();
7822   enum {
7823     NoArrayExpr = -1,
7824     ArraySubscript = 0,
7825     OMPArraySection = 1
7826   } IsArrayExpr = NoArrayExpr;
7827   if (AllowArraySection) {
7828     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7829       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7830       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7831         Base = TempASE->getBase()->IgnoreParenImpCasts();
7832       RefExpr = Base;
7833       IsArrayExpr = ArraySubscript;
7834     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7835       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7836       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7837         Base = TempOASE->getBase()->IgnoreParenImpCasts();
7838       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7839         Base = TempASE->getBase()->IgnoreParenImpCasts();
7840       RefExpr = Base;
7841       IsArrayExpr = OMPArraySection;
7842     }
7843   }
7844   ELoc = RefExpr->getExprLoc();
7845   ERange = RefExpr->getSourceRange();
7846   RefExpr = RefExpr->IgnoreParenImpCasts();
7847   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7848   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7849   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7850       (S.getCurrentThisType().isNull() || !ME ||
7851        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7852        !isa<FieldDecl>(ME->getMemberDecl()))) {
7853     if (IsArrayExpr != NoArrayExpr)
7854       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7855                                                          << ERange;
7856     else {
7857       S.Diag(ELoc,
7858              AllowArraySection
7859                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
7860                  : diag::err_omp_expected_var_name_member_expr)
7861           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7862     }
7863     return std::make_pair(nullptr, false);
7864   }
7865   return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7866 }
7867 
7868 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7869                                           SourceLocation StartLoc,
7870                                           SourceLocation LParenLoc,
7871                                           SourceLocation EndLoc) {
7872   SmallVector<Expr *, 8> Vars;
7873   SmallVector<Expr *, 8> PrivateCopies;
7874   for (auto &RefExpr : VarList) {
7875     assert(RefExpr && "NULL expr in OpenMP private clause.");
7876     SourceLocation ELoc;
7877     SourceRange ERange;
7878     Expr *SimpleRefExpr = RefExpr;
7879     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7880     if (Res.second) {
7881       // It will be analyzed later.
7882       Vars.push_back(RefExpr);
7883       PrivateCopies.push_back(nullptr);
7884     }
7885     ValueDecl *D = Res.first;
7886     if (!D)
7887       continue;
7888 
7889     QualType Type = D->getType();
7890     auto *VD = dyn_cast<VarDecl>(D);
7891 
7892     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7893     //  A variable that appears in a private clause must not have an incomplete
7894     //  type or a reference type.
7895     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7896       continue;
7897     Type = Type.getNonReferenceType();
7898 
7899     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7900     // in a Construct]
7901     //  Variables with the predetermined data-sharing attributes may not be
7902     //  listed in data-sharing attributes clauses, except for the cases
7903     //  listed below. For these exceptions only, listing a predetermined
7904     //  variable in a data-sharing attribute clause is allowed and overrides
7905     //  the variable's predetermined data-sharing attributes.
7906     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7907     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7908       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7909                                           << getOpenMPClauseName(OMPC_private);
7910       ReportOriginalDSA(*this, DSAStack, D, DVar);
7911       continue;
7912     }
7913 
7914     // Variably modified types are not supported for tasks.
7915     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7916         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7917       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7918           << getOpenMPClauseName(OMPC_private) << Type
7919           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7920       bool IsDecl =
7921           !VD ||
7922           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7923       Diag(D->getLocation(),
7924            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7925           << D;
7926       continue;
7927     }
7928 
7929     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7930     // A list item cannot appear in both a map clause and a data-sharing
7931     // attribute clause on the same construct
7932     if (DSAStack->getCurrentDirective() == OMPD_target) {
7933       if (DSAStack->checkMappableExprComponentListsForDecl(
7934               VD, /* CurrentRegionOnly = */ true,
7935               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef)
7936                   -> bool { return true; })) {
7937         Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
7938             << getOpenMPClauseName(OMPC_private)
7939             << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7940         ReportOriginalDSA(*this, DSAStack, D, DVar);
7941         continue;
7942       }
7943     }
7944 
7945     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7946     //  A variable of class type (or array thereof) that appears in a private
7947     //  clause requires an accessible, unambiguous default constructor for the
7948     //  class type.
7949     // Generate helper private variable and initialize it with the default
7950     // value. The address of the original variable is replaced by the address of
7951     // the new private variable in CodeGen. This new variable is not added to
7952     // IdResolver, so the code in the OpenMP region uses original variable for
7953     // proper diagnostics.
7954     Type = Type.getUnqualifiedType();
7955     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7956                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7957     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7958     if (VDPrivate->isInvalidDecl())
7959       continue;
7960     auto VDPrivateRefExpr = buildDeclRefExpr(
7961         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7962 
7963     DeclRefExpr *Ref = nullptr;
7964     if (!VD)
7965       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7966     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7967     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
7968     PrivateCopies.push_back(VDPrivateRefExpr);
7969   }
7970 
7971   if (Vars.empty())
7972     return nullptr;
7973 
7974   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7975                                   PrivateCopies);
7976 }
7977 
7978 namespace {
7979 class DiagsUninitializedSeveretyRAII {
7980 private:
7981   DiagnosticsEngine &Diags;
7982   SourceLocation SavedLoc;
7983   bool IsIgnored;
7984 
7985 public:
7986   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7987                                  bool IsIgnored)
7988       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7989     if (!IsIgnored) {
7990       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7991                         /*Map*/ diag::Severity::Ignored, Loc);
7992     }
7993   }
7994   ~DiagsUninitializedSeveretyRAII() {
7995     if (!IsIgnored)
7996       Diags.popMappings(SavedLoc);
7997   }
7998 };
7999 }
8000 
8001 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8002                                                SourceLocation StartLoc,
8003                                                SourceLocation LParenLoc,
8004                                                SourceLocation EndLoc) {
8005   SmallVector<Expr *, 8> Vars;
8006   SmallVector<Expr *, 8> PrivateCopies;
8007   SmallVector<Expr *, 8> Inits;
8008   SmallVector<Decl *, 4> ExprCaptures;
8009   bool IsImplicitClause =
8010       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8011   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8012 
8013   for (auto &RefExpr : VarList) {
8014     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
8015     SourceLocation ELoc;
8016     SourceRange ERange;
8017     Expr *SimpleRefExpr = RefExpr;
8018     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8019     if (Res.second) {
8020       // It will be analyzed later.
8021       Vars.push_back(RefExpr);
8022       PrivateCopies.push_back(nullptr);
8023       Inits.push_back(nullptr);
8024     }
8025     ValueDecl *D = Res.first;
8026     if (!D)
8027       continue;
8028 
8029     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
8030     QualType Type = D->getType();
8031     auto *VD = dyn_cast<VarDecl>(D);
8032 
8033     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8034     //  A variable that appears in a private clause must not have an incomplete
8035     //  type or a reference type.
8036     if (RequireCompleteType(ELoc, Type,
8037                             diag::err_omp_firstprivate_incomplete_type))
8038       continue;
8039     Type = Type.getNonReferenceType();
8040 
8041     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8042     //  A variable of class type (or array thereof) that appears in a private
8043     //  clause requires an accessible, unambiguous copy constructor for the
8044     //  class type.
8045     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
8046 
8047     // If an implicit firstprivate variable found it was checked already.
8048     DSAStackTy::DSAVarData TopDVar;
8049     if (!IsImplicitClause) {
8050       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8051       TopDVar = DVar;
8052       bool IsConstant = ElemType.isConstant(Context);
8053       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8054       //  A list item that specifies a given variable may not appear in more
8055       // than one clause on the same directive, except that a variable may be
8056       //  specified in both firstprivate and lastprivate clauses.
8057       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
8058           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
8059         Diag(ELoc, diag::err_omp_wrong_dsa)
8060             << getOpenMPClauseName(DVar.CKind)
8061             << getOpenMPClauseName(OMPC_firstprivate);
8062         ReportOriginalDSA(*this, DSAStack, D, DVar);
8063         continue;
8064       }
8065 
8066       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8067       // in a Construct]
8068       //  Variables with the predetermined data-sharing attributes may not be
8069       //  listed in data-sharing attributes clauses, except for the cases
8070       //  listed below. For these exceptions only, listing a predetermined
8071       //  variable in a data-sharing attribute clause is allowed and overrides
8072       //  the variable's predetermined data-sharing attributes.
8073       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8074       // in a Construct, C/C++, p.2]
8075       //  Variables with const-qualified type having no mutable member may be
8076       //  listed in a firstprivate clause, even if they are static data members.
8077       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
8078           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8079         Diag(ELoc, diag::err_omp_wrong_dsa)
8080             << getOpenMPClauseName(DVar.CKind)
8081             << getOpenMPClauseName(OMPC_firstprivate);
8082         ReportOriginalDSA(*this, DSAStack, D, DVar);
8083         continue;
8084       }
8085 
8086       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8087       // OpenMP [2.9.3.4, Restrictions, p.2]
8088       //  A list item that is private within a parallel region must not appear
8089       //  in a firstprivate clause on a worksharing construct if any of the
8090       //  worksharing regions arising from the worksharing construct ever bind
8091       //  to any of the parallel regions arising from the parallel construct.
8092       if (isOpenMPWorksharingDirective(CurrDir) &&
8093           !isOpenMPParallelDirective(CurrDir)) {
8094         DVar = DSAStack->getImplicitDSA(D, true);
8095         if (DVar.CKind != OMPC_shared &&
8096             (isOpenMPParallelDirective(DVar.DKind) ||
8097              DVar.DKind == OMPD_unknown)) {
8098           Diag(ELoc, diag::err_omp_required_access)
8099               << getOpenMPClauseName(OMPC_firstprivate)
8100               << getOpenMPClauseName(OMPC_shared);
8101           ReportOriginalDSA(*this, DSAStack, D, DVar);
8102           continue;
8103         }
8104       }
8105       // OpenMP [2.9.3.4, Restrictions, p.3]
8106       //  A list item that appears in a reduction clause of a parallel construct
8107       //  must not appear in a firstprivate clause on a worksharing or task
8108       //  construct if any of the worksharing or task regions arising from the
8109       //  worksharing or task construct ever bind to any of the parallel regions
8110       //  arising from the parallel construct.
8111       // OpenMP [2.9.3.4, Restrictions, p.4]
8112       //  A list item that appears in a reduction clause in worksharing
8113       //  construct must not appear in a firstprivate clause in a task construct
8114       //  encountered during execution of any of the worksharing regions arising
8115       //  from the worksharing construct.
8116       if (isOpenMPTaskingDirective(CurrDir)) {
8117         DVar = DSAStack->hasInnermostDSA(
8118             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8119             [](OpenMPDirectiveKind K) -> bool {
8120               return isOpenMPParallelDirective(K) ||
8121                      isOpenMPWorksharingDirective(K);
8122             },
8123             false);
8124         if (DVar.CKind == OMPC_reduction &&
8125             (isOpenMPParallelDirective(DVar.DKind) ||
8126              isOpenMPWorksharingDirective(DVar.DKind))) {
8127           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8128               << getOpenMPDirectiveName(DVar.DKind);
8129           ReportOriginalDSA(*this, DSAStack, D, DVar);
8130           continue;
8131         }
8132       }
8133 
8134       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8135       // A list item that is private within a teams region must not appear in a
8136       // firstprivate clause on a distribute construct if any of the distribute
8137       // regions arising from the distribute construct ever bind to any of the
8138       // teams regions arising from the teams construct.
8139       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8140       // A list item that appears in a reduction clause of a teams construct
8141       // must not appear in a firstprivate clause on a distribute construct if
8142       // any of the distribute regions arising from the distribute construct
8143       // ever bind to any of the teams regions arising from the teams construct.
8144       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8145       // A list item may appear in a firstprivate or lastprivate clause but not
8146       // both.
8147       if (CurrDir == OMPD_distribute) {
8148         DVar = DSAStack->hasInnermostDSA(
8149             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8150             [](OpenMPDirectiveKind K) -> bool {
8151               return isOpenMPTeamsDirective(K);
8152             },
8153             false);
8154         if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8155           Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
8156           ReportOriginalDSA(*this, DSAStack, D, DVar);
8157           continue;
8158         }
8159         DVar = DSAStack->hasInnermostDSA(
8160             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8161             [](OpenMPDirectiveKind K) -> bool {
8162               return isOpenMPTeamsDirective(K);
8163             },
8164             false);
8165         if (DVar.CKind == OMPC_reduction &&
8166             isOpenMPTeamsDirective(DVar.DKind)) {
8167           Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
8168           ReportOriginalDSA(*this, DSAStack, D, DVar);
8169           continue;
8170         }
8171         DVar = DSAStack->getTopDSA(D, false);
8172         if (DVar.CKind == OMPC_lastprivate) {
8173           Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8174           ReportOriginalDSA(*this, DSAStack, D, DVar);
8175           continue;
8176         }
8177       }
8178       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8179       // A list item cannot appear in both a map clause and a data-sharing
8180       // attribute clause on the same construct
8181       if (CurrDir == OMPD_target) {
8182         if (DSAStack->checkMappableExprComponentListsForDecl(
8183                 VD, /* CurrentRegionOnly = */ true,
8184                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef)
8185                     -> bool { return true; })) {
8186           Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
8187               << getOpenMPClauseName(OMPC_firstprivate)
8188               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8189           ReportOriginalDSA(*this, DSAStack, D, DVar);
8190           continue;
8191         }
8192       }
8193     }
8194 
8195     // Variably modified types are not supported for tasks.
8196     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
8197         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
8198       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8199           << getOpenMPClauseName(OMPC_firstprivate) << Type
8200           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8201       bool IsDecl =
8202           !VD ||
8203           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8204       Diag(D->getLocation(),
8205            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8206           << D;
8207       continue;
8208     }
8209 
8210     Type = Type.getUnqualifiedType();
8211     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8212                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
8213     // Generate helper private variable and initialize it with the value of the
8214     // original variable. The address of the original variable is replaced by
8215     // the address of the new private variable in the CodeGen. This new variable
8216     // is not added to IdResolver, so the code in the OpenMP region uses
8217     // original variable for proper diagnostics and variable capturing.
8218     Expr *VDInitRefExpr = nullptr;
8219     // For arrays generate initializer for single element and replace it by the
8220     // original array element in CodeGen.
8221     if (Type->isArrayType()) {
8222       auto VDInit =
8223           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
8224       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
8225       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
8226       ElemType = ElemType.getUnqualifiedType();
8227       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
8228                                       ".firstprivate.temp");
8229       InitializedEntity Entity =
8230           InitializedEntity::InitializeVariable(VDInitTemp);
8231       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8232 
8233       InitializationSequence InitSeq(*this, Entity, Kind, Init);
8234       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8235       if (Result.isInvalid())
8236         VDPrivate->setInvalidDecl();
8237       else
8238         VDPrivate->setInit(Result.getAs<Expr>());
8239       // Remove temp variable declaration.
8240       Context.Deallocate(VDInitTemp);
8241     } else {
8242       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8243                                   ".firstprivate.temp");
8244       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8245                                        RefExpr->getExprLoc());
8246       AddInitializerToDecl(VDPrivate,
8247                            DefaultLvalueConversion(VDInitRefExpr).get(),
8248                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8249     }
8250     if (VDPrivate->isInvalidDecl()) {
8251       if (IsImplicitClause) {
8252         Diag(RefExpr->getExprLoc(),
8253              diag::note_omp_task_predetermined_firstprivate_here);
8254       }
8255       continue;
8256     }
8257     CurContext->addDecl(VDPrivate);
8258     auto VDPrivateRefExpr = buildDeclRefExpr(
8259         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8260         RefExpr->getExprLoc());
8261     DeclRefExpr *Ref = nullptr;
8262     if (!VD) {
8263       if (TopDVar.CKind == OMPC_lastprivate)
8264         Ref = TopDVar.PrivateCopy;
8265       else {
8266         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8267         if (!IsOpenMPCapturedDecl(D))
8268           ExprCaptures.push_back(Ref->getDecl());
8269       }
8270     }
8271     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
8272     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
8273     PrivateCopies.push_back(VDPrivateRefExpr);
8274     Inits.push_back(VDInitRefExpr);
8275   }
8276 
8277   if (Vars.empty())
8278     return nullptr;
8279 
8280   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8281                                        Vars, PrivateCopies, Inits,
8282                                        buildPreInits(Context, ExprCaptures));
8283 }
8284 
8285 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8286                                               SourceLocation StartLoc,
8287                                               SourceLocation LParenLoc,
8288                                               SourceLocation EndLoc) {
8289   SmallVector<Expr *, 8> Vars;
8290   SmallVector<Expr *, 8> SrcExprs;
8291   SmallVector<Expr *, 8> DstExprs;
8292   SmallVector<Expr *, 8> AssignmentOps;
8293   SmallVector<Decl *, 4> ExprCaptures;
8294   SmallVector<Expr *, 4> ExprPostUpdates;
8295   for (auto &RefExpr : VarList) {
8296     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8297     SourceLocation ELoc;
8298     SourceRange ERange;
8299     Expr *SimpleRefExpr = RefExpr;
8300     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8301     if (Res.second) {
8302       // It will be analyzed later.
8303       Vars.push_back(RefExpr);
8304       SrcExprs.push_back(nullptr);
8305       DstExprs.push_back(nullptr);
8306       AssignmentOps.push_back(nullptr);
8307     }
8308     ValueDecl *D = Res.first;
8309     if (!D)
8310       continue;
8311 
8312     QualType Type = D->getType();
8313     auto *VD = dyn_cast<VarDecl>(D);
8314 
8315     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8316     //  A variable that appears in a lastprivate clause must not have an
8317     //  incomplete type or a reference type.
8318     if (RequireCompleteType(ELoc, Type,
8319                             diag::err_omp_lastprivate_incomplete_type))
8320       continue;
8321     Type = Type.getNonReferenceType();
8322 
8323     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8324     // in a Construct]
8325     //  Variables with the predetermined data-sharing attributes may not be
8326     //  listed in data-sharing attributes clauses, except for the cases
8327     //  listed below.
8328     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8329     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8330         DVar.CKind != OMPC_firstprivate &&
8331         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8332       Diag(ELoc, diag::err_omp_wrong_dsa)
8333           << getOpenMPClauseName(DVar.CKind)
8334           << getOpenMPClauseName(OMPC_lastprivate);
8335       ReportOriginalDSA(*this, DSAStack, D, DVar);
8336       continue;
8337     }
8338 
8339     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8340     // OpenMP [2.14.3.5, Restrictions, p.2]
8341     // A list item that is private within a parallel region, or that appears in
8342     // the reduction clause of a parallel construct, must not appear in a
8343     // lastprivate clause on a worksharing construct if any of the corresponding
8344     // worksharing regions ever binds to any of the corresponding parallel
8345     // regions.
8346     DSAStackTy::DSAVarData TopDVar = DVar;
8347     if (isOpenMPWorksharingDirective(CurrDir) &&
8348         !isOpenMPParallelDirective(CurrDir)) {
8349       DVar = DSAStack->getImplicitDSA(D, true);
8350       if (DVar.CKind != OMPC_shared) {
8351         Diag(ELoc, diag::err_omp_required_access)
8352             << getOpenMPClauseName(OMPC_lastprivate)
8353             << getOpenMPClauseName(OMPC_shared);
8354         ReportOriginalDSA(*this, DSAStack, D, DVar);
8355         continue;
8356       }
8357     }
8358 
8359     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8360     // A list item may appear in a firstprivate or lastprivate clause but not
8361     // both.
8362     if (CurrDir == OMPD_distribute) {
8363       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8364       if (DVar.CKind == OMPC_firstprivate) {
8365         Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8366         ReportOriginalDSA(*this, DSAStack, D, DVar);
8367         continue;
8368       }
8369     }
8370 
8371     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
8372     //  A variable of class type (or array thereof) that appears in a
8373     //  lastprivate clause requires an accessible, unambiguous default
8374     //  constructor for the class type, unless the list item is also specified
8375     //  in a firstprivate clause.
8376     //  A variable of class type (or array thereof) that appears in a
8377     //  lastprivate clause requires an accessible, unambiguous copy assignment
8378     //  operator for the class type.
8379     Type = Context.getBaseElementType(Type).getNonReferenceType();
8380     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
8381                                Type.getUnqualifiedType(), ".lastprivate.src",
8382                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8383     auto *PseudoSrcExpr =
8384         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
8385     auto *DstVD =
8386         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
8387                      D->hasAttrs() ? &D->getAttrs() : nullptr);
8388     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8389     // For arrays generate assignment operation for single element and replace
8390     // it by the original array element in CodeGen.
8391     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
8392                                    PseudoDstExpr, PseudoSrcExpr);
8393     if (AssignmentOp.isInvalid())
8394       continue;
8395     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8396                                        /*DiscardedValue=*/true);
8397     if (AssignmentOp.isInvalid())
8398       continue;
8399 
8400     DeclRefExpr *Ref = nullptr;
8401     if (!VD) {
8402       if (TopDVar.CKind == OMPC_firstprivate)
8403         Ref = TopDVar.PrivateCopy;
8404       else {
8405         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8406         if (!IsOpenMPCapturedDecl(D))
8407           ExprCaptures.push_back(Ref->getDecl());
8408       }
8409       if (TopDVar.CKind == OMPC_firstprivate ||
8410           (!IsOpenMPCapturedDecl(D) &&
8411            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
8412         ExprResult RefRes = DefaultLvalueConversion(Ref);
8413         if (!RefRes.isUsable())
8414           continue;
8415         ExprResult PostUpdateRes =
8416             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8417                        RefRes.get());
8418         if (!PostUpdateRes.isUsable())
8419           continue;
8420         ExprPostUpdates.push_back(
8421             IgnoredValueConversions(PostUpdateRes.get()).get());
8422       }
8423     }
8424     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
8425     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
8426     SrcExprs.push_back(PseudoSrcExpr);
8427     DstExprs.push_back(PseudoDstExpr);
8428     AssignmentOps.push_back(AssignmentOp.get());
8429   }
8430 
8431   if (Vars.empty())
8432     return nullptr;
8433 
8434   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8435                                       Vars, SrcExprs, DstExprs, AssignmentOps,
8436                                       buildPreInits(Context, ExprCaptures),
8437                                       buildPostUpdate(*this, ExprPostUpdates));
8438 }
8439 
8440 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8441                                          SourceLocation StartLoc,
8442                                          SourceLocation LParenLoc,
8443                                          SourceLocation EndLoc) {
8444   SmallVector<Expr *, 8> Vars;
8445   for (auto &RefExpr : VarList) {
8446     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
8447     SourceLocation ELoc;
8448     SourceRange ERange;
8449     Expr *SimpleRefExpr = RefExpr;
8450     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
8451     if (Res.second) {
8452       // It will be analyzed later.
8453       Vars.push_back(RefExpr);
8454     }
8455     ValueDecl *D = Res.first;
8456     if (!D)
8457       continue;
8458 
8459     auto *VD = dyn_cast<VarDecl>(D);
8460     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8461     // in a Construct]
8462     //  Variables with the predetermined data-sharing attributes may not be
8463     //  listed in data-sharing attributes clauses, except for the cases
8464     //  listed below. For these exceptions only, listing a predetermined
8465     //  variable in a data-sharing attribute clause is allowed and overrides
8466     //  the variable's predetermined data-sharing attributes.
8467     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8468     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8469         DVar.RefExpr) {
8470       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8471                                           << getOpenMPClauseName(OMPC_shared);
8472       ReportOriginalDSA(*this, DSAStack, D, DVar);
8473       continue;
8474     }
8475 
8476     DeclRefExpr *Ref = nullptr;
8477     if (!VD && IsOpenMPCapturedDecl(D))
8478       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8479     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
8480     Vars.push_back((VD || !Ref) ? RefExpr->IgnoreParens() : Ref);
8481   }
8482 
8483   if (Vars.empty())
8484     return nullptr;
8485 
8486   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8487 }
8488 
8489 namespace {
8490 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8491   DSAStackTy *Stack;
8492 
8493 public:
8494   bool VisitDeclRefExpr(DeclRefExpr *E) {
8495     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
8496       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
8497       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8498         return false;
8499       if (DVar.CKind != OMPC_unknown)
8500         return true;
8501       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8502           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8503           false);
8504       if (DVarPrivate.CKind != OMPC_unknown)
8505         return true;
8506       return false;
8507     }
8508     return false;
8509   }
8510   bool VisitStmt(Stmt *S) {
8511     for (auto Child : S->children()) {
8512       if (Child && Visit(Child))
8513         return true;
8514     }
8515     return false;
8516   }
8517   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
8518 };
8519 } // namespace
8520 
8521 namespace {
8522 // Transform MemberExpression for specified FieldDecl of current class to
8523 // DeclRefExpr to specified OMPCapturedExprDecl.
8524 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8525   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8526   ValueDecl *Field;
8527   DeclRefExpr *CapturedExpr;
8528 
8529 public:
8530   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8531       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8532 
8533   ExprResult TransformMemberExpr(MemberExpr *E) {
8534     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8535         E->getMemberDecl() == Field) {
8536       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
8537       return CapturedExpr;
8538     }
8539     return BaseTransform::TransformMemberExpr(E);
8540   }
8541   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8542 };
8543 } // namespace
8544 
8545 template <typename T>
8546 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8547                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
8548   for (auto &Set : Lookups) {
8549     for (auto *D : Set) {
8550       if (auto Res = Gen(cast<ValueDecl>(D)))
8551         return Res;
8552     }
8553   }
8554   return T();
8555 }
8556 
8557 static ExprResult
8558 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8559                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8560                          const DeclarationNameInfo &ReductionId, QualType Ty,
8561                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8562   if (ReductionIdScopeSpec.isInvalid())
8563     return ExprError();
8564   SmallVector<UnresolvedSet<8>, 4> Lookups;
8565   if (S) {
8566     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8567     Lookup.suppressDiagnostics();
8568     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8569       auto *D = Lookup.getRepresentativeDecl();
8570       do {
8571         S = S->getParent();
8572       } while (S && !S->isDeclScope(D));
8573       if (S)
8574         S = S->getParent();
8575       Lookups.push_back(UnresolvedSet<8>());
8576       Lookups.back().append(Lookup.begin(), Lookup.end());
8577       Lookup.clear();
8578     }
8579   } else if (auto *ULE =
8580                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8581     Lookups.push_back(UnresolvedSet<8>());
8582     Decl *PrevD = nullptr;
8583     for(auto *D : ULE->decls()) {
8584       if (D == PrevD)
8585         Lookups.push_back(UnresolvedSet<8>());
8586       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8587         Lookups.back().addDecl(DRD);
8588       PrevD = D;
8589     }
8590   }
8591   if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8592       Ty->containsUnexpandedParameterPack() ||
8593       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8594         return !D->isInvalidDecl() &&
8595                (D->getType()->isDependentType() ||
8596                 D->getType()->isInstantiationDependentType() ||
8597                 D->getType()->containsUnexpandedParameterPack());
8598       })) {
8599     UnresolvedSet<8> ResSet;
8600     for (auto &Set : Lookups) {
8601       ResSet.append(Set.begin(), Set.end());
8602       // The last item marks the end of all declarations at the specified scope.
8603       ResSet.addDecl(Set[Set.size() - 1]);
8604     }
8605     return UnresolvedLookupExpr::Create(
8606         SemaRef.Context, /*NamingClass=*/nullptr,
8607         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8608         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8609   }
8610   if (auto *VD = filterLookupForUDR<ValueDecl *>(
8611           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8612             if (!D->isInvalidDecl() &&
8613                 SemaRef.Context.hasSameType(D->getType(), Ty))
8614               return D;
8615             return nullptr;
8616           }))
8617     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8618   if (auto *VD = filterLookupForUDR<ValueDecl *>(
8619           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8620             if (!D->isInvalidDecl() &&
8621                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8622                 !Ty.isMoreQualifiedThan(D->getType()))
8623               return D;
8624             return nullptr;
8625           })) {
8626     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8627                        /*DetectVirtual=*/false);
8628     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8629       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8630               VD->getType().getUnqualifiedType()))) {
8631         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8632                                          /*DiagID=*/0) !=
8633             Sema::AR_inaccessible) {
8634           SemaRef.BuildBasePathArray(Paths, BasePath);
8635           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8636         }
8637       }
8638     }
8639   }
8640   if (ReductionIdScopeSpec.isSet()) {
8641     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8642     return ExprError();
8643   }
8644   return ExprEmpty();
8645 }
8646 
8647 OMPClause *Sema::ActOnOpenMPReductionClause(
8648     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8649     SourceLocation ColonLoc, SourceLocation EndLoc,
8650     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8651     ArrayRef<Expr *> UnresolvedReductions) {
8652   auto DN = ReductionId.getName();
8653   auto OOK = DN.getCXXOverloadedOperator();
8654   BinaryOperatorKind BOK = BO_Comma;
8655 
8656   // OpenMP [2.14.3.6, reduction clause]
8657   // C
8658   // reduction-identifier is either an identifier or one of the following
8659   // operators: +, -, *,  &, |, ^, && and ||
8660   // C++
8661   // reduction-identifier is either an id-expression or one of the following
8662   // operators: +, -, *, &, |, ^, && and ||
8663   // FIXME: Only 'min' and 'max' identifiers are supported for now.
8664   switch (OOK) {
8665   case OO_Plus:
8666   case OO_Minus:
8667     BOK = BO_Add;
8668     break;
8669   case OO_Star:
8670     BOK = BO_Mul;
8671     break;
8672   case OO_Amp:
8673     BOK = BO_And;
8674     break;
8675   case OO_Pipe:
8676     BOK = BO_Or;
8677     break;
8678   case OO_Caret:
8679     BOK = BO_Xor;
8680     break;
8681   case OO_AmpAmp:
8682     BOK = BO_LAnd;
8683     break;
8684   case OO_PipePipe:
8685     BOK = BO_LOr;
8686     break;
8687   case OO_New:
8688   case OO_Delete:
8689   case OO_Array_New:
8690   case OO_Array_Delete:
8691   case OO_Slash:
8692   case OO_Percent:
8693   case OO_Tilde:
8694   case OO_Exclaim:
8695   case OO_Equal:
8696   case OO_Less:
8697   case OO_Greater:
8698   case OO_LessEqual:
8699   case OO_GreaterEqual:
8700   case OO_PlusEqual:
8701   case OO_MinusEqual:
8702   case OO_StarEqual:
8703   case OO_SlashEqual:
8704   case OO_PercentEqual:
8705   case OO_CaretEqual:
8706   case OO_AmpEqual:
8707   case OO_PipeEqual:
8708   case OO_LessLess:
8709   case OO_GreaterGreater:
8710   case OO_LessLessEqual:
8711   case OO_GreaterGreaterEqual:
8712   case OO_EqualEqual:
8713   case OO_ExclaimEqual:
8714   case OO_PlusPlus:
8715   case OO_MinusMinus:
8716   case OO_Comma:
8717   case OO_ArrowStar:
8718   case OO_Arrow:
8719   case OO_Call:
8720   case OO_Subscript:
8721   case OO_Conditional:
8722   case OO_Coawait:
8723   case NUM_OVERLOADED_OPERATORS:
8724     llvm_unreachable("Unexpected reduction identifier");
8725   case OO_None:
8726     if (auto II = DN.getAsIdentifierInfo()) {
8727       if (II->isStr("max"))
8728         BOK = BO_GT;
8729       else if (II->isStr("min"))
8730         BOK = BO_LT;
8731     }
8732     break;
8733   }
8734   SourceRange ReductionIdRange;
8735   if (ReductionIdScopeSpec.isValid())
8736     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
8737   ReductionIdRange.setEnd(ReductionId.getEndLoc());
8738 
8739   SmallVector<Expr *, 8> Vars;
8740   SmallVector<Expr *, 8> Privates;
8741   SmallVector<Expr *, 8> LHSs;
8742   SmallVector<Expr *, 8> RHSs;
8743   SmallVector<Expr *, 8> ReductionOps;
8744   SmallVector<Decl *, 4> ExprCaptures;
8745   SmallVector<Expr *, 4> ExprPostUpdates;
8746   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8747   bool FirstIter = true;
8748   for (auto RefExpr : VarList) {
8749     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
8750     // OpenMP [2.1, C/C++]
8751     //  A list item is a variable or array section, subject to the restrictions
8752     //  specified in Section 2.4 on page 42 and in each of the sections
8753     // describing clauses and directives for which a list appears.
8754     // OpenMP  [2.14.3.3, Restrictions, p.1]
8755     //  A variable that is part of another variable (as an array or
8756     //  structure element) cannot appear in a private clause.
8757     if (!FirstIter && IR != ER)
8758       ++IR;
8759     FirstIter = false;
8760     SourceLocation ELoc;
8761     SourceRange ERange;
8762     Expr *SimpleRefExpr = RefExpr;
8763     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8764                               /*AllowArraySection=*/true);
8765     if (Res.second) {
8766       // It will be analyzed later.
8767       Vars.push_back(RefExpr);
8768       Privates.push_back(nullptr);
8769       LHSs.push_back(nullptr);
8770       RHSs.push_back(nullptr);
8771       // Try to find 'declare reduction' corresponding construct before using
8772       // builtin/overloaded operators.
8773       QualType Type = Context.DependentTy;
8774       CXXCastPath BasePath;
8775       ExprResult DeclareReductionRef = buildDeclareReductionRef(
8776           *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8777           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8778       if (CurContext->isDependentContext() &&
8779           (DeclareReductionRef.isUnset() ||
8780            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8781         ReductionOps.push_back(DeclareReductionRef.get());
8782       else
8783         ReductionOps.push_back(nullptr);
8784     }
8785     ValueDecl *D = Res.first;
8786     if (!D)
8787       continue;
8788 
8789     QualType Type;
8790     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8791     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8792     if (ASE)
8793       Type = ASE->getType().getNonReferenceType();
8794     else if (OASE) {
8795       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8796       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8797         Type = ATy->getElementType();
8798       else
8799         Type = BaseType->getPointeeType();
8800       Type = Type.getNonReferenceType();
8801     } else
8802       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8803     auto *VD = dyn_cast<VarDecl>(D);
8804 
8805     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8806     //  A variable that appears in a private clause must not have an incomplete
8807     //  type or a reference type.
8808     if (RequireCompleteType(ELoc, Type,
8809                             diag::err_omp_reduction_incomplete_type))
8810       continue;
8811     // OpenMP [2.14.3.6, reduction clause, Restrictions]
8812     // A list item that appears in a reduction clause must not be
8813     // const-qualified.
8814     if (Type.getNonReferenceType().isConstant(Context)) {
8815       Diag(ELoc, diag::err_omp_const_reduction_list_item)
8816           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8817       if (!ASE && !OASE) {
8818         bool IsDecl = !VD ||
8819                       VD->isThisDeclarationADefinition(Context) ==
8820                           VarDecl::DeclarationOnly;
8821         Diag(D->getLocation(),
8822              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8823             << D;
8824       }
8825       continue;
8826     }
8827     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8828     //  If a list-item is a reference type then it must bind to the same object
8829     //  for all threads of the team.
8830     if (!ASE && !OASE && VD) {
8831       VarDecl *VDDef = VD->getDefinition();
8832       if (VD->getType()->isReferenceType() && VDDef) {
8833         DSARefChecker Check(DSAStack);
8834         if (Check.Visit(VDDef->getInit())) {
8835           Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8836           Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8837           continue;
8838         }
8839       }
8840     }
8841 
8842     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8843     // in a Construct]
8844     //  Variables with the predetermined data-sharing attributes may not be
8845     //  listed in data-sharing attributes clauses, except for the cases
8846     //  listed below. For these exceptions only, listing a predetermined
8847     //  variable in a data-sharing attribute clause is allowed and overrides
8848     //  the variable's predetermined data-sharing attributes.
8849     // OpenMP [2.14.3.6, Restrictions, p.3]
8850     //  Any number of reduction clauses can be specified on the directive,
8851     //  but a list item can appear only once in the reduction clauses for that
8852     //  directive.
8853     DSAStackTy::DSAVarData DVar;
8854     DVar = DSAStack->getTopDSA(D, false);
8855     if (DVar.CKind == OMPC_reduction) {
8856       Diag(ELoc, diag::err_omp_once_referenced)
8857           << getOpenMPClauseName(OMPC_reduction);
8858       if (DVar.RefExpr)
8859         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8860     } else if (DVar.CKind != OMPC_unknown) {
8861       Diag(ELoc, diag::err_omp_wrong_dsa)
8862           << getOpenMPClauseName(DVar.CKind)
8863           << getOpenMPClauseName(OMPC_reduction);
8864       ReportOriginalDSA(*this, DSAStack, D, DVar);
8865       continue;
8866     }
8867 
8868     // OpenMP [2.14.3.6, Restrictions, p.1]
8869     //  A list item that appears in a reduction clause of a worksharing
8870     //  construct must be shared in the parallel regions to which any of the
8871     //  worksharing regions arising from the worksharing construct bind.
8872     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8873     if (isOpenMPWorksharingDirective(CurrDir) &&
8874         !isOpenMPParallelDirective(CurrDir)) {
8875       DVar = DSAStack->getImplicitDSA(D, true);
8876       if (DVar.CKind != OMPC_shared) {
8877         Diag(ELoc, diag::err_omp_required_access)
8878             << getOpenMPClauseName(OMPC_reduction)
8879             << getOpenMPClauseName(OMPC_shared);
8880         ReportOriginalDSA(*this, DSAStack, D, DVar);
8881         continue;
8882       }
8883     }
8884 
8885     // Try to find 'declare reduction' corresponding construct before using
8886     // builtin/overloaded operators.
8887     CXXCastPath BasePath;
8888     ExprResult DeclareReductionRef = buildDeclareReductionRef(
8889         *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8890         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8891     if (DeclareReductionRef.isInvalid())
8892       continue;
8893     if (CurContext->isDependentContext() &&
8894         (DeclareReductionRef.isUnset() ||
8895          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8896       Vars.push_back(RefExpr);
8897       Privates.push_back(nullptr);
8898       LHSs.push_back(nullptr);
8899       RHSs.push_back(nullptr);
8900       ReductionOps.push_back(DeclareReductionRef.get());
8901       continue;
8902     }
8903     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8904       // Not allowed reduction identifier is found.
8905       Diag(ReductionId.getLocStart(),
8906            diag::err_omp_unknown_reduction_identifier)
8907           << Type << ReductionIdRange;
8908       continue;
8909     }
8910 
8911     // OpenMP [2.14.3.6, reduction clause, Restrictions]
8912     // The type of a list item that appears in a reduction clause must be valid
8913     // for the reduction-identifier. For a max or min reduction in C, the type
8914     // of the list item must be an allowed arithmetic data type: char, int,
8915     // float, double, or _Bool, possibly modified with long, short, signed, or
8916     // unsigned. For a max or min reduction in C++, the type of the list item
8917     // must be an allowed arithmetic data type: char, wchar_t, int, float,
8918     // double, or bool, possibly modified with long, short, signed, or unsigned.
8919     if (DeclareReductionRef.isUnset()) {
8920       if ((BOK == BO_GT || BOK == BO_LT) &&
8921           !(Type->isScalarType() ||
8922             (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8923         Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8924             << getLangOpts().CPlusPlus;
8925         if (!ASE && !OASE) {
8926           bool IsDecl = !VD ||
8927                         VD->isThisDeclarationADefinition(Context) ==
8928                             VarDecl::DeclarationOnly;
8929           Diag(D->getLocation(),
8930                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8931               << D;
8932         }
8933         continue;
8934       }
8935       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8936           !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8937         Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8938         if (!ASE && !OASE) {
8939           bool IsDecl = !VD ||
8940                         VD->isThisDeclarationADefinition(Context) ==
8941                             VarDecl::DeclarationOnly;
8942           Diag(D->getLocation(),
8943                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8944               << D;
8945         }
8946         continue;
8947       }
8948     }
8949 
8950     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8951     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8952                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8953     auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8954                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8955     auto PrivateTy = Type;
8956     if (OASE ||
8957         (!ASE &&
8958          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8959       // For arays/array sections only:
8960       // Create pseudo array type for private copy. The size for this array will
8961       // be generated during codegen.
8962       // For array subscripts or single variables Private Ty is the same as Type
8963       // (type of the variable or single array element).
8964       PrivateTy = Context.getVariableArrayType(
8965           Type, new (Context) OpaqueValueExpr(SourceLocation(),
8966                                               Context.getSizeType(), VK_RValue),
8967           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8968     } else if (!ASE && !OASE &&
8969                Context.getAsArrayType(D->getType().getNonReferenceType()))
8970       PrivateTy = D->getType().getNonReferenceType();
8971     // Private copy.
8972     auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8973                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
8974     // Add initializer for private variable.
8975     Expr *Init = nullptr;
8976     auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8977     auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8978     if (DeclareReductionRef.isUsable()) {
8979       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8980       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8981       if (DRD->getInitializer()) {
8982         Init = DRDRef;
8983         RHSVD->setInit(DRDRef);
8984         RHSVD->setInitStyle(VarDecl::CallInit);
8985       }
8986     } else {
8987       switch (BOK) {
8988       case BO_Add:
8989       case BO_Xor:
8990       case BO_Or:
8991       case BO_LOr:
8992         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8993         if (Type->isScalarType() || Type->isAnyComplexType())
8994           Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8995         break;
8996       case BO_Mul:
8997       case BO_LAnd:
8998         if (Type->isScalarType() || Type->isAnyComplexType()) {
8999           // '*' and '&&' reduction ops - initializer is '1'.
9000           Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
9001         }
9002         break;
9003       case BO_And: {
9004         // '&' reduction op - initializer is '~0'.
9005         QualType OrigType = Type;
9006         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9007           Type = ComplexTy->getElementType();
9008         if (Type->isRealFloatingType()) {
9009           llvm::APFloat InitValue =
9010               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9011                                              /*isIEEE=*/true);
9012           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9013                                          Type, ELoc);
9014         } else if (Type->isScalarType()) {
9015           auto Size = Context.getTypeSize(Type);
9016           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9017           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9018           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9019         }
9020         if (Init && OrigType->isAnyComplexType()) {
9021           // Init = 0xFFFF + 0xFFFFi;
9022           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
9023           Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
9024         }
9025         Type = OrigType;
9026         break;
9027       }
9028       case BO_LT:
9029       case BO_GT: {
9030         // 'min' reduction op - initializer is 'Largest representable number in
9031         // the reduction list item type'.
9032         // 'max' reduction op - initializer is 'Least representable number in
9033         // the reduction list item type'.
9034         if (Type->isIntegerType() || Type->isPointerType()) {
9035           bool IsSigned = Type->hasSignedIntegerRepresentation();
9036           auto Size = Context.getTypeSize(Type);
9037           QualType IntTy =
9038               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9039           llvm::APInt InitValue =
9040               (BOK != BO_LT)
9041                   ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9042                              : llvm::APInt::getMinValue(Size)
9043                   : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9044                              : llvm::APInt::getMaxValue(Size);
9045           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9046           if (Type->isPointerType()) {
9047             // Cast to pointer type.
9048             auto CastExpr = BuildCStyleCastExpr(
9049                 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9050                 SourceLocation(), Init);
9051             if (CastExpr.isInvalid())
9052               continue;
9053             Init = CastExpr.get();
9054           }
9055         } else if (Type->isRealFloatingType()) {
9056           llvm::APFloat InitValue = llvm::APFloat::getLargest(
9057               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9058           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9059                                          Type, ELoc);
9060         }
9061         break;
9062       }
9063       case BO_PtrMemD:
9064       case BO_PtrMemI:
9065       case BO_MulAssign:
9066       case BO_Div:
9067       case BO_Rem:
9068       case BO_Sub:
9069       case BO_Shl:
9070       case BO_Shr:
9071       case BO_LE:
9072       case BO_GE:
9073       case BO_EQ:
9074       case BO_NE:
9075       case BO_AndAssign:
9076       case BO_XorAssign:
9077       case BO_OrAssign:
9078       case BO_Assign:
9079       case BO_AddAssign:
9080       case BO_SubAssign:
9081       case BO_DivAssign:
9082       case BO_RemAssign:
9083       case BO_ShlAssign:
9084       case BO_ShrAssign:
9085       case BO_Comma:
9086         llvm_unreachable("Unexpected reduction operation");
9087       }
9088     }
9089     if (Init && DeclareReductionRef.isUnset()) {
9090       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
9091                            /*TypeMayContainAuto=*/false);
9092     } else if (!Init)
9093       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
9094     if (RHSVD->isInvalidDecl())
9095       continue;
9096     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
9097       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9098                                                             << ReductionIdRange;
9099       bool IsDecl =
9100           !VD ||
9101           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9102       Diag(D->getLocation(),
9103            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9104           << D;
9105       continue;
9106     }
9107     // Store initializer for single element in private copy. Will be used during
9108     // codegen.
9109     PrivateVD->setInit(RHSVD->getInit());
9110     PrivateVD->setInitStyle(RHSVD->getInitStyle());
9111     auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
9112     ExprResult ReductionOp;
9113     if (DeclareReductionRef.isUsable()) {
9114       QualType RedTy = DeclareReductionRef.get()->getType();
9115       QualType PtrRedTy = Context.getPointerType(RedTy);
9116       ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9117       ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9118       if (!BasePath.empty()) {
9119         LHS = DefaultLvalueConversion(LHS.get());
9120         RHS = DefaultLvalueConversion(RHS.get());
9121         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9122                                        CK_UncheckedDerivedToBase, LHS.get(),
9123                                        &BasePath, LHS.get()->getValueKind());
9124         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9125                                        CK_UncheckedDerivedToBase, RHS.get(),
9126                                        &BasePath, RHS.get()->getValueKind());
9127       }
9128       FunctionProtoType::ExtProtoInfo EPI;
9129       QualType Params[] = {PtrRedTy, PtrRedTy};
9130       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9131       auto *OVE = new (Context) OpaqueValueExpr(
9132           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9133           DefaultLvalueConversion(DeclareReductionRef.get()).get());
9134       Expr *Args[] = {LHS.get(), RHS.get()};
9135       ReductionOp = new (Context)
9136           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9137     } else {
9138       ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9139                                ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9140       if (ReductionOp.isUsable()) {
9141         if (BOK != BO_LT && BOK != BO_GT) {
9142           ReductionOp =
9143               BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9144                          BO_Assign, LHSDRE, ReductionOp.get());
9145         } else {
9146           auto *ConditionalOp = new (Context) ConditionalOperator(
9147               ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9148               RHSDRE, Type, VK_LValue, OK_Ordinary);
9149           ReductionOp =
9150               BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9151                          BO_Assign, LHSDRE, ConditionalOp);
9152         }
9153         ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9154       }
9155       if (ReductionOp.isInvalid())
9156         continue;
9157     }
9158 
9159     DeclRefExpr *Ref = nullptr;
9160     Expr *VarsExpr = RefExpr->IgnoreParens();
9161     if (!VD) {
9162       if (ASE || OASE) {
9163         TransformExprToCaptures RebuildToCapture(*this, D);
9164         VarsExpr =
9165             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9166         Ref = RebuildToCapture.getCapturedExpr();
9167       } else {
9168         VarsExpr = Ref =
9169             buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9170       }
9171       if (!IsOpenMPCapturedDecl(D)) {
9172         ExprCaptures.push_back(Ref->getDecl());
9173         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9174           ExprResult RefRes = DefaultLvalueConversion(Ref);
9175           if (!RefRes.isUsable())
9176             continue;
9177           ExprResult PostUpdateRes =
9178               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9179                          SimpleRefExpr, RefRes.get());
9180           if (!PostUpdateRes.isUsable())
9181             continue;
9182           ExprPostUpdates.push_back(
9183               IgnoredValueConversions(PostUpdateRes.get()).get());
9184         }
9185       }
9186     }
9187     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9188     Vars.push_back(VarsExpr);
9189     Privates.push_back(PrivateDRE);
9190     LHSs.push_back(LHSDRE);
9191     RHSs.push_back(RHSDRE);
9192     ReductionOps.push_back(ReductionOp.get());
9193   }
9194 
9195   if (Vars.empty())
9196     return nullptr;
9197 
9198   return OMPReductionClause::Create(
9199       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
9200       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
9201       LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9202       buildPostUpdate(*this, ExprPostUpdates));
9203 }
9204 
9205 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9206                                      SourceLocation LinLoc) {
9207   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9208       LinKind == OMPC_LINEAR_unknown) {
9209     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9210     return true;
9211   }
9212   return false;
9213 }
9214 
9215 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9216                                  OpenMPLinearClauseKind LinKind,
9217                                  QualType Type) {
9218   auto *VD = dyn_cast_or_null<VarDecl>(D);
9219   // A variable must not have an incomplete type or a reference type.
9220   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9221     return true;
9222   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9223       !Type->isReferenceType()) {
9224     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9225         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9226     return true;
9227   }
9228   Type = Type.getNonReferenceType();
9229 
9230   // A list item must not be const-qualified.
9231   if (Type.isConstant(Context)) {
9232     Diag(ELoc, diag::err_omp_const_variable)
9233         << getOpenMPClauseName(OMPC_linear);
9234     if (D) {
9235       bool IsDecl =
9236           !VD ||
9237           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9238       Diag(D->getLocation(),
9239            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9240           << D;
9241     }
9242     return true;
9243   }
9244 
9245   // A list item must be of integral or pointer type.
9246   Type = Type.getUnqualifiedType().getCanonicalType();
9247   const auto *Ty = Type.getTypePtrOrNull();
9248   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9249               !Ty->isPointerType())) {
9250     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9251     if (D) {
9252       bool IsDecl =
9253           !VD ||
9254           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9255       Diag(D->getLocation(),
9256            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9257           << D;
9258     }
9259     return true;
9260   }
9261   return false;
9262 }
9263 
9264 OMPClause *Sema::ActOnOpenMPLinearClause(
9265     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9266     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9267     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9268   SmallVector<Expr *, 8> Vars;
9269   SmallVector<Expr *, 8> Privates;
9270   SmallVector<Expr *, 8> Inits;
9271   SmallVector<Decl *, 4> ExprCaptures;
9272   SmallVector<Expr *, 4> ExprPostUpdates;
9273   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
9274     LinKind = OMPC_LINEAR_val;
9275   for (auto &RefExpr : VarList) {
9276     assert(RefExpr && "NULL expr in OpenMP linear clause.");
9277     SourceLocation ELoc;
9278     SourceRange ERange;
9279     Expr *SimpleRefExpr = RefExpr;
9280     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9281                               /*AllowArraySection=*/false);
9282     if (Res.second) {
9283       // It will be analyzed later.
9284       Vars.push_back(RefExpr);
9285       Privates.push_back(nullptr);
9286       Inits.push_back(nullptr);
9287     }
9288     ValueDecl *D = Res.first;
9289     if (!D)
9290       continue;
9291 
9292     QualType Type = D->getType();
9293     auto *VD = dyn_cast<VarDecl>(D);
9294 
9295     // OpenMP [2.14.3.7, linear clause]
9296     //  A list-item cannot appear in more than one linear clause.
9297     //  A list-item that appears in a linear clause cannot appear in any
9298     //  other data-sharing attribute clause.
9299     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
9300     if (DVar.RefExpr) {
9301       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9302                                           << getOpenMPClauseName(OMPC_linear);
9303       ReportOriginalDSA(*this, DSAStack, D, DVar);
9304       continue;
9305     }
9306 
9307     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
9308       continue;
9309     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9310 
9311     // Build private copy of original var.
9312     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9313                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
9314     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
9315     // Build var to save initial value.
9316     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
9317     Expr *InitExpr;
9318     DeclRefExpr *Ref = nullptr;
9319     if (!VD) {
9320       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9321       if (!IsOpenMPCapturedDecl(D)) {
9322         ExprCaptures.push_back(Ref->getDecl());
9323         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9324           ExprResult RefRes = DefaultLvalueConversion(Ref);
9325           if (!RefRes.isUsable())
9326             continue;
9327           ExprResult PostUpdateRes =
9328               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9329                          SimpleRefExpr, RefRes.get());
9330           if (!PostUpdateRes.isUsable())
9331             continue;
9332           ExprPostUpdates.push_back(
9333               IgnoredValueConversions(PostUpdateRes.get()).get());
9334         }
9335       }
9336     }
9337     if (LinKind == OMPC_LINEAR_uval)
9338       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
9339     else
9340       InitExpr = VD ? SimpleRefExpr : Ref;
9341     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
9342                          /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
9343     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9344 
9345     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
9346     Vars.push_back(VD ? RefExpr->IgnoreParens() : Ref);
9347     Privates.push_back(PrivateRef);
9348     Inits.push_back(InitRef);
9349   }
9350 
9351   if (Vars.empty())
9352     return nullptr;
9353 
9354   Expr *StepExpr = Step;
9355   Expr *CalcStepExpr = nullptr;
9356   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9357       !Step->isInstantiationDependent() &&
9358       !Step->containsUnexpandedParameterPack()) {
9359     SourceLocation StepLoc = Step->getLocStart();
9360     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
9361     if (Val.isInvalid())
9362       return nullptr;
9363     StepExpr = Val.get();
9364 
9365     // Build var to save the step value.
9366     VarDecl *SaveVar =
9367         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
9368     ExprResult SaveRef =
9369         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
9370     ExprResult CalcStep =
9371         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
9372     CalcStep = ActOnFinishFullExpr(CalcStep.get());
9373 
9374     // Warn about zero linear step (it would be probably better specified as
9375     // making corresponding variables 'const').
9376     llvm::APSInt Result;
9377     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9378     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
9379       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9380                                                      << (Vars.size() > 1);
9381     if (!IsConstant && CalcStep.isUsable()) {
9382       // Calculate the step beforehand instead of doing this on each iteration.
9383       // (This is not used if the number of iterations may be kfold-ed).
9384       CalcStepExpr = CalcStep.get();
9385     }
9386   }
9387 
9388   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9389                                  ColonLoc, EndLoc, Vars, Privates, Inits,
9390                                  StepExpr, CalcStepExpr,
9391                                  buildPreInits(Context, ExprCaptures),
9392                                  buildPostUpdate(*this, ExprPostUpdates));
9393 }
9394 
9395 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9396                                      Expr *NumIterations, Sema &SemaRef,
9397                                      Scope *S, DSAStackTy *Stack) {
9398   // Walk the vars and build update/final expressions for the CodeGen.
9399   SmallVector<Expr *, 8> Updates;
9400   SmallVector<Expr *, 8> Finals;
9401   Expr *Step = Clause.getStep();
9402   Expr *CalcStep = Clause.getCalcStep();
9403   // OpenMP [2.14.3.7, linear clause]
9404   // If linear-step is not specified it is assumed to be 1.
9405   if (Step == nullptr)
9406     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
9407   else if (CalcStep) {
9408     Step = cast<BinaryOperator>(CalcStep)->getLHS();
9409   }
9410   bool HasErrors = false;
9411   auto CurInit = Clause.inits().begin();
9412   auto CurPrivate = Clause.privates().begin();
9413   auto LinKind = Clause.getModifier();
9414   for (auto &RefExpr : Clause.varlists()) {
9415     SourceLocation ELoc;
9416     SourceRange ERange;
9417     Expr *SimpleRefExpr = RefExpr;
9418     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9419                               /*AllowArraySection=*/false);
9420     ValueDecl *D = Res.first;
9421     if (Res.second || !D) {
9422       Updates.push_back(nullptr);
9423       Finals.push_back(nullptr);
9424       HasErrors = true;
9425       continue;
9426     }
9427     if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9428       D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9429               ->getMemberDecl();
9430     }
9431     auto &&Info = Stack->isLoopControlVariable(D);
9432     Expr *InitExpr = *CurInit;
9433 
9434     // Build privatized reference to the current linear var.
9435     auto DE = cast<DeclRefExpr>(SimpleRefExpr);
9436     Expr *CapturedRef;
9437     if (LinKind == OMPC_LINEAR_uval)
9438       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9439     else
9440       CapturedRef =
9441           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9442                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9443                            /*RefersToCapture=*/true);
9444 
9445     // Build update: Var = InitExpr + IV * Step
9446     ExprResult Update;
9447     if (!Info.first) {
9448       Update =
9449           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9450                              InitExpr, IV, Step, /* Subtract */ false);
9451     } else
9452       Update = *CurPrivate;
9453     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9454                                          /*DiscardedValue=*/true);
9455 
9456     // Build final: Var = InitExpr + NumIterations * Step
9457     ExprResult Final;
9458     if (!Info.first) {
9459       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9460                                  InitExpr, NumIterations, Step,
9461                                  /* Subtract */ false);
9462     } else
9463       Final = *CurPrivate;
9464     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9465                                         /*DiscardedValue=*/true);
9466 
9467     if (!Update.isUsable() || !Final.isUsable()) {
9468       Updates.push_back(nullptr);
9469       Finals.push_back(nullptr);
9470       HasErrors = true;
9471     } else {
9472       Updates.push_back(Update.get());
9473       Finals.push_back(Final.get());
9474     }
9475     ++CurInit;
9476     ++CurPrivate;
9477   }
9478   Clause.setUpdates(Updates);
9479   Clause.setFinals(Finals);
9480   return HasErrors;
9481 }
9482 
9483 OMPClause *Sema::ActOnOpenMPAlignedClause(
9484     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9485     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9486 
9487   SmallVector<Expr *, 8> Vars;
9488   for (auto &RefExpr : VarList) {
9489     assert(RefExpr && "NULL expr in OpenMP linear clause.");
9490     SourceLocation ELoc;
9491     SourceRange ERange;
9492     Expr *SimpleRefExpr = RefExpr;
9493     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9494                               /*AllowArraySection=*/false);
9495     if (Res.second) {
9496       // It will be analyzed later.
9497       Vars.push_back(RefExpr);
9498     }
9499     ValueDecl *D = Res.first;
9500     if (!D)
9501       continue;
9502 
9503     QualType QType = D->getType();
9504     auto *VD = dyn_cast<VarDecl>(D);
9505 
9506     // OpenMP  [2.8.1, simd construct, Restrictions]
9507     // The type of list items appearing in the aligned clause must be
9508     // array, pointer, reference to array, or reference to pointer.
9509     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
9510     const Type *Ty = QType.getTypePtrOrNull();
9511     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
9512       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
9513           << QType << getLangOpts().CPlusPlus << ERange;
9514       bool IsDecl =
9515           !VD ||
9516           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9517       Diag(D->getLocation(),
9518            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9519           << D;
9520       continue;
9521     }
9522 
9523     // OpenMP  [2.8.1, simd construct, Restrictions]
9524     // A list-item cannot appear in more than one aligned clause.
9525     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
9526       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
9527       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9528           << getOpenMPClauseName(OMPC_aligned);
9529       continue;
9530     }
9531 
9532     DeclRefExpr *Ref = nullptr;
9533     if (!VD && IsOpenMPCapturedDecl(D))
9534       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9535     Vars.push_back(DefaultFunctionArrayConversion(
9536                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9537                        .get());
9538   }
9539 
9540   // OpenMP [2.8.1, simd construct, Description]
9541   // The parameter of the aligned clause, alignment, must be a constant
9542   // positive integer expression.
9543   // If no optional parameter is specified, implementation-defined default
9544   // alignments for SIMD instructions on the target platforms are assumed.
9545   if (Alignment != nullptr) {
9546     ExprResult AlignResult =
9547         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9548     if (AlignResult.isInvalid())
9549       return nullptr;
9550     Alignment = AlignResult.get();
9551   }
9552   if (Vars.empty())
9553     return nullptr;
9554 
9555   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9556                                   EndLoc, Vars, Alignment);
9557 }
9558 
9559 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9560                                          SourceLocation StartLoc,
9561                                          SourceLocation LParenLoc,
9562                                          SourceLocation EndLoc) {
9563   SmallVector<Expr *, 8> Vars;
9564   SmallVector<Expr *, 8> SrcExprs;
9565   SmallVector<Expr *, 8> DstExprs;
9566   SmallVector<Expr *, 8> AssignmentOps;
9567   for (auto &RefExpr : VarList) {
9568     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9569     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9570       // It will be analyzed later.
9571       Vars.push_back(RefExpr);
9572       SrcExprs.push_back(nullptr);
9573       DstExprs.push_back(nullptr);
9574       AssignmentOps.push_back(nullptr);
9575       continue;
9576     }
9577 
9578     SourceLocation ELoc = RefExpr->getExprLoc();
9579     // OpenMP [2.1, C/C++]
9580     //  A list item is a variable name.
9581     // OpenMP  [2.14.4.1, Restrictions, p.1]
9582     //  A list item that appears in a copyin clause must be threadprivate.
9583     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
9584     if (!DE || !isa<VarDecl>(DE->getDecl())) {
9585       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9586           << 0 << RefExpr->getSourceRange();
9587       continue;
9588     }
9589 
9590     Decl *D = DE->getDecl();
9591     VarDecl *VD = cast<VarDecl>(D);
9592 
9593     QualType Type = VD->getType();
9594     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9595       // It will be analyzed later.
9596       Vars.push_back(DE);
9597       SrcExprs.push_back(nullptr);
9598       DstExprs.push_back(nullptr);
9599       AssignmentOps.push_back(nullptr);
9600       continue;
9601     }
9602 
9603     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9604     //  A list item that appears in a copyin clause must be threadprivate.
9605     if (!DSAStack->isThreadPrivate(VD)) {
9606       Diag(ELoc, diag::err_omp_required_access)
9607           << getOpenMPClauseName(OMPC_copyin)
9608           << getOpenMPDirectiveName(OMPD_threadprivate);
9609       continue;
9610     }
9611 
9612     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9613     //  A variable of class type (or array thereof) that appears in a
9614     //  copyin clause requires an accessible, unambiguous copy assignment
9615     //  operator for the class type.
9616     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
9617     auto *SrcVD =
9618         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9619                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9620     auto *PseudoSrcExpr = buildDeclRefExpr(
9621         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9622     auto *DstVD =
9623         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9624                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
9625     auto *PseudoDstExpr =
9626         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
9627     // For arrays generate assignment operation for single element and replace
9628     // it by the original array element in CodeGen.
9629     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9630                                    PseudoDstExpr, PseudoSrcExpr);
9631     if (AssignmentOp.isInvalid())
9632       continue;
9633     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9634                                        /*DiscardedValue=*/true);
9635     if (AssignmentOp.isInvalid())
9636       continue;
9637 
9638     DSAStack->addDSA(VD, DE, OMPC_copyin);
9639     Vars.push_back(DE);
9640     SrcExprs.push_back(PseudoSrcExpr);
9641     DstExprs.push_back(PseudoDstExpr);
9642     AssignmentOps.push_back(AssignmentOp.get());
9643   }
9644 
9645   if (Vars.empty())
9646     return nullptr;
9647 
9648   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9649                                  SrcExprs, DstExprs, AssignmentOps);
9650 }
9651 
9652 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9653                                               SourceLocation StartLoc,
9654                                               SourceLocation LParenLoc,
9655                                               SourceLocation EndLoc) {
9656   SmallVector<Expr *, 8> Vars;
9657   SmallVector<Expr *, 8> SrcExprs;
9658   SmallVector<Expr *, 8> DstExprs;
9659   SmallVector<Expr *, 8> AssignmentOps;
9660   for (auto &RefExpr : VarList) {
9661     assert(RefExpr && "NULL expr in OpenMP linear clause.");
9662     SourceLocation ELoc;
9663     SourceRange ERange;
9664     Expr *SimpleRefExpr = RefExpr;
9665     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9666                               /*AllowArraySection=*/false);
9667     if (Res.second) {
9668       // It will be analyzed later.
9669       Vars.push_back(RefExpr);
9670       SrcExprs.push_back(nullptr);
9671       DstExprs.push_back(nullptr);
9672       AssignmentOps.push_back(nullptr);
9673     }
9674     ValueDecl *D = Res.first;
9675     if (!D)
9676       continue;
9677 
9678     QualType Type = D->getType();
9679     auto *VD = dyn_cast<VarDecl>(D);
9680 
9681     // OpenMP [2.14.4.2, Restrictions, p.2]
9682     //  A list item that appears in a copyprivate clause may not appear in a
9683     //  private or firstprivate clause on the single construct.
9684     if (!VD || !DSAStack->isThreadPrivate(VD)) {
9685       auto DVar = DSAStack->getTopDSA(D, false);
9686       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9687           DVar.RefExpr) {
9688         Diag(ELoc, diag::err_omp_wrong_dsa)
9689             << getOpenMPClauseName(DVar.CKind)
9690             << getOpenMPClauseName(OMPC_copyprivate);
9691         ReportOriginalDSA(*this, DSAStack, D, DVar);
9692         continue;
9693       }
9694 
9695       // OpenMP [2.11.4.2, Restrictions, p.1]
9696       //  All list items that appear in a copyprivate clause must be either
9697       //  threadprivate or private in the enclosing context.
9698       if (DVar.CKind == OMPC_unknown) {
9699         DVar = DSAStack->getImplicitDSA(D, false);
9700         if (DVar.CKind == OMPC_shared) {
9701           Diag(ELoc, diag::err_omp_required_access)
9702               << getOpenMPClauseName(OMPC_copyprivate)
9703               << "threadprivate or private in the enclosing context";
9704           ReportOriginalDSA(*this, DSAStack, D, DVar);
9705           continue;
9706         }
9707       }
9708     }
9709 
9710     // Variably modified types are not supported.
9711     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
9712       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9713           << getOpenMPClauseName(OMPC_copyprivate) << Type
9714           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9715       bool IsDecl =
9716           !VD ||
9717           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9718       Diag(D->getLocation(),
9719            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9720           << D;
9721       continue;
9722     }
9723 
9724     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9725     //  A variable of class type (or array thereof) that appears in a
9726     //  copyin clause requires an accessible, unambiguous copy assignment
9727     //  operator for the class type.
9728     Type = Context.getBaseElementType(Type.getNonReferenceType())
9729                .getUnqualifiedType();
9730     auto *SrcVD =
9731         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9732                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9733     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
9734     auto *DstVD =
9735         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9736                      D->hasAttrs() ? &D->getAttrs() : nullptr);
9737     auto *PseudoDstExpr =
9738         buildDeclRefExpr(*this, DstVD, Type, ELoc);
9739     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9740                                    PseudoDstExpr, PseudoSrcExpr);
9741     if (AssignmentOp.isInvalid())
9742       continue;
9743     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
9744                                        /*DiscardedValue=*/true);
9745     if (AssignmentOp.isInvalid())
9746       continue;
9747 
9748     // No need to mark vars as copyprivate, they are already threadprivate or
9749     // implicitly private.
9750     assert(VD || IsOpenMPCapturedDecl(D));
9751     Vars.push_back(
9752         VD ? RefExpr->IgnoreParens()
9753            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9754     SrcExprs.push_back(PseudoSrcExpr);
9755     DstExprs.push_back(PseudoDstExpr);
9756     AssignmentOps.push_back(AssignmentOp.get());
9757   }
9758 
9759   if (Vars.empty())
9760     return nullptr;
9761 
9762   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9763                                       Vars, SrcExprs, DstExprs, AssignmentOps);
9764 }
9765 
9766 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9767                                         SourceLocation StartLoc,
9768                                         SourceLocation LParenLoc,
9769                                         SourceLocation EndLoc) {
9770   if (VarList.empty())
9771     return nullptr;
9772 
9773   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9774 }
9775 
9776 OMPClause *
9777 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9778                               SourceLocation DepLoc, SourceLocation ColonLoc,
9779                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9780                               SourceLocation LParenLoc, SourceLocation EndLoc) {
9781   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9782       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9783     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9784         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9785     return nullptr;
9786   }
9787   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9788       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9789        DepKind == OMPC_DEPEND_sink)) {
9790     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9791     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9792         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9793                                    /*Last=*/OMPC_DEPEND_unknown, Except)
9794         << getOpenMPClauseName(OMPC_depend);
9795     return nullptr;
9796   }
9797   SmallVector<Expr *, 8> Vars;
9798   DSAStackTy::OperatorOffsetTy OpsOffs;
9799   llvm::APSInt DepCounter(/*BitWidth=*/32);
9800   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9801   if (DepKind == OMPC_DEPEND_sink) {
9802     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9803       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9804       TotalDepCount.setIsUnsigned(/*Val=*/true);
9805     }
9806   }
9807   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9808       DSAStack->getParentOrderedRegionParam()) {
9809     for (auto &RefExpr : VarList) {
9810       assert(RefExpr && "NULL expr in OpenMP shared clause.");
9811       if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9812         // It will be analyzed later.
9813         Vars.push_back(RefExpr);
9814         continue;
9815       }
9816 
9817       SourceLocation ELoc = RefExpr->getExprLoc();
9818       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9819       if (DepKind == OMPC_DEPEND_sink) {
9820         if (DepCounter >= TotalDepCount) {
9821           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9822           continue;
9823         }
9824         ++DepCounter;
9825         // OpenMP  [2.13.9, Summary]
9826         // depend(dependence-type : vec), where dependence-type is:
9827         // 'sink' and where vec is the iteration vector, which has the form:
9828         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9829         // where n is the value specified by the ordered clause in the loop
9830         // directive, xi denotes the loop iteration variable of the i-th nested
9831         // loop associated with the loop directive, and di is a constant
9832         // non-negative integer.
9833         if (CurContext->isDependentContext()) {
9834           // It will be analyzed later.
9835           Vars.push_back(RefExpr);
9836           continue;
9837         }
9838         SimpleExpr = SimpleExpr->IgnoreImplicit();
9839         OverloadedOperatorKind OOK = OO_None;
9840         SourceLocation OOLoc;
9841         Expr *LHS = SimpleExpr;
9842         Expr *RHS = nullptr;
9843         if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9844           OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9845           OOLoc = BO->getOperatorLoc();
9846           LHS = BO->getLHS()->IgnoreParenImpCasts();
9847           RHS = BO->getRHS()->IgnoreParenImpCasts();
9848         } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9849           OOK = OCE->getOperator();
9850           OOLoc = OCE->getOperatorLoc();
9851           LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9852           RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9853         } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9854           OOK = MCE->getMethodDecl()
9855                     ->getNameInfo()
9856                     .getName()
9857                     .getCXXOverloadedOperator();
9858           OOLoc = MCE->getCallee()->getExprLoc();
9859           LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9860           RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9861         }
9862         SourceLocation ELoc;
9863         SourceRange ERange;
9864         auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9865                                   /*AllowArraySection=*/false);
9866         if (Res.second) {
9867           // It will be analyzed later.
9868           Vars.push_back(RefExpr);
9869         }
9870         ValueDecl *D = Res.first;
9871         if (!D)
9872           continue;
9873 
9874         if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9875           Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9876           continue;
9877         }
9878         if (RHS) {
9879           ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9880               RHS, OMPC_depend, /*StrictlyPositive=*/false);
9881           if (RHSRes.isInvalid())
9882             continue;
9883         }
9884         if (!CurContext->isDependentContext() &&
9885             DSAStack->getParentOrderedRegionParam() &&
9886             DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9887           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9888               << DSAStack->getParentLoopControlVariable(
9889                      DepCounter.getZExtValue());
9890           continue;
9891         }
9892         OpsOffs.push_back({RHS, OOK});
9893       } else {
9894         // OpenMP  [2.11.1.1, Restrictions, p.3]
9895         //  A variable that is part of another variable (such as a field of a
9896         //  structure) but is not an array element or an array section cannot
9897         //  appear  in a depend clause.
9898         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9899         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9900         auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9901         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9902             (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9903             (ASE &&
9904              !ASE->getBase()
9905                   ->getType()
9906                   .getNonReferenceType()
9907                   ->isPointerType() &&
9908              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9909           Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9910               << 0 << RefExpr->getSourceRange();
9911           continue;
9912         }
9913       }
9914       Vars.push_back(RefExpr->IgnoreParenImpCasts());
9915     }
9916 
9917     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9918         TotalDepCount > VarList.size() &&
9919         DSAStack->getParentOrderedRegionParam()) {
9920       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9921           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9922     }
9923     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9924         Vars.empty())
9925       return nullptr;
9926   }
9927   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9928                                     DepKind, DepLoc, ColonLoc, Vars);
9929   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9930     DSAStack->addDoacrossDependClause(C, OpsOffs);
9931   return C;
9932 }
9933 
9934 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9935                                          SourceLocation LParenLoc,
9936                                          SourceLocation EndLoc) {
9937   Expr *ValExpr = Device;
9938 
9939   // OpenMP [2.9.1, Restrictions]
9940   // The device expression must evaluate to a non-negative integer value.
9941   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9942                                  /*StrictlyPositive=*/false))
9943     return nullptr;
9944 
9945   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9946 }
9947 
9948 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9949                                    DSAStackTy *Stack, CXXRecordDecl *RD) {
9950   if (!RD || RD->isInvalidDecl())
9951     return true;
9952 
9953   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
9954     if (auto *CTD = CTSD->getSpecializedTemplate())
9955       RD = CTD->getTemplatedDecl();
9956   auto QTy = SemaRef.Context.getRecordType(RD);
9957   if (RD->isDynamicClass()) {
9958     SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9959     SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9960     return false;
9961   }
9962   auto *DC = RD;
9963   bool IsCorrect = true;
9964   for (auto *I : DC->decls()) {
9965     if (I) {
9966       if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9967         if (MD->isStatic()) {
9968           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9969           SemaRef.Diag(MD->getLocation(),
9970                        diag::note_omp_static_member_in_target);
9971           IsCorrect = false;
9972         }
9973       } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9974         if (VD->isStaticDataMember()) {
9975           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9976           SemaRef.Diag(VD->getLocation(),
9977                        diag::note_omp_static_member_in_target);
9978           IsCorrect = false;
9979         }
9980       }
9981     }
9982   }
9983 
9984   for (auto &I : RD->bases()) {
9985     if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9986                                 I.getType()->getAsCXXRecordDecl()))
9987       IsCorrect = false;
9988   }
9989   return IsCorrect;
9990 }
9991 
9992 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9993                               DSAStackTy *Stack, QualType QTy) {
9994   NamedDecl *ND;
9995   if (QTy->isIncompleteType(&ND)) {
9996     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9997     return false;
9998   } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9999     if (!RD->isInvalidDecl() &&
10000         !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
10001       return false;
10002   }
10003   return true;
10004 }
10005 
10006 /// \brief Return true if it can be proven that the provided array expression
10007 /// (array section or array subscript) does NOT specify the whole size of the
10008 /// array whose base type is \a BaseQTy.
10009 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10010                                                         const Expr *E,
10011                                                         QualType BaseQTy) {
10012   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10013 
10014   // If this is an array subscript, it refers to the whole size if the size of
10015   // the dimension is constant and equals 1. Also, an array section assumes the
10016   // format of an array subscript if no colon is used.
10017   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10018     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10019       return ATy->getSize().getSExtValue() != 1;
10020     // Size can't be evaluated statically.
10021     return false;
10022   }
10023 
10024   assert(OASE && "Expecting array section if not an array subscript.");
10025   auto *LowerBound = OASE->getLowerBound();
10026   auto *Length = OASE->getLength();
10027 
10028   // If there is a lower bound that does not evaluates to zero, we are not
10029   // convering the whole dimension.
10030   if (LowerBound) {
10031     llvm::APSInt ConstLowerBound;
10032     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10033       return false; // Can't get the integer value as a constant.
10034     if (ConstLowerBound.getSExtValue())
10035       return true;
10036   }
10037 
10038   // If we don't have a length we covering the whole dimension.
10039   if (!Length)
10040     return false;
10041 
10042   // If the base is a pointer, we don't have a way to get the size of the
10043   // pointee.
10044   if (BaseQTy->isPointerType())
10045     return false;
10046 
10047   // We can only check if the length is the same as the size of the dimension
10048   // if we have a constant array.
10049   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10050   if (!CATy)
10051     return false;
10052 
10053   llvm::APSInt ConstLength;
10054   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10055     return false; // Can't get the integer value as a constant.
10056 
10057   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10058 }
10059 
10060 // Return true if it can be proven that the provided array expression (array
10061 // section or array subscript) does NOT specify a single element of the array
10062 // whose base type is \a BaseQTy.
10063 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
10064                                                        const Expr *E,
10065                                                        QualType BaseQTy) {
10066   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10067 
10068   // An array subscript always refer to a single element. Also, an array section
10069   // assumes the format of an array subscript if no colon is used.
10070   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10071     return false;
10072 
10073   assert(OASE && "Expecting array section if not an array subscript.");
10074   auto *Length = OASE->getLength();
10075 
10076   // If we don't have a length we have to check if the array has unitary size
10077   // for this dimension. Also, we should always expect a length if the base type
10078   // is pointer.
10079   if (!Length) {
10080     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10081       return ATy->getSize().getSExtValue() != 1;
10082     // We cannot assume anything.
10083     return false;
10084   }
10085 
10086   // Check if the length evaluates to 1.
10087   llvm::APSInt ConstLength;
10088   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10089     return false; // Can't get the integer value as a constant.
10090 
10091   return ConstLength.getSExtValue() != 1;
10092 }
10093 
10094 // Return the expression of the base of the mappable expression or null if it
10095 // cannot be determined and do all the necessary checks to see if the expression
10096 // is valid as a standalone mappable expression. In the process, record all the
10097 // components of the expression.
10098 static Expr *CheckMapClauseExpressionBase(
10099     Sema &SemaRef, Expr *E,
10100     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10101     OpenMPClauseKind CKind) {
10102   SourceLocation ELoc = E->getExprLoc();
10103   SourceRange ERange = E->getSourceRange();
10104 
10105   // The base of elements of list in a map clause have to be either:
10106   //  - a reference to variable or field.
10107   //  - a member expression.
10108   //  - an array expression.
10109   //
10110   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10111   // reference to 'r'.
10112   //
10113   // If we have:
10114   //
10115   // struct SS {
10116   //   Bla S;
10117   //   foo() {
10118   //     #pragma omp target map (S.Arr[:12]);
10119   //   }
10120   // }
10121   //
10122   // We want to retrieve the member expression 'this->S';
10123 
10124   Expr *RelevantExpr = nullptr;
10125 
10126   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10127   //  If a list item is an array section, it must specify contiguous storage.
10128   //
10129   // For this restriction it is sufficient that we make sure only references
10130   // to variables or fields and array expressions, and that no array sections
10131   // exist except in the rightmost expression (unless they cover the whole
10132   // dimension of the array). E.g. these would be invalid:
10133   //
10134   //   r.ArrS[3:5].Arr[6:7]
10135   //
10136   //   r.ArrS[3:5].x
10137   //
10138   // but these would be valid:
10139   //   r.ArrS[3].Arr[6:7]
10140   //
10141   //   r.ArrS[3].x
10142 
10143   bool AllowUnitySizeArraySection = true;
10144   bool AllowWholeSizeArraySection = true;
10145 
10146   while (!RelevantExpr) {
10147     E = E->IgnoreParenImpCasts();
10148 
10149     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10150       if (!isa<VarDecl>(CurE->getDecl()))
10151         break;
10152 
10153       RelevantExpr = CurE;
10154 
10155       // If we got a reference to a declaration, we should not expect any array
10156       // section before that.
10157       AllowUnitySizeArraySection = false;
10158       AllowWholeSizeArraySection = false;
10159 
10160       // Record the component.
10161       CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10162           CurE, CurE->getDecl()));
10163       continue;
10164     }
10165 
10166     if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10167       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10168 
10169       if (isa<CXXThisExpr>(BaseE))
10170         // We found a base expression: this->Val.
10171         RelevantExpr = CurE;
10172       else
10173         E = BaseE;
10174 
10175       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10176         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10177             << CurE->getSourceRange();
10178         break;
10179       }
10180 
10181       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10182 
10183       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10184       //  A bit-field cannot appear in a map clause.
10185       //
10186       if (FD->isBitField()) {
10187         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10188             << CurE->getSourceRange() << getOpenMPClauseName(CKind);
10189         break;
10190       }
10191 
10192       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10193       //  If the type of a list item is a reference to a type T then the type
10194       //  will be considered to be T for all purposes of this clause.
10195       QualType CurType = BaseE->getType().getNonReferenceType();
10196 
10197       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10198       //  A list item cannot be a variable that is a member of a structure with
10199       //  a union type.
10200       //
10201       if (auto *RT = CurType->getAs<RecordType>())
10202         if (RT->isUnionType()) {
10203           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10204               << CurE->getSourceRange();
10205           break;
10206         }
10207 
10208       // If we got a member expression, we should not expect any array section
10209       // before that:
10210       //
10211       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10212       //  If a list item is an element of a structure, only the rightmost symbol
10213       //  of the variable reference can be an array section.
10214       //
10215       AllowUnitySizeArraySection = false;
10216       AllowWholeSizeArraySection = false;
10217 
10218       // Record the component.
10219       CurComponents.push_back(
10220           OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
10221       continue;
10222     }
10223 
10224     if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10225       E = CurE->getBase()->IgnoreParenImpCasts();
10226 
10227       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10228         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10229             << 0 << CurE->getSourceRange();
10230         break;
10231       }
10232 
10233       // If we got an array subscript that express the whole dimension we
10234       // can have any array expressions before. If it only expressing part of
10235       // the dimension, we can only have unitary-size array expressions.
10236       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10237                                                       E->getType()))
10238         AllowWholeSizeArraySection = false;
10239 
10240       // Record the component - we don't have any declaration associated.
10241       CurComponents.push_back(
10242           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10243       continue;
10244     }
10245 
10246     if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
10247       E = CurE->getBase()->IgnoreParenImpCasts();
10248 
10249       auto CurType =
10250           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10251 
10252       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10253       //  If the type of a list item is a reference to a type T then the type
10254       //  will be considered to be T for all purposes of this clause.
10255       if (CurType->isReferenceType())
10256         CurType = CurType->getPointeeType();
10257 
10258       bool IsPointer = CurType->isAnyPointerType();
10259 
10260       if (!IsPointer && !CurType->isArrayType()) {
10261         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10262             << 0 << CurE->getSourceRange();
10263         break;
10264       }
10265 
10266       bool NotWhole =
10267           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10268       bool NotUnity =
10269           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10270 
10271       if (AllowWholeSizeArraySection && AllowUnitySizeArraySection) {
10272         // Any array section is currently allowed.
10273         //
10274         // If this array section refers to the whole dimension we can still
10275         // accept other array sections before this one, except if the base is a
10276         // pointer. Otherwise, only unitary sections are accepted.
10277         if (NotWhole || IsPointer)
10278           AllowWholeSizeArraySection = false;
10279       } else if ((AllowUnitySizeArraySection && NotUnity) ||
10280                  (AllowWholeSizeArraySection && NotWhole)) {
10281         // A unity or whole array section is not allowed and that is not
10282         // compatible with the properties of the current array section.
10283         SemaRef.Diag(
10284             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10285             << CurE->getSourceRange();
10286         break;
10287       }
10288 
10289       // Record the component - we don't have any declaration associated.
10290       CurComponents.push_back(
10291           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
10292       continue;
10293     }
10294 
10295     // If nothing else worked, this is not a valid map clause expression.
10296     SemaRef.Diag(ELoc,
10297                  diag::err_omp_expected_named_var_member_or_array_expression)
10298         << ERange;
10299     break;
10300   }
10301 
10302   return RelevantExpr;
10303 }
10304 
10305 // Return true if expression E associated with value VD has conflicts with other
10306 // map information.
10307 static bool CheckMapConflicts(
10308     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10309     bool CurrentRegionOnly,
10310     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10311     OpenMPClauseKind CKind) {
10312   assert(VD && E);
10313   SourceLocation ELoc = E->getExprLoc();
10314   SourceRange ERange = E->getSourceRange();
10315 
10316   // In order to easily check the conflicts we need to match each component of
10317   // the expression under test with the components of the expressions that are
10318   // already in the stack.
10319 
10320   assert(!CurComponents.empty() && "Map clause expression with no components!");
10321   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
10322          "Map clause expression with unexpected base!");
10323 
10324   // Variables to help detecting enclosing problems in data environment nests.
10325   bool IsEnclosedByDataEnvironmentExpr = false;
10326   const Expr *EnclosingExpr = nullptr;
10327 
10328   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10329       VD, CurrentRegionOnly,
10330       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
10331               StackComponents) -> bool {
10332 
10333         assert(!StackComponents.empty() &&
10334                "Map clause expression with no components!");
10335         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
10336                "Map clause expression with unexpected base!");
10337 
10338         // The whole expression in the stack.
10339         auto *RE = StackComponents.front().getAssociatedExpression();
10340 
10341         // Expressions must start from the same base. Here we detect at which
10342         // point both expressions diverge from each other and see if we can
10343         // detect if the memory referred to both expressions is contiguous and
10344         // do not overlap.
10345         auto CI = CurComponents.rbegin();
10346         auto CE = CurComponents.rend();
10347         auto SI = StackComponents.rbegin();
10348         auto SE = StackComponents.rend();
10349         for (; CI != CE && SI != SE; ++CI, ++SI) {
10350 
10351           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10352           //  At most one list item can be an array item derived from a given
10353           //  variable in map clauses of the same construct.
10354           if (CurrentRegionOnly &&
10355               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10356                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10357               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10358                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10359             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
10360                          diag::err_omp_multiple_array_items_in_map_clause)
10361                 << CI->getAssociatedExpression()->getSourceRange();
10362             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10363                          diag::note_used_here)
10364                 << SI->getAssociatedExpression()->getSourceRange();
10365             return true;
10366           }
10367 
10368           // Do both expressions have the same kind?
10369           if (CI->getAssociatedExpression()->getStmtClass() !=
10370               SI->getAssociatedExpression()->getStmtClass())
10371             break;
10372 
10373           // Are we dealing with different variables/fields?
10374           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
10375             break;
10376         }
10377 
10378         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10379         //  List items of map clauses in the same construct must not share
10380         //  original storage.
10381         //
10382         // If the expressions are exactly the same or one is a subset of the
10383         // other, it means they are sharing storage.
10384         if (CI == CE && SI == SE) {
10385           if (CurrentRegionOnly) {
10386             if (CKind == OMPC_map)
10387               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10388             else {
10389               assert(CKind == OMPC_to || CKind == OMPC_from);
10390               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10391                   << ERange;
10392             }
10393             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10394                 << RE->getSourceRange();
10395             return true;
10396           } else {
10397             // If we find the same expression in the enclosing data environment,
10398             // that is legal.
10399             IsEnclosedByDataEnvironmentExpr = true;
10400             return false;
10401           }
10402         }
10403 
10404         QualType DerivedType =
10405             std::prev(CI)->getAssociatedDeclaration()->getType();
10406         SourceLocation DerivedLoc =
10407             std::prev(CI)->getAssociatedExpression()->getExprLoc();
10408 
10409         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10410         //  If the type of a list item is a reference to a type T then the type
10411         //  will be considered to be T for all purposes of this clause.
10412         DerivedType = DerivedType.getNonReferenceType();
10413 
10414         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10415         //  A variable for which the type is pointer and an array section
10416         //  derived from that variable must not appear as list items of map
10417         //  clauses of the same construct.
10418         //
10419         // Also, cover one of the cases in:
10420         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10421         //  If any part of the original storage of a list item has corresponding
10422         //  storage in the device data environment, all of the original storage
10423         //  must have corresponding storage in the device data environment.
10424         //
10425         if (DerivedType->isAnyPointerType()) {
10426           if (CI == CE || SI == SE) {
10427             SemaRef.Diag(
10428                 DerivedLoc,
10429                 diag::err_omp_pointer_mapped_along_with_derived_section)
10430                 << DerivedLoc;
10431           } else {
10432             assert(CI != CE && SI != SE);
10433             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10434                 << DerivedLoc;
10435           }
10436           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10437               << RE->getSourceRange();
10438           return true;
10439         }
10440 
10441         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10442         //  List items of map clauses in the same construct must not share
10443         //  original storage.
10444         //
10445         // An expression is a subset of the other.
10446         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
10447           if (CKind == OMPC_map)
10448             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10449           else {
10450             assert(CKind == OMPC_to || CKind == OMPC_from);
10451             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10452                 << ERange;
10453           }
10454           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10455               << RE->getSourceRange();
10456           return true;
10457         }
10458 
10459         // The current expression uses the same base as other expression in the
10460         // data environment but does not contain it completely.
10461         if (!CurrentRegionOnly && SI != SE)
10462           EnclosingExpr = RE;
10463 
10464         // The current expression is a subset of the expression in the data
10465         // environment.
10466         IsEnclosedByDataEnvironmentExpr |=
10467             (!CurrentRegionOnly && CI != CE && SI == SE);
10468 
10469         return false;
10470       });
10471 
10472   if (CurrentRegionOnly)
10473     return FoundError;
10474 
10475   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10476   //  If any part of the original storage of a list item has corresponding
10477   //  storage in the device data environment, all of the original storage must
10478   //  have corresponding storage in the device data environment.
10479   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10480   //  If a list item is an element of a structure, and a different element of
10481   //  the structure has a corresponding list item in the device data environment
10482   //  prior to a task encountering the construct associated with the map clause,
10483   //  then the list item must also have a corresponding list item in the device
10484   //  data environment prior to the task encountering the construct.
10485   //
10486   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10487     SemaRef.Diag(ELoc,
10488                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
10489         << ERange;
10490     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10491         << EnclosingExpr->getSourceRange();
10492     return true;
10493   }
10494 
10495   return FoundError;
10496 }
10497 
10498 namespace {
10499 // Utility struct that gathers all the related lists associated with a mappable
10500 // expression.
10501 struct MappableVarListInfo final {
10502   // The list of expressions.
10503   ArrayRef<Expr *> VarList;
10504   // The list of processed expressions.
10505   SmallVector<Expr *, 16> ProcessedVarList;
10506   // The mappble components for each expression.
10507   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10508   // The base declaration of the variable.
10509   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10510 
10511   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10512     // We have a list of components and base declarations for each entry in the
10513     // variable list.
10514     VarComponents.reserve(VarList.size());
10515     VarBaseDeclarations.reserve(VarList.size());
10516   }
10517 };
10518 }
10519 
10520 // Check the validity of the provided variable list for the provided clause kind
10521 // \a CKind. In the check process the valid expressions, and mappable expression
10522 // components and variables are extracted and used to fill \a Vars,
10523 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10524 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10525 static void
10526 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10527                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10528                             SourceLocation StartLoc,
10529                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10530                             bool IsMapTypeImplicit = false) {
10531   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10532   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
10533          "Unexpected clause kind with mappable expressions!");
10534 
10535   // Keep track of the mappable components and base declarations in this clause.
10536   // Each entry in the list is going to have a list of components associated. We
10537   // record each set of the components so that we can build the clause later on.
10538   // In the end we should have the same amount of declarations and component
10539   // lists.
10540 
10541   for (auto &RE : MVLI.VarList) {
10542     assert(RE && "Null expr in omp to/from/map clause");
10543     SourceLocation ELoc = RE->getExprLoc();
10544 
10545     auto *VE = RE->IgnoreParenLValueCasts();
10546 
10547     if (VE->isValueDependent() || VE->isTypeDependent() ||
10548         VE->isInstantiationDependent() ||
10549         VE->containsUnexpandedParameterPack()) {
10550       // We can only analyze this information once the missing information is
10551       // resolved.
10552       MVLI.ProcessedVarList.push_back(RE);
10553       continue;
10554     }
10555 
10556     auto *SimpleExpr = RE->IgnoreParenCasts();
10557 
10558     if (!RE->IgnoreParenImpCasts()->isLValue()) {
10559       SemaRef.Diag(ELoc,
10560                    diag::err_omp_expected_named_var_member_or_array_expression)
10561           << RE->getSourceRange();
10562       continue;
10563     }
10564 
10565     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10566     ValueDecl *CurDeclaration = nullptr;
10567 
10568     // Obtain the array or member expression bases if required. Also, fill the
10569     // components array with all the components identified in the process.
10570     auto *BE =
10571         CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
10572     if (!BE)
10573       continue;
10574 
10575     assert(!CurComponents.empty() &&
10576            "Invalid mappable expression information.");
10577 
10578     // For the following checks, we rely on the base declaration which is
10579     // expected to be associated with the last component. The declaration is
10580     // expected to be a variable or a field (if 'this' is being mapped).
10581     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10582     assert(CurDeclaration && "Null decl on map clause.");
10583     assert(
10584         CurDeclaration->isCanonicalDecl() &&
10585         "Expecting components to have associated only canonical declarations.");
10586 
10587     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10588     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
10589 
10590     assert((VD || FD) && "Only variables or fields are expected here!");
10591     (void)FD;
10592 
10593     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
10594     // threadprivate variables cannot appear in a map clause.
10595     // OpenMP 4.5 [2.10.5, target update Construct]
10596     // threadprivate variables cannot appear in a from clause.
10597     if (VD && DSAS->isThreadPrivate(VD)) {
10598       auto DVar = DSAS->getTopDSA(VD, false);
10599       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10600           << getOpenMPClauseName(CKind);
10601       ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
10602       continue;
10603     }
10604 
10605     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10606     //  A list item cannot appear in both a map clause and a data-sharing
10607     //  attribute clause on the same construct.
10608 
10609     // Check conflicts with other map clause expressions. We check the conflicts
10610     // with the current construct separately from the enclosing data
10611     // environment, because the restrictions are different. We only have to
10612     // check conflicts across regions for the map clauses.
10613     if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10614                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
10615       break;
10616     if (CKind == OMPC_map &&
10617         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10618                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
10619       break;
10620 
10621     // OpenMP 4.5 [2.10.5, target update Construct]
10622     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10623     //  If the type of a list item is a reference to a type T then the type will
10624     //  be considered to be T for all purposes of this clause.
10625     QualType Type = CurDeclaration->getType().getNonReferenceType();
10626 
10627     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10628     // A list item in a to or from clause must have a mappable type.
10629     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10630     //  A list item must have a mappable type.
10631     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10632                            DSAS, Type))
10633       continue;
10634 
10635     if (CKind == OMPC_map) {
10636       // target enter data
10637       // OpenMP [2.10.2, Restrictions, p. 99]
10638       // A map-type must be specified in all map clauses and must be either
10639       // to or alloc.
10640       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10641       if (DKind == OMPD_target_enter_data &&
10642           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10643         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10644             << (IsMapTypeImplicit ? 1 : 0)
10645             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10646             << getOpenMPDirectiveName(DKind);
10647         continue;
10648       }
10649 
10650       // target exit_data
10651       // OpenMP [2.10.3, Restrictions, p. 102]
10652       // A map-type must be specified in all map clauses and must be either
10653       // from, release, or delete.
10654       if (DKind == OMPD_target_exit_data &&
10655           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10656             MapType == OMPC_MAP_delete)) {
10657         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10658             << (IsMapTypeImplicit ? 1 : 0)
10659             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10660             << getOpenMPDirectiveName(DKind);
10661         continue;
10662       }
10663 
10664       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10665       // A list item cannot appear in both a map clause and a data-sharing
10666       // attribute clause on the same construct
10667       if (DKind == OMPD_target && VD) {
10668         auto DVar = DSAS->getTopDSA(VD, false);
10669         if (isOpenMPPrivate(DVar.CKind)) {
10670           SemaRef.Diag(ELoc, diag::err_omp_variable_in_map_and_dsa)
10671               << getOpenMPClauseName(DVar.CKind)
10672               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10673           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10674           continue;
10675         }
10676       }
10677     }
10678 
10679     // Save the current expression.
10680     MVLI.ProcessedVarList.push_back(RE);
10681 
10682     // Store the components in the stack so that they can be used to check
10683     // against other clauses later on.
10684     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents);
10685 
10686     // Save the components and declaration to create the clause. For purposes of
10687     // the clause creation, any component list that has has base 'this' uses
10688     // null as base declaration.
10689     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10690     MVLI.VarComponents.back().append(CurComponents.begin(),
10691                                      CurComponents.end());
10692     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10693                                                            : CurDeclaration);
10694   }
10695 }
10696 
10697 OMPClause *
10698 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10699                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10700                            SourceLocation MapLoc, SourceLocation ColonLoc,
10701                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10702                            SourceLocation LParenLoc, SourceLocation EndLoc) {
10703   MappableVarListInfo MVLI(VarList);
10704   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10705                               MapType, IsMapTypeImplicit);
10706 
10707   // We need to produce a map clause even if we don't have variables so that
10708   // other diagnostics related with non-existing map clauses are accurate.
10709   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10710                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10711                               MVLI.VarComponents, MapTypeModifier, MapType,
10712                               IsMapTypeImplicit, MapLoc);
10713 }
10714 
10715 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10716                                                TypeResult ParsedType) {
10717   assert(ParsedType.isUsable());
10718 
10719   QualType ReductionType = GetTypeFromParser(ParsedType.get());
10720   if (ReductionType.isNull())
10721     return QualType();
10722 
10723   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10724   // A type name in a declare reduction directive cannot be a function type, an
10725   // array type, a reference type, or a type qualified with const, volatile or
10726   // restrict.
10727   if (ReductionType.hasQualifiers()) {
10728     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10729     return QualType();
10730   }
10731 
10732   if (ReductionType->isFunctionType()) {
10733     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10734     return QualType();
10735   }
10736   if (ReductionType->isReferenceType()) {
10737     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10738     return QualType();
10739   }
10740   if (ReductionType->isArrayType()) {
10741     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10742     return QualType();
10743   }
10744   return ReductionType;
10745 }
10746 
10747 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10748     Scope *S, DeclContext *DC, DeclarationName Name,
10749     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10750     AccessSpecifier AS, Decl *PrevDeclInScope) {
10751   SmallVector<Decl *, 8> Decls;
10752   Decls.reserve(ReductionTypes.size());
10753 
10754   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10755                       ForRedeclaration);
10756   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10757   // A reduction-identifier may not be re-declared in the current scope for the
10758   // same type or for a type that is compatible according to the base language
10759   // rules.
10760   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10761   OMPDeclareReductionDecl *PrevDRD = nullptr;
10762   bool InCompoundScope = true;
10763   if (S != nullptr) {
10764     // Find previous declaration with the same name not referenced in other
10765     // declarations.
10766     FunctionScopeInfo *ParentFn = getEnclosingFunction();
10767     InCompoundScope =
10768         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10769     LookupName(Lookup, S);
10770     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10771                          /*AllowInlineNamespace=*/false);
10772     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10773     auto Filter = Lookup.makeFilter();
10774     while (Filter.hasNext()) {
10775       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10776       if (InCompoundScope) {
10777         auto I = UsedAsPrevious.find(PrevDecl);
10778         if (I == UsedAsPrevious.end())
10779           UsedAsPrevious[PrevDecl] = false;
10780         if (auto *D = PrevDecl->getPrevDeclInScope())
10781           UsedAsPrevious[D] = true;
10782       }
10783       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10784           PrevDecl->getLocation();
10785     }
10786     Filter.done();
10787     if (InCompoundScope) {
10788       for (auto &PrevData : UsedAsPrevious) {
10789         if (!PrevData.second) {
10790           PrevDRD = PrevData.first;
10791           break;
10792         }
10793       }
10794     }
10795   } else if (PrevDeclInScope != nullptr) {
10796     auto *PrevDRDInScope = PrevDRD =
10797         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10798     do {
10799       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10800           PrevDRDInScope->getLocation();
10801       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10802     } while (PrevDRDInScope != nullptr);
10803   }
10804   for (auto &TyData : ReductionTypes) {
10805     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10806     bool Invalid = false;
10807     if (I != PreviousRedeclTypes.end()) {
10808       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10809           << TyData.first;
10810       Diag(I->second, diag::note_previous_definition);
10811       Invalid = true;
10812     }
10813     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10814     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10815                                                 Name, TyData.first, PrevDRD);
10816     DC->addDecl(DRD);
10817     DRD->setAccess(AS);
10818     Decls.push_back(DRD);
10819     if (Invalid)
10820       DRD->setInvalidDecl();
10821     else
10822       PrevDRD = DRD;
10823   }
10824 
10825   return DeclGroupPtrTy::make(
10826       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10827 }
10828 
10829 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10830   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10831 
10832   // Enter new function scope.
10833   PushFunctionScope();
10834   getCurFunction()->setHasBranchProtectedScope();
10835   getCurFunction()->setHasOMPDeclareReductionCombiner();
10836 
10837   if (S != nullptr)
10838     PushDeclContext(S, DRD);
10839   else
10840     CurContext = DRD;
10841 
10842   PushExpressionEvaluationContext(PotentiallyEvaluated);
10843 
10844   QualType ReductionType = DRD->getType();
10845   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10846   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10847   // uses semantics of argument handles by value, but it should be passed by
10848   // reference. C lang does not support references, so pass all parameters as
10849   // pointers.
10850   // Create 'T omp_in;' variable.
10851   auto *OmpInParm =
10852       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10853   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10854   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10855   // uses semantics of argument handles by value, but it should be passed by
10856   // reference. C lang does not support references, so pass all parameters as
10857   // pointers.
10858   // Create 'T omp_out;' variable.
10859   auto *OmpOutParm =
10860       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10861   if (S != nullptr) {
10862     PushOnScopeChains(OmpInParm, S);
10863     PushOnScopeChains(OmpOutParm, S);
10864   } else {
10865     DRD->addDecl(OmpInParm);
10866     DRD->addDecl(OmpOutParm);
10867   }
10868 }
10869 
10870 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10871   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10872   DiscardCleanupsInEvaluationContext();
10873   PopExpressionEvaluationContext();
10874 
10875   PopDeclContext();
10876   PopFunctionScopeInfo();
10877 
10878   if (Combiner != nullptr)
10879     DRD->setCombiner(Combiner);
10880   else
10881     DRD->setInvalidDecl();
10882 }
10883 
10884 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10885   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10886 
10887   // Enter new function scope.
10888   PushFunctionScope();
10889   getCurFunction()->setHasBranchProtectedScope();
10890 
10891   if (S != nullptr)
10892     PushDeclContext(S, DRD);
10893   else
10894     CurContext = DRD;
10895 
10896   PushExpressionEvaluationContext(PotentiallyEvaluated);
10897 
10898   QualType ReductionType = DRD->getType();
10899   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10900   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10901   // uses semantics of argument handles by value, but it should be passed by
10902   // reference. C lang does not support references, so pass all parameters as
10903   // pointers.
10904   // Create 'T omp_priv;' variable.
10905   auto *OmpPrivParm =
10906       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10907   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10908   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10909   // uses semantics of argument handles by value, but it should be passed by
10910   // reference. C lang does not support references, so pass all parameters as
10911   // pointers.
10912   // Create 'T omp_orig;' variable.
10913   auto *OmpOrigParm =
10914       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10915   if (S != nullptr) {
10916     PushOnScopeChains(OmpPrivParm, S);
10917     PushOnScopeChains(OmpOrigParm, S);
10918   } else {
10919     DRD->addDecl(OmpPrivParm);
10920     DRD->addDecl(OmpOrigParm);
10921   }
10922 }
10923 
10924 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10925                                                      Expr *Initializer) {
10926   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10927   DiscardCleanupsInEvaluationContext();
10928   PopExpressionEvaluationContext();
10929 
10930   PopDeclContext();
10931   PopFunctionScopeInfo();
10932 
10933   if (Initializer != nullptr)
10934     DRD->setInitializer(Initializer);
10935   else
10936     DRD->setInvalidDecl();
10937 }
10938 
10939 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10940     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10941   for (auto *D : DeclReductions.get()) {
10942     if (IsValid) {
10943       auto *DRD = cast<OMPDeclareReductionDecl>(D);
10944       if (S != nullptr)
10945         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10946     } else
10947       D->setInvalidDecl();
10948   }
10949   return DeclReductions;
10950 }
10951 
10952 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10953                                            SourceLocation StartLoc,
10954                                            SourceLocation LParenLoc,
10955                                            SourceLocation EndLoc) {
10956   Expr *ValExpr = NumTeams;
10957 
10958   // OpenMP [teams Constrcut, Restrictions]
10959   // The num_teams expression must evaluate to a positive integer value.
10960   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10961                                  /*StrictlyPositive=*/true))
10962     return nullptr;
10963 
10964   return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10965 }
10966 
10967 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10968                                               SourceLocation StartLoc,
10969                                               SourceLocation LParenLoc,
10970                                               SourceLocation EndLoc) {
10971   Expr *ValExpr = ThreadLimit;
10972 
10973   // OpenMP [teams Constrcut, Restrictions]
10974   // The thread_limit expression must evaluate to a positive integer value.
10975   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10976                                  /*StrictlyPositive=*/true))
10977     return nullptr;
10978 
10979   return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
10980                                             EndLoc);
10981 }
10982 
10983 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10984                                            SourceLocation StartLoc,
10985                                            SourceLocation LParenLoc,
10986                                            SourceLocation EndLoc) {
10987   Expr *ValExpr = Priority;
10988 
10989   // OpenMP [2.9.1, task Constrcut]
10990   // The priority-value is a non-negative numerical scalar expression.
10991   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10992                                  /*StrictlyPositive=*/false))
10993     return nullptr;
10994 
10995   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10996 }
10997 
10998 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10999                                             SourceLocation StartLoc,
11000                                             SourceLocation LParenLoc,
11001                                             SourceLocation EndLoc) {
11002   Expr *ValExpr = Grainsize;
11003 
11004   // OpenMP [2.9.2, taskloop Constrcut]
11005   // The parameter of the grainsize clause must be a positive integer
11006   // expression.
11007   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11008                                  /*StrictlyPositive=*/true))
11009     return nullptr;
11010 
11011   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11012 }
11013 
11014 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11015                                            SourceLocation StartLoc,
11016                                            SourceLocation LParenLoc,
11017                                            SourceLocation EndLoc) {
11018   Expr *ValExpr = NumTasks;
11019 
11020   // OpenMP [2.9.2, taskloop Constrcut]
11021   // The parameter of the num_tasks clause must be a positive integer
11022   // expression.
11023   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11024                                  /*StrictlyPositive=*/true))
11025     return nullptr;
11026 
11027   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11028 }
11029 
11030 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11031                                        SourceLocation LParenLoc,
11032                                        SourceLocation EndLoc) {
11033   // OpenMP [2.13.2, critical construct, Description]
11034   // ... where hint-expression is an integer constant expression that evaluates
11035   // to a valid lock hint.
11036   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11037   if (HintExpr.isInvalid())
11038     return nullptr;
11039   return new (Context)
11040       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11041 }
11042 
11043 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11044     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11045     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11046     SourceLocation EndLoc) {
11047   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11048     std::string Values;
11049     Values += "'";
11050     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11051     Values += "'";
11052     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11053         << Values << getOpenMPClauseName(OMPC_dist_schedule);
11054     return nullptr;
11055   }
11056   Expr *ValExpr = ChunkSize;
11057   Stmt *HelperValStmt = nullptr;
11058   if (ChunkSize) {
11059     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11060         !ChunkSize->isInstantiationDependent() &&
11061         !ChunkSize->containsUnexpandedParameterPack()) {
11062       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11063       ExprResult Val =
11064           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11065       if (Val.isInvalid())
11066         return nullptr;
11067 
11068       ValExpr = Val.get();
11069 
11070       // OpenMP [2.7.1, Restrictions]
11071       //  chunk_size must be a loop invariant integer expression with a positive
11072       //  value.
11073       llvm::APSInt Result;
11074       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11075         if (Result.isSigned() && !Result.isStrictlyPositive()) {
11076           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11077               << "dist_schedule" << ChunkSize->getSourceRange();
11078           return nullptr;
11079         }
11080       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11081                  !CurContext->isDependentContext()) {
11082         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11083         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11084         HelperValStmt = buildPreInits(Context, Captures);
11085       }
11086     }
11087   }
11088 
11089   return new (Context)
11090       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
11091                             Kind, ValExpr, HelperValStmt);
11092 }
11093 
11094 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11095     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11096     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11097     SourceLocation KindLoc, SourceLocation EndLoc) {
11098   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
11099   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
11100       Kind != OMPC_DEFAULTMAP_scalar) {
11101     std::string Value;
11102     SourceLocation Loc;
11103     Value += "'";
11104     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11105       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11106                  OMPC_DEFAULTMAP_MODIFIER_tofrom);
11107       Loc = MLoc;
11108     } else {
11109       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
11110                  OMPC_DEFAULTMAP_scalar);
11111       Loc = KindLoc;
11112     }
11113     Value += "'";
11114     Diag(Loc, diag::err_omp_unexpected_clause_value)
11115         << Value << getOpenMPClauseName(OMPC_defaultmap);
11116     return nullptr;
11117   }
11118 
11119   return new (Context)
11120       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11121 }
11122 
11123 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11124   DeclContext *CurLexicalContext = getCurLexicalContext();
11125   if (!CurLexicalContext->isFileContext() &&
11126       !CurLexicalContext->isExternCContext() &&
11127       !CurLexicalContext->isExternCXXContext()) {
11128     Diag(Loc, diag::err_omp_region_not_file_context);
11129     return false;
11130   }
11131   if (IsInOpenMPDeclareTargetContext) {
11132     Diag(Loc, diag::err_omp_enclosed_declare_target);
11133     return false;
11134   }
11135 
11136   IsInOpenMPDeclareTargetContext = true;
11137   return true;
11138 }
11139 
11140 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11141   assert(IsInOpenMPDeclareTargetContext &&
11142          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11143 
11144   IsInOpenMPDeclareTargetContext = false;
11145 }
11146 
11147 void
11148 Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
11149                                    const DeclarationNameInfo &Id,
11150                                    OMPDeclareTargetDeclAttr::MapTypeTy MT,
11151                                    NamedDeclSetType &SameDirectiveDecls) {
11152   LookupResult Lookup(*this, Id, LookupOrdinaryName);
11153   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11154 
11155   if (Lookup.isAmbiguous())
11156     return;
11157   Lookup.suppressDiagnostics();
11158 
11159   if (!Lookup.isSingleResult()) {
11160     if (TypoCorrection Corrected =
11161             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11162                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11163                         CTK_ErrorRecovery)) {
11164       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11165                                   << Id.getName());
11166       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11167       return;
11168     }
11169 
11170     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11171     return;
11172   }
11173 
11174   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11175   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11176     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11177       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11178 
11179     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11180       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11181       ND->addAttr(A);
11182       if (ASTMutationListener *ML = Context.getASTMutationListener())
11183         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11184       checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11185     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11186       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11187           << Id.getName();
11188     }
11189   } else
11190     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11191 }
11192 
11193 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11194                                      Sema &SemaRef, Decl *D) {
11195   if (!D)
11196     return;
11197   Decl *LD = nullptr;
11198   if (isa<TagDecl>(D)) {
11199     LD = cast<TagDecl>(D)->getDefinition();
11200   } else if (isa<VarDecl>(D)) {
11201     LD = cast<VarDecl>(D)->getDefinition();
11202 
11203     // If this is an implicit variable that is legal and we do not need to do
11204     // anything.
11205     if (cast<VarDecl>(D)->isImplicit()) {
11206       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11207           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11208       D->addAttr(A);
11209       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11210         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11211       return;
11212     }
11213 
11214   } else if (isa<FunctionDecl>(D)) {
11215     const FunctionDecl *FD = nullptr;
11216     if (cast<FunctionDecl>(D)->hasBody(FD))
11217       LD = const_cast<FunctionDecl *>(FD);
11218 
11219     // If the definition is associated with the current declaration in the
11220     // target region (it can be e.g. a lambda) that is legal and we do not need
11221     // to do anything else.
11222     if (LD == D) {
11223       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11224           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11225       D->addAttr(A);
11226       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11227         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11228       return;
11229     }
11230   }
11231   if (!LD)
11232     LD = D;
11233   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11234       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11235     // Outlined declaration is not declared target.
11236     if (LD->isOutOfLine()) {
11237       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11238       SemaRef.Diag(SL, diag::note_used_here) << SR;
11239     } else {
11240       DeclContext *DC = LD->getDeclContext();
11241       while (DC) {
11242         if (isa<FunctionDecl>(DC) &&
11243             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11244           break;
11245         DC = DC->getParent();
11246       }
11247       if (DC)
11248         return;
11249 
11250       // Is not declared in target context.
11251       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11252       SemaRef.Diag(SL, diag::note_used_here) << SR;
11253     }
11254     // Mark decl as declared target to prevent further diagnostic.
11255     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11256         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11257     D->addAttr(A);
11258     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
11259       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11260   }
11261 }
11262 
11263 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11264                                    Sema &SemaRef, DSAStackTy *Stack,
11265                                    ValueDecl *VD) {
11266   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11267     return true;
11268   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11269     return false;
11270   return true;
11271 }
11272 
11273 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11274   if (!D || D->isInvalidDecl())
11275     return;
11276   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11277   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11278   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11279   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11280     if (DSAStack->isThreadPrivate(VD)) {
11281       Diag(SL, diag::err_omp_threadprivate_in_target);
11282       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11283       return;
11284     }
11285   }
11286   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11287     // Problem if any with var declared with incomplete type will be reported
11288     // as normal, so no need to check it here.
11289     if ((E || !VD->getType()->isIncompleteType()) &&
11290         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11291       // Mark decl as declared target to prevent further diagnostic.
11292       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
11293         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11294             Context, OMPDeclareTargetDeclAttr::MT_To);
11295         VD->addAttr(A);
11296         if (ASTMutationListener *ML = Context.getASTMutationListener())
11297           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
11298       }
11299       return;
11300     }
11301   }
11302   if (!E) {
11303     // Checking declaration inside declare target region.
11304     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11305         (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
11306       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11307           Context, OMPDeclareTargetDeclAttr::MT_To);
11308       D->addAttr(A);
11309       if (ASTMutationListener *ML = Context.getASTMutationListener())
11310         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
11311     }
11312     return;
11313   }
11314   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11315 }
11316 
11317 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11318                                      SourceLocation StartLoc,
11319                                      SourceLocation LParenLoc,
11320                                      SourceLocation EndLoc) {
11321   MappableVarListInfo MVLI(VarList);
11322   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11323   if (MVLI.ProcessedVarList.empty())
11324     return nullptr;
11325 
11326   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11327                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11328                              MVLI.VarComponents);
11329 }
11330 
11331 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11332                                        SourceLocation StartLoc,
11333                                        SourceLocation LParenLoc,
11334                                        SourceLocation EndLoc) {
11335   MappableVarListInfo MVLI(VarList);
11336   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11337   if (MVLI.ProcessedVarList.empty())
11338     return nullptr;
11339 
11340   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11341                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11342                                MVLI.VarComponents);
11343 }
11344