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   /// Struct that associates a component with the clause kind where they are
76   /// found.
77   struct MappedExprComponentTy {
78     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79     OpenMPClauseKind Kind = OMPC_unknown;
80   };
81   typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
82       MappedExprComponentsTy;
83   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84       CriticalsWithHintsTy;
85   typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86       DoacrossDependMapTy;
87 
88   struct SharingMapTy final {
89     DeclSAMapTy SharingMap;
90     AlignedMapTy AlignedMap;
91     MappedExprComponentsTy MappedExprComponents;
92     LoopControlVariablesMapTy LCVMap;
93     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
94     SourceLocation DefaultAttrLoc;
95     OpenMPDirectiveKind Directive = OMPD_unknown;
96     DeclarationNameInfo DirectiveName;
97     Scope *CurScope = nullptr;
98     SourceLocation ConstructLoc;
99     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100     /// get the data (loop counters etc.) about enclosing loop-based construct.
101     /// This data is required during codegen.
102     DoacrossDependMapTy DoacrossDepends;
103     /// \brief first argument (Expr *) contains optional argument of the
104     /// 'ordered' clause, the second one is true if the regions has 'ordered'
105     /// clause, false otherwise.
106     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
107     bool NowaitRegion = false;
108     bool CancelRegion = false;
109     unsigned AssociatedLoops = 1;
110     SourceLocation InnerTeamsRegionLoc;
111     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
112                  Scope *CurScope, SourceLocation Loc)
113         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114           ConstructLoc(Loc) {}
115     SharingMapTy() {}
116   };
117 
118   typedef SmallVector<SharingMapTy, 4> StackTy;
119 
120   /// \brief Stack of used declaration and their data-sharing attributes.
121   StackTy Stack;
122   /// \brief true, if check for DSA must be from parent directive, false, if
123   /// from current directive.
124   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
125   Sema &SemaRef;
126   bool ForceCapturing = false;
127   CriticalsWithHintsTy Criticals;
128 
129   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130 
131   DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
132 
133   /// \brief Checks if the variable is a local for OpenMP region.
134   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
135 
136 public:
137   explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
138 
139   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
141 
142   bool isForceVarCapturing() const { return ForceCapturing; }
143   void setForceVarCapturing(bool V) { ForceCapturing = V; }
144 
145   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
146             Scope *CurScope, SourceLocation Loc) {
147     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148     Stack.back().DefaultAttrLoc = Loc;
149   }
150 
151   void pop() {
152     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153     Stack.pop_back();
154   }
155 
156   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158   }
159   const std::pair<OMPCriticalDirective *, llvm::APSInt>
160   getCriticalWithHint(const DeclarationNameInfo &Name) const {
161     auto I = Criticals.find(Name.getAsString());
162     if (I != Criticals.end())
163       return I->second;
164     return std::make_pair(nullptr, llvm::APSInt());
165   }
166   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
167   /// add it and return NULL; otherwise return previous occurrence's expression
168   /// for diagnostics.
169   Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
170 
171   /// \brief Register specified variable as loop control variable.
172   void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
173   /// \brief Check if the specified variable is a loop control variable for
174   /// current region.
175   /// \return The index of the loop control variable in the list of associated
176   /// for-loops (from outer to inner).
177   LCDeclInfo isLoopControlVariable(ValueDecl *D);
178   /// \brief Check if the specified variable is a loop control variable for
179   /// parent region.
180   /// \return The index of the loop control variable in the list of associated
181   /// for-loops (from outer to inner).
182   LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
183   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184   /// parent directive.
185   ValueDecl *getParentLoopControlVariable(unsigned I);
186 
187   /// \brief Adds explicit data sharing attribute to the specified declaration.
188   void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189               DeclRefExpr *PrivateCopy = nullptr);
190 
191   /// \brief Returns data sharing attributes from top of the stack for the
192   /// specified declaration.
193   DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
194   /// \brief Returns data-sharing attributes for the specified declaration.
195   DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
196   /// \brief Checks if the specified variables has data-sharing attributes which
197   /// match specified \a CPred predicate in any directive which matches \a DPred
198   /// predicate.
199   DSAVarData hasDSA(ValueDecl *D,
200                     const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201                     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202                     bool FromParent);
203   /// \brief Checks if the specified variables has data-sharing attributes which
204   /// match specified \a CPred predicate in any innermost directive which
205   /// matches \a DPred predicate.
206   DSAVarData
207   hasInnermostDSA(ValueDecl *D,
208                   const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209                   const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210                   bool FromParent);
211   /// \brief Checks if the specified variables has explicit data-sharing
212   /// attributes which match specified \a CPred predicate at the specified
213   /// OpenMP region.
214   bool hasExplicitDSA(ValueDecl *D,
215                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
216                       unsigned Level, bool NotLastprivate = false);
217 
218   /// \brief Returns true if the directive at level \Level matches in the
219   /// specified \a DPred predicate.
220   bool hasExplicitDirective(
221       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222       unsigned Level);
223 
224   /// \brief Finds a directive which matches specified \a DPred predicate.
225   bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226                                                   const DeclarationNameInfo &,
227                                                   SourceLocation)> &DPred,
228                     bool FromParent);
229 
230   /// \brief Returns currently analyzed directive.
231   OpenMPDirectiveKind getCurrentDirective() const {
232     return Stack.back().Directive;
233   }
234   /// \brief Returns parent directive.
235   OpenMPDirectiveKind getParentDirective() const {
236     if (Stack.size() > 2)
237       return Stack[Stack.size() - 2].Directive;
238     return OMPD_unknown;
239   }
240 
241   /// \brief Set default data sharing attribute to none.
242   void setDefaultDSANone(SourceLocation Loc) {
243     Stack.back().DefaultAttr = DSA_none;
244     Stack.back().DefaultAttrLoc = Loc;
245   }
246   /// \brief Set default data sharing attribute to shared.
247   void setDefaultDSAShared(SourceLocation Loc) {
248     Stack.back().DefaultAttr = DSA_shared;
249     Stack.back().DefaultAttrLoc = Loc;
250   }
251 
252   DefaultDataSharingAttributes getDefaultDSA() const {
253     return Stack.back().DefaultAttr;
254   }
255   SourceLocation getDefaultDSALocation() const {
256     return Stack.back().DefaultAttrLoc;
257   }
258 
259   /// \brief Checks if the specified variable is a threadprivate.
260   bool isThreadPrivate(VarDecl *D) {
261     DSAVarData DVar = getTopDSA(D, false);
262     return isOpenMPThreadPrivate(DVar.CKind);
263   }
264 
265   /// \brief Marks current region as ordered (it has an 'ordered' clause).
266   void setOrderedRegion(bool IsOrdered, Expr *Param) {
267     Stack.back().OrderedRegion.setInt(IsOrdered);
268     Stack.back().OrderedRegion.setPointer(Param);
269   }
270   /// \brief Returns true, if parent region is ordered (has associated
271   /// 'ordered' clause), false - otherwise.
272   bool isParentOrderedRegion() const {
273     if (Stack.size() > 2)
274       return Stack[Stack.size() - 2].OrderedRegion.getInt();
275     return false;
276   }
277   /// \brief Returns optional parameter for the ordered region.
278   Expr *getParentOrderedRegionParam() const {
279     if (Stack.size() > 2)
280       return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281     return nullptr;
282   }
283   /// \brief Marks current region as nowait (it has a 'nowait' clause).
284   void setNowaitRegion(bool IsNowait = true) {
285     Stack.back().NowaitRegion = IsNowait;
286   }
287   /// \brief Returns true, if parent region is nowait (has associated
288   /// 'nowait' clause), false - otherwise.
289   bool isParentNowaitRegion() const {
290     if (Stack.size() > 2)
291       return Stack[Stack.size() - 2].NowaitRegion;
292     return false;
293   }
294   /// \brief Marks parent region as cancel region.
295   void setParentCancelRegion(bool Cancel = true) {
296     if (Stack.size() > 2)
297       Stack[Stack.size() - 2].CancelRegion =
298           Stack[Stack.size() - 2].CancelRegion || Cancel;
299   }
300   /// \brief Return true if current region has inner cancel construct.
301   bool isCancelRegion() const { return Stack.back().CancelRegion; }
302 
303   /// \brief Set collapse value for the region.
304   void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
305   /// \brief Return collapse value for region.
306   unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
307 
308   /// \brief Marks current target region as one with closely nested teams
309   /// region.
310   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311     if (Stack.size() > 2)
312       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313   }
314   /// \brief Returns true, if current region has closely nested teams region.
315   bool hasInnerTeamsRegion() const {
316     return getInnerTeamsRegionLoc().isValid();
317   }
318   /// \brief Returns location of the nested teams region (if any).
319   SourceLocation getInnerTeamsRegionLoc() const {
320     if (Stack.size() > 1)
321       return Stack.back().InnerTeamsRegionLoc;
322     return SourceLocation();
323   }
324 
325   Scope *getCurScope() const { return Stack.back().CurScope; }
326   Scope *getCurScope() { return Stack.back().CurScope; }
327   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
328 
329   // Do the check specified in \a Check to all component lists and return true
330   // if any issue is found.
331   bool checkMappableExprComponentListsForDecl(
332       ValueDecl *VD, bool CurrentRegionOnly,
333       const llvm::function_ref<
334           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335                OpenMPClauseKind)> &Check) {
336     auto SI = Stack.rbegin();
337     auto SE = Stack.rend();
338 
339     if (SI == SE)
340       return false;
341 
342     if (CurrentRegionOnly) {
343       SE = std::next(SI);
344     } else {
345       ++SI;
346     }
347 
348     for (; SI != SE; ++SI) {
349       auto MI = SI->MappedExprComponents.find(VD);
350       if (MI != SI->MappedExprComponents.end())
351         for (auto &L : MI->second.Components)
352           if (Check(L, MI->second.Kind))
353             return true;
354     }
355     return false;
356   }
357 
358   // Create a new mappable expression component list associated with a given
359   // declaration and initialize it with the provided list of components.
360   void addMappableExpressionComponents(
361       ValueDecl *VD,
362       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363       OpenMPClauseKind WhereFoundClauseKind) {
364     assert(Stack.size() > 1 &&
365            "Not expecting to retrieve components from a empty stack!");
366     auto &MEC = Stack.back().MappedExprComponents[VD];
367     // Create new entry and append the new components there.
368     MEC.Components.resize(MEC.Components.size() + 1);
369     MEC.Components.back().append(Components.begin(), Components.end());
370     MEC.Kind = WhereFoundClauseKind;
371   }
372 
373   unsigned getNestingLevel() const {
374     assert(Stack.size() > 1);
375     return Stack.size() - 2;
376   }
377   void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378     assert(Stack.size() > 2);
379     assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380     Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381   }
382   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383   getDoacrossDependClauses() const {
384     assert(Stack.size() > 1);
385     if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386       auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387       return llvm::make_range(Ref.begin(), Ref.end());
388     }
389     return llvm::make_range(Stack[0].DoacrossDepends.end(),
390                             Stack[0].DoacrossDepends.end());
391   }
392 };
393 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
394   return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
396 }
397 } // namespace
398 
399 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400   auto *VD = dyn_cast<VarDecl>(D);
401   auto *FD = dyn_cast<FieldDecl>(D);
402   if (VD != nullptr) {
403     VD = VD->getCanonicalDecl();
404     D = VD;
405   } else {
406     assert(FD);
407     FD = FD->getCanonicalDecl();
408     D = FD;
409   }
410   return D;
411 }
412 
413 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
414                                           ValueDecl *D) {
415   D = getCanonicalDecl(D);
416   auto *VD = dyn_cast<VarDecl>(D);
417   auto *FD = dyn_cast<FieldDecl>(D);
418   DSAVarData DVar;
419   if (Iter == std::prev(Stack.rend())) {
420     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421     // in a region but not in construct]
422     //  File-scope or namespace-scope variables referenced in called routines
423     //  in the region are shared unless they appear in a threadprivate
424     //  directive.
425     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
426       DVar.CKind = OMPC_shared;
427 
428     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429     // in a region but not in construct]
430     //  Variables with static storage duration that are declared in called
431     //  routines in the region are shared.
432     if (VD && VD->hasGlobalStorage())
433       DVar.CKind = OMPC_shared;
434 
435     // Non-static data members are shared by default.
436     if (FD)
437       DVar.CKind = OMPC_shared;
438 
439     return DVar;
440   }
441 
442   DVar.DKind = Iter->Directive;
443   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444   // in a Construct, C/C++, predetermined, p.1]
445   // Variables with automatic storage duration that are declared in a scope
446   // inside the construct are private.
447   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
449     DVar.CKind = OMPC_private;
450     return DVar;
451   }
452 
453   // Explicitly specified attributes and local variables with predetermined
454   // attributes.
455   if (Iter->SharingMap.count(D)) {
456     DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
457     DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
458     DVar.CKind = Iter->SharingMap[D].Attributes;
459     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
460     return DVar;
461   }
462 
463   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464   // in a Construct, C/C++, implicitly determined, p.1]
465   //  In a parallel or task construct, the data-sharing attributes of these
466   //  variables are determined by the default clause, if present.
467   switch (Iter->DefaultAttr) {
468   case DSA_shared:
469     DVar.CKind = OMPC_shared;
470     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
471     return DVar;
472   case DSA_none:
473     return DVar;
474   case DSA_unspecified:
475     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476     // in a Construct, implicitly determined, p.2]
477     //  In a parallel construct, if no default clause is present, these
478     //  variables are shared.
479     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
480     if (isOpenMPParallelDirective(DVar.DKind) ||
481         isOpenMPTeamsDirective(DVar.DKind)) {
482       DVar.CKind = OMPC_shared;
483       return DVar;
484     }
485 
486     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487     // in a Construct, implicitly determined, p.4]
488     //  In a task construct, if no default clause is present, a variable that in
489     //  the enclosing context is determined to be shared by all implicit tasks
490     //  bound to the current team is shared.
491     if (isOpenMPTaskingDirective(DVar.DKind)) {
492       DSAVarData DVarTemp;
493       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
494            I != EE; ++I) {
495         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
496         // Referenced in a Construct, implicitly determined, p.6]
497         //  In a task construct, if no default clause is present, a variable
498         //  whose data-sharing attribute is not determined by the rules above is
499         //  firstprivate.
500         DVarTemp = getDSA(I, D);
501         if (DVarTemp.CKind != OMPC_shared) {
502           DVar.RefExpr = nullptr;
503           DVar.CKind = OMPC_firstprivate;
504           return DVar;
505         }
506         if (isParallelOrTaskRegion(I->Directive))
507           break;
508       }
509       DVar.CKind =
510           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
511       return DVar;
512     }
513   }
514   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515   // in a Construct, implicitly determined, p.3]
516   //  For constructs other than task, if no default clause is present, these
517   //  variables inherit their data-sharing attributes from the enclosing
518   //  context.
519   return getDSA(++Iter, D);
520 }
521 
522 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
523   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
524   D = getCanonicalDecl(D);
525   auto It = Stack.back().AlignedMap.find(D);
526   if (It == Stack.back().AlignedMap.end()) {
527     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528     Stack.back().AlignedMap[D] = NewDE;
529     return nullptr;
530   } else {
531     assert(It->second && "Unexpected nullptr expr in the aligned map");
532     return It->second;
533   }
534   return nullptr;
535 }
536 
537 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
538   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
539   D = getCanonicalDecl(D);
540   Stack.back().LCVMap.insert(
541       std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
542 }
543 
544 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
545   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
546   D = getCanonicalDecl(D);
547   return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548                                           : LCDeclInfo(0, nullptr);
549 }
550 
551 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
552   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
553   D = getCanonicalDecl(D);
554   return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555              ? Stack[Stack.size() - 2].LCVMap[D]
556              : LCDeclInfo(0, nullptr);
557 }
558 
559 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
560   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561   if (Stack[Stack.size() - 2].LCVMap.size() < I)
562     return nullptr;
563   for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
564     if (Pair.second.first == I)
565       return Pair.first;
566   }
567   return nullptr;
568 }
569 
570 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571                         DeclRefExpr *PrivateCopy) {
572   D = getCanonicalDecl(D);
573   if (A == OMPC_threadprivate) {
574     auto &Data = Stack[0].SharingMap[D];
575     Data.Attributes = A;
576     Data.RefExpr.setPointer(E);
577     Data.PrivateCopy = nullptr;
578   } else {
579     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
580     auto &Data = Stack.back().SharingMap[D];
581     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584            (isLoopControlVariable(D).first && A == OMPC_private));
585     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586       Data.RefExpr.setInt(/*IntVal=*/true);
587       return;
588     }
589     const bool IsLastprivate =
590         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591     Data.Attributes = A;
592     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593     Data.PrivateCopy = PrivateCopy;
594     if (PrivateCopy) {
595       auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596       Data.Attributes = A;
597       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598       Data.PrivateCopy = nullptr;
599     }
600   }
601 }
602 
603 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
604   D = D->getCanonicalDecl();
605   if (Stack.size() > 2) {
606     reverse_iterator I = Iter, E = std::prev(Stack.rend());
607     Scope *TopScope = nullptr;
608     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
609       ++I;
610     }
611     if (I == E)
612       return false;
613     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
614     Scope *CurScope = getCurScope();
615     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
616       CurScope = CurScope->getParent();
617     }
618     return CurScope != TopScope;
619   }
620   return false;
621 }
622 
623 /// \brief Build a variable declaration for OpenMP loop iteration variable.
624 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
625                              StringRef Name, const AttrVec *Attrs = nullptr) {
626   DeclContext *DC = SemaRef.CurContext;
627   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629   VarDecl *Decl =
630       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
631   if (Attrs) {
632     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633          I != E; ++I)
634       Decl->addAttr(*I);
635   }
636   Decl->setImplicit();
637   return Decl;
638 }
639 
640 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641                                      SourceLocation Loc,
642                                      bool RefersToCapture = false) {
643   D->setReferenced();
644   D->markUsed(S.Context);
645   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646                              SourceLocation(), D, RefersToCapture, Loc, Ty,
647                              VK_LValue);
648 }
649 
650 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651   D = getCanonicalDecl(D);
652   DSAVarData DVar;
653 
654   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655   // in a Construct, C/C++, predetermined, p.1]
656   //  Variables appearing in threadprivate directives are threadprivate.
657   auto *VD = dyn_cast<VarDecl>(D);
658   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
660          SemaRef.getLangOpts().OpenMPUseTLS &&
661          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
662       (VD && VD->getStorageClass() == SC_Register &&
663        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664     addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
665                                D->getLocation()),
666            OMPC_threadprivate);
667   }
668   if (Stack[0].SharingMap.count(D)) {
669     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
670     DVar.CKind = OMPC_threadprivate;
671     return DVar;
672   }
673 
674   if (Stack.size() == 1) {
675     // Not in OpenMP execution region and top scope was already checked.
676     return DVar;
677   }
678 
679   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680   // in a Construct, C/C++, predetermined, p.4]
681   //  Static data members are shared.
682   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683   // in a Construct, C/C++, predetermined, p.7]
684   //  Variables with static storage duration that are declared in a scope
685   //  inside the construct are shared.
686   auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
687   if (VD && VD->isStaticDataMember()) {
688     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
689     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
690       return DVar;
691 
692     DVar.CKind = OMPC_shared;
693     return DVar;
694   }
695 
696   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
697   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698   Type = SemaRef.getASTContext().getBaseElementType(Type);
699   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700   // in a Construct, C/C++, predetermined, p.6]
701   //  Variables with const qualified type having no mutable member are
702   //  shared.
703   CXXRecordDecl *RD =
704       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
705   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706     if (auto *CTD = CTSD->getSpecializedTemplate())
707       RD = CTD->getTemplatedDecl();
708   if (IsConstant &&
709       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710         RD->hasMutableFields())) {
711     // Variables with const-qualified type having no mutable member may be
712     // listed in a firstprivate clause, even if they are static data members.
713     DSAVarData DVarTemp = hasDSA(
714         D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715         MatchesAlways, FromParent);
716     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717       return DVar;
718 
719     DVar.CKind = OMPC_shared;
720     return DVar;
721   }
722 
723   // Explicitly specified attributes and local variables with predetermined
724   // attributes.
725   auto StartI = std::next(Stack.rbegin());
726   auto EndI = std::prev(Stack.rend());
727   if (FromParent && StartI != EndI) {
728     StartI = std::next(StartI);
729   }
730   auto I = std::prev(StartI);
731   if (I->SharingMap.count(D)) {
732     DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
733     DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
734     DVar.CKind = I->SharingMap[D].Attributes;
735     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
736   }
737 
738   return DVar;
739 }
740 
741 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742                                                   bool FromParent) {
743   D = getCanonicalDecl(D);
744   auto StartI = Stack.rbegin();
745   auto EndI = std::prev(Stack.rend());
746   if (FromParent && StartI != EndI) {
747     StartI = std::next(StartI);
748   }
749   return getDSA(StartI, D);
750 }
751 
752 DSAStackTy::DSAVarData
753 DSAStackTy::hasDSA(ValueDecl *D,
754                    const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755                    const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756                    bool FromParent) {
757   D = getCanonicalDecl(D);
758   auto StartI = std::next(Stack.rbegin());
759   auto EndI = Stack.rend();
760   if (FromParent && StartI != EndI) {
761     StartI = std::next(StartI);
762   }
763   for (auto I = StartI, EE = EndI; I != EE; ++I) {
764     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
765       continue;
766     DSAVarData DVar = getDSA(I, D);
767     if (CPred(DVar.CKind))
768       return DVar;
769   }
770   return DSAVarData();
771 }
772 
773 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776     bool FromParent) {
777   D = getCanonicalDecl(D);
778   auto StartI = std::next(Stack.rbegin());
779   auto EndI = Stack.rend();
780   if (FromParent && StartI != EndI)
781     StartI = std::next(StartI);
782   if (StartI == EndI || !DPred(StartI->Directive))
783     return DSAVarData();
784   DSAVarData DVar = getDSA(StartI, D);
785   return CPred(DVar.CKind) ? DVar : 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     if (Ty->isReferenceType())
907       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
908 
909     // Locate map clauses and see if the variable being captured is referred to
910     // in any of those clauses. Here we only care about variables, not fields,
911     // because fields are part of aggregates.
912     bool IsVariableUsedInMapClause = false;
913     bool IsVariableAssociatedWithSection = false;
914 
915     DSAStack->checkMappableExprComponentListsForDecl(
916         D, /*CurrentRegionOnly=*/true,
917         [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
918                 MapExprComponents,
919             OpenMPClauseKind WhereFoundClauseKind) {
920           // Only the map clause information influences how a variable is
921           // captured. E.g. is_device_ptr does not require changing the default
922           // behaviour.
923           if (WhereFoundClauseKind != OMPC_map)
924             return false;
925 
926           auto EI = MapExprComponents.rbegin();
927           auto EE = MapExprComponents.rend();
928 
929           assert(EI != EE && "Invalid map expression!");
930 
931           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933 
934           ++EI;
935           if (EI == EE)
936             return false;
937 
938           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940               isa<MemberExpr>(EI->getAssociatedExpression())) {
941             IsVariableAssociatedWithSection = true;
942             // There is nothing more we need to know about this variable.
943             return true;
944           }
945 
946           // Keep looking for more map info.
947           return false;
948         });
949 
950     if (IsVariableUsedInMapClause) {
951       // If variable is identified in a map clause it is always captured by
952       // reference except if it is a pointer that is dereferenced somehow.
953       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954     } else {
955       // By default, all the data that has a scalar type is mapped by copy.
956       IsByRef = !Ty->isScalarType();
957     }
958   }
959 
960   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961     IsByRef = !DSAStack->hasExplicitDSA(
962         D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963         Level, /*NotLastprivate=*/true);
964   }
965 
966   // When passing data by copy, we need to make sure it fits the uintptr size
967   // and alignment, because the runtime library only deals with uintptr types.
968   // If it does not fit the uintptr size, we need to pass the data by reference
969   // instead.
970   if (!IsByRef &&
971       (Ctx.getTypeSizeInChars(Ty) >
972            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
973        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
974     IsByRef = true;
975   }
976 
977   return IsByRef;
978 }
979 
980 unsigned Sema::getOpenMPNestingLevel() const {
981   assert(getLangOpts().OpenMP);
982   return DSAStack->getNestingLevel();
983 }
984 
985 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
986   assert(LangOpts.OpenMP && "OpenMP is not allowed");
987   D = getCanonicalDecl(D);
988 
989   // If we are attempting to capture a global variable in a directive with
990   // 'target' we return true so that this global is also mapped to the device.
991   //
992   // FIXME: If the declaration is enclosed in a 'declare target' directive,
993   // then it should not be captured. Therefore, an extra check has to be
994   // inserted here once support for 'declare target' is added.
995   //
996   auto *VD = dyn_cast<VarDecl>(D);
997   if (VD && !VD->hasLocalStorage()) {
998     if (DSAStack->getCurrentDirective() == OMPD_target &&
999         !DSAStack->isClauseParsingMode())
1000       return VD;
1001     if (DSAStack->hasDirective(
1002             [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003                SourceLocation) -> bool {
1004               return isOpenMPTargetExecutionDirective(K);
1005             },
1006             false))
1007       return VD;
1008   }
1009 
1010   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011       (!DSAStack->isClauseParsingMode() ||
1012        DSAStack->getParentDirective() != OMPD_unknown)) {
1013     auto &&Info = DSAStack->isLoopControlVariable(D);
1014     if (Info.first ||
1015         (VD && VD->hasLocalStorage() &&
1016          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
1017         (VD && DSAStack->isForceVarCapturing()))
1018       return VD ? VD : Info.second;
1019     auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1020     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1021       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1022     DVarPrivate = DSAStack->hasDSA(
1023         D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024         DSAStack->isClauseParsingMode());
1025     if (DVarPrivate.CKind != OMPC_unknown)
1026       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1027   }
1028   return nullptr;
1029 }
1030 
1031 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
1032   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033   return DSAStack->hasExplicitDSA(
1034       D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
1035 }
1036 
1037 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
1038   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039   // Return true if the current level is no longer enclosed in a target region.
1040 
1041   auto *VD = dyn_cast<VarDecl>(D);
1042   return VD && !VD->hasLocalStorage() &&
1043          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044                                         Level);
1045 }
1046 
1047 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1048 
1049 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050                                const DeclarationNameInfo &DirName,
1051                                Scope *CurScope, SourceLocation Loc) {
1052   DSAStack->push(DKind, DirName, CurScope, Loc);
1053   PushExpressionEvaluationContext(PotentiallyEvaluated);
1054 }
1055 
1056 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057   DSAStack->setClauseParsingMode(K);
1058 }
1059 
1060 void Sema::EndOpenMPClause() {
1061   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1062 }
1063 
1064 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1065   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066   //  A variable of class type (or array thereof) that appears in a lastprivate
1067   //  clause requires an accessible, unambiguous default constructor for the
1068   //  class type, unless the list item is also specified in a firstprivate
1069   //  clause.
1070   if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1071     for (auto *C : D->clauses()) {
1072       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073         SmallVector<Expr *, 8> PrivateCopies;
1074         for (auto *DE : Clause->varlists()) {
1075           if (DE->isValueDependent() || DE->isTypeDependent()) {
1076             PrivateCopies.push_back(nullptr);
1077             continue;
1078           }
1079           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1080           VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081           QualType Type = VD->getType().getNonReferenceType();
1082           auto DVar = DSAStack->getTopDSA(VD, false);
1083           if (DVar.CKind == OMPC_lastprivate) {
1084             // Generate helper private variable and initialize it with the
1085             // default value. The address of the original variable is replaced
1086             // by the address of the new private variable in CodeGen. This new
1087             // variable is not added to IdResolver, so the code in the OpenMP
1088             // region uses original variable for proper diagnostics.
1089             auto *VDPrivate = buildVarDecl(
1090                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1091                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
1092             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
1093             if (VDPrivate->isInvalidDecl())
1094               continue;
1095             PrivateCopies.push_back(buildDeclRefExpr(
1096                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1097           } else {
1098             // The variable is also a firstprivate, so initialization sequence
1099             // for private copy is generated already.
1100             PrivateCopies.push_back(nullptr);
1101           }
1102         }
1103         // Set initializers to private copies if no errors were found.
1104         if (PrivateCopies.size() == Clause->varlist_size())
1105           Clause->setPrivateCopies(PrivateCopies);
1106       }
1107     }
1108   }
1109 
1110   DSAStack->pop();
1111   DiscardCleanupsInEvaluationContext();
1112   PopExpressionEvaluationContext();
1113 }
1114 
1115 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116                                      Expr *NumIterations, Sema &SemaRef,
1117                                      Scope *S, DSAStackTy *Stack);
1118 
1119 namespace {
1120 
1121 class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122 private:
1123   Sema &SemaRef;
1124 
1125 public:
1126   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1127   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1128     NamedDecl *ND = Candidate.getCorrectionDecl();
1129     if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1130       return VD->hasGlobalStorage() &&
1131              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132                                    SemaRef.getCurScope());
1133     }
1134     return false;
1135   }
1136 };
1137 
1138 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139 private:
1140   Sema &SemaRef;
1141 
1142 public:
1143   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145     NamedDecl *ND = Candidate.getCorrectionDecl();
1146     if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148                                    SemaRef.getCurScope());
1149     }
1150     return false;
1151   }
1152 };
1153 
1154 } // namespace
1155 
1156 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157                                          CXXScopeSpec &ScopeSpec,
1158                                          const DeclarationNameInfo &Id) {
1159   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161 
1162   if (Lookup.isAmbiguous())
1163     return ExprError();
1164 
1165   VarDecl *VD;
1166   if (!Lookup.isSingleResult()) {
1167     if (TypoCorrection Corrected = CorrectTypo(
1168             Id, LookupOrdinaryName, CurScope, nullptr,
1169             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1170       diagnoseTypo(Corrected,
1171                    PDiag(Lookup.empty()
1172                              ? diag::err_undeclared_var_use_suggest
1173                              : diag::err_omp_expected_var_arg_suggest)
1174                        << Id.getName());
1175       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1176     } else {
1177       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178                                        : diag::err_omp_expected_var_arg)
1179           << Id.getName();
1180       return ExprError();
1181     }
1182   } else {
1183     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1184       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1185       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186       return ExprError();
1187     }
1188   }
1189   Lookup.suppressDiagnostics();
1190 
1191   // OpenMP [2.9.2, Syntax, C/C++]
1192   //   Variables must be file-scope, namespace-scope, or static block-scope.
1193   if (!VD->hasGlobalStorage()) {
1194     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1195         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196     bool IsDecl =
1197         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1198     Diag(VD->getLocation(),
1199          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200         << VD;
1201     return ExprError();
1202   }
1203 
1204   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1206   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207   //   A threadprivate directive for file-scope variables must appear outside
1208   //   any definition or declaration.
1209   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210       !getCurLexicalContext()->isTranslationUnit()) {
1211     Diag(Id.getLoc(), diag::err_omp_var_scope)
1212         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213     bool IsDecl =
1214         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215     Diag(VD->getLocation(),
1216          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217         << VD;
1218     return ExprError();
1219   }
1220   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221   //   A threadprivate directive for static class member variables must appear
1222   //   in the class definition, in the same scope in which the member
1223   //   variables are declared.
1224   if (CanonicalVD->isStaticDataMember() &&
1225       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226     Diag(Id.getLoc(), diag::err_omp_var_scope)
1227         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228     bool IsDecl =
1229         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230     Diag(VD->getLocation(),
1231          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232         << VD;
1233     return ExprError();
1234   }
1235   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236   //   A threadprivate directive for namespace-scope variables must appear
1237   //   outside any definition or declaration other than the namespace
1238   //   definition itself.
1239   if (CanonicalVD->getDeclContext()->isNamespace() &&
1240       (!getCurLexicalContext()->isFileContext() ||
1241        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242     Diag(Id.getLoc(), diag::err_omp_var_scope)
1243         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244     bool IsDecl =
1245         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246     Diag(VD->getLocation(),
1247          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248         << VD;
1249     return ExprError();
1250   }
1251   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252   //   A threadprivate directive for static block-scope variables must appear
1253   //   in the scope of the variable and not in a nested scope.
1254   if (CanonicalVD->isStaticLocal() && CurScope &&
1255       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1256     Diag(Id.getLoc(), diag::err_omp_var_scope)
1257         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258     bool IsDecl =
1259         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260     Diag(VD->getLocation(),
1261          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262         << VD;
1263     return ExprError();
1264   }
1265 
1266   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267   //   A threadprivate directive must lexically precede all references to any
1268   //   of the variables in its list.
1269   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1270     Diag(Id.getLoc(), diag::err_omp_var_used)
1271         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1272     return ExprError();
1273   }
1274 
1275   QualType ExprType = VD->getType().getNonReferenceType();
1276   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277                              SourceLocation(), VD,
1278                              /*RefersToEnclosingVariableOrCapture=*/false,
1279                              Id.getLoc(), ExprType, VK_LValue);
1280 }
1281 
1282 Sema::DeclGroupPtrTy
1283 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284                                         ArrayRef<Expr *> VarList) {
1285   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1286     CurContext->addDecl(D);
1287     return DeclGroupPtrTy::make(DeclGroupRef(D));
1288   }
1289   return nullptr;
1290 }
1291 
1292 namespace {
1293 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294   Sema &SemaRef;
1295 
1296 public:
1297   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1298     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1299       if (VD->hasLocalStorage()) {
1300         SemaRef.Diag(E->getLocStart(),
1301                      diag::err_omp_local_var_in_threadprivate_init)
1302             << E->getSourceRange();
1303         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304             << VD << VD->getSourceRange();
1305         return true;
1306       }
1307     }
1308     return false;
1309   }
1310   bool VisitStmt(const Stmt *S) {
1311     for (auto Child : S->children()) {
1312       if (Child && Visit(Child))
1313         return true;
1314     }
1315     return false;
1316   }
1317   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1318 };
1319 } // namespace
1320 
1321 OMPThreadPrivateDecl *
1322 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1323   SmallVector<Expr *, 8> Vars;
1324   for (auto &RefExpr : VarList) {
1325     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1326     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327     SourceLocation ILoc = DE->getExprLoc();
1328 
1329     // Mark variable as used.
1330     VD->setReferenced();
1331     VD->markUsed(Context);
1332 
1333     QualType QType = VD->getType();
1334     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335       // It will be analyzed later.
1336       Vars.push_back(DE);
1337       continue;
1338     }
1339 
1340     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341     //   A threadprivate variable must not have an incomplete type.
1342     if (RequireCompleteType(ILoc, VD->getType(),
1343                             diag::err_omp_threadprivate_incomplete_type)) {
1344       continue;
1345     }
1346 
1347     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348     //   A threadprivate variable must not have a reference type.
1349     if (VD->getType()->isReferenceType()) {
1350       Diag(ILoc, diag::err_omp_ref_type_arg)
1351           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352       bool IsDecl =
1353           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354       Diag(VD->getLocation(),
1355            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356           << VD;
1357       continue;
1358     }
1359 
1360     // Check if this is a TLS variable. If TLS is not being supported, produce
1361     // the corresponding diagnostic.
1362     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364            getLangOpts().OpenMPUseTLS &&
1365            getASTContext().getTargetInfo().isTLSSupported())) ||
1366         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367          !VD->isLocalVarDecl())) {
1368       Diag(ILoc, diag::err_omp_var_thread_local)
1369           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1370       bool IsDecl =
1371           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372       Diag(VD->getLocation(),
1373            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374           << VD;
1375       continue;
1376     }
1377 
1378     // Check if initial value of threadprivate variable reference variable with
1379     // local storage (it is not supported by runtime).
1380     if (auto Init = VD->getAnyInitializer()) {
1381       LocalVarRefChecker Checker(*this);
1382       if (Checker.Visit(Init))
1383         continue;
1384     }
1385 
1386     Vars.push_back(RefExpr);
1387     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1388     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389         Context, SourceRange(Loc, Loc)));
1390     if (auto *ML = Context.getASTMutationListener())
1391       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1392   }
1393   OMPThreadPrivateDecl *D = nullptr;
1394   if (!Vars.empty()) {
1395     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396                                      Vars);
1397     D->setAccess(AS_public);
1398   }
1399   return D;
1400 }
1401 
1402 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1403                               const ValueDecl *D, DSAStackTy::DSAVarData DVar,
1404                               bool IsLoopIterVar = false) {
1405   if (DVar.RefExpr) {
1406     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407         << getOpenMPClauseName(DVar.CKind);
1408     return;
1409   }
1410   enum {
1411     PDSA_StaticMemberShared,
1412     PDSA_StaticLocalVarShared,
1413     PDSA_LoopIterVarPrivate,
1414     PDSA_LoopIterVarLinear,
1415     PDSA_LoopIterVarLastprivate,
1416     PDSA_ConstVarShared,
1417     PDSA_GlobalVarShared,
1418     PDSA_TaskVarFirstprivate,
1419     PDSA_LocalVarPrivate,
1420     PDSA_Implicit
1421   } Reason = PDSA_Implicit;
1422   bool ReportHint = false;
1423   auto ReportLoc = D->getLocation();
1424   auto *VD = dyn_cast<VarDecl>(D);
1425   if (IsLoopIterVar) {
1426     if (DVar.CKind == OMPC_private)
1427       Reason = PDSA_LoopIterVarPrivate;
1428     else if (DVar.CKind == OMPC_lastprivate)
1429       Reason = PDSA_LoopIterVarLastprivate;
1430     else
1431       Reason = PDSA_LoopIterVarLinear;
1432   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433              DVar.CKind == OMPC_firstprivate) {
1434     Reason = PDSA_TaskVarFirstprivate;
1435     ReportLoc = DVar.ImplicitDSALoc;
1436   } else if (VD && VD->isStaticLocal())
1437     Reason = PDSA_StaticLocalVarShared;
1438   else if (VD && VD->isStaticDataMember())
1439     Reason = PDSA_StaticMemberShared;
1440   else if (VD && VD->isFileVarDecl())
1441     Reason = PDSA_GlobalVarShared;
1442   else if (D->getType().isConstant(SemaRef.getASTContext()))
1443     Reason = PDSA_ConstVarShared;
1444   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1445     ReportHint = true;
1446     Reason = PDSA_LocalVarPrivate;
1447   }
1448   if (Reason != PDSA_Implicit) {
1449     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1450         << Reason << ReportHint
1451         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452   } else if (DVar.ImplicitDSALoc.isValid()) {
1453     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454         << getOpenMPClauseName(DVar.CKind);
1455   }
1456 }
1457 
1458 namespace {
1459 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460   DSAStackTy *Stack;
1461   Sema &SemaRef;
1462   bool ErrorFound;
1463   CapturedStmt *CS;
1464   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1465   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
1466 
1467 public:
1468   void VisitDeclRefExpr(DeclRefExpr *E) {
1469     if (E->isTypeDependent() || E->isValueDependent() ||
1470         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471       return;
1472     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1473       // Skip internally declared variables.
1474       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475         return;
1476 
1477       auto DVar = Stack->getTopDSA(VD, false);
1478       // Check if the variable has explicit DSA set and stop analysis if it so.
1479       if (DVar.RefExpr)
1480         return;
1481 
1482       auto ELoc = E->getExprLoc();
1483       auto DKind = Stack->getCurrentDirective();
1484       // The default(none) clause requires that each variable that is referenced
1485       // in the construct, and does not have a predetermined data-sharing
1486       // attribute, must have its data-sharing attribute explicitly determined
1487       // by being listed in a data-sharing attribute clause.
1488       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1489           isParallelOrTaskRegion(DKind) &&
1490           VarsWithInheritedDSA.count(VD) == 0) {
1491         VarsWithInheritedDSA[VD] = E;
1492         return;
1493       }
1494 
1495       // OpenMP [2.9.3.6, Restrictions, p.2]
1496       //  A list item that appears in a reduction clause of the innermost
1497       //  enclosing worksharing or parallel construct may not be accessed in an
1498       //  explicit task.
1499       DVar = Stack->hasInnermostDSA(
1500           VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501           [](OpenMPDirectiveKind K) -> bool {
1502             return isOpenMPParallelDirective(K) ||
1503                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504           },
1505           false);
1506       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1507         ErrorFound = true;
1508         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1510         return;
1511       }
1512 
1513       // Define implicit data-sharing attributes for task.
1514       DVar = Stack->getImplicitDSA(VD, false);
1515       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516           !Stack->isLoopControlVariable(VD).first)
1517         ImplicitFirstprivate.push_back(E);
1518     }
1519   }
1520   void VisitMemberExpr(MemberExpr *E) {
1521     if (E->isTypeDependent() || E->isValueDependent() ||
1522         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523       return;
1524     if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525       if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526         auto DVar = Stack->getTopDSA(FD, false);
1527         // Check if the variable has explicit DSA set and stop analysis if it
1528         // so.
1529         if (DVar.RefExpr)
1530           return;
1531 
1532         auto ELoc = E->getExprLoc();
1533         auto DKind = Stack->getCurrentDirective();
1534         // OpenMP [2.9.3.6, Restrictions, p.2]
1535         //  A list item that appears in a reduction clause of the innermost
1536         //  enclosing worksharing or parallel construct may not be accessed in
1537         //  an  explicit task.
1538         DVar = Stack->hasInnermostDSA(
1539             FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540             [](OpenMPDirectiveKind K) -> bool {
1541               return isOpenMPParallelDirective(K) ||
1542                      isOpenMPWorksharingDirective(K) ||
1543                      isOpenMPTeamsDirective(K);
1544             },
1545             false);
1546         if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
1547           ErrorFound = true;
1548           SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549           ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550           return;
1551         }
1552 
1553         // Define implicit data-sharing attributes for task.
1554         DVar = Stack->getImplicitDSA(FD, false);
1555         if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556             !Stack->isLoopControlVariable(FD).first)
1557           ImplicitFirstprivate.push_back(E);
1558       }
1559     }
1560   }
1561   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1562     for (auto *C : S->clauses()) {
1563       // Skip analysis of arguments of implicitly defined firstprivate clause
1564       // for task directives.
1565       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1566         for (auto *CC : C->children()) {
1567           if (CC)
1568             Visit(CC);
1569         }
1570     }
1571   }
1572   void VisitStmt(Stmt *S) {
1573     for (auto *C : S->children()) {
1574       if (C && !isa<OMPExecutableDirective>(C))
1575         Visit(C);
1576     }
1577   }
1578 
1579   bool isErrorFound() { return ErrorFound; }
1580   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1581   llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
1582     return VarsWithInheritedDSA;
1583   }
1584 
1585   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1586       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1587 };
1588 } // namespace
1589 
1590 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1591   switch (DKind) {
1592   case OMPD_parallel:
1593   case OMPD_parallel_for:
1594   case OMPD_parallel_for_simd:
1595   case OMPD_parallel_sections:
1596   case OMPD_teams: {
1597     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1598     QualType KmpInt32PtrTy =
1599         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1600     Sema::CapturedParamNameType Params[] = {
1601         std::make_pair(".global_tid.", KmpInt32PtrTy),
1602         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1603         std::make_pair(StringRef(), QualType()) // __context with shared vars
1604     };
1605     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1606                              Params);
1607     break;
1608   }
1609   case OMPD_simd:
1610   case OMPD_for:
1611   case OMPD_for_simd:
1612   case OMPD_sections:
1613   case OMPD_section:
1614   case OMPD_single:
1615   case OMPD_master:
1616   case OMPD_critical:
1617   case OMPD_taskgroup:
1618   case OMPD_distribute:
1619   case OMPD_ordered:
1620   case OMPD_atomic:
1621   case OMPD_target_data:
1622   case OMPD_target:
1623   case OMPD_target_parallel:
1624   case OMPD_target_parallel_for:
1625   case OMPD_target_parallel_for_simd:
1626   case OMPD_target_simd: {
1627     Sema::CapturedParamNameType Params[] = {
1628         std::make_pair(StringRef(), QualType()) // __context with shared vars
1629     };
1630     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1631                              Params);
1632     break;
1633   }
1634   case OMPD_task: {
1635     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1636     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1637     FunctionProtoType::ExtProtoInfo EPI;
1638     EPI.Variadic = true;
1639     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1640     Sema::CapturedParamNameType Params[] = {
1641         std::make_pair(".global_tid.", KmpInt32Ty),
1642         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1643         std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1644         std::make_pair(".copy_fn.",
1645                        Context.getPointerType(CopyFnType).withConst()),
1646         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1647         std::make_pair(StringRef(), QualType()) // __context with shared vars
1648     };
1649     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1650                              Params);
1651     // Mark this captured region as inlined, because we don't use outlined
1652     // function directly.
1653     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1654         AlwaysInlineAttr::CreateImplicit(
1655             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1656     break;
1657   }
1658   case OMPD_taskloop:
1659   case OMPD_taskloop_simd: {
1660     QualType KmpInt32Ty =
1661         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1662     QualType KmpUInt64Ty =
1663         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1664     QualType KmpInt64Ty =
1665         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1666     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1667     FunctionProtoType::ExtProtoInfo EPI;
1668     EPI.Variadic = true;
1669     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1670     Sema::CapturedParamNameType Params[] = {
1671         std::make_pair(".global_tid.", KmpInt32Ty),
1672         std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1673         std::make_pair(".privates.",
1674                        Context.VoidPtrTy.withConst().withRestrict()),
1675         std::make_pair(
1676             ".copy_fn.",
1677             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1678         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1679         std::make_pair(".lb.", KmpUInt64Ty),
1680         std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1681         std::make_pair(".liter.", KmpInt32Ty),
1682         std::make_pair(StringRef(), QualType()) // __context with shared vars
1683     };
1684     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1685                              Params);
1686     // Mark this captured region as inlined, because we don't use outlined
1687     // function directly.
1688     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1689         AlwaysInlineAttr::CreateImplicit(
1690             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1691     break;
1692   }
1693   case OMPD_distribute_parallel_for_simd:
1694   case OMPD_distribute_simd:
1695   case OMPD_distribute_parallel_for:
1696   case OMPD_teams_distribute:
1697   case OMPD_teams_distribute_simd: {
1698     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1699     QualType KmpInt32PtrTy =
1700         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1701     Sema::CapturedParamNameType Params[] = {
1702         std::make_pair(".global_tid.", KmpInt32PtrTy),
1703         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1704         std::make_pair(".previous.lb.", Context.getSizeType()),
1705         std::make_pair(".previous.ub.", Context.getSizeType()),
1706         std::make_pair(StringRef(), QualType()) // __context with shared vars
1707     };
1708     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1709                              Params);
1710     break;
1711   }
1712   case OMPD_threadprivate:
1713   case OMPD_taskyield:
1714   case OMPD_barrier:
1715   case OMPD_taskwait:
1716   case OMPD_cancellation_point:
1717   case OMPD_cancel:
1718   case OMPD_flush:
1719   case OMPD_target_enter_data:
1720   case OMPD_target_exit_data:
1721   case OMPD_declare_reduction:
1722   case OMPD_declare_simd:
1723   case OMPD_declare_target:
1724   case OMPD_end_declare_target:
1725   case OMPD_target_update:
1726     llvm_unreachable("OpenMP Directive is not allowed");
1727   case OMPD_unknown:
1728     llvm_unreachable("Unknown OpenMP directive");
1729   }
1730 }
1731 
1732 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
1733                                              Expr *CaptureExpr, bool WithInit,
1734                                              bool AsExpression) {
1735   assert(CaptureExpr);
1736   ASTContext &C = S.getASTContext();
1737   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
1738   QualType Ty = Init->getType();
1739   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1740     if (S.getLangOpts().CPlusPlus)
1741       Ty = C.getLValueReferenceType(Ty);
1742     else {
1743       Ty = C.getPointerType(Ty);
1744       ExprResult Res =
1745           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1746       if (!Res.isUsable())
1747         return nullptr;
1748       Init = Res.get();
1749     }
1750     WithInit = true;
1751   }
1752   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty);
1753   if (!WithInit)
1754     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
1755   S.CurContext->addHiddenDecl(CED);
1756   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false,
1757                          /*TypeMayContainAuto=*/true);
1758   return CED;
1759 }
1760 
1761 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1762                                  bool WithInit) {
1763   OMPCapturedExprDecl *CD;
1764   if (auto *VD = S.IsOpenMPCapturedDecl(D))
1765     CD = cast<OMPCapturedExprDecl>(VD);
1766   else
1767     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1768                           /*AsExpression=*/false);
1769   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1770                           CaptureExpr->getExprLoc());
1771 }
1772 
1773 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1774   if (!Ref) {
1775     auto *CD =
1776         buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1777                          CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1778     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1779                            CaptureExpr->getExprLoc());
1780   }
1781   ExprResult Res = Ref;
1782   if (!S.getLangOpts().CPlusPlus &&
1783       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1784       Ref->getType()->isPointerType())
1785     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1786   if (!Res.isUsable())
1787     return ExprError();
1788   return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
1789 }
1790 
1791 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1792                                       ArrayRef<OMPClause *> Clauses) {
1793   if (!S.isUsable()) {
1794     ActOnCapturedRegionError();
1795     return StmtError();
1796   }
1797 
1798   OMPOrderedClause *OC = nullptr;
1799   OMPScheduleClause *SC = nullptr;
1800   SmallVector<OMPLinearClause *, 4> LCs;
1801   // This is required for proper codegen.
1802   for (auto *Clause : Clauses) {
1803     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1804         Clause->getClauseKind() == OMPC_copyprivate ||
1805         (getLangOpts().OpenMPUseTLS &&
1806          getASTContext().getTargetInfo().isTLSSupported() &&
1807          Clause->getClauseKind() == OMPC_copyin)) {
1808       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1809       // Mark all variables in private list clauses as used in inner region.
1810       for (auto *VarRef : Clause->children()) {
1811         if (auto *E = cast_or_null<Expr>(VarRef)) {
1812           MarkDeclarationsReferencedInExpr(E);
1813         }
1814       }
1815       DSAStack->setForceVarCapturing(/*V=*/false);
1816     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1817       // Mark all variables in private list clauses as used in inner region.
1818       // Required for proper codegen of combined directives.
1819       // TODO: add processing for other clauses.
1820       if (auto *C = OMPClauseWithPreInit::get(Clause)) {
1821         if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1822           for (auto *D : DS->decls())
1823             MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1824         }
1825       }
1826       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1827         if (auto *E = C->getPostUpdateExpr())
1828           MarkDeclarationsReferencedInExpr(E);
1829       }
1830     }
1831     if (Clause->getClauseKind() == OMPC_schedule)
1832       SC = cast<OMPScheduleClause>(Clause);
1833     else if (Clause->getClauseKind() == OMPC_ordered)
1834       OC = cast<OMPOrderedClause>(Clause);
1835     else if (Clause->getClauseKind() == OMPC_linear)
1836       LCs.push_back(cast<OMPLinearClause>(Clause));
1837   }
1838   bool ErrorFound = false;
1839   // OpenMP, 2.7.1 Loop Construct, Restrictions
1840   // The nonmonotonic modifier cannot be specified if an ordered clause is
1841   // specified.
1842   if (SC &&
1843       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1844        SC->getSecondScheduleModifier() ==
1845            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1846       OC) {
1847     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1848              ? SC->getFirstScheduleModifierLoc()
1849              : SC->getSecondScheduleModifierLoc(),
1850          diag::err_omp_schedule_nonmonotonic_ordered)
1851         << SourceRange(OC->getLocStart(), OC->getLocEnd());
1852     ErrorFound = true;
1853   }
1854   if (!LCs.empty() && OC && OC->getNumForLoops()) {
1855     for (auto *C : LCs) {
1856       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1857           << SourceRange(OC->getLocStart(), OC->getLocEnd());
1858     }
1859     ErrorFound = true;
1860   }
1861   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1862       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1863       OC->getNumForLoops()) {
1864     Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1865         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1866     ErrorFound = true;
1867   }
1868   if (ErrorFound) {
1869     ActOnCapturedRegionError();
1870     return StmtError();
1871   }
1872   return ActOnCapturedRegionEnd(S.get());
1873 }
1874 
1875 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1876                                   OpenMPDirectiveKind CurrentRegion,
1877                                   const DeclarationNameInfo &CurrentName,
1878                                   OpenMPDirectiveKind CancelRegion,
1879                                   SourceLocation StartLoc) {
1880   if (Stack->getCurScope()) {
1881     auto ParentRegion = Stack->getParentDirective();
1882     auto OffendingRegion = ParentRegion;
1883     bool NestingProhibited = false;
1884     bool CloseNesting = true;
1885     bool OrphanSeen = false;
1886     enum {
1887       NoRecommend,
1888       ShouldBeInParallelRegion,
1889       ShouldBeInOrderedRegion,
1890       ShouldBeInTargetRegion,
1891       ShouldBeInTeamsRegion
1892     } Recommend = NoRecommend;
1893     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
1894       // OpenMP [2.16, Nesting of Regions]
1895       // OpenMP constructs may not be nested inside a simd region.
1896       // OpenMP [2.8.1,simd Construct, Restrictions]
1897       // An ordered construct with the simd clause is the only OpenMP
1898       // construct that can appear in the simd region.
1899       // Allowing a SIMD construct nested in another SIMD construct is an
1900       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1901       // message.
1902       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1903                                  ? diag::err_omp_prohibited_region_simd
1904                                  : diag::warn_omp_nesting_simd);
1905       return CurrentRegion != OMPD_simd;
1906     }
1907     if (ParentRegion == OMPD_atomic) {
1908       // OpenMP [2.16, Nesting of Regions]
1909       // OpenMP constructs may not be nested inside an atomic region.
1910       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1911       return true;
1912     }
1913     if (CurrentRegion == OMPD_section) {
1914       // OpenMP [2.7.2, sections Construct, Restrictions]
1915       // Orphaned section directives are prohibited. That is, the section
1916       // directives must appear within the sections construct and must not be
1917       // encountered elsewhere in the sections region.
1918       if (ParentRegion != OMPD_sections &&
1919           ParentRegion != OMPD_parallel_sections) {
1920         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1921             << (ParentRegion != OMPD_unknown)
1922             << getOpenMPDirectiveName(ParentRegion);
1923         return true;
1924       }
1925       return false;
1926     }
1927     // Allow some constructs (except teams) to be orphaned (they could be
1928     // used in functions, called from OpenMP regions with the required
1929     // preconditions).
1930     if (ParentRegion == OMPD_unknown && !isOpenMPTeamsDirective(CurrentRegion))
1931       return false;
1932     if (CurrentRegion == OMPD_cancellation_point ||
1933         CurrentRegion == OMPD_cancel) {
1934       // OpenMP [2.16, Nesting of Regions]
1935       // A cancellation point construct for which construct-type-clause is
1936       // taskgroup must be nested inside a task construct. A cancellation
1937       // point construct for which construct-type-clause is not taskgroup must
1938       // be closely nested inside an OpenMP construct that matches the type
1939       // specified in construct-type-clause.
1940       // A cancel construct for which construct-type-clause is taskgroup must be
1941       // nested inside a task construct. A cancel construct for which
1942       // construct-type-clause is not taskgroup must be closely nested inside an
1943       // OpenMP construct that matches the type specified in
1944       // construct-type-clause.
1945       NestingProhibited =
1946           !((CancelRegion == OMPD_parallel &&
1947              (ParentRegion == OMPD_parallel ||
1948               ParentRegion == OMPD_target_parallel)) ||
1949             (CancelRegion == OMPD_for &&
1950              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
1951               ParentRegion == OMPD_target_parallel_for)) ||
1952             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1953             (CancelRegion == OMPD_sections &&
1954              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
1955               ParentRegion == OMPD_parallel_sections)));
1956     } else if (CurrentRegion == OMPD_master) {
1957       // OpenMP [2.16, Nesting of Regions]
1958       // A master region may not be closely nested inside a worksharing,
1959       // atomic, or explicit task region.
1960       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1961                           isOpenMPTaskingDirective(ParentRegion);
1962     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1963       // OpenMP [2.16, Nesting of Regions]
1964       // A critical region may not be nested (closely or otherwise) inside a
1965       // critical region with the same name. Note that this restriction is not
1966       // sufficient to prevent deadlock.
1967       SourceLocation PreviousCriticalLoc;
1968       bool DeadLock = Stack->hasDirective(
1969           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
1970                                               const DeclarationNameInfo &DNI,
1971                                               SourceLocation Loc) -> bool {
1972             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
1973               PreviousCriticalLoc = Loc;
1974               return true;
1975             } else
1976               return false;
1977           },
1978           false /* skip top directive */);
1979       if (DeadLock) {
1980         SemaRef.Diag(StartLoc,
1981                      diag::err_omp_prohibited_region_critical_same_name)
1982             << CurrentName.getName();
1983         if (PreviousCriticalLoc.isValid())
1984           SemaRef.Diag(PreviousCriticalLoc,
1985                        diag::note_omp_previous_critical_region);
1986         return true;
1987       }
1988     } else if (CurrentRegion == OMPD_barrier) {
1989       // OpenMP [2.16, Nesting of Regions]
1990       // A barrier region may not be closely nested inside a worksharing,
1991       // explicit task, critical, ordered, atomic, or master region.
1992       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1993                           isOpenMPTaskingDirective(ParentRegion) ||
1994                           ParentRegion == OMPD_master ||
1995                           ParentRegion == OMPD_critical ||
1996                           ParentRegion == OMPD_ordered;
1997     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1998                !isOpenMPParallelDirective(CurrentRegion)) {
1999       // OpenMP [2.16, Nesting of Regions]
2000       // A worksharing region may not be closely nested inside a worksharing,
2001       // explicit task, critical, ordered, atomic, or master region.
2002       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2003                           isOpenMPTaskingDirective(ParentRegion) ||
2004                           ParentRegion == OMPD_master ||
2005                           ParentRegion == OMPD_critical ||
2006                           ParentRegion == OMPD_ordered;
2007       Recommend = ShouldBeInParallelRegion;
2008     } else if (CurrentRegion == OMPD_ordered) {
2009       // OpenMP [2.16, Nesting of Regions]
2010       // An ordered region may not be closely nested inside a critical,
2011       // atomic, or explicit task region.
2012       // An ordered region must be closely nested inside a loop region (or
2013       // parallel loop region) with an ordered clause.
2014       // OpenMP [2.8.1,simd Construct, Restrictions]
2015       // An ordered construct with the simd clause is the only OpenMP construct
2016       // that can appear in the simd region.
2017       NestingProhibited = ParentRegion == OMPD_critical ||
2018                           isOpenMPTaskingDirective(ParentRegion) ||
2019                           !(isOpenMPSimdDirective(ParentRegion) ||
2020                             Stack->isParentOrderedRegion());
2021       Recommend = ShouldBeInOrderedRegion;
2022     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2023       // OpenMP [2.16, Nesting of Regions]
2024       // If specified, a teams construct must be contained within a target
2025       // construct.
2026       NestingProhibited = ParentRegion != OMPD_target;
2027       OrphanSeen = ParentRegion == OMPD_unknown;
2028       Recommend = ShouldBeInTargetRegion;
2029       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2030     }
2031     if (!NestingProhibited && ParentRegion == OMPD_teams) {
2032       // OpenMP [2.16, Nesting of Regions]
2033       // distribute, parallel, parallel sections, parallel workshare, and the
2034       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2035       // constructs that can be closely nested in the teams region.
2036       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2037                           !isOpenMPDistributeDirective(CurrentRegion);
2038       Recommend = ShouldBeInParallelRegion;
2039     }
2040     if (!NestingProhibited &&
2041         isOpenMPNestingDistributeDirective(CurrentRegion)) {
2042       // OpenMP 4.5 [2.17 Nesting of Regions]
2043       // The region associated with the distribute construct must be strictly
2044       // nested inside a teams region
2045       NestingProhibited = ParentRegion != OMPD_teams;
2046       Recommend = ShouldBeInTeamsRegion;
2047     }
2048     if (!NestingProhibited &&
2049         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2050          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2051       // OpenMP 4.5 [2.17 Nesting of Regions]
2052       // If a target, target update, target data, target enter data, or
2053       // target exit data construct is encountered during execution of a
2054       // target region, the behavior is unspecified.
2055       NestingProhibited = Stack->hasDirective(
2056           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2057                              SourceLocation) -> bool {
2058             if (isOpenMPTargetExecutionDirective(K)) {
2059               OffendingRegion = K;
2060               return true;
2061             } else
2062               return false;
2063           },
2064           false /* don't skip top directive */);
2065       CloseNesting = false;
2066     }
2067     if (NestingProhibited) {
2068       if (OrphanSeen) {
2069         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2070             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2071       } else {
2072         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2073             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2074             << Recommend << getOpenMPDirectiveName(CurrentRegion);
2075       }
2076       return true;
2077     }
2078   }
2079   return false;
2080 }
2081 
2082 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2083                            ArrayRef<OMPClause *> Clauses,
2084                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2085   bool ErrorFound = false;
2086   unsigned NamedModifiersNumber = 0;
2087   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2088       OMPD_unknown + 1);
2089   SmallVector<SourceLocation, 4> NameModifierLoc;
2090   for (const auto *C : Clauses) {
2091     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2092       // At most one if clause without a directive-name-modifier can appear on
2093       // the directive.
2094       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2095       if (FoundNameModifiers[CurNM]) {
2096         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2097             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2098             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2099         ErrorFound = true;
2100       } else if (CurNM != OMPD_unknown) {
2101         NameModifierLoc.push_back(IC->getNameModifierLoc());
2102         ++NamedModifiersNumber;
2103       }
2104       FoundNameModifiers[CurNM] = IC;
2105       if (CurNM == OMPD_unknown)
2106         continue;
2107       // Check if the specified name modifier is allowed for the current
2108       // directive.
2109       // At most one if clause with the particular directive-name-modifier can
2110       // appear on the directive.
2111       bool MatchFound = false;
2112       for (auto NM : AllowedNameModifiers) {
2113         if (CurNM == NM) {
2114           MatchFound = true;
2115           break;
2116         }
2117       }
2118       if (!MatchFound) {
2119         S.Diag(IC->getNameModifierLoc(),
2120                diag::err_omp_wrong_if_directive_name_modifier)
2121             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2122         ErrorFound = true;
2123       }
2124     }
2125   }
2126   // If any if clause on the directive includes a directive-name-modifier then
2127   // all if clauses on the directive must include a directive-name-modifier.
2128   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2129     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2130       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2131              diag::err_omp_no_more_if_clause);
2132     } else {
2133       std::string Values;
2134       std::string Sep(", ");
2135       unsigned AllowedCnt = 0;
2136       unsigned TotalAllowedNum =
2137           AllowedNameModifiers.size() - NamedModifiersNumber;
2138       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2139            ++Cnt) {
2140         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2141         if (!FoundNameModifiers[NM]) {
2142           Values += "'";
2143           Values += getOpenMPDirectiveName(NM);
2144           Values += "'";
2145           if (AllowedCnt + 2 == TotalAllowedNum)
2146             Values += " or ";
2147           else if (AllowedCnt + 1 != TotalAllowedNum)
2148             Values += Sep;
2149           ++AllowedCnt;
2150         }
2151       }
2152       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2153              diag::err_omp_unnamed_if_clause)
2154           << (TotalAllowedNum > 1) << Values;
2155     }
2156     for (auto Loc : NameModifierLoc) {
2157       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2158     }
2159     ErrorFound = true;
2160   }
2161   return ErrorFound;
2162 }
2163 
2164 StmtResult Sema::ActOnOpenMPExecutableDirective(
2165     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2166     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2167     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2168   StmtResult Res = StmtError();
2169   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2170                             StartLoc))
2171     return StmtError();
2172 
2173   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2174   llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
2175   bool ErrorFound = false;
2176   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2177   if (AStmt) {
2178     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2179 
2180     // Check default data sharing attributes for referenced variables.
2181     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2182     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2183     if (DSAChecker.isErrorFound())
2184       return StmtError();
2185     // Generate list of implicitly defined firstprivate variables.
2186     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2187 
2188     if (!DSAChecker.getImplicitFirstprivate().empty()) {
2189       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2190               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2191               SourceLocation(), SourceLocation())) {
2192         ClausesWithImplicit.push_back(Implicit);
2193         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2194                      DSAChecker.getImplicitFirstprivate().size();
2195       } else
2196         ErrorFound = true;
2197     }
2198   }
2199 
2200   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2201   switch (Kind) {
2202   case OMPD_parallel:
2203     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2204                                        EndLoc);
2205     AllowedNameModifiers.push_back(OMPD_parallel);
2206     break;
2207   case OMPD_simd:
2208     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2209                                    VarsWithInheritedDSA);
2210     break;
2211   case OMPD_for:
2212     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2213                                   VarsWithInheritedDSA);
2214     break;
2215   case OMPD_for_simd:
2216     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2217                                       EndLoc, VarsWithInheritedDSA);
2218     break;
2219   case OMPD_sections:
2220     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2221                                        EndLoc);
2222     break;
2223   case OMPD_section:
2224     assert(ClausesWithImplicit.empty() &&
2225            "No clauses are allowed for 'omp section' directive");
2226     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2227     break;
2228   case OMPD_single:
2229     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2230                                      EndLoc);
2231     break;
2232   case OMPD_master:
2233     assert(ClausesWithImplicit.empty() &&
2234            "No clauses are allowed for 'omp master' directive");
2235     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2236     break;
2237   case OMPD_critical:
2238     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2239                                        StartLoc, EndLoc);
2240     break;
2241   case OMPD_parallel_for:
2242     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2243                                           EndLoc, VarsWithInheritedDSA);
2244     AllowedNameModifiers.push_back(OMPD_parallel);
2245     break;
2246   case OMPD_parallel_for_simd:
2247     Res = ActOnOpenMPParallelForSimdDirective(
2248         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2249     AllowedNameModifiers.push_back(OMPD_parallel);
2250     break;
2251   case OMPD_parallel_sections:
2252     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2253                                                StartLoc, EndLoc);
2254     AllowedNameModifiers.push_back(OMPD_parallel);
2255     break;
2256   case OMPD_task:
2257     Res =
2258         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2259     AllowedNameModifiers.push_back(OMPD_task);
2260     break;
2261   case OMPD_taskyield:
2262     assert(ClausesWithImplicit.empty() &&
2263            "No clauses are allowed for 'omp taskyield' directive");
2264     assert(AStmt == nullptr &&
2265            "No associated statement allowed for 'omp taskyield' directive");
2266     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2267     break;
2268   case OMPD_barrier:
2269     assert(ClausesWithImplicit.empty() &&
2270            "No clauses are allowed for 'omp barrier' directive");
2271     assert(AStmt == nullptr &&
2272            "No associated statement allowed for 'omp barrier' directive");
2273     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2274     break;
2275   case OMPD_taskwait:
2276     assert(ClausesWithImplicit.empty() &&
2277            "No clauses are allowed for 'omp taskwait' directive");
2278     assert(AStmt == nullptr &&
2279            "No associated statement allowed for 'omp taskwait' directive");
2280     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2281     break;
2282   case OMPD_taskgroup:
2283     assert(ClausesWithImplicit.empty() &&
2284            "No clauses are allowed for 'omp taskgroup' directive");
2285     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2286     break;
2287   case OMPD_flush:
2288     assert(AStmt == nullptr &&
2289            "No associated statement allowed for 'omp flush' directive");
2290     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2291     break;
2292   case OMPD_ordered:
2293     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2294                                       EndLoc);
2295     break;
2296   case OMPD_atomic:
2297     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2298                                      EndLoc);
2299     break;
2300   case OMPD_teams:
2301     Res =
2302         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2303     break;
2304   case OMPD_target:
2305     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2306                                      EndLoc);
2307     AllowedNameModifiers.push_back(OMPD_target);
2308     break;
2309   case OMPD_target_parallel:
2310     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2311                                              StartLoc, EndLoc);
2312     AllowedNameModifiers.push_back(OMPD_target);
2313     AllowedNameModifiers.push_back(OMPD_parallel);
2314     break;
2315   case OMPD_target_parallel_for:
2316     Res = ActOnOpenMPTargetParallelForDirective(
2317         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2318     AllowedNameModifiers.push_back(OMPD_target);
2319     AllowedNameModifiers.push_back(OMPD_parallel);
2320     break;
2321   case OMPD_cancellation_point:
2322     assert(ClausesWithImplicit.empty() &&
2323            "No clauses are allowed for 'omp cancellation point' directive");
2324     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2325                                "cancellation point' directive");
2326     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2327     break;
2328   case OMPD_cancel:
2329     assert(AStmt == nullptr &&
2330            "No associated statement allowed for 'omp cancel' directive");
2331     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2332                                      CancelRegion);
2333     AllowedNameModifiers.push_back(OMPD_cancel);
2334     break;
2335   case OMPD_target_data:
2336     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2337                                          EndLoc);
2338     AllowedNameModifiers.push_back(OMPD_target_data);
2339     break;
2340   case OMPD_target_enter_data:
2341     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2342                                               EndLoc);
2343     AllowedNameModifiers.push_back(OMPD_target_enter_data);
2344     break;
2345   case OMPD_target_exit_data:
2346     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2347                                              EndLoc);
2348     AllowedNameModifiers.push_back(OMPD_target_exit_data);
2349     break;
2350   case OMPD_taskloop:
2351     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2352                                        EndLoc, VarsWithInheritedDSA);
2353     AllowedNameModifiers.push_back(OMPD_taskloop);
2354     break;
2355   case OMPD_taskloop_simd:
2356     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2357                                            EndLoc, VarsWithInheritedDSA);
2358     AllowedNameModifiers.push_back(OMPD_taskloop);
2359     break;
2360   case OMPD_distribute:
2361     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2362                                          EndLoc, VarsWithInheritedDSA);
2363     break;
2364   case OMPD_target_update:
2365     assert(!AStmt && "Statement is not allowed for target update");
2366     Res =
2367         ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2368     AllowedNameModifiers.push_back(OMPD_target_update);
2369     break;
2370   case OMPD_distribute_parallel_for:
2371     Res = ActOnOpenMPDistributeParallelForDirective(
2372         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2373     AllowedNameModifiers.push_back(OMPD_parallel);
2374     break;
2375   case OMPD_distribute_parallel_for_simd:
2376     Res = ActOnOpenMPDistributeParallelForSimdDirective(
2377         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2378     AllowedNameModifiers.push_back(OMPD_parallel);
2379     break;
2380   case OMPD_distribute_simd:
2381     Res = ActOnOpenMPDistributeSimdDirective(
2382         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2383     break;
2384   case OMPD_target_parallel_for_simd:
2385     Res = ActOnOpenMPTargetParallelForSimdDirective(
2386         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2387     AllowedNameModifiers.push_back(OMPD_target);
2388     AllowedNameModifiers.push_back(OMPD_parallel);
2389     break;
2390   case OMPD_target_simd:
2391     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2392                                          EndLoc, VarsWithInheritedDSA);
2393     AllowedNameModifiers.push_back(OMPD_target);
2394     break;
2395   case OMPD_teams_distribute:
2396     Res = ActOnOpenMPTeamsDistributeDirective(
2397         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2398     break;
2399   case OMPD_teams_distribute_simd:
2400     Res = ActOnOpenMPTeamsDistributeSimdDirective(
2401         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2402     break;
2403   case OMPD_declare_target:
2404   case OMPD_end_declare_target:
2405   case OMPD_threadprivate:
2406   case OMPD_declare_reduction:
2407   case OMPD_declare_simd:
2408     llvm_unreachable("OpenMP Directive is not allowed");
2409   case OMPD_unknown:
2410     llvm_unreachable("Unknown OpenMP directive");
2411   }
2412 
2413   for (auto P : VarsWithInheritedDSA) {
2414     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2415         << P.first << P.second->getSourceRange();
2416   }
2417   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2418 
2419   if (!AllowedNameModifiers.empty())
2420     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2421                  ErrorFound;
2422 
2423   if (ErrorFound)
2424     return StmtError();
2425   return Res;
2426 }
2427 
2428 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2429     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
2430     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
2431     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2432     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
2433   assert(Aligneds.size() == Alignments.size());
2434   assert(Linears.size() == LinModifiers.size());
2435   assert(Linears.size() == Steps.size());
2436   if (!DG || DG.get().isNull())
2437     return DeclGroupPtrTy();
2438 
2439   if (!DG.get().isSingleDecl()) {
2440     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
2441     return DG;
2442   }
2443   auto *ADecl = DG.get().getSingleDecl();
2444   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2445     ADecl = FTD->getTemplatedDecl();
2446 
2447   auto *FD = dyn_cast<FunctionDecl>(ADecl);
2448   if (!FD) {
2449     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
2450     return DeclGroupPtrTy();
2451   }
2452 
2453   // OpenMP [2.8.2, declare simd construct, Description]
2454   // The parameter of the simdlen clause must be a constant positive integer
2455   // expression.
2456   ExprResult SL;
2457   if (Simdlen)
2458     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
2459   // OpenMP [2.8.2, declare simd construct, Description]
2460   // The special this pointer can be used as if was one of the arguments to the
2461   // function in any of the linear, aligned, or uniform clauses.
2462   // The uniform clause declares one or more arguments to have an invariant
2463   // value for all concurrent invocations of the function in the execution of a
2464   // single SIMD loop.
2465   llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2466   Expr *UniformedLinearThis = nullptr;
2467   for (auto *E : Uniforms) {
2468     E = E->IgnoreParenImpCasts();
2469     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2470       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2471         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2472             FD->getParamDecl(PVD->getFunctionScopeIndex())
2473                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2474           UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
2475           continue;
2476         }
2477     if (isa<CXXThisExpr>(E)) {
2478       UniformedLinearThis = E;
2479       continue;
2480     }
2481     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2482         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2483   }
2484   // OpenMP [2.8.2, declare simd construct, Description]
2485   // The aligned clause declares that the object to which each list item points
2486   // is aligned to the number of bytes expressed in the optional parameter of
2487   // the aligned clause.
2488   // The special this pointer can be used as if was one of the arguments to the
2489   // function in any of the linear, aligned, or uniform clauses.
2490   // The type of list items appearing in the aligned clause must be array,
2491   // pointer, reference to array, or reference to pointer.
2492   llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2493   Expr *AlignedThis = nullptr;
2494   for (auto *E : Aligneds) {
2495     E = E->IgnoreParenImpCasts();
2496     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2497       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2498         auto *CanonPVD = PVD->getCanonicalDecl();
2499         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2500             FD->getParamDecl(PVD->getFunctionScopeIndex())
2501                     ->getCanonicalDecl() == CanonPVD) {
2502           // OpenMP  [2.8.1, simd construct, Restrictions]
2503           // A list-item cannot appear in more than one aligned clause.
2504           if (AlignedArgs.count(CanonPVD) > 0) {
2505             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2506                 << 1 << E->getSourceRange();
2507             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2508                  diag::note_omp_explicit_dsa)
2509                 << getOpenMPClauseName(OMPC_aligned);
2510             continue;
2511           }
2512           AlignedArgs[CanonPVD] = E;
2513           QualType QTy = PVD->getType()
2514                              .getNonReferenceType()
2515                              .getUnqualifiedType()
2516                              .getCanonicalType();
2517           const Type *Ty = QTy.getTypePtrOrNull();
2518           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2519             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2520                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2521             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2522           }
2523           continue;
2524         }
2525       }
2526     if (isa<CXXThisExpr>(E)) {
2527       if (AlignedThis) {
2528         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2529             << 2 << E->getSourceRange();
2530         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2531             << getOpenMPClauseName(OMPC_aligned);
2532       }
2533       AlignedThis = E;
2534       continue;
2535     }
2536     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2537         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2538   }
2539   // The optional parameter of the aligned clause, alignment, must be a constant
2540   // positive integer expression. If no optional parameter is specified,
2541   // implementation-defined default alignments for SIMD instructions on the
2542   // target platforms are assumed.
2543   SmallVector<Expr *, 4> NewAligns;
2544   for (auto *E : Alignments) {
2545     ExprResult Align;
2546     if (E)
2547       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2548     NewAligns.push_back(Align.get());
2549   }
2550   // OpenMP [2.8.2, declare simd construct, Description]
2551   // The linear clause declares one or more list items to be private to a SIMD
2552   // lane and to have a linear relationship with respect to the iteration space
2553   // of a loop.
2554   // The special this pointer can be used as if was one of the arguments to the
2555   // function in any of the linear, aligned, or uniform clauses.
2556   // When a linear-step expression is specified in a linear clause it must be
2557   // either a constant integer expression or an integer-typed parameter that is
2558   // specified in a uniform clause on the directive.
2559   llvm::DenseMap<Decl *, Expr *> LinearArgs;
2560   const bool IsUniformedThis = UniformedLinearThis != nullptr;
2561   auto MI = LinModifiers.begin();
2562   for (auto *E : Linears) {
2563     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2564     ++MI;
2565     E = E->IgnoreParenImpCasts();
2566     if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2567       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2568         auto *CanonPVD = PVD->getCanonicalDecl();
2569         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2570             FD->getParamDecl(PVD->getFunctionScopeIndex())
2571                     ->getCanonicalDecl() == CanonPVD) {
2572           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
2573           // A list-item cannot appear in more than one linear clause.
2574           if (LinearArgs.count(CanonPVD) > 0) {
2575             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2576                 << getOpenMPClauseName(OMPC_linear)
2577                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2578             Diag(LinearArgs[CanonPVD]->getExprLoc(),
2579                  diag::note_omp_explicit_dsa)
2580                 << getOpenMPClauseName(OMPC_linear);
2581             continue;
2582           }
2583           // Each argument can appear in at most one uniform or linear clause.
2584           if (UniformedArgs.count(CanonPVD) > 0) {
2585             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2586                 << getOpenMPClauseName(OMPC_linear)
2587                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2588             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2589                  diag::note_omp_explicit_dsa)
2590                 << getOpenMPClauseName(OMPC_uniform);
2591             continue;
2592           }
2593           LinearArgs[CanonPVD] = E;
2594           if (E->isValueDependent() || E->isTypeDependent() ||
2595               E->isInstantiationDependent() ||
2596               E->containsUnexpandedParameterPack())
2597             continue;
2598           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2599                                       PVD->getOriginalType());
2600           continue;
2601         }
2602       }
2603     if (isa<CXXThisExpr>(E)) {
2604       if (UniformedLinearThis) {
2605         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2606             << getOpenMPClauseName(OMPC_linear)
2607             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2608             << E->getSourceRange();
2609         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2610             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2611                                                    : OMPC_linear);
2612         continue;
2613       }
2614       UniformedLinearThis = E;
2615       if (E->isValueDependent() || E->isTypeDependent() ||
2616           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2617         continue;
2618       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2619                                   E->getType());
2620       continue;
2621     }
2622     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2623         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2624   }
2625   Expr *Step = nullptr;
2626   Expr *NewStep = nullptr;
2627   SmallVector<Expr *, 4> NewSteps;
2628   for (auto *E : Steps) {
2629     // Skip the same step expression, it was checked already.
2630     if (Step == E || !E) {
2631       NewSteps.push_back(E ? NewStep : nullptr);
2632       continue;
2633     }
2634     Step = E;
2635     if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2636       if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2637         auto *CanonPVD = PVD->getCanonicalDecl();
2638         if (UniformedArgs.count(CanonPVD) == 0) {
2639           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2640               << Step->getSourceRange();
2641         } else if (E->isValueDependent() || E->isTypeDependent() ||
2642                    E->isInstantiationDependent() ||
2643                    E->containsUnexpandedParameterPack() ||
2644                    CanonPVD->getType()->hasIntegerRepresentation())
2645           NewSteps.push_back(Step);
2646         else {
2647           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2648               << Step->getSourceRange();
2649         }
2650         continue;
2651       }
2652     NewStep = Step;
2653     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2654         !Step->isInstantiationDependent() &&
2655         !Step->containsUnexpandedParameterPack()) {
2656       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2657                     .get();
2658       if (NewStep)
2659         NewStep = VerifyIntegerConstantExpression(NewStep).get();
2660     }
2661     NewSteps.push_back(NewStep);
2662   }
2663   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2664       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
2665       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
2666       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2667       const_cast<Expr **>(Linears.data()), Linears.size(),
2668       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2669       NewSteps.data(), NewSteps.size(), SR);
2670   ADecl->addAttr(NewAttr);
2671   return ConvertDeclToDeclGroup(ADecl);
2672 }
2673 
2674 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2675                                               Stmt *AStmt,
2676                                               SourceLocation StartLoc,
2677                                               SourceLocation EndLoc) {
2678   if (!AStmt)
2679     return StmtError();
2680 
2681   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2682   // 1.2.2 OpenMP Language Terminology
2683   // Structured block - An executable statement with a single entry at the
2684   // top and a single exit at the bottom.
2685   // The point of exit cannot be a branch out of the structured block.
2686   // longjmp() and throw() must not violate the entry/exit criteria.
2687   CS->getCapturedDecl()->setNothrow();
2688 
2689   getCurFunction()->setHasBranchProtectedScope();
2690 
2691   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2692                                       DSAStack->isCancelRegion());
2693 }
2694 
2695 namespace {
2696 /// \brief Helper class for checking canonical form of the OpenMP loops and
2697 /// extracting iteration space of each loop in the loop nest, that will be used
2698 /// for IR generation.
2699 class OpenMPIterationSpaceChecker {
2700   /// \brief Reference to Sema.
2701   Sema &SemaRef;
2702   /// \brief A location for diagnostics (when there is no some better location).
2703   SourceLocation DefaultLoc;
2704   /// \brief A location for diagnostics (when increment is not compatible).
2705   SourceLocation ConditionLoc;
2706   /// \brief A source location for referring to loop init later.
2707   SourceRange InitSrcRange;
2708   /// \brief A source location for referring to condition later.
2709   SourceRange ConditionSrcRange;
2710   /// \brief A source location for referring to increment later.
2711   SourceRange IncrementSrcRange;
2712   /// \brief Loop variable.
2713   ValueDecl *LCDecl = nullptr;
2714   /// \brief Reference to loop variable.
2715   Expr *LCRef = nullptr;
2716   /// \brief Lower bound (initializer for the var).
2717   Expr *LB = nullptr;
2718   /// \brief Upper bound.
2719   Expr *UB = nullptr;
2720   /// \brief Loop step (increment).
2721   Expr *Step = nullptr;
2722   /// \brief This flag is true when condition is one of:
2723   ///   Var <  UB
2724   ///   Var <= UB
2725   ///   UB  >  Var
2726   ///   UB  >= Var
2727   bool TestIsLessOp = false;
2728   /// \brief This flag is true when condition is strict ( < or > ).
2729   bool TestIsStrictOp = false;
2730   /// \brief This flag is true when step is subtracted on each iteration.
2731   bool SubtractStep = false;
2732 
2733 public:
2734   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2735       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
2736   /// \brief Check init-expr for canonical loop form and save loop counter
2737   /// variable - #Var and its initialization value - #LB.
2738   bool CheckInit(Stmt *S, bool EmitDiags = true);
2739   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2740   /// for less/greater and for strict/non-strict comparison.
2741   bool CheckCond(Expr *S);
2742   /// \brief Check incr-expr for canonical loop form and return true if it
2743   /// does not conform, otherwise save loop step (#Step).
2744   bool CheckInc(Expr *S);
2745   /// \brief Return the loop counter variable.
2746   ValueDecl *GetLoopDecl() const { return LCDecl; }
2747   /// \brief Return the reference expression to loop counter variable.
2748   Expr *GetLoopDeclRefExpr() const { return LCRef; }
2749   /// \brief Source range of the loop init.
2750   SourceRange GetInitSrcRange() const { return InitSrcRange; }
2751   /// \brief Source range of the loop condition.
2752   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2753   /// \brief Source range of the loop increment.
2754   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2755   /// \brief True if the step should be subtracted.
2756   bool ShouldSubtractStep() const { return SubtractStep; }
2757   /// \brief Build the expression to calculate the number of iterations.
2758   Expr *
2759   BuildNumIterations(Scope *S, const bool LimitedType,
2760                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2761   /// \brief Build the precondition expression for the loops.
2762   Expr *BuildPreCond(Scope *S, Expr *Cond,
2763                      llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
2764   /// \brief Build reference expression to the counter be used for codegen.
2765   DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2766                                DSAStackTy &DSA) const;
2767   /// \brief Build reference expression to the private counter be used for
2768   /// codegen.
2769   Expr *BuildPrivateCounterVar() const;
2770   /// \brief Build initialization of the counter be used for codegen.
2771   Expr *BuildCounterInit() const;
2772   /// \brief Build step of the counter be used for codegen.
2773   Expr *BuildCounterStep() const;
2774   /// \brief Return true if any expression is dependent.
2775   bool Dependent() const;
2776 
2777 private:
2778   /// \brief Check the right-hand side of an assignment in the increment
2779   /// expression.
2780   bool CheckIncRHS(Expr *RHS);
2781   /// \brief Helper to set loop counter variable and its initializer.
2782   bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
2783   /// \brief Helper to set upper bound.
2784   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2785              SourceLocation SL);
2786   /// \brief Helper to set loop increment.
2787   bool SetStep(Expr *NewStep, bool Subtract);
2788 };
2789 
2790 bool OpenMPIterationSpaceChecker::Dependent() const {
2791   if (!LCDecl) {
2792     assert(!LB && !UB && !Step);
2793     return false;
2794   }
2795   return LCDecl->getType()->isDependentType() ||
2796          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2797          (Step && Step->isValueDependent());
2798 }
2799 
2800 static Expr *getExprAsWritten(Expr *E) {
2801   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2802     E = ExprTemp->getSubExpr();
2803 
2804   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2805     E = MTE->GetTemporaryExpr();
2806 
2807   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2808     E = Binder->getSubExpr();
2809 
2810   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2811     E = ICE->getSubExprAsWritten();
2812   return E->IgnoreParens();
2813 }
2814 
2815 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2816                                                  Expr *NewLCRefExpr,
2817                                                  Expr *NewLB) {
2818   // State consistency checking to ensure correct usage.
2819   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
2820          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2821   if (!NewLCDecl || !NewLB)
2822     return true;
2823   LCDecl = getCanonicalDecl(NewLCDecl);
2824   LCRef = NewLCRefExpr;
2825   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2826     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2827       if ((Ctor->isCopyOrMoveConstructor() ||
2828            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2829           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2830         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2831   LB = NewLB;
2832   return false;
2833 }
2834 
2835 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2836                                         SourceRange SR, SourceLocation SL) {
2837   // State consistency checking to ensure correct usage.
2838   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2839          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2840   if (!NewUB)
2841     return true;
2842   UB = NewUB;
2843   TestIsLessOp = LessOp;
2844   TestIsStrictOp = StrictOp;
2845   ConditionSrcRange = SR;
2846   ConditionLoc = SL;
2847   return false;
2848 }
2849 
2850 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2851   // State consistency checking to ensure correct usage.
2852   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
2853   if (!NewStep)
2854     return true;
2855   if (!NewStep->isValueDependent()) {
2856     // Check that the step is integer expression.
2857     SourceLocation StepLoc = NewStep->getLocStart();
2858     ExprResult Val =
2859         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2860     if (Val.isInvalid())
2861       return true;
2862     NewStep = Val.get();
2863 
2864     // OpenMP [2.6, Canonical Loop Form, Restrictions]
2865     //  If test-expr is of form var relational-op b and relational-op is < or
2866     //  <= then incr-expr must cause var to increase on each iteration of the
2867     //  loop. If test-expr is of form var relational-op b and relational-op is
2868     //  > or >= then incr-expr must cause var to decrease on each iteration of
2869     //  the loop.
2870     //  If test-expr is of form b relational-op var and relational-op is < or
2871     //  <= then incr-expr must cause var to decrease on each iteration of the
2872     //  loop. If test-expr is of form b relational-op var and relational-op is
2873     //  > or >= then incr-expr must cause var to increase on each iteration of
2874     //  the loop.
2875     llvm::APSInt Result;
2876     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2877     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2878     bool IsConstNeg =
2879         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2880     bool IsConstPos =
2881         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2882     bool IsConstZero = IsConstant && !Result.getBoolValue();
2883     if (UB && (IsConstZero ||
2884                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2885                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
2886       SemaRef.Diag(NewStep->getExprLoc(),
2887                    diag::err_omp_loop_incr_not_compatible)
2888           << LCDecl << TestIsLessOp << NewStep->getSourceRange();
2889       SemaRef.Diag(ConditionLoc,
2890                    diag::note_omp_loop_cond_requres_compatible_incr)
2891           << TestIsLessOp << ConditionSrcRange;
2892       return true;
2893     }
2894     if (TestIsLessOp == Subtract) {
2895       NewStep =
2896           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
2897               .get();
2898       Subtract = !Subtract;
2899     }
2900   }
2901 
2902   Step = NewStep;
2903   SubtractStep = Subtract;
2904   return false;
2905 }
2906 
2907 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2908   // Check init-expr for canonical loop form and save loop counter
2909   // variable - #Var and its initialization value - #LB.
2910   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2911   //   var = lb
2912   //   integer-type var = lb
2913   //   random-access-iterator-type var = lb
2914   //   pointer-type var = lb
2915   //
2916   if (!S) {
2917     if (EmitDiags) {
2918       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2919     }
2920     return true;
2921   }
2922   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
2923     if (!ExprTemp->cleanupsHaveSideEffects())
2924       S = ExprTemp->getSubExpr();
2925 
2926   InitSrcRange = S->getSourceRange();
2927   if (Expr *E = dyn_cast<Expr>(S))
2928     S = E->IgnoreParens();
2929   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
2930     if (BO->getOpcode() == BO_Assign) {
2931       auto *LHS = BO->getLHS()->IgnoreParens();
2932       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2933         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2934           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2935             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2936         return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
2937       }
2938       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2939         if (ME->isArrow() &&
2940             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2941           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2942       }
2943     }
2944   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
2945     if (DS->isSingleDecl()) {
2946       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2947         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2948           // Accept non-canonical init form here but emit ext. warning.
2949           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2950             SemaRef.Diag(S->getLocStart(),
2951                          diag::ext_omp_loop_not_canonical_init)
2952                 << S->getSourceRange();
2953           return SetLCDeclAndLB(Var, nullptr, Var->getInit());
2954         }
2955       }
2956     }
2957   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2958     if (CE->getOperator() == OO_Equal) {
2959       auto *LHS = CE->getArg(0);
2960       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
2961         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
2962           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2963             return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2964         return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
2965       }
2966       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
2967         if (ME->isArrow() &&
2968             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
2969           return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
2970       }
2971     }
2972   }
2973 
2974   if (Dependent() || SemaRef.CurContext->isDependentContext())
2975     return false;
2976   if (EmitDiags) {
2977     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2978         << S->getSourceRange();
2979   }
2980   return true;
2981 }
2982 
2983 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2984 /// variable (which may be the loop variable) if possible.
2985 static const ValueDecl *GetInitLCDecl(Expr *E) {
2986   if (!E)
2987     return nullptr;
2988   E = getExprAsWritten(E);
2989   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2990     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2991       if ((Ctor->isCopyOrMoveConstructor() ||
2992            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2993           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2994         E = CE->getArg(0)->IgnoreParenImpCasts();
2995   if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
2996     if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2997       if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2998         if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
2999           return getCanonicalDecl(ME->getMemberDecl());
3000       return getCanonicalDecl(VD);
3001     }
3002   }
3003   if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3004     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3005       return getCanonicalDecl(ME->getMemberDecl());
3006   return nullptr;
3007 }
3008 
3009 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3010   // Check test-expr for canonical form, save upper-bound UB, flags for
3011   // less/greater and for strict/non-strict comparison.
3012   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3013   //   var relational-op b
3014   //   b relational-op var
3015   //
3016   if (!S) {
3017     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
3018     return true;
3019   }
3020   S = getExprAsWritten(S);
3021   SourceLocation CondLoc = S->getLocStart();
3022   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3023     if (BO->isRelationalOp()) {
3024       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3025         return SetUB(BO->getRHS(),
3026                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3027                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3028                      BO->getSourceRange(), BO->getOperatorLoc());
3029       if (GetInitLCDecl(BO->getRHS()) == LCDecl)
3030         return SetUB(BO->getLHS(),
3031                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3032                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3033                      BO->getSourceRange(), BO->getOperatorLoc());
3034     }
3035   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3036     if (CE->getNumArgs() == 2) {
3037       auto Op = CE->getOperator();
3038       switch (Op) {
3039       case OO_Greater:
3040       case OO_GreaterEqual:
3041       case OO_Less:
3042       case OO_LessEqual:
3043         if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3044           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3045                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3046                        CE->getOperatorLoc());
3047         if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
3048           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3049                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3050                        CE->getOperatorLoc());
3051         break;
3052       default:
3053         break;
3054       }
3055     }
3056   }
3057   if (Dependent() || SemaRef.CurContext->isDependentContext())
3058     return false;
3059   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3060       << S->getSourceRange() << LCDecl;
3061   return true;
3062 }
3063 
3064 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3065   // RHS of canonical loop form increment can be:
3066   //   var + incr
3067   //   incr + var
3068   //   var - incr
3069   //
3070   RHS = RHS->IgnoreParenImpCasts();
3071   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
3072     if (BO->isAdditiveOp()) {
3073       bool IsAdd = BO->getOpcode() == BO_Add;
3074       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3075         return SetStep(BO->getRHS(), !IsAdd);
3076       if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
3077         return SetStep(BO->getLHS(), false);
3078     }
3079   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3080     bool IsAdd = CE->getOperator() == OO_Plus;
3081     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3082       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3083         return SetStep(CE->getArg(1), !IsAdd);
3084       if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
3085         return SetStep(CE->getArg(0), false);
3086     }
3087   }
3088   if (Dependent() || SemaRef.CurContext->isDependentContext())
3089     return false;
3090   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3091       << RHS->getSourceRange() << LCDecl;
3092   return true;
3093 }
3094 
3095 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3096   // Check incr-expr for canonical loop form and return true if it
3097   // does not conform.
3098   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3099   //   ++var
3100   //   var++
3101   //   --var
3102   //   var--
3103   //   var += incr
3104   //   var -= incr
3105   //   var = var + incr
3106   //   var = incr + var
3107   //   var = var - incr
3108   //
3109   if (!S) {
3110     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
3111     return true;
3112   }
3113   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3114     if (!ExprTemp->cleanupsHaveSideEffects())
3115       S = ExprTemp->getSubExpr();
3116 
3117   IncrementSrcRange = S->getSourceRange();
3118   S = S->IgnoreParens();
3119   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
3120     if (UO->isIncrementDecrementOp() &&
3121         GetInitLCDecl(UO->getSubExpr()) == LCDecl)
3122       return SetStep(SemaRef
3123                          .ActOnIntegerConstant(UO->getLocStart(),
3124                                                (UO->isDecrementOp() ? -1 : 1))
3125                          .get(),
3126                      false);
3127   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
3128     switch (BO->getOpcode()) {
3129     case BO_AddAssign:
3130     case BO_SubAssign:
3131       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3132         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3133       break;
3134     case BO_Assign:
3135       if (GetInitLCDecl(BO->getLHS()) == LCDecl)
3136         return CheckIncRHS(BO->getRHS());
3137       break;
3138     default:
3139       break;
3140     }
3141   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3142     switch (CE->getOperator()) {
3143     case OO_PlusPlus:
3144     case OO_MinusMinus:
3145       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3146         return SetStep(SemaRef
3147                            .ActOnIntegerConstant(
3148                                CE->getLocStart(),
3149                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3150                            .get(),
3151                        false);
3152       break;
3153     case OO_PlusEqual:
3154     case OO_MinusEqual:
3155       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3156         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3157       break;
3158     case OO_Equal:
3159       if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
3160         return CheckIncRHS(CE->getArg(1));
3161       break;
3162     default:
3163       break;
3164     }
3165   }
3166   if (Dependent() || SemaRef.CurContext->isDependentContext())
3167     return false;
3168   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3169       << S->getSourceRange() << LCDecl;
3170   return true;
3171 }
3172 
3173 static ExprResult
3174 tryBuildCapture(Sema &SemaRef, Expr *Capture,
3175                 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3176   if (SemaRef.CurContext->isDependentContext())
3177     return ExprResult(Capture);
3178   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3179     return SemaRef.PerformImplicitConversion(
3180         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3181         /*AllowExplicit=*/true);
3182   auto I = Captures.find(Capture);
3183   if (I != Captures.end())
3184     return buildCapture(SemaRef, Capture, I->second);
3185   DeclRefExpr *Ref = nullptr;
3186   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3187   Captures[Capture] = Ref;
3188   return Res;
3189 }
3190 
3191 /// \brief Build the expression to calculate the number of iterations.
3192 Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3193     Scope *S, const bool LimitedType,
3194     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3195   ExprResult Diff;
3196   auto VarType = LCDecl->getType().getNonReferenceType();
3197   if (VarType->isIntegerType() || VarType->isPointerType() ||
3198       SemaRef.getLangOpts().CPlusPlus) {
3199     // Upper - Lower
3200     auto *UBExpr = TestIsLessOp ? UB : LB;
3201     auto *LBExpr = TestIsLessOp ? LB : UB;
3202     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3203     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
3204     if (!Upper || !Lower)
3205       return nullptr;
3206 
3207     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3208 
3209     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3210       // BuildBinOp already emitted error, this one is to point user to upper
3211       // and lower bound, and to tell what is passed to 'operator-'.
3212       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3213           << Upper->getSourceRange() << Lower->getSourceRange();
3214       return nullptr;
3215     }
3216   }
3217 
3218   if (!Diff.isUsable())
3219     return nullptr;
3220 
3221   // Upper - Lower [- 1]
3222   if (TestIsStrictOp)
3223     Diff = SemaRef.BuildBinOp(
3224         S, DefaultLoc, BO_Sub, Diff.get(),
3225         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3226   if (!Diff.isUsable())
3227     return nullptr;
3228 
3229   // Upper - Lower [- 1] + Step
3230   auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3231   if (!NewStep.isUsable())
3232     return nullptr;
3233   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3234   if (!Diff.isUsable())
3235     return nullptr;
3236 
3237   // Parentheses (for dumping/debugging purposes only).
3238   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3239   if (!Diff.isUsable())
3240     return nullptr;
3241 
3242   // (Upper - Lower [- 1] + Step) / Step
3243   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3244   if (!Diff.isUsable())
3245     return nullptr;
3246 
3247   // OpenMP runtime requires 32-bit or 64-bit loop variables.
3248   QualType Type = Diff.get()->getType();
3249   auto &C = SemaRef.Context;
3250   bool UseVarType = VarType->hasIntegerRepresentation() &&
3251                     C.getTypeSize(Type) > C.getTypeSize(VarType);
3252   if (!Type->isIntegerType() || UseVarType) {
3253     unsigned NewSize =
3254         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3255     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3256                                : Type->hasSignedIntegerRepresentation();
3257     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3258     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3259       Diff = SemaRef.PerformImplicitConversion(
3260           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3261       if (!Diff.isUsable())
3262         return nullptr;
3263     }
3264   }
3265   if (LimitedType) {
3266     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3267     if (NewSize != C.getTypeSize(Type)) {
3268       if (NewSize < C.getTypeSize(Type)) {
3269         assert(NewSize == 64 && "incorrect loop var size");
3270         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3271             << InitSrcRange << ConditionSrcRange;
3272       }
3273       QualType NewType = C.getIntTypeForBitwidth(
3274           NewSize, Type->hasSignedIntegerRepresentation() ||
3275                        C.getTypeSize(Type) < NewSize);
3276       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3277         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3278                                                  Sema::AA_Converting, true);
3279         if (!Diff.isUsable())
3280           return nullptr;
3281       }
3282     }
3283   }
3284 
3285   return Diff.get();
3286 }
3287 
3288 Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3289     Scope *S, Expr *Cond,
3290     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
3291   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3292   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3293   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3294 
3295   auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3296   auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3297   if (!NewLB.isUsable() || !NewUB.isUsable())
3298     return nullptr;
3299 
3300   auto CondExpr = SemaRef.BuildBinOp(
3301       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3302                                   : (TestIsStrictOp ? BO_GT : BO_GE),
3303       NewLB.get(), NewUB.get());
3304   if (CondExpr.isUsable()) {
3305     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3306                                                 SemaRef.Context.BoolTy))
3307       CondExpr = SemaRef.PerformImplicitConversion(
3308           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3309           /*AllowExplicit=*/true);
3310   }
3311   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3312   // Otherwise use original loop conditon and evaluate it in runtime.
3313   return CondExpr.isUsable() ? CondExpr.get() : Cond;
3314 }
3315 
3316 /// \brief Build reference expression to the counter be used for codegen.
3317 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
3318     llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
3319   auto *VD = dyn_cast<VarDecl>(LCDecl);
3320   if (!VD) {
3321     VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3322     auto *Ref = buildDeclRefExpr(
3323         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
3324     DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3325     // If the loop control decl is explicitly marked as private, do not mark it
3326     // as captured again.
3327     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3328       Captures.insert(std::make_pair(LCRef, Ref));
3329     return Ref;
3330   }
3331   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
3332                           DefaultLoc);
3333 }
3334 
3335 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3336   if (LCDecl && !LCDecl->isInvalidDecl()) {
3337     auto Type = LCDecl->getType().getNonReferenceType();
3338     auto *PrivateVar =
3339         buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3340                      LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
3341     if (PrivateVar->isInvalidDecl())
3342       return nullptr;
3343     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3344   }
3345   return nullptr;
3346 }
3347 
3348 /// \brief Build instillation of the counter be used for codegen.
3349 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3350 
3351 /// \brief Build step of the counter be used for codegen.
3352 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3353 
3354 /// \brief Iteration space of a single for loop.
3355 struct LoopIterationSpace final {
3356   /// \brief Condition of the loop.
3357   Expr *PreCond = nullptr;
3358   /// \brief This expression calculates the number of iterations in the loop.
3359   /// It is always possible to calculate it before starting the loop.
3360   Expr *NumIterations = nullptr;
3361   /// \brief The loop counter variable.
3362   Expr *CounterVar = nullptr;
3363   /// \brief Private loop counter variable.
3364   Expr *PrivateCounterVar = nullptr;
3365   /// \brief This is initializer for the initial value of #CounterVar.
3366   Expr *CounterInit = nullptr;
3367   /// \brief This is step for the #CounterVar used to generate its update:
3368   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3369   Expr *CounterStep = nullptr;
3370   /// \brief Should step be subtracted?
3371   bool Subtract = false;
3372   /// \brief Source range of the loop init.
3373   SourceRange InitSrcRange;
3374   /// \brief Source range of the loop condition.
3375   SourceRange CondSrcRange;
3376   /// \brief Source range of the loop increment.
3377   SourceRange IncSrcRange;
3378 };
3379 
3380 } // namespace
3381 
3382 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3383   assert(getLangOpts().OpenMP && "OpenMP is not active.");
3384   assert(Init && "Expected loop in canonical form.");
3385   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3386   if (AssociatedLoops > 0 &&
3387       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3388     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3389     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3390       if (auto *D = ISC.GetLoopDecl()) {
3391         auto *VD = dyn_cast<VarDecl>(D);
3392         if (!VD) {
3393           if (auto *Private = IsOpenMPCapturedDecl(D))
3394             VD = Private;
3395           else {
3396             auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3397                                      /*WithInit=*/false);
3398             VD = cast<VarDecl>(Ref->getDecl());
3399           }
3400         }
3401         DSAStack->addLoopControlVariable(D, VD);
3402       }
3403     }
3404     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3405   }
3406 }
3407 
3408 /// \brief Called on a for stmt to check and extract its iteration space
3409 /// for further processing (such as collapsing).
3410 static bool CheckOpenMPIterationSpace(
3411     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3412     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3413     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3414     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3415     LoopIterationSpace &ResultIterSpace,
3416     llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3417   // OpenMP [2.6, Canonical Loop Form]
3418   //   for (init-expr; test-expr; incr-expr) structured-block
3419   auto *For = dyn_cast_or_null<ForStmt>(S);
3420   if (!For) {
3421     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3422         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3423         << getOpenMPDirectiveName(DKind) << NestedLoopCount
3424         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3425     if (NestedLoopCount > 1) {
3426       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3427         SemaRef.Diag(DSA.getConstructLoc(),
3428                      diag::note_omp_collapse_ordered_expr)
3429             << 2 << CollapseLoopCountExpr->getSourceRange()
3430             << OrderedLoopCountExpr->getSourceRange();
3431       else if (CollapseLoopCountExpr)
3432         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3433                      diag::note_omp_collapse_ordered_expr)
3434             << 0 << CollapseLoopCountExpr->getSourceRange();
3435       else
3436         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3437                      diag::note_omp_collapse_ordered_expr)
3438             << 1 << OrderedLoopCountExpr->getSourceRange();
3439     }
3440     return true;
3441   }
3442   assert(For->getBody());
3443 
3444   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3445 
3446   // Check init.
3447   auto Init = For->getInit();
3448   if (ISC.CheckInit(Init))
3449     return true;
3450 
3451   bool HasErrors = false;
3452 
3453   // Check loop variable's type.
3454   if (auto *LCDecl = ISC.GetLoopDecl()) {
3455     auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
3456 
3457     // OpenMP [2.6, Canonical Loop Form]
3458     // Var is one of the following:
3459     //   A variable of signed or unsigned integer type.
3460     //   For C++, a variable of a random access iterator type.
3461     //   For C, a variable of a pointer type.
3462     auto VarType = LCDecl->getType().getNonReferenceType();
3463     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3464         !VarType->isPointerType() &&
3465         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3466       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3467           << SemaRef.getLangOpts().CPlusPlus;
3468       HasErrors = true;
3469     }
3470 
3471     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3472     // a Construct
3473     // The loop iteration variable(s) in the associated for-loop(s) of a for or
3474     // parallel for construct is (are) private.
3475     // The loop iteration variable in the associated for-loop of a simd
3476     // construct with just one associated for-loop is linear with a
3477     // constant-linear-step that is the increment of the associated for-loop.
3478     // Exclude loop var from the list of variables with implicitly defined data
3479     // sharing attributes.
3480     VarsWithImplicitDSA.erase(LCDecl);
3481 
3482     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3483     // in a Construct, C/C++].
3484     // The loop iteration variable in the associated for-loop of a simd
3485     // construct with just one associated for-loop may be listed in a linear
3486     // clause with a constant-linear-step that is the increment of the
3487     // associated for-loop.
3488     // The loop iteration variable(s) in the associated for-loop(s) of a for or
3489     // parallel for construct may be listed in a private or lastprivate clause.
3490     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3491     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3492     // declared in the loop and it is predetermined as a private.
3493     auto PredeterminedCKind =
3494         isOpenMPSimdDirective(DKind)
3495             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3496             : OMPC_private;
3497     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3498           DVar.CKind != PredeterminedCKind) ||
3499          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3500            isOpenMPDistributeDirective(DKind)) &&
3501           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3502           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3503         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3504       SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3505           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3506           << getOpenMPClauseName(PredeterminedCKind);
3507       if (DVar.RefExpr == nullptr)
3508         DVar.CKind = PredeterminedCKind;
3509       ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3510       HasErrors = true;
3511     } else if (LoopDeclRefExpr != nullptr) {
3512       // Make the loop iteration variable private (for worksharing constructs),
3513       // linear (for simd directives with the only one associated loop) or
3514       // lastprivate (for simd directives with several collapsed or ordered
3515       // loops).
3516       if (DVar.CKind == OMPC_unknown)
3517         DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3518                           [](OpenMPDirectiveKind) -> bool { return true; },
3519                           /*FromParent=*/false);
3520       DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3521     }
3522 
3523     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3524 
3525     // Check test-expr.
3526     HasErrors |= ISC.CheckCond(For->getCond());
3527 
3528     // Check incr-expr.
3529     HasErrors |= ISC.CheckInc(For->getInc());
3530   }
3531 
3532   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3533     return HasErrors;
3534 
3535   // Build the loop's iteration space representation.
3536   ResultIterSpace.PreCond =
3537       ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
3538   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3539       DSA.getCurScope(),
3540       (isOpenMPWorksharingDirective(DKind) ||
3541        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3542       Captures);
3543   ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
3544   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3545   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3546   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3547   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3548   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3549   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3550   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3551 
3552   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3553                 ResultIterSpace.NumIterations == nullptr ||
3554                 ResultIterSpace.CounterVar == nullptr ||
3555                 ResultIterSpace.PrivateCounterVar == nullptr ||
3556                 ResultIterSpace.CounterInit == nullptr ||
3557                 ResultIterSpace.CounterStep == nullptr);
3558 
3559   return HasErrors;
3560 }
3561 
3562 /// \brief Build 'VarRef = Start.
3563 static ExprResult
3564 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3565                  ExprResult Start,
3566                  llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3567   // Build 'VarRef = Start.
3568   auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3569   if (!NewStart.isUsable())
3570     return ExprError();
3571   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
3572                                    VarRef.get()->getType())) {
3573     NewStart = SemaRef.PerformImplicitConversion(
3574         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3575         /*AllowExplicit=*/true);
3576     if (!NewStart.isUsable())
3577       return ExprError();
3578   }
3579 
3580   auto Init =
3581       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3582   return Init;
3583 }
3584 
3585 /// \brief Build 'VarRef = Start + Iter * Step'.
3586 static ExprResult
3587 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3588                    ExprResult VarRef, ExprResult Start, ExprResult Iter,
3589                    ExprResult Step, bool Subtract,
3590                    llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
3591   // Add parentheses (for debugging purposes only).
3592   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3593   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3594       !Step.isUsable())
3595     return ExprError();
3596 
3597   ExprResult NewStep = Step;
3598   if (Captures)
3599     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
3600   if (NewStep.isInvalid())
3601     return ExprError();
3602   ExprResult Update =
3603       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3604   if (!Update.isUsable())
3605     return ExprError();
3606 
3607   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3608   // 'VarRef = Start (+|-) Iter * Step'.
3609   ExprResult NewStart = Start;
3610   if (Captures)
3611     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
3612   if (NewStart.isInvalid())
3613     return ExprError();
3614 
3615   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3616   ExprResult SavedUpdate = Update;
3617   ExprResult UpdateVal;
3618   if (VarRef.get()->getType()->isOverloadableType() ||
3619       NewStart.get()->getType()->isOverloadableType() ||
3620       Update.get()->getType()->isOverloadableType()) {
3621     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3622     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3623     Update =
3624         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3625     if (Update.isUsable()) {
3626       UpdateVal =
3627           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3628                              VarRef.get(), SavedUpdate.get());
3629       if (UpdateVal.isUsable()) {
3630         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3631                                             UpdateVal.get());
3632       }
3633     }
3634     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3635   }
3636 
3637   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3638   if (!Update.isUsable() || !UpdateVal.isUsable()) {
3639     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3640                                 NewStart.get(), SavedUpdate.get());
3641     if (!Update.isUsable())
3642       return ExprError();
3643 
3644     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3645                                      VarRef.get()->getType())) {
3646       Update = SemaRef.PerformImplicitConversion(
3647           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3648       if (!Update.isUsable())
3649         return ExprError();
3650     }
3651 
3652     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3653   }
3654   return Update;
3655 }
3656 
3657 /// \brief Convert integer expression \a E to make it have at least \a Bits
3658 /// bits.
3659 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
3660   if (E == nullptr)
3661     return ExprError();
3662   auto &C = SemaRef.Context;
3663   QualType OldType = E->getType();
3664   unsigned HasBits = C.getTypeSize(OldType);
3665   if (HasBits >= Bits)
3666     return ExprResult(E);
3667   // OK to convert to signed, because new type has more bits than old.
3668   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3669   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3670                                            true);
3671 }
3672 
3673 /// \brief Check if the given expression \a E is a constant integer that fits
3674 /// into \a Bits bits.
3675 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3676   if (E == nullptr)
3677     return false;
3678   llvm::APSInt Result;
3679   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3680     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3681   return false;
3682 }
3683 
3684 /// Build preinits statement for the given declarations.
3685 static Stmt *buildPreInits(ASTContext &Context,
3686                            SmallVectorImpl<Decl *> &PreInits) {
3687   if (!PreInits.empty()) {
3688     return new (Context) DeclStmt(
3689         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3690         SourceLocation(), SourceLocation());
3691   }
3692   return nullptr;
3693 }
3694 
3695 /// Build preinits statement for the given declarations.
3696 static Stmt *buildPreInits(ASTContext &Context,
3697                            llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3698   if (!Captures.empty()) {
3699     SmallVector<Decl *, 16> PreInits;
3700     for (auto &Pair : Captures)
3701       PreInits.push_back(Pair.second->getDecl());
3702     return buildPreInits(Context, PreInits);
3703   }
3704   return nullptr;
3705 }
3706 
3707 /// Build postupdate expression for the given list of postupdates expressions.
3708 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3709   Expr *PostUpdate = nullptr;
3710   if (!PostUpdates.empty()) {
3711     for (auto *E : PostUpdates) {
3712       Expr *ConvE = S.BuildCStyleCastExpr(
3713                          E->getExprLoc(),
3714                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3715                          E->getExprLoc(), E)
3716                         .get();
3717       PostUpdate = PostUpdate
3718                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3719                                               PostUpdate, ConvE)
3720                              .get()
3721                        : ConvE;
3722     }
3723   }
3724   return PostUpdate;
3725 }
3726 
3727 /// \brief Called on a for stmt to check itself and nested loops (if any).
3728 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3729 /// number of collapsed loops otherwise.
3730 static unsigned
3731 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3732                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3733                 DSAStackTy &DSA,
3734                 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
3735                 OMPLoopDirective::HelperExprs &Built) {
3736   unsigned NestedLoopCount = 1;
3737   if (CollapseLoopCountExpr) {
3738     // Found 'collapse' clause - calculate collapse number.
3739     llvm::APSInt Result;
3740     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3741       NestedLoopCount = Result.getLimitedValue();
3742   }
3743   if (OrderedLoopCountExpr) {
3744     // Found 'ordered' clause - calculate collapse number.
3745     llvm::APSInt Result;
3746     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3747       if (Result.getLimitedValue() < NestedLoopCount) {
3748         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3749                      diag::err_omp_wrong_ordered_loop_count)
3750             << OrderedLoopCountExpr->getSourceRange();
3751         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3752                      diag::note_collapse_loop_count)
3753             << CollapseLoopCountExpr->getSourceRange();
3754       }
3755       NestedLoopCount = Result.getLimitedValue();
3756     }
3757   }
3758   // This is helper routine for loop directives (e.g., 'for', 'simd',
3759   // 'for simd', etc.).
3760   llvm::MapVector<Expr *, DeclRefExpr *> Captures;
3761   SmallVector<LoopIterationSpace, 4> IterSpaces;
3762   IterSpaces.resize(NestedLoopCount);
3763   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3764   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3765     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3766                                   NestedLoopCount, CollapseLoopCountExpr,
3767                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
3768                                   IterSpaces[Cnt], Captures))
3769       return 0;
3770     // Move on to the next nested for loop, or to the loop body.
3771     // OpenMP [2.8.1, simd construct, Restrictions]
3772     // All loops associated with the construct must be perfectly nested; that
3773     // is, there must be no intervening code nor any OpenMP directive between
3774     // any two loops.
3775     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3776   }
3777 
3778   Built.clear(/* size */ NestedLoopCount);
3779 
3780   if (SemaRef.CurContext->isDependentContext())
3781     return NestedLoopCount;
3782 
3783   // An example of what is generated for the following code:
3784   //
3785   //   #pragma omp simd collapse(2) ordered(2)
3786   //   for (i = 0; i < NI; ++i)
3787   //     for (k = 0; k < NK; ++k)
3788   //       for (j = J0; j < NJ; j+=2) {
3789   //         <loop body>
3790   //       }
3791   //
3792   // We generate the code below.
3793   // Note: the loop body may be outlined in CodeGen.
3794   // Note: some counters may be C++ classes, operator- is used to find number of
3795   // iterations and operator+= to calculate counter value.
3796   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3797   // or i64 is currently supported).
3798   //
3799   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3800   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3801   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3802   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3803   //     // similar updates for vars in clauses (e.g. 'linear')
3804   //     <loop body (using local i and j)>
3805   //   }
3806   //   i = NI; // assign final values of counters
3807   //   j = NJ;
3808   //
3809 
3810   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3811   // the iteration counts of the collapsed for loops.
3812   // Precondition tests if there is at least one iteration (all conditions are
3813   // true).
3814   auto PreCond = ExprResult(IterSpaces[0].PreCond);
3815   auto N0 = IterSpaces[0].NumIterations;
3816   ExprResult LastIteration32 = WidenIterationCount(
3817       32 /* Bits */, SemaRef
3818                          .PerformImplicitConversion(
3819                              N0->IgnoreImpCasts(), N0->getType(),
3820                              Sema::AA_Converting, /*AllowExplicit=*/true)
3821                          .get(),
3822       SemaRef);
3823   ExprResult LastIteration64 = WidenIterationCount(
3824       64 /* Bits */, SemaRef
3825                          .PerformImplicitConversion(
3826                              N0->IgnoreImpCasts(), N0->getType(),
3827                              Sema::AA_Converting, /*AllowExplicit=*/true)
3828                          .get(),
3829       SemaRef);
3830 
3831   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3832     return NestedLoopCount;
3833 
3834   auto &C = SemaRef.Context;
3835   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3836 
3837   Scope *CurScope = DSA.getCurScope();
3838   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3839     if (PreCond.isUsable()) {
3840       PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3841                                    PreCond.get(), IterSpaces[Cnt].PreCond);
3842     }
3843     auto N = IterSpaces[Cnt].NumIterations;
3844     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3845     if (LastIteration32.isUsable())
3846       LastIteration32 = SemaRef.BuildBinOp(
3847           CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3848           SemaRef
3849               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3850                                          Sema::AA_Converting,
3851                                          /*AllowExplicit=*/true)
3852               .get());
3853     if (LastIteration64.isUsable())
3854       LastIteration64 = SemaRef.BuildBinOp(
3855           CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3856           SemaRef
3857               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3858                                          Sema::AA_Converting,
3859                                          /*AllowExplicit=*/true)
3860               .get());
3861   }
3862 
3863   // Choose either the 32-bit or 64-bit version.
3864   ExprResult LastIteration = LastIteration64;
3865   if (LastIteration32.isUsable() &&
3866       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3867       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3868        FitsInto(
3869            32 /* Bits */,
3870            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3871            LastIteration64.get(), SemaRef)))
3872     LastIteration = LastIteration32;
3873   QualType VType = LastIteration.get()->getType();
3874   QualType RealVType = VType;
3875   QualType StrideVType = VType;
3876   if (isOpenMPTaskLoopDirective(DKind)) {
3877     VType =
3878         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3879     StrideVType =
3880         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3881   }
3882 
3883   if (!LastIteration.isUsable())
3884     return 0;
3885 
3886   // Save the number of iterations.
3887   ExprResult NumIterations = LastIteration;
3888   {
3889     LastIteration = SemaRef.BuildBinOp(
3890         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3891         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3892     if (!LastIteration.isUsable())
3893       return 0;
3894   }
3895 
3896   // Calculate the last iteration number beforehand instead of doing this on
3897   // each iteration. Do not do this if the number of iterations may be kfold-ed.
3898   llvm::APSInt Result;
3899   bool IsConstant =
3900       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3901   ExprResult CalcLastIteration;
3902   if (!IsConstant) {
3903     ExprResult SaveRef =
3904         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
3905     LastIteration = SaveRef;
3906 
3907     // Prepare SaveRef + 1.
3908     NumIterations = SemaRef.BuildBinOp(
3909         CurScope, SourceLocation(), BO_Add, SaveRef.get(),
3910         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3911     if (!NumIterations.isUsable())
3912       return 0;
3913   }
3914 
3915   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3916 
3917   // Build variables passed into runtime, necessary for worksharing directives.
3918   ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
3919   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3920       isOpenMPDistributeDirective(DKind)) {
3921     // Lower bound variable, initialized with zero.
3922     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3923     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3924     SemaRef.AddInitializerToDecl(
3925         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3926         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3927 
3928     // Upper bound variable, initialized with last iteration number.
3929     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3930     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3931     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3932                                  /*DirectInit*/ false,
3933                                  /*TypeMayContainAuto*/ false);
3934 
3935     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3936     // This will be used to implement clause 'lastprivate'.
3937     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3938     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3939     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3940     SemaRef.AddInitializerToDecl(
3941         ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3942         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3943 
3944     // Stride variable returned by runtime (we initialize it to 1 by default).
3945     VarDecl *STDecl =
3946         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
3947     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
3948     SemaRef.AddInitializerToDecl(
3949         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3950         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3951 
3952     // Build expression: UB = min(UB, LastIteration)
3953     // It is necessary for CodeGen of directives with static scheduling.
3954     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3955                                                 UB.get(), LastIteration.get());
3956     ExprResult CondOp = SemaRef.ActOnConditionalOp(
3957         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3958     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3959                              CondOp.get());
3960     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3961 
3962     // If we have a combined directive that combines 'distribute', 'for' or
3963     // 'simd' we need to be able to access the bounds of the schedule of the
3964     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
3965     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
3966     if (isOpenMPLoopBoundSharingDirective(DKind)) {
3967       auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
3968 
3969       // We expect to have at least 2 more parameters than the 'parallel'
3970       // directive does - the lower and upper bounds of the previous schedule.
3971       assert(CD->getNumParams() >= 4 &&
3972              "Unexpected number of parameters in loop combined directive");
3973 
3974       // Set the proper type for the bounds given what we learned from the
3975       // enclosed loops.
3976       auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
3977       auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
3978 
3979       // Previous lower and upper bounds are obtained from the region
3980       // parameters.
3981       PrevLB =
3982           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
3983       PrevUB =
3984           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
3985     }
3986   }
3987 
3988   // Build the iteration variable and its initialization before loop.
3989   ExprResult IV;
3990   ExprResult Init;
3991   {
3992     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
3993     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
3994     Expr *RHS =
3995         (isOpenMPWorksharingDirective(DKind) ||
3996          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
3997             ? LB.get()
3998             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3999     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4000     Init = SemaRef.ActOnFinishFullExpr(Init.get());
4001   }
4002 
4003   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
4004   SourceLocation CondLoc;
4005   ExprResult Cond =
4006       (isOpenMPWorksharingDirective(DKind) ||
4007        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4008           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4009           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4010                                NumIterations.get());
4011 
4012   // Loop increment (IV = IV + 1)
4013   SourceLocation IncLoc;
4014   ExprResult Inc =
4015       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4016                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4017   if (!Inc.isUsable())
4018     return 0;
4019   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
4020   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4021   if (!Inc.isUsable())
4022     return 0;
4023 
4024   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4025   // Used for directives with static scheduling.
4026   ExprResult NextLB, NextUB;
4027   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4028       isOpenMPDistributeDirective(DKind)) {
4029     // LB + ST
4030     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4031     if (!NextLB.isUsable())
4032       return 0;
4033     // LB = LB + ST
4034     NextLB =
4035         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4036     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4037     if (!NextLB.isUsable())
4038       return 0;
4039     // UB + ST
4040     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4041     if (!NextUB.isUsable())
4042       return 0;
4043     // UB = UB + ST
4044     NextUB =
4045         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4046     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4047     if (!NextUB.isUsable())
4048       return 0;
4049   }
4050 
4051   // Build updates and final values of the loop counters.
4052   bool HasErrors = false;
4053   Built.Counters.resize(NestedLoopCount);
4054   Built.Inits.resize(NestedLoopCount);
4055   Built.Updates.resize(NestedLoopCount);
4056   Built.Finals.resize(NestedLoopCount);
4057   SmallVector<Expr *, 4> LoopMultipliers;
4058   {
4059     ExprResult Div;
4060     // Go from inner nested loop to outer.
4061     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4062       LoopIterationSpace &IS = IterSpaces[Cnt];
4063       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4064       // Build: Iter = (IV / Div) % IS.NumIters
4065       // where Div is product of previous iterations' IS.NumIters.
4066       ExprResult Iter;
4067       if (Div.isUsable()) {
4068         Iter =
4069             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4070       } else {
4071         Iter = IV;
4072         assert((Cnt == (int)NestedLoopCount - 1) &&
4073                "unusable div expected on first iteration only");
4074       }
4075 
4076       if (Cnt != 0 && Iter.isUsable())
4077         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4078                                   IS.NumIterations);
4079       if (!Iter.isUsable()) {
4080         HasErrors = true;
4081         break;
4082       }
4083 
4084       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4085       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4086       auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4087                                           IS.CounterVar->getExprLoc(),
4088                                           /*RefersToCapture=*/true);
4089       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4090                                          IS.CounterInit, Captures);
4091       if (!Init.isUsable()) {
4092         HasErrors = true;
4093         break;
4094       }
4095       ExprResult Update = BuildCounterUpdate(
4096           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4097           IS.CounterStep, IS.Subtract, &Captures);
4098       if (!Update.isUsable()) {
4099         HasErrors = true;
4100         break;
4101       }
4102 
4103       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4104       ExprResult Final = BuildCounterUpdate(
4105           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4106           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
4107       if (!Final.isUsable()) {
4108         HasErrors = true;
4109         break;
4110       }
4111 
4112       // Build Div for the next iteration: Div <- Div * IS.NumIters
4113       if (Cnt != 0) {
4114         if (Div.isUnset())
4115           Div = IS.NumIterations;
4116         else
4117           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4118                                    IS.NumIterations);
4119 
4120         // Add parentheses (for debugging purposes only).
4121         if (Div.isUsable())
4122           Div = tryBuildCapture(SemaRef, Div.get(), Captures);
4123         if (!Div.isUsable()) {
4124           HasErrors = true;
4125           break;
4126         }
4127         LoopMultipliers.push_back(Div.get());
4128       }
4129       if (!Update.isUsable() || !Final.isUsable()) {
4130         HasErrors = true;
4131         break;
4132       }
4133       // Save results
4134       Built.Counters[Cnt] = IS.CounterVar;
4135       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4136       Built.Inits[Cnt] = Init.get();
4137       Built.Updates[Cnt] = Update.get();
4138       Built.Finals[Cnt] = Final.get();
4139     }
4140   }
4141 
4142   if (HasErrors)
4143     return 0;
4144 
4145   // Save results
4146   Built.IterationVarRef = IV.get();
4147   Built.LastIteration = LastIteration.get();
4148   Built.NumIterations = NumIterations.get();
4149   Built.CalcLastIteration =
4150       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4151   Built.PreCond = PreCond.get();
4152   Built.PreInits = buildPreInits(C, Captures);
4153   Built.Cond = Cond.get();
4154   Built.Init = Init.get();
4155   Built.Inc = Inc.get();
4156   Built.LB = LB.get();
4157   Built.UB = UB.get();
4158   Built.IL = IL.get();
4159   Built.ST = ST.get();
4160   Built.EUB = EUB.get();
4161   Built.NLB = NextLB.get();
4162   Built.NUB = NextUB.get();
4163   Built.PrevLB = PrevLB.get();
4164   Built.PrevUB = PrevUB.get();
4165 
4166   Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4167   // Fill data for doacross depend clauses.
4168   for (auto Pair : DSA.getDoacrossDependClauses()) {
4169     if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4170       Pair.first->setCounterValue(CounterVal);
4171     else {
4172       if (NestedLoopCount != Pair.second.size() ||
4173           NestedLoopCount != LoopMultipliers.size() + 1) {
4174         // Erroneous case - clause has some problems.
4175         Pair.first->setCounterValue(CounterVal);
4176         continue;
4177       }
4178       assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4179       auto I = Pair.second.rbegin();
4180       auto IS = IterSpaces.rbegin();
4181       auto ILM = LoopMultipliers.rbegin();
4182       Expr *UpCounterVal = CounterVal;
4183       Expr *Multiplier = nullptr;
4184       for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4185         if (I->first) {
4186           assert(IS->CounterStep);
4187           Expr *NormalizedOffset =
4188               SemaRef
4189                   .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4190                               I->first, IS->CounterStep)
4191                   .get();
4192           if (Multiplier) {
4193             NormalizedOffset =
4194                 SemaRef
4195                     .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4196                                 NormalizedOffset, Multiplier)
4197                     .get();
4198           }
4199           assert(I->second == OO_Plus || I->second == OO_Minus);
4200           BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
4201           UpCounterVal = SemaRef
4202                              .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4203                                          UpCounterVal, NormalizedOffset)
4204                              .get();
4205         }
4206         Multiplier = *ILM;
4207         ++I;
4208         ++IS;
4209         ++ILM;
4210       }
4211       Pair.first->setCounterValue(UpCounterVal);
4212     }
4213   }
4214 
4215   return NestedLoopCount;
4216 }
4217 
4218 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4219   auto CollapseClauses =
4220       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4221   if (CollapseClauses.begin() != CollapseClauses.end())
4222     return (*CollapseClauses.begin())->getNumForLoops();
4223   return nullptr;
4224 }
4225 
4226 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4227   auto OrderedClauses =
4228       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4229   if (OrderedClauses.begin() != OrderedClauses.end())
4230     return (*OrderedClauses.begin())->getNumForLoops();
4231   return nullptr;
4232 }
4233 
4234 static bool checkSimdlenSafelenSpecified(Sema &S,
4235                                          const ArrayRef<OMPClause *> Clauses) {
4236   OMPSafelenClause *Safelen = nullptr;
4237   OMPSimdlenClause *Simdlen = nullptr;
4238 
4239   for (auto *Clause : Clauses) {
4240     if (Clause->getClauseKind() == OMPC_safelen)
4241       Safelen = cast<OMPSafelenClause>(Clause);
4242     else if (Clause->getClauseKind() == OMPC_simdlen)
4243       Simdlen = cast<OMPSimdlenClause>(Clause);
4244     if (Safelen && Simdlen)
4245       break;
4246   }
4247 
4248   if (Simdlen && Safelen) {
4249     llvm::APSInt SimdlenRes, SafelenRes;
4250     auto SimdlenLength = Simdlen->getSimdlen();
4251     auto SafelenLength = Safelen->getSafelen();
4252     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4253         SimdlenLength->isInstantiationDependent() ||
4254         SimdlenLength->containsUnexpandedParameterPack())
4255       return false;
4256     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4257         SafelenLength->isInstantiationDependent() ||
4258         SafelenLength->containsUnexpandedParameterPack())
4259       return false;
4260     SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4261     SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4262     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4263     // If both simdlen and safelen clauses are specified, the value of the
4264     // simdlen parameter must be less than or equal to the value of the safelen
4265     // parameter.
4266     if (SimdlenRes > SafelenRes) {
4267       S.Diag(SimdlenLength->getExprLoc(),
4268              diag::err_omp_wrong_simdlen_safelen_values)
4269           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4270       return true;
4271     }
4272   }
4273   return false;
4274 }
4275 
4276 StmtResult Sema::ActOnOpenMPSimdDirective(
4277     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4278     SourceLocation EndLoc,
4279     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4280   if (!AStmt)
4281     return StmtError();
4282 
4283   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4284   OMPLoopDirective::HelperExprs B;
4285   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4286   // define the nested loops number.
4287   unsigned NestedLoopCount = CheckOpenMPLoop(
4288       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4289       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4290   if (NestedLoopCount == 0)
4291     return StmtError();
4292 
4293   assert((CurContext->isDependentContext() || B.builtAll()) &&
4294          "omp simd loop exprs were not built");
4295 
4296   if (!CurContext->isDependentContext()) {
4297     // Finalize the clauses that need pre-built expressions for CodeGen.
4298     for (auto C : Clauses) {
4299       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4300         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4301                                      B.NumIterations, *this, CurScope,
4302                                      DSAStack))
4303           return StmtError();
4304     }
4305   }
4306 
4307   if (checkSimdlenSafelenSpecified(*this, Clauses))
4308     return StmtError();
4309 
4310   getCurFunction()->setHasBranchProtectedScope();
4311   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4312                                   Clauses, AStmt, B);
4313 }
4314 
4315 StmtResult Sema::ActOnOpenMPForDirective(
4316     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4317     SourceLocation EndLoc,
4318     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4319   if (!AStmt)
4320     return StmtError();
4321 
4322   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4323   OMPLoopDirective::HelperExprs B;
4324   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4325   // define the nested loops number.
4326   unsigned NestedLoopCount = CheckOpenMPLoop(
4327       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4328       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4329   if (NestedLoopCount == 0)
4330     return StmtError();
4331 
4332   assert((CurContext->isDependentContext() || B.builtAll()) &&
4333          "omp for loop exprs were not built");
4334 
4335   if (!CurContext->isDependentContext()) {
4336     // Finalize the clauses that need pre-built expressions for CodeGen.
4337     for (auto C : Clauses) {
4338       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4339         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4340                                      B.NumIterations, *this, CurScope,
4341                                      DSAStack))
4342           return StmtError();
4343     }
4344   }
4345 
4346   getCurFunction()->setHasBranchProtectedScope();
4347   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4348                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
4349 }
4350 
4351 StmtResult Sema::ActOnOpenMPForSimdDirective(
4352     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4353     SourceLocation EndLoc,
4354     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4355   if (!AStmt)
4356     return StmtError();
4357 
4358   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4359   OMPLoopDirective::HelperExprs B;
4360   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4361   // define the nested loops number.
4362   unsigned NestedLoopCount =
4363       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4364                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4365                       VarsWithImplicitDSA, B);
4366   if (NestedLoopCount == 0)
4367     return StmtError();
4368 
4369   assert((CurContext->isDependentContext() || B.builtAll()) &&
4370          "omp for simd loop exprs were not built");
4371 
4372   if (!CurContext->isDependentContext()) {
4373     // Finalize the clauses that need pre-built expressions for CodeGen.
4374     for (auto C : Clauses) {
4375       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4376         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4377                                      B.NumIterations, *this, CurScope,
4378                                      DSAStack))
4379           return StmtError();
4380     }
4381   }
4382 
4383   if (checkSimdlenSafelenSpecified(*this, Clauses))
4384     return StmtError();
4385 
4386   getCurFunction()->setHasBranchProtectedScope();
4387   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4388                                      Clauses, AStmt, B);
4389 }
4390 
4391 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4392                                               Stmt *AStmt,
4393                                               SourceLocation StartLoc,
4394                                               SourceLocation EndLoc) {
4395   if (!AStmt)
4396     return StmtError();
4397 
4398   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4399   auto BaseStmt = AStmt;
4400   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4401     BaseStmt = CS->getCapturedStmt();
4402   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4403     auto S = C->children();
4404     if (S.begin() == S.end())
4405       return StmtError();
4406     // All associated statements must be '#pragma omp section' except for
4407     // the first one.
4408     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4409       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4410         if (SectionStmt)
4411           Diag(SectionStmt->getLocStart(),
4412                diag::err_omp_sections_substmt_not_section);
4413         return StmtError();
4414       }
4415       cast<OMPSectionDirective>(SectionStmt)
4416           ->setHasCancel(DSAStack->isCancelRegion());
4417     }
4418   } else {
4419     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4420     return StmtError();
4421   }
4422 
4423   getCurFunction()->setHasBranchProtectedScope();
4424 
4425   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4426                                       DSAStack->isCancelRegion());
4427 }
4428 
4429 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4430                                              SourceLocation StartLoc,
4431                                              SourceLocation EndLoc) {
4432   if (!AStmt)
4433     return StmtError();
4434 
4435   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4436 
4437   getCurFunction()->setHasBranchProtectedScope();
4438   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4439 
4440   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4441                                      DSAStack->isCancelRegion());
4442 }
4443 
4444 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4445                                             Stmt *AStmt,
4446                                             SourceLocation StartLoc,
4447                                             SourceLocation EndLoc) {
4448   if (!AStmt)
4449     return StmtError();
4450 
4451   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4452 
4453   getCurFunction()->setHasBranchProtectedScope();
4454 
4455   // OpenMP [2.7.3, single Construct, Restrictions]
4456   // The copyprivate clause must not be used with the nowait clause.
4457   OMPClause *Nowait = nullptr;
4458   OMPClause *Copyprivate = nullptr;
4459   for (auto *Clause : Clauses) {
4460     if (Clause->getClauseKind() == OMPC_nowait)
4461       Nowait = Clause;
4462     else if (Clause->getClauseKind() == OMPC_copyprivate)
4463       Copyprivate = Clause;
4464     if (Copyprivate && Nowait) {
4465       Diag(Copyprivate->getLocStart(),
4466            diag::err_omp_single_copyprivate_with_nowait);
4467       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4468       return StmtError();
4469     }
4470   }
4471 
4472   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4473 }
4474 
4475 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4476                                             SourceLocation StartLoc,
4477                                             SourceLocation EndLoc) {
4478   if (!AStmt)
4479     return StmtError();
4480 
4481   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4482 
4483   getCurFunction()->setHasBranchProtectedScope();
4484 
4485   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4486 }
4487 
4488 StmtResult Sema::ActOnOpenMPCriticalDirective(
4489     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4490     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4491   if (!AStmt)
4492     return StmtError();
4493 
4494   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4495 
4496   bool ErrorFound = false;
4497   llvm::APSInt Hint;
4498   SourceLocation HintLoc;
4499   bool DependentHint = false;
4500   for (auto *C : Clauses) {
4501     if (C->getClauseKind() == OMPC_hint) {
4502       if (!DirName.getName()) {
4503         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4504         ErrorFound = true;
4505       }
4506       Expr *E = cast<OMPHintClause>(C)->getHint();
4507       if (E->isTypeDependent() || E->isValueDependent() ||
4508           E->isInstantiationDependent())
4509         DependentHint = true;
4510       else {
4511         Hint = E->EvaluateKnownConstInt(Context);
4512         HintLoc = C->getLocStart();
4513       }
4514     }
4515   }
4516   if (ErrorFound)
4517     return StmtError();
4518   auto Pair = DSAStack->getCriticalWithHint(DirName);
4519   if (Pair.first && DirName.getName() && !DependentHint) {
4520     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4521       Diag(StartLoc, diag::err_omp_critical_with_hint);
4522       if (HintLoc.isValid()) {
4523         Diag(HintLoc, diag::note_omp_critical_hint_here)
4524             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4525       } else
4526         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4527       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4528         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4529             << 1
4530             << C->getHint()->EvaluateKnownConstInt(Context).toString(
4531                    /*Radix=*/10, /*Signed=*/false);
4532       } else
4533         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4534     }
4535   }
4536 
4537   getCurFunction()->setHasBranchProtectedScope();
4538 
4539   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4540                                            Clauses, AStmt);
4541   if (!Pair.first && DirName.getName() && !DependentHint)
4542     DSAStack->addCriticalWithHint(Dir, Hint);
4543   return Dir;
4544 }
4545 
4546 StmtResult Sema::ActOnOpenMPParallelForDirective(
4547     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4548     SourceLocation EndLoc,
4549     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4550   if (!AStmt)
4551     return StmtError();
4552 
4553   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4554   // 1.2.2 OpenMP Language Terminology
4555   // Structured block - An executable statement with a single entry at the
4556   // top and a single exit at the bottom.
4557   // The point of exit cannot be a branch out of the structured block.
4558   // longjmp() and throw() must not violate the entry/exit criteria.
4559   CS->getCapturedDecl()->setNothrow();
4560 
4561   OMPLoopDirective::HelperExprs B;
4562   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4563   // define the nested loops number.
4564   unsigned NestedLoopCount =
4565       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4566                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4567                       VarsWithImplicitDSA, B);
4568   if (NestedLoopCount == 0)
4569     return StmtError();
4570 
4571   assert((CurContext->isDependentContext() || B.builtAll()) &&
4572          "omp parallel for loop exprs were not built");
4573 
4574   if (!CurContext->isDependentContext()) {
4575     // Finalize the clauses that need pre-built expressions for CodeGen.
4576     for (auto C : Clauses) {
4577       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4578         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4579                                      B.NumIterations, *this, CurScope,
4580                                      DSAStack))
4581           return StmtError();
4582     }
4583   }
4584 
4585   getCurFunction()->setHasBranchProtectedScope();
4586   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4587                                          NestedLoopCount, Clauses, AStmt, B,
4588                                          DSAStack->isCancelRegion());
4589 }
4590 
4591 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4592     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4593     SourceLocation EndLoc,
4594     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
4595   if (!AStmt)
4596     return StmtError();
4597 
4598   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4599   // 1.2.2 OpenMP Language Terminology
4600   // Structured block - An executable statement with a single entry at the
4601   // top and a single exit at the bottom.
4602   // The point of exit cannot be a branch out of the structured block.
4603   // longjmp() and throw() must not violate the entry/exit criteria.
4604   CS->getCapturedDecl()->setNothrow();
4605 
4606   OMPLoopDirective::HelperExprs B;
4607   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4608   // define the nested loops number.
4609   unsigned NestedLoopCount =
4610       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4611                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4612                       VarsWithImplicitDSA, B);
4613   if (NestedLoopCount == 0)
4614     return StmtError();
4615 
4616   if (!CurContext->isDependentContext()) {
4617     // Finalize the clauses that need pre-built expressions for CodeGen.
4618     for (auto C : Clauses) {
4619       if (auto *LC = dyn_cast<OMPLinearClause>(C))
4620         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4621                                      B.NumIterations, *this, CurScope,
4622                                      DSAStack))
4623           return StmtError();
4624     }
4625   }
4626 
4627   if (checkSimdlenSafelenSpecified(*this, Clauses))
4628     return StmtError();
4629 
4630   getCurFunction()->setHasBranchProtectedScope();
4631   return OMPParallelForSimdDirective::Create(
4632       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4633 }
4634 
4635 StmtResult
4636 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4637                                            Stmt *AStmt, SourceLocation StartLoc,
4638                                            SourceLocation EndLoc) {
4639   if (!AStmt)
4640     return StmtError();
4641 
4642   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4643   auto BaseStmt = AStmt;
4644   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4645     BaseStmt = CS->getCapturedStmt();
4646   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4647     auto S = C->children();
4648     if (S.begin() == S.end())
4649       return StmtError();
4650     // All associated statements must be '#pragma omp section' except for
4651     // the first one.
4652     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4653       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4654         if (SectionStmt)
4655           Diag(SectionStmt->getLocStart(),
4656                diag::err_omp_parallel_sections_substmt_not_section);
4657         return StmtError();
4658       }
4659       cast<OMPSectionDirective>(SectionStmt)
4660           ->setHasCancel(DSAStack->isCancelRegion());
4661     }
4662   } else {
4663     Diag(AStmt->getLocStart(),
4664          diag::err_omp_parallel_sections_not_compound_stmt);
4665     return StmtError();
4666   }
4667 
4668   getCurFunction()->setHasBranchProtectedScope();
4669 
4670   return OMPParallelSectionsDirective::Create(
4671       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4672 }
4673 
4674 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4675                                           Stmt *AStmt, SourceLocation StartLoc,
4676                                           SourceLocation EndLoc) {
4677   if (!AStmt)
4678     return StmtError();
4679 
4680   auto *CS = cast<CapturedStmt>(AStmt);
4681   // 1.2.2 OpenMP Language Terminology
4682   // Structured block - An executable statement with a single entry at the
4683   // top and a single exit at the bottom.
4684   // The point of exit cannot be a branch out of the structured block.
4685   // longjmp() and throw() must not violate the entry/exit criteria.
4686   CS->getCapturedDecl()->setNothrow();
4687 
4688   getCurFunction()->setHasBranchProtectedScope();
4689 
4690   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4691                                   DSAStack->isCancelRegion());
4692 }
4693 
4694 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4695                                                SourceLocation EndLoc) {
4696   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4697 }
4698 
4699 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4700                                              SourceLocation EndLoc) {
4701   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4702 }
4703 
4704 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4705                                               SourceLocation EndLoc) {
4706   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4707 }
4708 
4709 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4710                                                SourceLocation StartLoc,
4711                                                SourceLocation EndLoc) {
4712   if (!AStmt)
4713     return StmtError();
4714 
4715   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4716 
4717   getCurFunction()->setHasBranchProtectedScope();
4718 
4719   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4720 }
4721 
4722 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4723                                            SourceLocation StartLoc,
4724                                            SourceLocation EndLoc) {
4725   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4726   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4727 }
4728 
4729 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4730                                              Stmt *AStmt,
4731                                              SourceLocation StartLoc,
4732                                              SourceLocation EndLoc) {
4733   OMPClause *DependFound = nullptr;
4734   OMPClause *DependSourceClause = nullptr;
4735   OMPClause *DependSinkClause = nullptr;
4736   bool ErrorFound = false;
4737   OMPThreadsClause *TC = nullptr;
4738   OMPSIMDClause *SC = nullptr;
4739   for (auto *C : Clauses) {
4740     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4741       DependFound = C;
4742       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4743         if (DependSourceClause) {
4744           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4745               << getOpenMPDirectiveName(OMPD_ordered)
4746               << getOpenMPClauseName(OMPC_depend) << 2;
4747           ErrorFound = true;
4748         } else
4749           DependSourceClause = C;
4750         if (DependSinkClause) {
4751           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4752               << 0;
4753           ErrorFound = true;
4754         }
4755       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4756         if (DependSourceClause) {
4757           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4758               << 1;
4759           ErrorFound = true;
4760         }
4761         DependSinkClause = C;
4762       }
4763     } else if (C->getClauseKind() == OMPC_threads)
4764       TC = cast<OMPThreadsClause>(C);
4765     else if (C->getClauseKind() == OMPC_simd)
4766       SC = cast<OMPSIMDClause>(C);
4767   }
4768   if (!ErrorFound && !SC &&
4769       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4770     // OpenMP [2.8.1,simd Construct, Restrictions]
4771     // An ordered construct with the simd clause is the only OpenMP construct
4772     // that can appear in the simd region.
4773     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4774     ErrorFound = true;
4775   } else if (DependFound && (TC || SC)) {
4776     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4777         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4778     ErrorFound = true;
4779   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4780     Diag(DependFound->getLocStart(),
4781          diag::err_omp_ordered_directive_without_param);
4782     ErrorFound = true;
4783   } else if (TC || Clauses.empty()) {
4784     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4785       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4786       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4787           << (TC != nullptr);
4788       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4789       ErrorFound = true;
4790     }
4791   }
4792   if ((!AStmt && !DependFound) || ErrorFound)
4793     return StmtError();
4794 
4795   if (AStmt) {
4796     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4797 
4798     getCurFunction()->setHasBranchProtectedScope();
4799   }
4800 
4801   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4802 }
4803 
4804 namespace {
4805 /// \brief Helper class for checking expression in 'omp atomic [update]'
4806 /// construct.
4807 class OpenMPAtomicUpdateChecker {
4808   /// \brief Error results for atomic update expressions.
4809   enum ExprAnalysisErrorCode {
4810     /// \brief A statement is not an expression statement.
4811     NotAnExpression,
4812     /// \brief Expression is not builtin binary or unary operation.
4813     NotABinaryOrUnaryExpression,
4814     /// \brief Unary operation is not post-/pre- increment/decrement operation.
4815     NotAnUnaryIncDecExpression,
4816     /// \brief An expression is not of scalar type.
4817     NotAScalarType,
4818     /// \brief A binary operation is not an assignment operation.
4819     NotAnAssignmentOp,
4820     /// \brief RHS part of the binary operation is not a binary expression.
4821     NotABinaryExpression,
4822     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4823     /// expression.
4824     NotABinaryOperator,
4825     /// \brief RHS binary operation does not have reference to the updated LHS
4826     /// part.
4827     NotAnUpdateExpression,
4828     /// \brief No errors is found.
4829     NoError
4830   };
4831   /// \brief Reference to Sema.
4832   Sema &SemaRef;
4833   /// \brief A location for note diagnostics (when error is found).
4834   SourceLocation NoteLoc;
4835   /// \brief 'x' lvalue part of the source atomic expression.
4836   Expr *X;
4837   /// \brief 'expr' rvalue part of the source atomic expression.
4838   Expr *E;
4839   /// \brief Helper expression of the form
4840   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4841   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4842   Expr *UpdateExpr;
4843   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4844   /// important for non-associative operations.
4845   bool IsXLHSInRHSPart;
4846   BinaryOperatorKind Op;
4847   SourceLocation OpLoc;
4848   /// \brief true if the source expression is a postfix unary operation, false
4849   /// if it is a prefix unary operation.
4850   bool IsPostfixUpdate;
4851 
4852 public:
4853   OpenMPAtomicUpdateChecker(Sema &SemaRef)
4854       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4855         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4856   /// \brief Check specified statement that it is suitable for 'atomic update'
4857   /// constructs and extract 'x', 'expr' and Operation from the original
4858   /// expression. If DiagId and NoteId == 0, then only check is performed
4859   /// without error notification.
4860   /// \param DiagId Diagnostic which should be emitted if error is found.
4861   /// \param NoteId Diagnostic note for the main error message.
4862   /// \return true if statement is not an update expression, false otherwise.
4863   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4864   /// \brief Return the 'x' lvalue part of the source atomic expression.
4865   Expr *getX() const { return X; }
4866   /// \brief Return the 'expr' rvalue part of the source atomic expression.
4867   Expr *getExpr() const { return E; }
4868   /// \brief Return the update expression used in calculation of the updated
4869   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4870   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4871   Expr *getUpdateExpr() const { return UpdateExpr; }
4872   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4873   /// false otherwise.
4874   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4875 
4876   /// \brief true if the source expression is a postfix unary operation, false
4877   /// if it is a prefix unary operation.
4878   bool isPostfixUpdate() const { return IsPostfixUpdate; }
4879 
4880 private:
4881   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4882                             unsigned NoteId = 0);
4883 };
4884 } // namespace
4885 
4886 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4887     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4888   ExprAnalysisErrorCode ErrorFound = NoError;
4889   SourceLocation ErrorLoc, NoteLoc;
4890   SourceRange ErrorRange, NoteRange;
4891   // Allowed constructs are:
4892   //  x = x binop expr;
4893   //  x = expr binop x;
4894   if (AtomicBinOp->getOpcode() == BO_Assign) {
4895     X = AtomicBinOp->getLHS();
4896     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4897             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4898       if (AtomicInnerBinOp->isMultiplicativeOp() ||
4899           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4900           AtomicInnerBinOp->isBitwiseOp()) {
4901         Op = AtomicInnerBinOp->getOpcode();
4902         OpLoc = AtomicInnerBinOp->getOperatorLoc();
4903         auto *LHS = AtomicInnerBinOp->getLHS();
4904         auto *RHS = AtomicInnerBinOp->getRHS();
4905         llvm::FoldingSetNodeID XId, LHSId, RHSId;
4906         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4907                                           /*Canonical=*/true);
4908         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4909                                             /*Canonical=*/true);
4910         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4911                                             /*Canonical=*/true);
4912         if (XId == LHSId) {
4913           E = RHS;
4914           IsXLHSInRHSPart = true;
4915         } else if (XId == RHSId) {
4916           E = LHS;
4917           IsXLHSInRHSPart = false;
4918         } else {
4919           ErrorLoc = AtomicInnerBinOp->getExprLoc();
4920           ErrorRange = AtomicInnerBinOp->getSourceRange();
4921           NoteLoc = X->getExprLoc();
4922           NoteRange = X->getSourceRange();
4923           ErrorFound = NotAnUpdateExpression;
4924         }
4925       } else {
4926         ErrorLoc = AtomicInnerBinOp->getExprLoc();
4927         ErrorRange = AtomicInnerBinOp->getSourceRange();
4928         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4929         NoteRange = SourceRange(NoteLoc, NoteLoc);
4930         ErrorFound = NotABinaryOperator;
4931       }
4932     } else {
4933       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4934       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4935       ErrorFound = NotABinaryExpression;
4936     }
4937   } else {
4938     ErrorLoc = AtomicBinOp->getExprLoc();
4939     ErrorRange = AtomicBinOp->getSourceRange();
4940     NoteLoc = AtomicBinOp->getOperatorLoc();
4941     NoteRange = SourceRange(NoteLoc, NoteLoc);
4942     ErrorFound = NotAnAssignmentOp;
4943   }
4944   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4945     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4946     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4947     return true;
4948   } else if (SemaRef.CurContext->isDependentContext())
4949     E = X = UpdateExpr = nullptr;
4950   return ErrorFound != NoError;
4951 }
4952 
4953 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4954                                                unsigned NoteId) {
4955   ExprAnalysisErrorCode ErrorFound = NoError;
4956   SourceLocation ErrorLoc, NoteLoc;
4957   SourceRange ErrorRange, NoteRange;
4958   // Allowed constructs are:
4959   //  x++;
4960   //  x--;
4961   //  ++x;
4962   //  --x;
4963   //  x binop= expr;
4964   //  x = x binop expr;
4965   //  x = expr binop x;
4966   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4967     AtomicBody = AtomicBody->IgnoreParenImpCasts();
4968     if (AtomicBody->getType()->isScalarType() ||
4969         AtomicBody->isInstantiationDependent()) {
4970       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4971               AtomicBody->IgnoreParenImpCasts())) {
4972         // Check for Compound Assignment Operation
4973         Op = BinaryOperator::getOpForCompoundAssignment(
4974             AtomicCompAssignOp->getOpcode());
4975         OpLoc = AtomicCompAssignOp->getOperatorLoc();
4976         E = AtomicCompAssignOp->getRHS();
4977         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
4978         IsXLHSInRHSPart = true;
4979       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4980                      AtomicBody->IgnoreParenImpCasts())) {
4981         // Check for Binary Operation
4982         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4983           return true;
4984       } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
4985                      AtomicBody->IgnoreParenImpCasts())) {
4986         // Check for Unary Operation
4987         if (AtomicUnaryOp->isIncrementDecrementOp()) {
4988           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
4989           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4990           OpLoc = AtomicUnaryOp->getOperatorLoc();
4991           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
4992           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4993           IsXLHSInRHSPart = true;
4994         } else {
4995           ErrorFound = NotAnUnaryIncDecExpression;
4996           ErrorLoc = AtomicUnaryOp->getExprLoc();
4997           ErrorRange = AtomicUnaryOp->getSourceRange();
4998           NoteLoc = AtomicUnaryOp->getOperatorLoc();
4999           NoteRange = SourceRange(NoteLoc, NoteLoc);
5000         }
5001       } else if (!AtomicBody->isInstantiationDependent()) {
5002         ErrorFound = NotABinaryOrUnaryExpression;
5003         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5004         NoteRange = ErrorRange = AtomicBody->getSourceRange();
5005       }
5006     } else {
5007       ErrorFound = NotAScalarType;
5008       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5009       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5010     }
5011   } else {
5012     ErrorFound = NotAnExpression;
5013     NoteLoc = ErrorLoc = S->getLocStart();
5014     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5015   }
5016   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
5017     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5018     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5019     return true;
5020   } else if (SemaRef.CurContext->isDependentContext())
5021     E = X = UpdateExpr = nullptr;
5022   if (ErrorFound == NoError && E && X) {
5023     // Build an update expression of form 'OpaqueValueExpr(x) binop
5024     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5025     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5026     auto *OVEX = new (SemaRef.getASTContext())
5027         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5028     auto *OVEExpr = new (SemaRef.getASTContext())
5029         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5030     auto Update =
5031         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5032                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
5033     if (Update.isInvalid())
5034       return true;
5035     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5036                                                Sema::AA_Casting);
5037     if (Update.isInvalid())
5038       return true;
5039     UpdateExpr = Update.get();
5040   }
5041   return ErrorFound != NoError;
5042 }
5043 
5044 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5045                                             Stmt *AStmt,
5046                                             SourceLocation StartLoc,
5047                                             SourceLocation EndLoc) {
5048   if (!AStmt)
5049     return StmtError();
5050 
5051   auto *CS = cast<CapturedStmt>(AStmt);
5052   // 1.2.2 OpenMP Language Terminology
5053   // Structured block - An executable statement with a single entry at the
5054   // top and a single exit at the bottom.
5055   // The point of exit cannot be a branch out of the structured block.
5056   // longjmp() and throw() must not violate the entry/exit criteria.
5057   OpenMPClauseKind AtomicKind = OMPC_unknown;
5058   SourceLocation AtomicKindLoc;
5059   for (auto *C : Clauses) {
5060     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
5061         C->getClauseKind() == OMPC_update ||
5062         C->getClauseKind() == OMPC_capture) {
5063       if (AtomicKind != OMPC_unknown) {
5064         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5065             << SourceRange(C->getLocStart(), C->getLocEnd());
5066         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5067             << getOpenMPClauseName(AtomicKind);
5068       } else {
5069         AtomicKind = C->getClauseKind();
5070         AtomicKindLoc = C->getLocStart();
5071       }
5072     }
5073   }
5074 
5075   auto Body = CS->getCapturedStmt();
5076   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5077     Body = EWC->getSubExpr();
5078 
5079   Expr *X = nullptr;
5080   Expr *V = nullptr;
5081   Expr *E = nullptr;
5082   Expr *UE = nullptr;
5083   bool IsXLHSInRHSPart = false;
5084   bool IsPostfixUpdate = false;
5085   // OpenMP [2.12.6, atomic Construct]
5086   // In the next expressions:
5087   // * x and v (as applicable) are both l-value expressions with scalar type.
5088   // * During the execution of an atomic region, multiple syntactic
5089   // occurrences of x must designate the same storage location.
5090   // * Neither of v and expr (as applicable) may access the storage location
5091   // designated by x.
5092   // * Neither of x and expr (as applicable) may access the storage location
5093   // designated by v.
5094   // * expr is an expression with scalar type.
5095   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5096   // * binop, binop=, ++, and -- are not overloaded operators.
5097   // * The expression x binop expr must be numerically equivalent to x binop
5098   // (expr). This requirement is satisfied if the operators in expr have
5099   // precedence greater than binop, or by using parentheses around expr or
5100   // subexpressions of expr.
5101   // * The expression expr binop x must be numerically equivalent to (expr)
5102   // binop x. This requirement is satisfied if the operators in expr have
5103   // precedence equal to or greater than binop, or by using parentheses around
5104   // expr or subexpressions of expr.
5105   // * For forms that allow multiple occurrences of x, the number of times
5106   // that x is evaluated is unspecified.
5107   if (AtomicKind == OMPC_read) {
5108     enum {
5109       NotAnExpression,
5110       NotAnAssignmentOp,
5111       NotAScalarType,
5112       NotAnLValue,
5113       NoError
5114     } ErrorFound = NoError;
5115     SourceLocation ErrorLoc, NoteLoc;
5116     SourceRange ErrorRange, NoteRange;
5117     // If clause is read:
5118     //  v = x;
5119     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5120       auto *AtomicBinOp =
5121           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5122       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5123         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5124         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5125         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5126             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5127           if (!X->isLValue() || !V->isLValue()) {
5128             auto NotLValueExpr = X->isLValue() ? V : X;
5129             ErrorFound = NotAnLValue;
5130             ErrorLoc = AtomicBinOp->getExprLoc();
5131             ErrorRange = AtomicBinOp->getSourceRange();
5132             NoteLoc = NotLValueExpr->getExprLoc();
5133             NoteRange = NotLValueExpr->getSourceRange();
5134           }
5135         } else if (!X->isInstantiationDependent() ||
5136                    !V->isInstantiationDependent()) {
5137           auto NotScalarExpr =
5138               (X->isInstantiationDependent() || X->getType()->isScalarType())
5139                   ? V
5140                   : X;
5141           ErrorFound = NotAScalarType;
5142           ErrorLoc = AtomicBinOp->getExprLoc();
5143           ErrorRange = AtomicBinOp->getSourceRange();
5144           NoteLoc = NotScalarExpr->getExprLoc();
5145           NoteRange = NotScalarExpr->getSourceRange();
5146         }
5147       } else if (!AtomicBody->isInstantiationDependent()) {
5148         ErrorFound = NotAnAssignmentOp;
5149         ErrorLoc = AtomicBody->getExprLoc();
5150         ErrorRange = AtomicBody->getSourceRange();
5151         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5152                               : AtomicBody->getExprLoc();
5153         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5154                                 : AtomicBody->getSourceRange();
5155       }
5156     } else {
5157       ErrorFound = NotAnExpression;
5158       NoteLoc = ErrorLoc = Body->getLocStart();
5159       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5160     }
5161     if (ErrorFound != NoError) {
5162       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5163           << ErrorRange;
5164       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5165                                                       << NoteRange;
5166       return StmtError();
5167     } else if (CurContext->isDependentContext())
5168       V = X = nullptr;
5169   } else if (AtomicKind == OMPC_write) {
5170     enum {
5171       NotAnExpression,
5172       NotAnAssignmentOp,
5173       NotAScalarType,
5174       NotAnLValue,
5175       NoError
5176     } ErrorFound = NoError;
5177     SourceLocation ErrorLoc, NoteLoc;
5178     SourceRange ErrorRange, NoteRange;
5179     // If clause is write:
5180     //  x = expr;
5181     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5182       auto *AtomicBinOp =
5183           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5184       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5185         X = AtomicBinOp->getLHS();
5186         E = AtomicBinOp->getRHS();
5187         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5188             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5189           if (!X->isLValue()) {
5190             ErrorFound = NotAnLValue;
5191             ErrorLoc = AtomicBinOp->getExprLoc();
5192             ErrorRange = AtomicBinOp->getSourceRange();
5193             NoteLoc = X->getExprLoc();
5194             NoteRange = X->getSourceRange();
5195           }
5196         } else if (!X->isInstantiationDependent() ||
5197                    !E->isInstantiationDependent()) {
5198           auto NotScalarExpr =
5199               (X->isInstantiationDependent() || X->getType()->isScalarType())
5200                   ? E
5201                   : X;
5202           ErrorFound = NotAScalarType;
5203           ErrorLoc = AtomicBinOp->getExprLoc();
5204           ErrorRange = AtomicBinOp->getSourceRange();
5205           NoteLoc = NotScalarExpr->getExprLoc();
5206           NoteRange = NotScalarExpr->getSourceRange();
5207         }
5208       } else if (!AtomicBody->isInstantiationDependent()) {
5209         ErrorFound = NotAnAssignmentOp;
5210         ErrorLoc = AtomicBody->getExprLoc();
5211         ErrorRange = AtomicBody->getSourceRange();
5212         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5213                               : AtomicBody->getExprLoc();
5214         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5215                                 : AtomicBody->getSourceRange();
5216       }
5217     } else {
5218       ErrorFound = NotAnExpression;
5219       NoteLoc = ErrorLoc = Body->getLocStart();
5220       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5221     }
5222     if (ErrorFound != NoError) {
5223       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5224           << ErrorRange;
5225       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5226                                                       << NoteRange;
5227       return StmtError();
5228     } else if (CurContext->isDependentContext())
5229       E = X = nullptr;
5230   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5231     // If clause is update:
5232     //  x++;
5233     //  x--;
5234     //  ++x;
5235     //  --x;
5236     //  x binop= expr;
5237     //  x = x binop expr;
5238     //  x = expr binop x;
5239     OpenMPAtomicUpdateChecker Checker(*this);
5240     if (Checker.checkStatement(
5241             Body, (AtomicKind == OMPC_update)
5242                       ? diag::err_omp_atomic_update_not_expression_statement
5243                       : diag::err_omp_atomic_not_expression_statement,
5244             diag::note_omp_atomic_update))
5245       return StmtError();
5246     if (!CurContext->isDependentContext()) {
5247       E = Checker.getExpr();
5248       X = Checker.getX();
5249       UE = Checker.getUpdateExpr();
5250       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5251     }
5252   } else if (AtomicKind == OMPC_capture) {
5253     enum {
5254       NotAnAssignmentOp,
5255       NotACompoundStatement,
5256       NotTwoSubstatements,
5257       NotASpecificExpression,
5258       NoError
5259     } ErrorFound = NoError;
5260     SourceLocation ErrorLoc, NoteLoc;
5261     SourceRange ErrorRange, NoteRange;
5262     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5263       // If clause is a capture:
5264       //  v = x++;
5265       //  v = x--;
5266       //  v = ++x;
5267       //  v = --x;
5268       //  v = x binop= expr;
5269       //  v = x = x binop expr;
5270       //  v = x = expr binop x;
5271       auto *AtomicBinOp =
5272           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5273       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5274         V = AtomicBinOp->getLHS();
5275         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5276         OpenMPAtomicUpdateChecker Checker(*this);
5277         if (Checker.checkStatement(
5278                 Body, diag::err_omp_atomic_capture_not_expression_statement,
5279                 diag::note_omp_atomic_update))
5280           return StmtError();
5281         E = Checker.getExpr();
5282         X = Checker.getX();
5283         UE = Checker.getUpdateExpr();
5284         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5285         IsPostfixUpdate = Checker.isPostfixUpdate();
5286       } else if (!AtomicBody->isInstantiationDependent()) {
5287         ErrorLoc = AtomicBody->getExprLoc();
5288         ErrorRange = AtomicBody->getSourceRange();
5289         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5290                               : AtomicBody->getExprLoc();
5291         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5292                                 : AtomicBody->getSourceRange();
5293         ErrorFound = NotAnAssignmentOp;
5294       }
5295       if (ErrorFound != NoError) {
5296         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5297             << ErrorRange;
5298         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5299         return StmtError();
5300       } else if (CurContext->isDependentContext()) {
5301         UE = V = E = X = nullptr;
5302       }
5303     } else {
5304       // If clause is a capture:
5305       //  { v = x; x = expr; }
5306       //  { v = x; x++; }
5307       //  { v = x; x--; }
5308       //  { v = x; ++x; }
5309       //  { v = x; --x; }
5310       //  { v = x; x binop= expr; }
5311       //  { v = x; x = x binop expr; }
5312       //  { v = x; x = expr binop x; }
5313       //  { x++; v = x; }
5314       //  { x--; v = x; }
5315       //  { ++x; v = x; }
5316       //  { --x; v = x; }
5317       //  { x binop= expr; v = x; }
5318       //  { x = x binop expr; v = x; }
5319       //  { x = expr binop x; v = x; }
5320       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5321         // Check that this is { expr1; expr2; }
5322         if (CS->size() == 2) {
5323           auto *First = CS->body_front();
5324           auto *Second = CS->body_back();
5325           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5326             First = EWC->getSubExpr()->IgnoreParenImpCasts();
5327           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5328             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5329           // Need to find what subexpression is 'v' and what is 'x'.
5330           OpenMPAtomicUpdateChecker Checker(*this);
5331           bool IsUpdateExprFound = !Checker.checkStatement(Second);
5332           BinaryOperator *BinOp = nullptr;
5333           if (IsUpdateExprFound) {
5334             BinOp = dyn_cast<BinaryOperator>(First);
5335             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5336           }
5337           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5338             //  { v = x; x++; }
5339             //  { v = x; x--; }
5340             //  { v = x; ++x; }
5341             //  { v = x; --x; }
5342             //  { v = x; x binop= expr; }
5343             //  { v = x; x = x binop expr; }
5344             //  { v = x; x = expr binop x; }
5345             // Check that the first expression has form v = x.
5346             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5347             llvm::FoldingSetNodeID XId, PossibleXId;
5348             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5349             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5350             IsUpdateExprFound = XId == PossibleXId;
5351             if (IsUpdateExprFound) {
5352               V = BinOp->getLHS();
5353               X = Checker.getX();
5354               E = Checker.getExpr();
5355               UE = Checker.getUpdateExpr();
5356               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5357               IsPostfixUpdate = true;
5358             }
5359           }
5360           if (!IsUpdateExprFound) {
5361             IsUpdateExprFound = !Checker.checkStatement(First);
5362             BinOp = nullptr;
5363             if (IsUpdateExprFound) {
5364               BinOp = dyn_cast<BinaryOperator>(Second);
5365               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5366             }
5367             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5368               //  { x++; v = x; }
5369               //  { x--; v = x; }
5370               //  { ++x; v = x; }
5371               //  { --x; v = x; }
5372               //  { x binop= expr; v = x; }
5373               //  { x = x binop expr; v = x; }
5374               //  { x = expr binop x; v = x; }
5375               // Check that the second expression has form v = x.
5376               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5377               llvm::FoldingSetNodeID XId, PossibleXId;
5378               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5379               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5380               IsUpdateExprFound = XId == PossibleXId;
5381               if (IsUpdateExprFound) {
5382                 V = BinOp->getLHS();
5383                 X = Checker.getX();
5384                 E = Checker.getExpr();
5385                 UE = Checker.getUpdateExpr();
5386                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5387                 IsPostfixUpdate = false;
5388               }
5389             }
5390           }
5391           if (!IsUpdateExprFound) {
5392             //  { v = x; x = expr; }
5393             auto *FirstExpr = dyn_cast<Expr>(First);
5394             auto *SecondExpr = dyn_cast<Expr>(Second);
5395             if (!FirstExpr || !SecondExpr ||
5396                 !(FirstExpr->isInstantiationDependent() ||
5397                   SecondExpr->isInstantiationDependent())) {
5398               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5399               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5400                 ErrorFound = NotAnAssignmentOp;
5401                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5402                                                 : First->getLocStart();
5403                 NoteRange = ErrorRange = FirstBinOp
5404                                              ? FirstBinOp->getSourceRange()
5405                                              : SourceRange(ErrorLoc, ErrorLoc);
5406               } else {
5407                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5408                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5409                   ErrorFound = NotAnAssignmentOp;
5410                   NoteLoc = ErrorLoc = SecondBinOp
5411                                            ? SecondBinOp->getOperatorLoc()
5412                                            : Second->getLocStart();
5413                   NoteRange = ErrorRange =
5414                       SecondBinOp ? SecondBinOp->getSourceRange()
5415                                   : SourceRange(ErrorLoc, ErrorLoc);
5416                 } else {
5417                   auto *PossibleXRHSInFirst =
5418                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
5419                   auto *PossibleXLHSInSecond =
5420                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
5421                   llvm::FoldingSetNodeID X1Id, X2Id;
5422                   PossibleXRHSInFirst->Profile(X1Id, Context,
5423                                                /*Canonical=*/true);
5424                   PossibleXLHSInSecond->Profile(X2Id, Context,
5425                                                 /*Canonical=*/true);
5426                   IsUpdateExprFound = X1Id == X2Id;
5427                   if (IsUpdateExprFound) {
5428                     V = FirstBinOp->getLHS();
5429                     X = SecondBinOp->getLHS();
5430                     E = SecondBinOp->getRHS();
5431                     UE = nullptr;
5432                     IsXLHSInRHSPart = false;
5433                     IsPostfixUpdate = true;
5434                   } else {
5435                     ErrorFound = NotASpecificExpression;
5436                     ErrorLoc = FirstBinOp->getExprLoc();
5437                     ErrorRange = FirstBinOp->getSourceRange();
5438                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5439                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
5440                   }
5441                 }
5442               }
5443             }
5444           }
5445         } else {
5446           NoteLoc = ErrorLoc = Body->getLocStart();
5447           NoteRange = ErrorRange =
5448               SourceRange(Body->getLocStart(), Body->getLocStart());
5449           ErrorFound = NotTwoSubstatements;
5450         }
5451       } else {
5452         NoteLoc = ErrorLoc = Body->getLocStart();
5453         NoteRange = ErrorRange =
5454             SourceRange(Body->getLocStart(), Body->getLocStart());
5455         ErrorFound = NotACompoundStatement;
5456       }
5457       if (ErrorFound != NoError) {
5458         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5459             << ErrorRange;
5460         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5461         return StmtError();
5462       } else if (CurContext->isDependentContext()) {
5463         UE = V = E = X = nullptr;
5464       }
5465     }
5466   }
5467 
5468   getCurFunction()->setHasBranchProtectedScope();
5469 
5470   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5471                                     X, V, E, UE, IsXLHSInRHSPart,
5472                                     IsPostfixUpdate);
5473 }
5474 
5475 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5476                                             Stmt *AStmt,
5477                                             SourceLocation StartLoc,
5478                                             SourceLocation EndLoc) {
5479   if (!AStmt)
5480     return StmtError();
5481 
5482   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5483   // 1.2.2 OpenMP Language Terminology
5484   // Structured block - An executable statement with a single entry at the
5485   // top and a single exit at the bottom.
5486   // The point of exit cannot be a branch out of the structured block.
5487   // longjmp() and throw() must not violate the entry/exit criteria.
5488   CS->getCapturedDecl()->setNothrow();
5489 
5490   // OpenMP [2.16, Nesting of Regions]
5491   // If specified, a teams construct must be contained within a target
5492   // construct. That target construct must contain no statements or directives
5493   // outside of the teams construct.
5494   if (DSAStack->hasInnerTeamsRegion()) {
5495     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5496     bool OMPTeamsFound = true;
5497     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5498       auto I = CS->body_begin();
5499       while (I != CS->body_end()) {
5500         auto *OED = dyn_cast<OMPExecutableDirective>(*I);
5501         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5502           OMPTeamsFound = false;
5503           break;
5504         }
5505         ++I;
5506       }
5507       assert(I != CS->body_end() && "Not found statement");
5508       S = *I;
5509     } else {
5510       auto *OED = dyn_cast<OMPExecutableDirective>(S);
5511       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
5512     }
5513     if (!OMPTeamsFound) {
5514       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5515       Diag(DSAStack->getInnerTeamsRegionLoc(),
5516            diag::note_omp_nested_teams_construct_here);
5517       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5518           << isa<OMPExecutableDirective>(S);
5519       return StmtError();
5520     }
5521   }
5522 
5523   getCurFunction()->setHasBranchProtectedScope();
5524 
5525   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5526 }
5527 
5528 StmtResult
5529 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5530                                          Stmt *AStmt, SourceLocation StartLoc,
5531                                          SourceLocation EndLoc) {
5532   if (!AStmt)
5533     return StmtError();
5534 
5535   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5536   // 1.2.2 OpenMP Language Terminology
5537   // Structured block - An executable statement with a single entry at the
5538   // top and a single exit at the bottom.
5539   // The point of exit cannot be a branch out of the structured block.
5540   // longjmp() and throw() must not violate the entry/exit criteria.
5541   CS->getCapturedDecl()->setNothrow();
5542 
5543   getCurFunction()->setHasBranchProtectedScope();
5544 
5545   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5546                                             AStmt);
5547 }
5548 
5549 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5550     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5551     SourceLocation EndLoc,
5552     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5553   if (!AStmt)
5554     return StmtError();
5555 
5556   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5557   // 1.2.2 OpenMP Language Terminology
5558   // Structured block - An executable statement with a single entry at the
5559   // top and a single exit at the bottom.
5560   // The point of exit cannot be a branch out of the structured block.
5561   // longjmp() and throw() must not violate the entry/exit criteria.
5562   CS->getCapturedDecl()->setNothrow();
5563 
5564   OMPLoopDirective::HelperExprs B;
5565   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5566   // define the nested loops number.
5567   unsigned NestedLoopCount =
5568       CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5569                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5570                       VarsWithImplicitDSA, B);
5571   if (NestedLoopCount == 0)
5572     return StmtError();
5573 
5574   assert((CurContext->isDependentContext() || B.builtAll()) &&
5575          "omp target parallel for loop exprs were not built");
5576 
5577   if (!CurContext->isDependentContext()) {
5578     // Finalize the clauses that need pre-built expressions for CodeGen.
5579     for (auto C : Clauses) {
5580       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5581         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5582                                      B.NumIterations, *this, CurScope,
5583                                      DSAStack))
5584           return StmtError();
5585     }
5586   }
5587 
5588   getCurFunction()->setHasBranchProtectedScope();
5589   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5590                                                NestedLoopCount, Clauses, AStmt,
5591                                                B, DSAStack->isCancelRegion());
5592 }
5593 
5594 /// \brief Check for existence of a map clause in the list of clauses.
5595 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5596   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5597        I != E; ++I) {
5598     if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5599       return true;
5600     }
5601   }
5602 
5603   return false;
5604 }
5605 
5606 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5607                                                 Stmt *AStmt,
5608                                                 SourceLocation StartLoc,
5609                                                 SourceLocation EndLoc) {
5610   if (!AStmt)
5611     return StmtError();
5612 
5613   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5614 
5615   // OpenMP [2.10.1, Restrictions, p. 97]
5616   // At least one map clause must appear on the directive.
5617   if (!HasMapClause(Clauses)) {
5618     Diag(StartLoc, diag::err_omp_no_map_for_directive)
5619         << getOpenMPDirectiveName(OMPD_target_data);
5620     return StmtError();
5621   }
5622 
5623   getCurFunction()->setHasBranchProtectedScope();
5624 
5625   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5626                                         AStmt);
5627 }
5628 
5629 StmtResult
5630 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5631                                           SourceLocation StartLoc,
5632                                           SourceLocation EndLoc) {
5633   // OpenMP [2.10.2, Restrictions, p. 99]
5634   // At least one map clause must appear on the directive.
5635   if (!HasMapClause(Clauses)) {
5636     Diag(StartLoc, diag::err_omp_no_map_for_directive)
5637         << getOpenMPDirectiveName(OMPD_target_enter_data);
5638     return StmtError();
5639   }
5640 
5641   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5642                                              Clauses);
5643 }
5644 
5645 StmtResult
5646 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5647                                          SourceLocation StartLoc,
5648                                          SourceLocation EndLoc) {
5649   // OpenMP [2.10.3, Restrictions, p. 102]
5650   // At least one map clause must appear on the directive.
5651   if (!HasMapClause(Clauses)) {
5652     Diag(StartLoc, diag::err_omp_no_map_for_directive)
5653         << getOpenMPDirectiveName(OMPD_target_exit_data);
5654     return StmtError();
5655   }
5656 
5657   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5658 }
5659 
5660 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5661                                                   SourceLocation StartLoc,
5662                                                   SourceLocation EndLoc) {
5663   bool seenMotionClause = false;
5664   for (auto *C : Clauses) {
5665     if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
5666       seenMotionClause = true;
5667   }
5668   if (!seenMotionClause) {
5669     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5670     return StmtError();
5671   }
5672   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5673 }
5674 
5675 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5676                                            Stmt *AStmt, SourceLocation StartLoc,
5677                                            SourceLocation EndLoc) {
5678   if (!AStmt)
5679     return StmtError();
5680 
5681   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5682   // 1.2.2 OpenMP Language Terminology
5683   // Structured block - An executable statement with a single entry at the
5684   // top and a single exit at the bottom.
5685   // The point of exit cannot be a branch out of the structured block.
5686   // longjmp() and throw() must not violate the entry/exit criteria.
5687   CS->getCapturedDecl()->setNothrow();
5688 
5689   getCurFunction()->setHasBranchProtectedScope();
5690 
5691   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5692 }
5693 
5694 StmtResult
5695 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5696                                             SourceLocation EndLoc,
5697                                             OpenMPDirectiveKind CancelRegion) {
5698   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5699       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5700     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5701         << getOpenMPDirectiveName(CancelRegion);
5702     return StmtError();
5703   }
5704   if (DSAStack->isParentNowaitRegion()) {
5705     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5706     return StmtError();
5707   }
5708   if (DSAStack->isParentOrderedRegion()) {
5709     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5710     return StmtError();
5711   }
5712   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5713                                                CancelRegion);
5714 }
5715 
5716 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5717                                             SourceLocation StartLoc,
5718                                             SourceLocation EndLoc,
5719                                             OpenMPDirectiveKind CancelRegion) {
5720   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5721       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5722     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5723         << getOpenMPDirectiveName(CancelRegion);
5724     return StmtError();
5725   }
5726   if (DSAStack->isParentNowaitRegion()) {
5727     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5728     return StmtError();
5729   }
5730   if (DSAStack->isParentOrderedRegion()) {
5731     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5732     return StmtError();
5733   }
5734   DSAStack->setParentCancelRegion(/*Cancel=*/true);
5735   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5736                                     CancelRegion);
5737 }
5738 
5739 static bool checkGrainsizeNumTasksClauses(Sema &S,
5740                                           ArrayRef<OMPClause *> Clauses) {
5741   OMPClause *PrevClause = nullptr;
5742   bool ErrorFound = false;
5743   for (auto *C : Clauses) {
5744     if (C->getClauseKind() == OMPC_grainsize ||
5745         C->getClauseKind() == OMPC_num_tasks) {
5746       if (!PrevClause)
5747         PrevClause = C;
5748       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5749         S.Diag(C->getLocStart(),
5750                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5751             << getOpenMPClauseName(C->getClauseKind())
5752             << getOpenMPClauseName(PrevClause->getClauseKind());
5753         S.Diag(PrevClause->getLocStart(),
5754                diag::note_omp_previous_grainsize_num_tasks)
5755             << getOpenMPClauseName(PrevClause->getClauseKind());
5756         ErrorFound = true;
5757       }
5758     }
5759   }
5760   return ErrorFound;
5761 }
5762 
5763 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5764     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5765     SourceLocation EndLoc,
5766     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5767   if (!AStmt)
5768     return StmtError();
5769 
5770   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5771   OMPLoopDirective::HelperExprs B;
5772   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5773   // define the nested loops number.
5774   unsigned NestedLoopCount =
5775       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5776                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5777                       VarsWithImplicitDSA, B);
5778   if (NestedLoopCount == 0)
5779     return StmtError();
5780 
5781   assert((CurContext->isDependentContext() || B.builtAll()) &&
5782          "omp for loop exprs were not built");
5783 
5784   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5785   // The grainsize clause and num_tasks clause are mutually exclusive and may
5786   // not appear on the same taskloop directive.
5787   if (checkGrainsizeNumTasksClauses(*this, Clauses))
5788     return StmtError();
5789 
5790   getCurFunction()->setHasBranchProtectedScope();
5791   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5792                                       NestedLoopCount, Clauses, AStmt, B);
5793 }
5794 
5795 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5796     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5797     SourceLocation EndLoc,
5798     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5799   if (!AStmt)
5800     return StmtError();
5801 
5802   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5803   OMPLoopDirective::HelperExprs B;
5804   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5805   // define the nested loops number.
5806   unsigned NestedLoopCount =
5807       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5808                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5809                       VarsWithImplicitDSA, B);
5810   if (NestedLoopCount == 0)
5811     return StmtError();
5812 
5813   assert((CurContext->isDependentContext() || B.builtAll()) &&
5814          "omp for loop exprs were not built");
5815 
5816   if (!CurContext->isDependentContext()) {
5817     // Finalize the clauses that need pre-built expressions for CodeGen.
5818     for (auto C : Clauses) {
5819       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5820         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5821                                      B.NumIterations, *this, CurScope,
5822                                      DSAStack))
5823           return StmtError();
5824     }
5825   }
5826 
5827   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5828   // The grainsize clause and num_tasks clause are mutually exclusive and may
5829   // not appear on the same taskloop directive.
5830   if (checkGrainsizeNumTasksClauses(*this, Clauses))
5831     return StmtError();
5832 
5833   getCurFunction()->setHasBranchProtectedScope();
5834   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5835                                           NestedLoopCount, Clauses, AStmt, B);
5836 }
5837 
5838 StmtResult Sema::ActOnOpenMPDistributeDirective(
5839     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5840     SourceLocation EndLoc,
5841     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5842   if (!AStmt)
5843     return StmtError();
5844 
5845   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5846   OMPLoopDirective::HelperExprs B;
5847   // In presence of clause 'collapse' with number of loops, it will
5848   // define the nested loops number.
5849   unsigned NestedLoopCount =
5850       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5851                       nullptr /*ordered not a clause on distribute*/, AStmt,
5852                       *this, *DSAStack, VarsWithImplicitDSA, B);
5853   if (NestedLoopCount == 0)
5854     return StmtError();
5855 
5856   assert((CurContext->isDependentContext() || B.builtAll()) &&
5857          "omp for loop exprs were not built");
5858 
5859   getCurFunction()->setHasBranchProtectedScope();
5860   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5861                                         NestedLoopCount, Clauses, AStmt, B);
5862 }
5863 
5864 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5865     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5866     SourceLocation EndLoc,
5867     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5868   if (!AStmt)
5869     return StmtError();
5870 
5871   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5872   // 1.2.2 OpenMP Language Terminology
5873   // Structured block - An executable statement with a single entry at the
5874   // top and a single exit at the bottom.
5875   // The point of exit cannot be a branch out of the structured block.
5876   // longjmp() and throw() must not violate the entry/exit criteria.
5877   CS->getCapturedDecl()->setNothrow();
5878 
5879   OMPLoopDirective::HelperExprs B;
5880   // In presence of clause 'collapse' with number of loops, it will
5881   // define the nested loops number.
5882   unsigned NestedLoopCount = CheckOpenMPLoop(
5883       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
5884       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5885       VarsWithImplicitDSA, B);
5886   if (NestedLoopCount == 0)
5887     return StmtError();
5888 
5889   assert((CurContext->isDependentContext() || B.builtAll()) &&
5890          "omp for loop exprs were not built");
5891 
5892   getCurFunction()->setHasBranchProtectedScope();
5893   return OMPDistributeParallelForDirective::Create(
5894       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5895 }
5896 
5897 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
5898     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5899     SourceLocation EndLoc,
5900     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5901   if (!AStmt)
5902     return StmtError();
5903 
5904   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5905   // 1.2.2 OpenMP Language Terminology
5906   // Structured block - An executable statement with a single entry at the
5907   // top and a single exit at the bottom.
5908   // The point of exit cannot be a branch out of the structured block.
5909   // longjmp() and throw() must not violate the entry/exit criteria.
5910   CS->getCapturedDecl()->setNothrow();
5911 
5912   OMPLoopDirective::HelperExprs B;
5913   // In presence of clause 'collapse' with number of loops, it will
5914   // define the nested loops number.
5915   unsigned NestedLoopCount = CheckOpenMPLoop(
5916       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
5917       nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
5918       VarsWithImplicitDSA, B);
5919   if (NestedLoopCount == 0)
5920     return StmtError();
5921 
5922   assert((CurContext->isDependentContext() || B.builtAll()) &&
5923          "omp for loop exprs were not built");
5924 
5925   if (checkSimdlenSafelenSpecified(*this, Clauses))
5926     return StmtError();
5927 
5928   getCurFunction()->setHasBranchProtectedScope();
5929   return OMPDistributeParallelForSimdDirective::Create(
5930       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
5931 }
5932 
5933 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
5934     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5935     SourceLocation EndLoc,
5936     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5937   if (!AStmt)
5938     return StmtError();
5939 
5940   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5941   // 1.2.2 OpenMP Language Terminology
5942   // Structured block - An executable statement with a single entry at the
5943   // top and a single exit at the bottom.
5944   // The point of exit cannot be a branch out of the structured block.
5945   // longjmp() and throw() must not violate the entry/exit criteria.
5946   CS->getCapturedDecl()->setNothrow();
5947 
5948   OMPLoopDirective::HelperExprs B;
5949   // In presence of clause 'collapse' with number of loops, it will
5950   // define the nested loops number.
5951   unsigned NestedLoopCount =
5952       CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
5953                       nullptr /*ordered not a clause on distribute*/, AStmt,
5954                       *this, *DSAStack, VarsWithImplicitDSA, B);
5955   if (NestedLoopCount == 0)
5956     return StmtError();
5957 
5958   assert((CurContext->isDependentContext() || B.builtAll()) &&
5959          "omp for loop exprs were not built");
5960 
5961   if (checkSimdlenSafelenSpecified(*this, Clauses))
5962     return StmtError();
5963 
5964   getCurFunction()->setHasBranchProtectedScope();
5965   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
5966                                             NestedLoopCount, Clauses, AStmt, B);
5967 }
5968 
5969 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
5970     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5971     SourceLocation EndLoc,
5972     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5973   if (!AStmt)
5974     return StmtError();
5975 
5976   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5977   // 1.2.2 OpenMP Language Terminology
5978   // Structured block - An executable statement with a single entry at the
5979   // top and a single exit at the bottom.
5980   // The point of exit cannot be a branch out of the structured block.
5981   // longjmp() and throw() must not violate the entry/exit criteria.
5982   CS->getCapturedDecl()->setNothrow();
5983 
5984   OMPLoopDirective::HelperExprs B;
5985   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5986   // define the nested loops number.
5987   unsigned NestedLoopCount = CheckOpenMPLoop(
5988       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
5989       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5990       VarsWithImplicitDSA, B);
5991   if (NestedLoopCount == 0)
5992     return StmtError();
5993 
5994   assert((CurContext->isDependentContext() || B.builtAll()) &&
5995          "omp target parallel for simd loop exprs were not built");
5996 
5997   if (!CurContext->isDependentContext()) {
5998     // Finalize the clauses that need pre-built expressions for CodeGen.
5999     for (auto C : Clauses) {
6000       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6001         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6002                                      B.NumIterations, *this, CurScope,
6003                                      DSAStack))
6004           return StmtError();
6005     }
6006   }
6007   if (checkSimdlenSafelenSpecified(*this, Clauses))
6008     return StmtError();
6009 
6010   getCurFunction()->setHasBranchProtectedScope();
6011   return OMPTargetParallelForSimdDirective::Create(
6012       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6013 }
6014 
6015 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6016     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6017     SourceLocation EndLoc,
6018     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6019   if (!AStmt)
6020     return StmtError();
6021 
6022   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6023   // 1.2.2 OpenMP Language Terminology
6024   // Structured block - An executable statement with a single entry at the
6025   // top and a single exit at the bottom.
6026   // The point of exit cannot be a branch out of the structured block.
6027   // longjmp() and throw() must not violate the entry/exit criteria.
6028   CS->getCapturedDecl()->setNothrow();
6029 
6030   OMPLoopDirective::HelperExprs B;
6031   // In presence of clause 'collapse' with number of loops, it will define the
6032   // nested loops number.
6033   unsigned NestedLoopCount =
6034       CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6035                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6036                       VarsWithImplicitDSA, B);
6037   if (NestedLoopCount == 0)
6038     return StmtError();
6039 
6040   assert((CurContext->isDependentContext() || B.builtAll()) &&
6041          "omp target simd loop exprs were not built");
6042 
6043   if (!CurContext->isDependentContext()) {
6044     // Finalize the clauses that need pre-built expressions for CodeGen.
6045     for (auto C : Clauses) {
6046       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6047         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6048                                      B.NumIterations, *this, CurScope,
6049                                      DSAStack))
6050           return StmtError();
6051     }
6052   }
6053 
6054   if (checkSimdlenSafelenSpecified(*this, Clauses))
6055     return StmtError();
6056 
6057   getCurFunction()->setHasBranchProtectedScope();
6058   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6059                                         NestedLoopCount, Clauses, AStmt, B);
6060 }
6061 
6062 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6063     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6064     SourceLocation EndLoc,
6065     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6066   if (!AStmt)
6067     return StmtError();
6068 
6069   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6070   // 1.2.2 OpenMP Language Terminology
6071   // Structured block - An executable statement with a single entry at the
6072   // top and a single exit at the bottom.
6073   // The point of exit cannot be a branch out of the structured block.
6074   // longjmp() and throw() must not violate the entry/exit criteria.
6075   CS->getCapturedDecl()->setNothrow();
6076 
6077   OMPLoopDirective::HelperExprs B;
6078   // In presence of clause 'collapse' with number of loops, it will
6079   // define the nested loops number.
6080   unsigned NestedLoopCount =
6081       CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6082                       nullptr /*ordered not a clause on distribute*/, AStmt,
6083                       *this, *DSAStack, VarsWithImplicitDSA, B);
6084   if (NestedLoopCount == 0)
6085     return StmtError();
6086 
6087   assert((CurContext->isDependentContext() || B.builtAll()) &&
6088          "omp teams distribute loop exprs were not built");
6089 
6090   getCurFunction()->setHasBranchProtectedScope();
6091   return OMPTeamsDistributeDirective::Create(
6092       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6093 }
6094 
6095 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6096     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6097     SourceLocation EndLoc,
6098     llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6099   if (!AStmt)
6100     return StmtError();
6101 
6102   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6103   // 1.2.2 OpenMP Language Terminology
6104   // Structured block - An executable statement with a single entry at the
6105   // top and a single exit at the bottom.
6106   // The point of exit cannot be a branch out of the structured block.
6107   // longjmp() and throw() must not violate the entry/exit criteria.
6108   CS->getCapturedDecl()->setNothrow();
6109 
6110   OMPLoopDirective::HelperExprs B;
6111   // In presence of clause 'collapse' with number of loops, it will
6112   // define the nested loops number.
6113   unsigned NestedLoopCount =
6114       CheckOpenMPLoop(OMPD_teams_distribute_simd,
6115                       getCollapseNumberExpr(Clauses),
6116                       nullptr /*ordered not a clause on distribute*/, AStmt,
6117                       *this, *DSAStack, VarsWithImplicitDSA, B);
6118 
6119   if (NestedLoopCount == 0)
6120     return StmtError();
6121 
6122   assert((CurContext->isDependentContext() || B.builtAll()) &&
6123          "omp teams distribute simd loop exprs were not built");
6124 
6125   if (!CurContext->isDependentContext()) {
6126     // Finalize the clauses that need pre-built expressions for CodeGen.
6127     for (auto C : Clauses) {
6128       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6129         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6130                                      B.NumIterations, *this, CurScope,
6131                                      DSAStack))
6132           return StmtError();
6133     }
6134   }
6135 
6136   if (checkSimdlenSafelenSpecified(*this, Clauses))
6137     return StmtError();
6138 
6139   getCurFunction()->setHasBranchProtectedScope();
6140   return OMPTeamsDistributeSimdDirective::Create(
6141       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6142 }
6143 
6144 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
6145                                              SourceLocation StartLoc,
6146                                              SourceLocation LParenLoc,
6147                                              SourceLocation EndLoc) {
6148   OMPClause *Res = nullptr;
6149   switch (Kind) {
6150   case OMPC_final:
6151     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6152     break;
6153   case OMPC_num_threads:
6154     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6155     break;
6156   case OMPC_safelen:
6157     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6158     break;
6159   case OMPC_simdlen:
6160     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6161     break;
6162   case OMPC_collapse:
6163     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6164     break;
6165   case OMPC_ordered:
6166     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6167     break;
6168   case OMPC_device:
6169     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6170     break;
6171   case OMPC_num_teams:
6172     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6173     break;
6174   case OMPC_thread_limit:
6175     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6176     break;
6177   case OMPC_priority:
6178     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6179     break;
6180   case OMPC_grainsize:
6181     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6182     break;
6183   case OMPC_num_tasks:
6184     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6185     break;
6186   case OMPC_hint:
6187     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6188     break;
6189   case OMPC_if:
6190   case OMPC_default:
6191   case OMPC_proc_bind:
6192   case OMPC_schedule:
6193   case OMPC_private:
6194   case OMPC_firstprivate:
6195   case OMPC_lastprivate:
6196   case OMPC_shared:
6197   case OMPC_reduction:
6198   case OMPC_linear:
6199   case OMPC_aligned:
6200   case OMPC_copyin:
6201   case OMPC_copyprivate:
6202   case OMPC_nowait:
6203   case OMPC_untied:
6204   case OMPC_mergeable:
6205   case OMPC_threadprivate:
6206   case OMPC_flush:
6207   case OMPC_read:
6208   case OMPC_write:
6209   case OMPC_update:
6210   case OMPC_capture:
6211   case OMPC_seq_cst:
6212   case OMPC_depend:
6213   case OMPC_threads:
6214   case OMPC_simd:
6215   case OMPC_map:
6216   case OMPC_nogroup:
6217   case OMPC_dist_schedule:
6218   case OMPC_defaultmap:
6219   case OMPC_unknown:
6220   case OMPC_uniform:
6221   case OMPC_to:
6222   case OMPC_from:
6223   case OMPC_use_device_ptr:
6224   case OMPC_is_device_ptr:
6225     llvm_unreachable("Clause is not allowed.");
6226   }
6227   return Res;
6228 }
6229 
6230 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6231                                      Expr *Condition, SourceLocation StartLoc,
6232                                      SourceLocation LParenLoc,
6233                                      SourceLocation NameModifierLoc,
6234                                      SourceLocation ColonLoc,
6235                                      SourceLocation EndLoc) {
6236   Expr *ValExpr = Condition;
6237   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6238       !Condition->isInstantiationDependent() &&
6239       !Condition->containsUnexpandedParameterPack()) {
6240     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6241     if (Val.isInvalid())
6242       return nullptr;
6243 
6244     ValExpr = MakeFullExpr(Val.get()).get();
6245   }
6246 
6247   return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
6248                                    NameModifierLoc, ColonLoc, EndLoc);
6249 }
6250 
6251 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6252                                         SourceLocation StartLoc,
6253                                         SourceLocation LParenLoc,
6254                                         SourceLocation EndLoc) {
6255   Expr *ValExpr = Condition;
6256   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6257       !Condition->isInstantiationDependent() &&
6258       !Condition->containsUnexpandedParameterPack()) {
6259     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
6260     if (Val.isInvalid())
6261       return nullptr;
6262 
6263     ValExpr = MakeFullExpr(Val.get()).get();
6264   }
6265 
6266   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6267 }
6268 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6269                                                         Expr *Op) {
6270   if (!Op)
6271     return ExprError();
6272 
6273   class IntConvertDiagnoser : public ICEConvertDiagnoser {
6274   public:
6275     IntConvertDiagnoser()
6276         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
6277     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6278                                          QualType T) override {
6279       return S.Diag(Loc, diag::err_omp_not_integral) << T;
6280     }
6281     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6282                                              QualType T) override {
6283       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6284     }
6285     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6286                                                QualType T,
6287                                                QualType ConvTy) override {
6288       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6289     }
6290     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6291                                            QualType ConvTy) override {
6292       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6293              << ConvTy->isEnumeralType() << ConvTy;
6294     }
6295     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6296                                             QualType T) override {
6297       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6298     }
6299     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6300                                         QualType ConvTy) override {
6301       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
6302              << ConvTy->isEnumeralType() << ConvTy;
6303     }
6304     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6305                                              QualType) override {
6306       llvm_unreachable("conversion functions are permitted");
6307     }
6308   } ConvertDiagnoser;
6309   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6310 }
6311 
6312 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
6313                                       OpenMPClauseKind CKind,
6314                                       bool StrictlyPositive) {
6315   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6316       !ValExpr->isInstantiationDependent()) {
6317     SourceLocation Loc = ValExpr->getExprLoc();
6318     ExprResult Value =
6319         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6320     if (Value.isInvalid())
6321       return false;
6322 
6323     ValExpr = Value.get();
6324     // The expression must evaluate to a non-negative integer value.
6325     llvm::APSInt Result;
6326     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
6327         Result.isSigned() &&
6328         !((!StrictlyPositive && Result.isNonNegative()) ||
6329           (StrictlyPositive && Result.isStrictlyPositive()))) {
6330       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
6331           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6332           << ValExpr->getSourceRange();
6333       return false;
6334     }
6335   }
6336   return true;
6337 }
6338 
6339 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6340                                              SourceLocation StartLoc,
6341                                              SourceLocation LParenLoc,
6342                                              SourceLocation EndLoc) {
6343   Expr *ValExpr = NumThreads;
6344 
6345   // OpenMP [2.5, Restrictions]
6346   //  The num_threads expression must evaluate to a positive integer value.
6347   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6348                                  /*StrictlyPositive=*/true))
6349     return nullptr;
6350 
6351   return new (Context)
6352       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6353 }
6354 
6355 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
6356                                                        OpenMPClauseKind CKind,
6357                                                        bool StrictlyPositive) {
6358   if (!E)
6359     return ExprError();
6360   if (E->isValueDependent() || E->isTypeDependent() ||
6361       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
6362     return E;
6363   llvm::APSInt Result;
6364   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6365   if (ICE.isInvalid())
6366     return ExprError();
6367   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6368       (!StrictlyPositive && !Result.isNonNegative())) {
6369     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
6370         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6371         << E->getSourceRange();
6372     return ExprError();
6373   }
6374   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6375     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6376         << E->getSourceRange();
6377     return ExprError();
6378   }
6379   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6380     DSAStack->setAssociatedLoops(Result.getExtValue());
6381   else if (CKind == OMPC_ordered)
6382     DSAStack->setAssociatedLoops(Result.getExtValue());
6383   return ICE;
6384 }
6385 
6386 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6387                                           SourceLocation LParenLoc,
6388                                           SourceLocation EndLoc) {
6389   // OpenMP [2.8.1, simd construct, Description]
6390   // The parameter of the safelen clause must be a constant
6391   // positive integer expression.
6392   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6393   if (Safelen.isInvalid())
6394     return nullptr;
6395   return new (Context)
6396       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
6397 }
6398 
6399 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6400                                           SourceLocation LParenLoc,
6401                                           SourceLocation EndLoc) {
6402   // OpenMP [2.8.1, simd construct, Description]
6403   // The parameter of the simdlen clause must be a constant
6404   // positive integer expression.
6405   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6406   if (Simdlen.isInvalid())
6407     return nullptr;
6408   return new (Context)
6409       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6410 }
6411 
6412 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6413                                            SourceLocation StartLoc,
6414                                            SourceLocation LParenLoc,
6415                                            SourceLocation EndLoc) {
6416   // OpenMP [2.7.1, loop construct, Description]
6417   // OpenMP [2.8.1, simd construct, Description]
6418   // OpenMP [2.9.6, distribute construct, Description]
6419   // The parameter of the collapse clause must be a constant
6420   // positive integer expression.
6421   ExprResult NumForLoopsResult =
6422       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6423   if (NumForLoopsResult.isInvalid())
6424     return nullptr;
6425   return new (Context)
6426       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
6427 }
6428 
6429 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6430                                           SourceLocation EndLoc,
6431                                           SourceLocation LParenLoc,
6432                                           Expr *NumForLoops) {
6433   // OpenMP [2.7.1, loop construct, Description]
6434   // OpenMP [2.8.1, simd construct, Description]
6435   // OpenMP [2.9.6, distribute construct, Description]
6436   // The parameter of the ordered clause must be a constant
6437   // positive integer expression if any.
6438   if (NumForLoops && LParenLoc.isValid()) {
6439     ExprResult NumForLoopsResult =
6440         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6441     if (NumForLoopsResult.isInvalid())
6442       return nullptr;
6443     NumForLoops = NumForLoopsResult.get();
6444   } else
6445     NumForLoops = nullptr;
6446   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
6447   return new (Context)
6448       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6449 }
6450 
6451 OMPClause *Sema::ActOnOpenMPSimpleClause(
6452     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6453     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
6454   OMPClause *Res = nullptr;
6455   switch (Kind) {
6456   case OMPC_default:
6457     Res =
6458         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
6459                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
6460     break;
6461   case OMPC_proc_bind:
6462     Res = ActOnOpenMPProcBindClause(
6463         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
6464         LParenLoc, EndLoc);
6465     break;
6466   case OMPC_if:
6467   case OMPC_final:
6468   case OMPC_num_threads:
6469   case OMPC_safelen:
6470   case OMPC_simdlen:
6471   case OMPC_collapse:
6472   case OMPC_schedule:
6473   case OMPC_private:
6474   case OMPC_firstprivate:
6475   case OMPC_lastprivate:
6476   case OMPC_shared:
6477   case OMPC_reduction:
6478   case OMPC_linear:
6479   case OMPC_aligned:
6480   case OMPC_copyin:
6481   case OMPC_copyprivate:
6482   case OMPC_ordered:
6483   case OMPC_nowait:
6484   case OMPC_untied:
6485   case OMPC_mergeable:
6486   case OMPC_threadprivate:
6487   case OMPC_flush:
6488   case OMPC_read:
6489   case OMPC_write:
6490   case OMPC_update:
6491   case OMPC_capture:
6492   case OMPC_seq_cst:
6493   case OMPC_depend:
6494   case OMPC_device:
6495   case OMPC_threads:
6496   case OMPC_simd:
6497   case OMPC_map:
6498   case OMPC_num_teams:
6499   case OMPC_thread_limit:
6500   case OMPC_priority:
6501   case OMPC_grainsize:
6502   case OMPC_nogroup:
6503   case OMPC_num_tasks:
6504   case OMPC_hint:
6505   case OMPC_dist_schedule:
6506   case OMPC_defaultmap:
6507   case OMPC_unknown:
6508   case OMPC_uniform:
6509   case OMPC_to:
6510   case OMPC_from:
6511   case OMPC_use_device_ptr:
6512   case OMPC_is_device_ptr:
6513     llvm_unreachable("Clause is not allowed.");
6514   }
6515   return Res;
6516 }
6517 
6518 static std::string
6519 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
6520                         ArrayRef<unsigned> Exclude = llvm::None) {
6521   std::string Values;
6522   unsigned Bound = Last >= 2 ? Last - 2 : 0;
6523   unsigned Skipped = Exclude.size();
6524   auto S = Exclude.begin(), E = Exclude.end();
6525   for (unsigned i = First; i < Last; ++i) {
6526     if (std::find(S, E, i) != E) {
6527       --Skipped;
6528       continue;
6529     }
6530     Values += "'";
6531     Values += getOpenMPSimpleClauseTypeName(K, i);
6532     Values += "'";
6533     if (i == Bound - Skipped)
6534       Values += " or ";
6535     else if (i != Bound + 1 - Skipped)
6536       Values += ", ";
6537   }
6538   return Values;
6539 }
6540 
6541 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6542                                           SourceLocation KindKwLoc,
6543                                           SourceLocation StartLoc,
6544                                           SourceLocation LParenLoc,
6545                                           SourceLocation EndLoc) {
6546   if (Kind == OMPC_DEFAULT_unknown) {
6547     static_assert(OMPC_DEFAULT_unknown > 0,
6548                   "OMPC_DEFAULT_unknown not greater than 0");
6549     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6550         << getListOfPossibleValues(OMPC_default, /*First=*/0,
6551                                    /*Last=*/OMPC_DEFAULT_unknown)
6552         << getOpenMPClauseName(OMPC_default);
6553     return nullptr;
6554   }
6555   switch (Kind) {
6556   case OMPC_DEFAULT_none:
6557     DSAStack->setDefaultDSANone(KindKwLoc);
6558     break;
6559   case OMPC_DEFAULT_shared:
6560     DSAStack->setDefaultDSAShared(KindKwLoc);
6561     break;
6562   case OMPC_DEFAULT_unknown:
6563     llvm_unreachable("Clause kind is not allowed.");
6564     break;
6565   }
6566   return new (Context)
6567       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6568 }
6569 
6570 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6571                                            SourceLocation KindKwLoc,
6572                                            SourceLocation StartLoc,
6573                                            SourceLocation LParenLoc,
6574                                            SourceLocation EndLoc) {
6575   if (Kind == OMPC_PROC_BIND_unknown) {
6576     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6577         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6578                                    /*Last=*/OMPC_PROC_BIND_unknown)
6579         << getOpenMPClauseName(OMPC_proc_bind);
6580     return nullptr;
6581   }
6582   return new (Context)
6583       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6584 }
6585 
6586 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6587     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6588     SourceLocation StartLoc, SourceLocation LParenLoc,
6589     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6590     SourceLocation EndLoc) {
6591   OMPClause *Res = nullptr;
6592   switch (Kind) {
6593   case OMPC_schedule:
6594     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6595     assert(Argument.size() == NumberOfElements &&
6596            ArgumentLoc.size() == NumberOfElements);
6597     Res = ActOnOpenMPScheduleClause(
6598         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6599         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6600         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6601         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6602         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6603     break;
6604   case OMPC_if:
6605     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6606     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6607                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6608                               DelimLoc, EndLoc);
6609     break;
6610   case OMPC_dist_schedule:
6611     Res = ActOnOpenMPDistScheduleClause(
6612         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
6613         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
6614     break;
6615   case OMPC_defaultmap:
6616     enum { Modifier, DefaultmapKind };
6617     Res = ActOnOpenMPDefaultmapClause(
6618         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
6619         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
6620         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
6621         EndLoc);
6622     break;
6623   case OMPC_final:
6624   case OMPC_num_threads:
6625   case OMPC_safelen:
6626   case OMPC_simdlen:
6627   case OMPC_collapse:
6628   case OMPC_default:
6629   case OMPC_proc_bind:
6630   case OMPC_private:
6631   case OMPC_firstprivate:
6632   case OMPC_lastprivate:
6633   case OMPC_shared:
6634   case OMPC_reduction:
6635   case OMPC_linear:
6636   case OMPC_aligned:
6637   case OMPC_copyin:
6638   case OMPC_copyprivate:
6639   case OMPC_ordered:
6640   case OMPC_nowait:
6641   case OMPC_untied:
6642   case OMPC_mergeable:
6643   case OMPC_threadprivate:
6644   case OMPC_flush:
6645   case OMPC_read:
6646   case OMPC_write:
6647   case OMPC_update:
6648   case OMPC_capture:
6649   case OMPC_seq_cst:
6650   case OMPC_depend:
6651   case OMPC_device:
6652   case OMPC_threads:
6653   case OMPC_simd:
6654   case OMPC_map:
6655   case OMPC_num_teams:
6656   case OMPC_thread_limit:
6657   case OMPC_priority:
6658   case OMPC_grainsize:
6659   case OMPC_nogroup:
6660   case OMPC_num_tasks:
6661   case OMPC_hint:
6662   case OMPC_unknown:
6663   case OMPC_uniform:
6664   case OMPC_to:
6665   case OMPC_from:
6666   case OMPC_use_device_ptr:
6667   case OMPC_is_device_ptr:
6668     llvm_unreachable("Clause is not allowed.");
6669   }
6670   return Res;
6671 }
6672 
6673 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6674                                    OpenMPScheduleClauseModifier M2,
6675                                    SourceLocation M1Loc, SourceLocation M2Loc) {
6676   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6677     SmallVector<unsigned, 2> Excluded;
6678     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6679       Excluded.push_back(M2);
6680     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6681       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6682     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6683       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6684     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6685         << getListOfPossibleValues(OMPC_schedule,
6686                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6687                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6688                                    Excluded)
6689         << getOpenMPClauseName(OMPC_schedule);
6690     return true;
6691   }
6692   return false;
6693 }
6694 
6695 OMPClause *Sema::ActOnOpenMPScheduleClause(
6696     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6697     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6698     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6699     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6700   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6701       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6702     return nullptr;
6703   // OpenMP, 2.7.1, Loop Construct, Restrictions
6704   // Either the monotonic modifier or the nonmonotonic modifier can be specified
6705   // but not both.
6706   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6707       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6708        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6709       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6710        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6711     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6712         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6713         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6714     return nullptr;
6715   }
6716   if (Kind == OMPC_SCHEDULE_unknown) {
6717     std::string Values;
6718     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6719       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6720       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6721                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6722                                        Exclude);
6723     } else {
6724       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6725                                        /*Last=*/OMPC_SCHEDULE_unknown);
6726     }
6727     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6728         << Values << getOpenMPClauseName(OMPC_schedule);
6729     return nullptr;
6730   }
6731   // OpenMP, 2.7.1, Loop Construct, Restrictions
6732   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6733   // schedule(guided).
6734   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6735        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6736       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6737     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6738          diag::err_omp_schedule_nonmonotonic_static);
6739     return nullptr;
6740   }
6741   Expr *ValExpr = ChunkSize;
6742   Stmt *HelperValStmt = nullptr;
6743   if (ChunkSize) {
6744     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6745         !ChunkSize->isInstantiationDependent() &&
6746         !ChunkSize->containsUnexpandedParameterPack()) {
6747       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6748       ExprResult Val =
6749           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6750       if (Val.isInvalid())
6751         return nullptr;
6752 
6753       ValExpr = Val.get();
6754 
6755       // OpenMP [2.7.1, Restrictions]
6756       //  chunk_size must be a loop invariant integer expression with a positive
6757       //  value.
6758       llvm::APSInt Result;
6759       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6760         if (Result.isSigned() && !Result.isStrictlyPositive()) {
6761           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6762               << "schedule" << 1 << ChunkSize->getSourceRange();
6763           return nullptr;
6764         }
6765       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
6766                  !CurContext->isDependentContext()) {
6767         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6768         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6769         HelperValStmt = buildPreInits(Context, Captures);
6770       }
6771     }
6772   }
6773 
6774   return new (Context)
6775       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
6776                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
6777 }
6778 
6779 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6780                                    SourceLocation StartLoc,
6781                                    SourceLocation EndLoc) {
6782   OMPClause *Res = nullptr;
6783   switch (Kind) {
6784   case OMPC_ordered:
6785     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6786     break;
6787   case OMPC_nowait:
6788     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6789     break;
6790   case OMPC_untied:
6791     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6792     break;
6793   case OMPC_mergeable:
6794     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6795     break;
6796   case OMPC_read:
6797     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6798     break;
6799   case OMPC_write:
6800     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6801     break;
6802   case OMPC_update:
6803     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6804     break;
6805   case OMPC_capture:
6806     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6807     break;
6808   case OMPC_seq_cst:
6809     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6810     break;
6811   case OMPC_threads:
6812     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6813     break;
6814   case OMPC_simd:
6815     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6816     break;
6817   case OMPC_nogroup:
6818     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6819     break;
6820   case OMPC_if:
6821   case OMPC_final:
6822   case OMPC_num_threads:
6823   case OMPC_safelen:
6824   case OMPC_simdlen:
6825   case OMPC_collapse:
6826   case OMPC_schedule:
6827   case OMPC_private:
6828   case OMPC_firstprivate:
6829   case OMPC_lastprivate:
6830   case OMPC_shared:
6831   case OMPC_reduction:
6832   case OMPC_linear:
6833   case OMPC_aligned:
6834   case OMPC_copyin:
6835   case OMPC_copyprivate:
6836   case OMPC_default:
6837   case OMPC_proc_bind:
6838   case OMPC_threadprivate:
6839   case OMPC_flush:
6840   case OMPC_depend:
6841   case OMPC_device:
6842   case OMPC_map:
6843   case OMPC_num_teams:
6844   case OMPC_thread_limit:
6845   case OMPC_priority:
6846   case OMPC_grainsize:
6847   case OMPC_num_tasks:
6848   case OMPC_hint:
6849   case OMPC_dist_schedule:
6850   case OMPC_defaultmap:
6851   case OMPC_unknown:
6852   case OMPC_uniform:
6853   case OMPC_to:
6854   case OMPC_from:
6855   case OMPC_use_device_ptr:
6856   case OMPC_is_device_ptr:
6857     llvm_unreachable("Clause is not allowed.");
6858   }
6859   return Res;
6860 }
6861 
6862 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6863                                          SourceLocation EndLoc) {
6864   DSAStack->setNowaitRegion();
6865   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6866 }
6867 
6868 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6869                                          SourceLocation EndLoc) {
6870   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6871 }
6872 
6873 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6874                                             SourceLocation EndLoc) {
6875   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6876 }
6877 
6878 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6879                                        SourceLocation EndLoc) {
6880   return new (Context) OMPReadClause(StartLoc, EndLoc);
6881 }
6882 
6883 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6884                                         SourceLocation EndLoc) {
6885   return new (Context) OMPWriteClause(StartLoc, EndLoc);
6886 }
6887 
6888 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6889                                          SourceLocation EndLoc) {
6890   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6891 }
6892 
6893 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6894                                           SourceLocation EndLoc) {
6895   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6896 }
6897 
6898 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6899                                          SourceLocation EndLoc) {
6900   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6901 }
6902 
6903 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6904                                           SourceLocation EndLoc) {
6905   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6906 }
6907 
6908 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6909                                        SourceLocation EndLoc) {
6910   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6911 }
6912 
6913 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6914                                           SourceLocation EndLoc) {
6915   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6916 }
6917 
6918 OMPClause *Sema::ActOnOpenMPVarListClause(
6919     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6920     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6921     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
6922     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
6923     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
6924     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
6925     SourceLocation DepLinMapLoc) {
6926   OMPClause *Res = nullptr;
6927   switch (Kind) {
6928   case OMPC_private:
6929     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6930     break;
6931   case OMPC_firstprivate:
6932     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6933     break;
6934   case OMPC_lastprivate:
6935     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6936     break;
6937   case OMPC_shared:
6938     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6939     break;
6940   case OMPC_reduction:
6941     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6942                                      EndLoc, ReductionIdScopeSpec, ReductionId);
6943     break;
6944   case OMPC_linear:
6945     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
6946                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
6947     break;
6948   case OMPC_aligned:
6949     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
6950                                    ColonLoc, EndLoc);
6951     break;
6952   case OMPC_copyin:
6953     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
6954     break;
6955   case OMPC_copyprivate:
6956     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6957     break;
6958   case OMPC_flush:
6959     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
6960     break;
6961   case OMPC_depend:
6962     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
6963                                   StartLoc, LParenLoc, EndLoc);
6964     break;
6965   case OMPC_map:
6966     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
6967                                DepLinMapLoc, ColonLoc, VarList, StartLoc,
6968                                LParenLoc, EndLoc);
6969     break;
6970   case OMPC_to:
6971     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
6972     break;
6973   case OMPC_from:
6974     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
6975     break;
6976   case OMPC_use_device_ptr:
6977     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
6978     break;
6979   case OMPC_is_device_ptr:
6980     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
6981     break;
6982   case OMPC_if:
6983   case OMPC_final:
6984   case OMPC_num_threads:
6985   case OMPC_safelen:
6986   case OMPC_simdlen:
6987   case OMPC_collapse:
6988   case OMPC_default:
6989   case OMPC_proc_bind:
6990   case OMPC_schedule:
6991   case OMPC_ordered:
6992   case OMPC_nowait:
6993   case OMPC_untied:
6994   case OMPC_mergeable:
6995   case OMPC_threadprivate:
6996   case OMPC_read:
6997   case OMPC_write:
6998   case OMPC_update:
6999   case OMPC_capture:
7000   case OMPC_seq_cst:
7001   case OMPC_device:
7002   case OMPC_threads:
7003   case OMPC_simd:
7004   case OMPC_num_teams:
7005   case OMPC_thread_limit:
7006   case OMPC_priority:
7007   case OMPC_grainsize:
7008   case OMPC_nogroup:
7009   case OMPC_num_tasks:
7010   case OMPC_hint:
7011   case OMPC_dist_schedule:
7012   case OMPC_defaultmap:
7013   case OMPC_unknown:
7014   case OMPC_uniform:
7015     llvm_unreachable("Clause is not allowed.");
7016   }
7017   return Res;
7018 }
7019 
7020 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
7021                                        ExprObjectKind OK, SourceLocation Loc) {
7022   ExprResult Res = BuildDeclRefExpr(
7023       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7024   if (!Res.isUsable())
7025     return ExprError();
7026   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7027     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7028     if (!Res.isUsable())
7029       return ExprError();
7030   }
7031   if (VK != VK_LValue && Res.get()->isGLValue()) {
7032     Res = DefaultLvalueConversion(Res.get());
7033     if (!Res.isUsable())
7034       return ExprError();
7035   }
7036   return Res;
7037 }
7038 
7039 static std::pair<ValueDecl *, bool>
7040 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7041                SourceRange &ERange, bool AllowArraySection = false) {
7042   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7043       RefExpr->containsUnexpandedParameterPack())
7044     return std::make_pair(nullptr, true);
7045 
7046   // OpenMP [3.1, C/C++]
7047   //  A list item is a variable name.
7048   // OpenMP  [2.9.3.3, Restrictions, p.1]
7049   //  A variable that is part of another variable (as an array or
7050   //  structure element) cannot appear in a private clause.
7051   RefExpr = RefExpr->IgnoreParens();
7052   enum {
7053     NoArrayExpr = -1,
7054     ArraySubscript = 0,
7055     OMPArraySection = 1
7056   } IsArrayExpr = NoArrayExpr;
7057   if (AllowArraySection) {
7058     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7059       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7060       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7061         Base = TempASE->getBase()->IgnoreParenImpCasts();
7062       RefExpr = Base;
7063       IsArrayExpr = ArraySubscript;
7064     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7065       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7066       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7067         Base = TempOASE->getBase()->IgnoreParenImpCasts();
7068       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7069         Base = TempASE->getBase()->IgnoreParenImpCasts();
7070       RefExpr = Base;
7071       IsArrayExpr = OMPArraySection;
7072     }
7073   }
7074   ELoc = RefExpr->getExprLoc();
7075   ERange = RefExpr->getSourceRange();
7076   RefExpr = RefExpr->IgnoreParenImpCasts();
7077   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7078   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7079   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7080       (S.getCurrentThisType().isNull() || !ME ||
7081        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7082        !isa<FieldDecl>(ME->getMemberDecl()))) {
7083     if (IsArrayExpr != NoArrayExpr)
7084       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7085                                                          << ERange;
7086     else {
7087       S.Diag(ELoc,
7088              AllowArraySection
7089                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
7090                  : diag::err_omp_expected_var_name_member_expr)
7091           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7092     }
7093     return std::make_pair(nullptr, false);
7094   }
7095   return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7096 }
7097 
7098 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7099                                           SourceLocation StartLoc,
7100                                           SourceLocation LParenLoc,
7101                                           SourceLocation EndLoc) {
7102   SmallVector<Expr *, 8> Vars;
7103   SmallVector<Expr *, 8> PrivateCopies;
7104   for (auto &RefExpr : VarList) {
7105     assert(RefExpr && "NULL expr in OpenMP private clause.");
7106     SourceLocation ELoc;
7107     SourceRange ERange;
7108     Expr *SimpleRefExpr = RefExpr;
7109     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7110     if (Res.second) {
7111       // It will be analyzed later.
7112       Vars.push_back(RefExpr);
7113       PrivateCopies.push_back(nullptr);
7114     }
7115     ValueDecl *D = Res.first;
7116     if (!D)
7117       continue;
7118 
7119     QualType Type = D->getType();
7120     auto *VD = dyn_cast<VarDecl>(D);
7121 
7122     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7123     //  A variable that appears in a private clause must not have an incomplete
7124     //  type or a reference type.
7125     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
7126       continue;
7127     Type = Type.getNonReferenceType();
7128 
7129     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7130     // in a Construct]
7131     //  Variables with the predetermined data-sharing attributes may not be
7132     //  listed in data-sharing attributes clauses, except for the cases
7133     //  listed below. For these exceptions only, listing a predetermined
7134     //  variable in a data-sharing attribute clause is allowed and overrides
7135     //  the variable's predetermined data-sharing attributes.
7136     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7137     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
7138       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7139                                           << getOpenMPClauseName(OMPC_private);
7140       ReportOriginalDSA(*this, DSAStack, D, DVar);
7141       continue;
7142     }
7143 
7144     // Variably modified types are not supported for tasks.
7145     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7146         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7147       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7148           << getOpenMPClauseName(OMPC_private) << Type
7149           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7150       bool IsDecl =
7151           !VD ||
7152           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7153       Diag(D->getLocation(),
7154            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7155           << D;
7156       continue;
7157     }
7158 
7159     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7160     // A list item cannot appear in both a map clause and a data-sharing
7161     // attribute clause on the same construct
7162     if (DSAStack->getCurrentDirective() == OMPD_target) {
7163       OpenMPClauseKind ConflictKind;
7164       if (DSAStack->checkMappableExprComponentListsForDecl(
7165               VD, /*CurrentRegionOnly=*/true,
7166               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7167                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
7168                 ConflictKind = WhereFoundClauseKind;
7169                 return true;
7170               })) {
7171         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7172             << getOpenMPClauseName(OMPC_private)
7173             << getOpenMPClauseName(ConflictKind)
7174             << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7175         ReportOriginalDSA(*this, DSAStack, D, DVar);
7176         continue;
7177       }
7178     }
7179 
7180     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7181     //  A variable of class type (or array thereof) that appears in a private
7182     //  clause requires an accessible, unambiguous default constructor for the
7183     //  class type.
7184     // Generate helper private variable and initialize it with the default
7185     // value. The address of the original variable is replaced by the address of
7186     // the new private variable in CodeGen. This new variable is not added to
7187     // IdResolver, so the code in the OpenMP region uses original variable for
7188     // proper diagnostics.
7189     Type = Type.getUnqualifiedType();
7190     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7191                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7192     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
7193     if (VDPrivate->isInvalidDecl())
7194       continue;
7195     auto VDPrivateRefExpr = buildDeclRefExpr(
7196         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
7197 
7198     DeclRefExpr *Ref = nullptr;
7199     if (!VD && !CurContext->isDependentContext())
7200       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7201     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
7202     Vars.push_back((VD || CurContext->isDependentContext())
7203                        ? RefExpr->IgnoreParens()
7204                        : Ref);
7205     PrivateCopies.push_back(VDPrivateRefExpr);
7206   }
7207 
7208   if (Vars.empty())
7209     return nullptr;
7210 
7211   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7212                                   PrivateCopies);
7213 }
7214 
7215 namespace {
7216 class DiagsUninitializedSeveretyRAII {
7217 private:
7218   DiagnosticsEngine &Diags;
7219   SourceLocation SavedLoc;
7220   bool IsIgnored;
7221 
7222 public:
7223   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7224                                  bool IsIgnored)
7225       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7226     if (!IsIgnored) {
7227       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7228                         /*Map*/ diag::Severity::Ignored, Loc);
7229     }
7230   }
7231   ~DiagsUninitializedSeveretyRAII() {
7232     if (!IsIgnored)
7233       Diags.popMappings(SavedLoc);
7234   }
7235 };
7236 }
7237 
7238 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7239                                                SourceLocation StartLoc,
7240                                                SourceLocation LParenLoc,
7241                                                SourceLocation EndLoc) {
7242   SmallVector<Expr *, 8> Vars;
7243   SmallVector<Expr *, 8> PrivateCopies;
7244   SmallVector<Expr *, 8> Inits;
7245   SmallVector<Decl *, 4> ExprCaptures;
7246   bool IsImplicitClause =
7247       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7248   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7249 
7250   for (auto &RefExpr : VarList) {
7251     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
7252     SourceLocation ELoc;
7253     SourceRange ERange;
7254     Expr *SimpleRefExpr = RefExpr;
7255     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7256     if (Res.second) {
7257       // It will be analyzed later.
7258       Vars.push_back(RefExpr);
7259       PrivateCopies.push_back(nullptr);
7260       Inits.push_back(nullptr);
7261     }
7262     ValueDecl *D = Res.first;
7263     if (!D)
7264       continue;
7265 
7266     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
7267     QualType Type = D->getType();
7268     auto *VD = dyn_cast<VarDecl>(D);
7269 
7270     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7271     //  A variable that appears in a private clause must not have an incomplete
7272     //  type or a reference type.
7273     if (RequireCompleteType(ELoc, Type,
7274                             diag::err_omp_firstprivate_incomplete_type))
7275       continue;
7276     Type = Type.getNonReferenceType();
7277 
7278     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7279     //  A variable of class type (or array thereof) that appears in a private
7280     //  clause requires an accessible, unambiguous copy constructor for the
7281     //  class type.
7282     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7283 
7284     // If an implicit firstprivate variable found it was checked already.
7285     DSAStackTy::DSAVarData TopDVar;
7286     if (!IsImplicitClause) {
7287       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7288       TopDVar = DVar;
7289       bool IsConstant = ElemType.isConstant(Context);
7290       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7291       //  A list item that specifies a given variable may not appear in more
7292       // than one clause on the same directive, except that a variable may be
7293       //  specified in both firstprivate and lastprivate clauses.
7294       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
7295           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
7296         Diag(ELoc, diag::err_omp_wrong_dsa)
7297             << getOpenMPClauseName(DVar.CKind)
7298             << getOpenMPClauseName(OMPC_firstprivate);
7299         ReportOriginalDSA(*this, DSAStack, D, DVar);
7300         continue;
7301       }
7302 
7303       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7304       // in a Construct]
7305       //  Variables with the predetermined data-sharing attributes may not be
7306       //  listed in data-sharing attributes clauses, except for the cases
7307       //  listed below. For these exceptions only, listing a predetermined
7308       //  variable in a data-sharing attribute clause is allowed and overrides
7309       //  the variable's predetermined data-sharing attributes.
7310       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7311       // in a Construct, C/C++, p.2]
7312       //  Variables with const-qualified type having no mutable member may be
7313       //  listed in a firstprivate clause, even if they are static data members.
7314       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
7315           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7316         Diag(ELoc, diag::err_omp_wrong_dsa)
7317             << getOpenMPClauseName(DVar.CKind)
7318             << getOpenMPClauseName(OMPC_firstprivate);
7319         ReportOriginalDSA(*this, DSAStack, D, DVar);
7320         continue;
7321       }
7322 
7323       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7324       // OpenMP [2.9.3.4, Restrictions, p.2]
7325       //  A list item that is private within a parallel region must not appear
7326       //  in a firstprivate clause on a worksharing construct if any of the
7327       //  worksharing regions arising from the worksharing construct ever bind
7328       //  to any of the parallel regions arising from the parallel construct.
7329       if (isOpenMPWorksharingDirective(CurrDir) &&
7330           !isOpenMPParallelDirective(CurrDir)) {
7331         DVar = DSAStack->getImplicitDSA(D, true);
7332         if (DVar.CKind != OMPC_shared &&
7333             (isOpenMPParallelDirective(DVar.DKind) ||
7334              DVar.DKind == OMPD_unknown)) {
7335           Diag(ELoc, diag::err_omp_required_access)
7336               << getOpenMPClauseName(OMPC_firstprivate)
7337               << getOpenMPClauseName(OMPC_shared);
7338           ReportOriginalDSA(*this, DSAStack, D, DVar);
7339           continue;
7340         }
7341       }
7342       // OpenMP [2.9.3.4, Restrictions, p.3]
7343       //  A list item that appears in a reduction clause of a parallel construct
7344       //  must not appear in a firstprivate clause on a worksharing or task
7345       //  construct if any of the worksharing or task regions arising from the
7346       //  worksharing or task construct ever bind to any of the parallel regions
7347       //  arising from the parallel construct.
7348       // OpenMP [2.9.3.4, Restrictions, p.4]
7349       //  A list item that appears in a reduction clause in worksharing
7350       //  construct must not appear in a firstprivate clause in a task construct
7351       //  encountered during execution of any of the worksharing regions arising
7352       //  from the worksharing construct.
7353       if (isOpenMPTaskingDirective(CurrDir)) {
7354         DVar = DSAStack->hasInnermostDSA(
7355             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7356             [](OpenMPDirectiveKind K) -> bool {
7357               return isOpenMPParallelDirective(K) ||
7358                      isOpenMPWorksharingDirective(K);
7359             },
7360             false);
7361         if (DVar.CKind == OMPC_reduction &&
7362             (isOpenMPParallelDirective(DVar.DKind) ||
7363              isOpenMPWorksharingDirective(DVar.DKind))) {
7364           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7365               << getOpenMPDirectiveName(DVar.DKind);
7366           ReportOriginalDSA(*this, DSAStack, D, DVar);
7367           continue;
7368         }
7369       }
7370 
7371       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7372       // A list item that is private within a teams region must not appear in a
7373       // firstprivate clause on a distribute construct if any of the distribute
7374       // regions arising from the distribute construct ever bind to any of the
7375       // teams regions arising from the teams construct.
7376       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7377       // A list item that appears in a reduction clause of a teams construct
7378       // must not appear in a firstprivate clause on a distribute construct if
7379       // any of the distribute regions arising from the distribute construct
7380       // ever bind to any of the teams regions arising from the teams construct.
7381       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7382       // A list item may appear in a firstprivate or lastprivate clause but not
7383       // both.
7384       if (CurrDir == OMPD_distribute) {
7385         DVar = DSAStack->hasInnermostDSA(
7386             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7387             [](OpenMPDirectiveKind K) -> bool {
7388               return isOpenMPTeamsDirective(K);
7389             },
7390             false);
7391         if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7392           Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
7393           ReportOriginalDSA(*this, DSAStack, D, DVar);
7394           continue;
7395         }
7396         DVar = DSAStack->hasInnermostDSA(
7397             D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7398             [](OpenMPDirectiveKind K) -> bool {
7399               return isOpenMPTeamsDirective(K);
7400             },
7401             false);
7402         if (DVar.CKind == OMPC_reduction &&
7403             isOpenMPTeamsDirective(DVar.DKind)) {
7404           Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
7405           ReportOriginalDSA(*this, DSAStack, D, DVar);
7406           continue;
7407         }
7408         DVar = DSAStack->getTopDSA(D, false);
7409         if (DVar.CKind == OMPC_lastprivate) {
7410           Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7411           ReportOriginalDSA(*this, DSAStack, D, DVar);
7412           continue;
7413         }
7414       }
7415       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7416       // A list item cannot appear in both a map clause and a data-sharing
7417       // attribute clause on the same construct
7418       if (CurrDir == OMPD_target) {
7419         OpenMPClauseKind ConflictKind;
7420         if (DSAStack->checkMappableExprComponentListsForDecl(
7421                 VD, /*CurrentRegionOnly=*/true,
7422                 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7423                     OpenMPClauseKind WhereFoundClauseKind) -> bool {
7424                   ConflictKind = WhereFoundClauseKind;
7425                   return true;
7426                 })) {
7427           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
7428               << getOpenMPClauseName(OMPC_firstprivate)
7429               << getOpenMPClauseName(ConflictKind)
7430               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7431           ReportOriginalDSA(*this, DSAStack, D, DVar);
7432           continue;
7433         }
7434       }
7435     }
7436 
7437     // Variably modified types are not supported for tasks.
7438     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
7439         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
7440       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7441           << getOpenMPClauseName(OMPC_firstprivate) << Type
7442           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7443       bool IsDecl =
7444           !VD ||
7445           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7446       Diag(D->getLocation(),
7447            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7448           << D;
7449       continue;
7450     }
7451 
7452     Type = Type.getUnqualifiedType();
7453     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7454                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
7455     // Generate helper private variable and initialize it with the value of the
7456     // original variable. The address of the original variable is replaced by
7457     // the address of the new private variable in the CodeGen. This new variable
7458     // is not added to IdResolver, so the code in the OpenMP region uses
7459     // original variable for proper diagnostics and variable capturing.
7460     Expr *VDInitRefExpr = nullptr;
7461     // For arrays generate initializer for single element and replace it by the
7462     // original array element in CodeGen.
7463     if (Type->isArrayType()) {
7464       auto VDInit =
7465           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
7466       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
7467       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
7468       ElemType = ElemType.getUnqualifiedType();
7469       auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
7470                                       ".firstprivate.temp");
7471       InitializedEntity Entity =
7472           InitializedEntity::InitializeVariable(VDInitTemp);
7473       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
7474 
7475       InitializationSequence InitSeq(*this, Entity, Kind, Init);
7476       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
7477       if (Result.isInvalid())
7478         VDPrivate->setInvalidDecl();
7479       else
7480         VDPrivate->setInit(Result.getAs<Expr>());
7481       // Remove temp variable declaration.
7482       Context.Deallocate(VDInitTemp);
7483     } else {
7484       auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
7485                                   ".firstprivate.temp");
7486       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
7487                                        RefExpr->getExprLoc());
7488       AddInitializerToDecl(VDPrivate,
7489                            DefaultLvalueConversion(VDInitRefExpr).get(),
7490                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
7491     }
7492     if (VDPrivate->isInvalidDecl()) {
7493       if (IsImplicitClause) {
7494         Diag(RefExpr->getExprLoc(),
7495              diag::note_omp_task_predetermined_firstprivate_here);
7496       }
7497       continue;
7498     }
7499     CurContext->addDecl(VDPrivate);
7500     auto VDPrivateRefExpr = buildDeclRefExpr(
7501         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
7502         RefExpr->getExprLoc());
7503     DeclRefExpr *Ref = nullptr;
7504     if (!VD && !CurContext->isDependentContext()) {
7505       if (TopDVar.CKind == OMPC_lastprivate)
7506         Ref = TopDVar.PrivateCopy;
7507       else {
7508         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7509         if (!IsOpenMPCapturedDecl(D))
7510           ExprCaptures.push_back(Ref->getDecl());
7511       }
7512     }
7513     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
7514     Vars.push_back((VD || CurContext->isDependentContext())
7515                        ? RefExpr->IgnoreParens()
7516                        : Ref);
7517     PrivateCopies.push_back(VDPrivateRefExpr);
7518     Inits.push_back(VDInitRefExpr);
7519   }
7520 
7521   if (Vars.empty())
7522     return nullptr;
7523 
7524   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7525                                        Vars, PrivateCopies, Inits,
7526                                        buildPreInits(Context, ExprCaptures));
7527 }
7528 
7529 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
7530                                               SourceLocation StartLoc,
7531                                               SourceLocation LParenLoc,
7532                                               SourceLocation EndLoc) {
7533   SmallVector<Expr *, 8> Vars;
7534   SmallVector<Expr *, 8> SrcExprs;
7535   SmallVector<Expr *, 8> DstExprs;
7536   SmallVector<Expr *, 8> AssignmentOps;
7537   SmallVector<Decl *, 4> ExprCaptures;
7538   SmallVector<Expr *, 4> ExprPostUpdates;
7539   for (auto &RefExpr : VarList) {
7540     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7541     SourceLocation ELoc;
7542     SourceRange ERange;
7543     Expr *SimpleRefExpr = RefExpr;
7544     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7545     if (Res.second) {
7546       // It will be analyzed later.
7547       Vars.push_back(RefExpr);
7548       SrcExprs.push_back(nullptr);
7549       DstExprs.push_back(nullptr);
7550       AssignmentOps.push_back(nullptr);
7551     }
7552     ValueDecl *D = Res.first;
7553     if (!D)
7554       continue;
7555 
7556     QualType Type = D->getType();
7557     auto *VD = dyn_cast<VarDecl>(D);
7558 
7559     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
7560     //  A variable that appears in a lastprivate clause must not have an
7561     //  incomplete type or a reference type.
7562     if (RequireCompleteType(ELoc, Type,
7563                             diag::err_omp_lastprivate_incomplete_type))
7564       continue;
7565     Type = Type.getNonReferenceType();
7566 
7567     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7568     // in a Construct]
7569     //  Variables with the predetermined data-sharing attributes may not be
7570     //  listed in data-sharing attributes clauses, except for the cases
7571     //  listed below.
7572     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7573     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
7574         DVar.CKind != OMPC_firstprivate &&
7575         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
7576       Diag(ELoc, diag::err_omp_wrong_dsa)
7577           << getOpenMPClauseName(DVar.CKind)
7578           << getOpenMPClauseName(OMPC_lastprivate);
7579       ReportOriginalDSA(*this, DSAStack, D, DVar);
7580       continue;
7581     }
7582 
7583     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7584     // OpenMP [2.14.3.5, Restrictions, p.2]
7585     // A list item that is private within a parallel region, or that appears in
7586     // the reduction clause of a parallel construct, must not appear in a
7587     // lastprivate clause on a worksharing construct if any of the corresponding
7588     // worksharing regions ever binds to any of the corresponding parallel
7589     // regions.
7590     DSAStackTy::DSAVarData TopDVar = DVar;
7591     if (isOpenMPWorksharingDirective(CurrDir) &&
7592         !isOpenMPParallelDirective(CurrDir)) {
7593       DVar = DSAStack->getImplicitDSA(D, true);
7594       if (DVar.CKind != OMPC_shared) {
7595         Diag(ELoc, diag::err_omp_required_access)
7596             << getOpenMPClauseName(OMPC_lastprivate)
7597             << getOpenMPClauseName(OMPC_shared);
7598         ReportOriginalDSA(*this, DSAStack, D, DVar);
7599         continue;
7600       }
7601     }
7602 
7603     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7604     // A list item may appear in a firstprivate or lastprivate clause but not
7605     // both.
7606     if (CurrDir == OMPD_distribute) {
7607       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7608       if (DVar.CKind == OMPC_firstprivate) {
7609         Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
7610         ReportOriginalDSA(*this, DSAStack, D, DVar);
7611         continue;
7612       }
7613     }
7614 
7615     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
7616     //  A variable of class type (or array thereof) that appears in a
7617     //  lastprivate clause requires an accessible, unambiguous default
7618     //  constructor for the class type, unless the list item is also specified
7619     //  in a firstprivate clause.
7620     //  A variable of class type (or array thereof) that appears in a
7621     //  lastprivate clause requires an accessible, unambiguous copy assignment
7622     //  operator for the class type.
7623     Type = Context.getBaseElementType(Type).getNonReferenceType();
7624     auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
7625                                Type.getUnqualifiedType(), ".lastprivate.src",
7626                                D->hasAttrs() ? &D->getAttrs() : nullptr);
7627     auto *PseudoSrcExpr =
7628         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
7629     auto *DstVD =
7630         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
7631                      D->hasAttrs() ? &D->getAttrs() : nullptr);
7632     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
7633     // For arrays generate assignment operation for single element and replace
7634     // it by the original array element in CodeGen.
7635     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
7636                                    PseudoDstExpr, PseudoSrcExpr);
7637     if (AssignmentOp.isInvalid())
7638       continue;
7639     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
7640                                        /*DiscardedValue=*/true);
7641     if (AssignmentOp.isInvalid())
7642       continue;
7643 
7644     DeclRefExpr *Ref = nullptr;
7645     if (!VD && !CurContext->isDependentContext()) {
7646       if (TopDVar.CKind == OMPC_firstprivate)
7647         Ref = TopDVar.PrivateCopy;
7648       else {
7649         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
7650         if (!IsOpenMPCapturedDecl(D))
7651           ExprCaptures.push_back(Ref->getDecl());
7652       }
7653       if (TopDVar.CKind == OMPC_firstprivate ||
7654           (!IsOpenMPCapturedDecl(D) &&
7655            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
7656         ExprResult RefRes = DefaultLvalueConversion(Ref);
7657         if (!RefRes.isUsable())
7658           continue;
7659         ExprResult PostUpdateRes =
7660             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
7661                        RefRes.get());
7662         if (!PostUpdateRes.isUsable())
7663           continue;
7664         ExprPostUpdates.push_back(
7665             IgnoredValueConversions(PostUpdateRes.get()).get());
7666       }
7667     }
7668     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
7669     Vars.push_back((VD || CurContext->isDependentContext())
7670                        ? RefExpr->IgnoreParens()
7671                        : Ref);
7672     SrcExprs.push_back(PseudoSrcExpr);
7673     DstExprs.push_back(PseudoDstExpr);
7674     AssignmentOps.push_back(AssignmentOp.get());
7675   }
7676 
7677   if (Vars.empty())
7678     return nullptr;
7679 
7680   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
7681                                       Vars, SrcExprs, DstExprs, AssignmentOps,
7682                                       buildPreInits(Context, ExprCaptures),
7683                                       buildPostUpdate(*this, ExprPostUpdates));
7684 }
7685 
7686 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
7687                                          SourceLocation StartLoc,
7688                                          SourceLocation LParenLoc,
7689                                          SourceLocation EndLoc) {
7690   SmallVector<Expr *, 8> Vars;
7691   for (auto &RefExpr : VarList) {
7692     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
7693     SourceLocation ELoc;
7694     SourceRange ERange;
7695     Expr *SimpleRefExpr = RefExpr;
7696     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
7697     if (Res.second) {
7698       // It will be analyzed later.
7699       Vars.push_back(RefExpr);
7700     }
7701     ValueDecl *D = Res.first;
7702     if (!D)
7703       continue;
7704 
7705     auto *VD = dyn_cast<VarDecl>(D);
7706     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7707     // in a Construct]
7708     //  Variables with the predetermined data-sharing attributes may not be
7709     //  listed in data-sharing attributes clauses, except for the cases
7710     //  listed below. For these exceptions only, listing a predetermined
7711     //  variable in a data-sharing attribute clause is allowed and overrides
7712     //  the variable's predetermined data-sharing attributes.
7713     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
7714     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7715         DVar.RefExpr) {
7716       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7717                                           << getOpenMPClauseName(OMPC_shared);
7718       ReportOriginalDSA(*this, DSAStack, D, DVar);
7719       continue;
7720     }
7721 
7722     DeclRefExpr *Ref = nullptr;
7723     if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
7724       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
7725     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
7726     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
7727                        ? RefExpr->IgnoreParens()
7728                        : Ref);
7729   }
7730 
7731   if (Vars.empty())
7732     return nullptr;
7733 
7734   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7735 }
7736 
7737 namespace {
7738 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7739   DSAStackTy *Stack;
7740 
7741 public:
7742   bool VisitDeclRefExpr(DeclRefExpr *E) {
7743     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7744       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7745       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7746         return false;
7747       if (DVar.CKind != OMPC_unknown)
7748         return true;
7749       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
7750           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
7751           false);
7752       if (DVarPrivate.CKind != OMPC_unknown)
7753         return true;
7754       return false;
7755     }
7756     return false;
7757   }
7758   bool VisitStmt(Stmt *S) {
7759     for (auto Child : S->children()) {
7760       if (Child && Visit(Child))
7761         return true;
7762     }
7763     return false;
7764   }
7765   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
7766 };
7767 } // namespace
7768 
7769 namespace {
7770 // Transform MemberExpression for specified FieldDecl of current class to
7771 // DeclRefExpr to specified OMPCapturedExprDecl.
7772 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
7773   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
7774   ValueDecl *Field;
7775   DeclRefExpr *CapturedExpr;
7776 
7777 public:
7778   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
7779       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
7780 
7781   ExprResult TransformMemberExpr(MemberExpr *E) {
7782     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
7783         E->getMemberDecl() == Field) {
7784       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
7785       return CapturedExpr;
7786     }
7787     return BaseTransform::TransformMemberExpr(E);
7788   }
7789   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
7790 };
7791 } // namespace
7792 
7793 template <typename T>
7794 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
7795                             const llvm::function_ref<T(ValueDecl *)> &Gen) {
7796   for (auto &Set : Lookups) {
7797     for (auto *D : Set) {
7798       if (auto Res = Gen(cast<ValueDecl>(D)))
7799         return Res;
7800     }
7801   }
7802   return T();
7803 }
7804 
7805 static ExprResult
7806 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
7807                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
7808                          const DeclarationNameInfo &ReductionId, QualType Ty,
7809                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
7810   if (ReductionIdScopeSpec.isInvalid())
7811     return ExprError();
7812   SmallVector<UnresolvedSet<8>, 4> Lookups;
7813   if (S) {
7814     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
7815     Lookup.suppressDiagnostics();
7816     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
7817       auto *D = Lookup.getRepresentativeDecl();
7818       do {
7819         S = S->getParent();
7820       } while (S && !S->isDeclScope(D));
7821       if (S)
7822         S = S->getParent();
7823       Lookups.push_back(UnresolvedSet<8>());
7824       Lookups.back().append(Lookup.begin(), Lookup.end());
7825       Lookup.clear();
7826     }
7827   } else if (auto *ULE =
7828                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
7829     Lookups.push_back(UnresolvedSet<8>());
7830     Decl *PrevD = nullptr;
7831     for (auto *D : ULE->decls()) {
7832       if (D == PrevD)
7833         Lookups.push_back(UnresolvedSet<8>());
7834       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
7835         Lookups.back().addDecl(DRD);
7836       PrevD = D;
7837     }
7838   }
7839   if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
7840       Ty->containsUnexpandedParameterPack() ||
7841       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
7842         return !D->isInvalidDecl() &&
7843                (D->getType()->isDependentType() ||
7844                 D->getType()->isInstantiationDependentType() ||
7845                 D->getType()->containsUnexpandedParameterPack());
7846       })) {
7847     UnresolvedSet<8> ResSet;
7848     for (auto &Set : Lookups) {
7849       ResSet.append(Set.begin(), Set.end());
7850       // The last item marks the end of all declarations at the specified scope.
7851       ResSet.addDecl(Set[Set.size() - 1]);
7852     }
7853     return UnresolvedLookupExpr::Create(
7854         SemaRef.Context, /*NamingClass=*/nullptr,
7855         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
7856         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
7857   }
7858   if (auto *VD = filterLookupForUDR<ValueDecl *>(
7859           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
7860             if (!D->isInvalidDecl() &&
7861                 SemaRef.Context.hasSameType(D->getType(), Ty))
7862               return D;
7863             return nullptr;
7864           }))
7865     return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7866   if (auto *VD = filterLookupForUDR<ValueDecl *>(
7867           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
7868             if (!D->isInvalidDecl() &&
7869                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
7870                 !Ty.isMoreQualifiedThan(D->getType()))
7871               return D;
7872             return nullptr;
7873           })) {
7874     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7875                        /*DetectVirtual=*/false);
7876     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
7877       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
7878               VD->getType().getUnqualifiedType()))) {
7879         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
7880                                          /*DiagID=*/0) !=
7881             Sema::AR_inaccessible) {
7882           SemaRef.BuildBasePathArray(Paths, BasePath);
7883           return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
7884         }
7885       }
7886     }
7887   }
7888   if (ReductionIdScopeSpec.isSet()) {
7889     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
7890     return ExprError();
7891   }
7892   return ExprEmpty();
7893 }
7894 
7895 OMPClause *Sema::ActOnOpenMPReductionClause(
7896     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7897     SourceLocation ColonLoc, SourceLocation EndLoc,
7898     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
7899     ArrayRef<Expr *> UnresolvedReductions) {
7900   auto DN = ReductionId.getName();
7901   auto OOK = DN.getCXXOverloadedOperator();
7902   BinaryOperatorKind BOK = BO_Comma;
7903 
7904   // OpenMP [2.14.3.6, reduction clause]
7905   // C
7906   // reduction-identifier is either an identifier or one of the following
7907   // operators: +, -, *,  &, |, ^, && and ||
7908   // C++
7909   // reduction-identifier is either an id-expression or one of the following
7910   // operators: +, -, *, &, |, ^, && and ||
7911   // FIXME: Only 'min' and 'max' identifiers are supported for now.
7912   switch (OOK) {
7913   case OO_Plus:
7914   case OO_Minus:
7915     BOK = BO_Add;
7916     break;
7917   case OO_Star:
7918     BOK = BO_Mul;
7919     break;
7920   case OO_Amp:
7921     BOK = BO_And;
7922     break;
7923   case OO_Pipe:
7924     BOK = BO_Or;
7925     break;
7926   case OO_Caret:
7927     BOK = BO_Xor;
7928     break;
7929   case OO_AmpAmp:
7930     BOK = BO_LAnd;
7931     break;
7932   case OO_PipePipe:
7933     BOK = BO_LOr;
7934     break;
7935   case OO_New:
7936   case OO_Delete:
7937   case OO_Array_New:
7938   case OO_Array_Delete:
7939   case OO_Slash:
7940   case OO_Percent:
7941   case OO_Tilde:
7942   case OO_Exclaim:
7943   case OO_Equal:
7944   case OO_Less:
7945   case OO_Greater:
7946   case OO_LessEqual:
7947   case OO_GreaterEqual:
7948   case OO_PlusEqual:
7949   case OO_MinusEqual:
7950   case OO_StarEqual:
7951   case OO_SlashEqual:
7952   case OO_PercentEqual:
7953   case OO_CaretEqual:
7954   case OO_AmpEqual:
7955   case OO_PipeEqual:
7956   case OO_LessLess:
7957   case OO_GreaterGreater:
7958   case OO_LessLessEqual:
7959   case OO_GreaterGreaterEqual:
7960   case OO_EqualEqual:
7961   case OO_ExclaimEqual:
7962   case OO_PlusPlus:
7963   case OO_MinusMinus:
7964   case OO_Comma:
7965   case OO_ArrowStar:
7966   case OO_Arrow:
7967   case OO_Call:
7968   case OO_Subscript:
7969   case OO_Conditional:
7970   case OO_Coawait:
7971   case NUM_OVERLOADED_OPERATORS:
7972     llvm_unreachable("Unexpected reduction identifier");
7973   case OO_None:
7974     if (auto II = DN.getAsIdentifierInfo()) {
7975       if (II->isStr("max"))
7976         BOK = BO_GT;
7977       else if (II->isStr("min"))
7978         BOK = BO_LT;
7979     }
7980     break;
7981   }
7982   SourceRange ReductionIdRange;
7983   if (ReductionIdScopeSpec.isValid())
7984     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
7985   ReductionIdRange.setEnd(ReductionId.getEndLoc());
7986 
7987   SmallVector<Expr *, 8> Vars;
7988   SmallVector<Expr *, 8> Privates;
7989   SmallVector<Expr *, 8> LHSs;
7990   SmallVector<Expr *, 8> RHSs;
7991   SmallVector<Expr *, 8> ReductionOps;
7992   SmallVector<Decl *, 4> ExprCaptures;
7993   SmallVector<Expr *, 4> ExprPostUpdates;
7994   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
7995   bool FirstIter = true;
7996   for (auto RefExpr : VarList) {
7997     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
7998     // OpenMP [2.1, C/C++]
7999     //  A list item is a variable or array section, subject to the restrictions
8000     //  specified in Section 2.4 on page 42 and in each of the sections
8001     // describing clauses and directives for which a list appears.
8002     // OpenMP  [2.14.3.3, Restrictions, p.1]
8003     //  A variable that is part of another variable (as an array or
8004     //  structure element) cannot appear in a private clause.
8005     if (!FirstIter && IR != ER)
8006       ++IR;
8007     FirstIter = false;
8008     SourceLocation ELoc;
8009     SourceRange ERange;
8010     Expr *SimpleRefExpr = RefExpr;
8011     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8012                               /*AllowArraySection=*/true);
8013     if (Res.second) {
8014       // It will be analyzed later.
8015       Vars.push_back(RefExpr);
8016       Privates.push_back(nullptr);
8017       LHSs.push_back(nullptr);
8018       RHSs.push_back(nullptr);
8019       // Try to find 'declare reduction' corresponding construct before using
8020       // builtin/overloaded operators.
8021       QualType Type = Context.DependentTy;
8022       CXXCastPath BasePath;
8023       ExprResult DeclareReductionRef = buildDeclareReductionRef(
8024           *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8025           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8026       if (CurContext->isDependentContext() &&
8027           (DeclareReductionRef.isUnset() ||
8028            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8029         ReductionOps.push_back(DeclareReductionRef.get());
8030       else
8031         ReductionOps.push_back(nullptr);
8032     }
8033     ValueDecl *D = Res.first;
8034     if (!D)
8035       continue;
8036 
8037     QualType Type;
8038     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8039     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8040     if (ASE)
8041       Type = ASE->getType().getNonReferenceType();
8042     else if (OASE) {
8043       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8044       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8045         Type = ATy->getElementType();
8046       else
8047         Type = BaseType->getPointeeType();
8048       Type = Type.getNonReferenceType();
8049     } else
8050       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8051     auto *VD = dyn_cast<VarDecl>(D);
8052 
8053     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8054     //  A variable that appears in a private clause must not have an incomplete
8055     //  type or a reference type.
8056     if (RequireCompleteType(ELoc, Type,
8057                             diag::err_omp_reduction_incomplete_type))
8058       continue;
8059     // OpenMP [2.14.3.6, reduction clause, Restrictions]
8060     // A list item that appears in a reduction clause must not be
8061     // const-qualified.
8062     if (Type.getNonReferenceType().isConstant(Context)) {
8063       Diag(ELoc, diag::err_omp_const_reduction_list_item)
8064           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
8065       if (!ASE && !OASE) {
8066         bool IsDecl = !VD ||
8067                       VD->isThisDeclarationADefinition(Context) ==
8068                           VarDecl::DeclarationOnly;
8069         Diag(D->getLocation(),
8070              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8071             << D;
8072       }
8073       continue;
8074     }
8075     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8076     //  If a list-item is a reference type then it must bind to the same object
8077     //  for all threads of the team.
8078     if (!ASE && !OASE && VD) {
8079       VarDecl *VDDef = VD->getDefinition();
8080       if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
8081         DSARefChecker Check(DSAStack);
8082         if (Check.Visit(VDDef->getInit())) {
8083           Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8084           Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8085           continue;
8086         }
8087       }
8088     }
8089 
8090     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8091     // in a Construct]
8092     //  Variables with the predetermined data-sharing attributes may not be
8093     //  listed in data-sharing attributes clauses, except for the cases
8094     //  listed below. For these exceptions only, listing a predetermined
8095     //  variable in a data-sharing attribute clause is allowed and overrides
8096     //  the variable's predetermined data-sharing attributes.
8097     // OpenMP [2.14.3.6, Restrictions, p.3]
8098     //  Any number of reduction clauses can be specified on the directive,
8099     //  but a list item can appear only once in the reduction clauses for that
8100     //  directive.
8101     DSAStackTy::DSAVarData DVar;
8102     DVar = DSAStack->getTopDSA(D, false);
8103     if (DVar.CKind == OMPC_reduction) {
8104       Diag(ELoc, diag::err_omp_once_referenced)
8105           << getOpenMPClauseName(OMPC_reduction);
8106       if (DVar.RefExpr)
8107         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
8108     } else if (DVar.CKind != OMPC_unknown) {
8109       Diag(ELoc, diag::err_omp_wrong_dsa)
8110           << getOpenMPClauseName(DVar.CKind)
8111           << getOpenMPClauseName(OMPC_reduction);
8112       ReportOriginalDSA(*this, DSAStack, D, DVar);
8113       continue;
8114     }
8115 
8116     // OpenMP [2.14.3.6, Restrictions, p.1]
8117     //  A list item that appears in a reduction clause of a worksharing
8118     //  construct must be shared in the parallel regions to which any of the
8119     //  worksharing regions arising from the worksharing construct bind.
8120     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8121     if (isOpenMPWorksharingDirective(CurrDir) &&
8122         !isOpenMPParallelDirective(CurrDir)) {
8123       DVar = DSAStack->getImplicitDSA(D, true);
8124       if (DVar.CKind != OMPC_shared) {
8125         Diag(ELoc, diag::err_omp_required_access)
8126             << getOpenMPClauseName(OMPC_reduction)
8127             << getOpenMPClauseName(OMPC_shared);
8128         ReportOriginalDSA(*this, DSAStack, D, DVar);
8129         continue;
8130       }
8131     }
8132 
8133     // Try to find 'declare reduction' corresponding construct before using
8134     // builtin/overloaded operators.
8135     CXXCastPath BasePath;
8136     ExprResult DeclareReductionRef = buildDeclareReductionRef(
8137         *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8138         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8139     if (DeclareReductionRef.isInvalid())
8140       continue;
8141     if (CurContext->isDependentContext() &&
8142         (DeclareReductionRef.isUnset() ||
8143          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8144       Vars.push_back(RefExpr);
8145       Privates.push_back(nullptr);
8146       LHSs.push_back(nullptr);
8147       RHSs.push_back(nullptr);
8148       ReductionOps.push_back(DeclareReductionRef.get());
8149       continue;
8150     }
8151     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8152       // Not allowed reduction identifier is found.
8153       Diag(ReductionId.getLocStart(),
8154            diag::err_omp_unknown_reduction_identifier)
8155           << Type << ReductionIdRange;
8156       continue;
8157     }
8158 
8159     // OpenMP [2.14.3.6, reduction clause, Restrictions]
8160     // The type of a list item that appears in a reduction clause must be valid
8161     // for the reduction-identifier. For a max or min reduction in C, the type
8162     // of the list item must be an allowed arithmetic data type: char, int,
8163     // float, double, or _Bool, possibly modified with long, short, signed, or
8164     // unsigned. For a max or min reduction in C++, the type of the list item
8165     // must be an allowed arithmetic data type: char, wchar_t, int, float,
8166     // double, or bool, possibly modified with long, short, signed, or unsigned.
8167     if (DeclareReductionRef.isUnset()) {
8168       if ((BOK == BO_GT || BOK == BO_LT) &&
8169           !(Type->isScalarType() ||
8170             (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8171         Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8172             << getLangOpts().CPlusPlus;
8173         if (!ASE && !OASE) {
8174           bool IsDecl = !VD ||
8175                         VD->isThisDeclarationADefinition(Context) ==
8176                             VarDecl::DeclarationOnly;
8177           Diag(D->getLocation(),
8178                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8179               << D;
8180         }
8181         continue;
8182       }
8183       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8184           !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8185         Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8186         if (!ASE && !OASE) {
8187           bool IsDecl = !VD ||
8188                         VD->isThisDeclarationADefinition(Context) ==
8189                             VarDecl::DeclarationOnly;
8190           Diag(D->getLocation(),
8191                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8192               << D;
8193         }
8194         continue;
8195       }
8196     }
8197 
8198     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
8199     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
8200                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8201     auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8202                                D->hasAttrs() ? &D->getAttrs() : nullptr);
8203     auto PrivateTy = Type;
8204     if (OASE ||
8205         (!ASE &&
8206          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
8207       // For arrays/array sections only:
8208       // Create pseudo array type for private copy. The size for this array will
8209       // be generated during codegen.
8210       // For array subscripts or single variables Private Ty is the same as Type
8211       // (type of the variable or single array element).
8212       PrivateTy = Context.getVariableArrayType(
8213           Type, new (Context) OpaqueValueExpr(SourceLocation(),
8214                                               Context.getSizeType(), VK_RValue),
8215           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
8216     } else if (!ASE && !OASE &&
8217                Context.getAsArrayType(D->getType().getNonReferenceType()))
8218       PrivateTy = D->getType().getNonReferenceType();
8219     // Private copy.
8220     auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8221                                    D->hasAttrs() ? &D->getAttrs() : nullptr);
8222     // Add initializer for private variable.
8223     Expr *Init = nullptr;
8224     auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8225     auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8226     if (DeclareReductionRef.isUsable()) {
8227       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8228       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8229       if (DRD->getInitializer()) {
8230         Init = DRDRef;
8231         RHSVD->setInit(DRDRef);
8232         RHSVD->setInitStyle(VarDecl::CallInit);
8233       }
8234     } else {
8235       switch (BOK) {
8236       case BO_Add:
8237       case BO_Xor:
8238       case BO_Or:
8239       case BO_LOr:
8240         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8241         if (Type->isScalarType() || Type->isAnyComplexType())
8242           Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8243         break;
8244       case BO_Mul:
8245       case BO_LAnd:
8246         if (Type->isScalarType() || Type->isAnyComplexType()) {
8247           // '*' and '&&' reduction ops - initializer is '1'.
8248           Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
8249         }
8250         break;
8251       case BO_And: {
8252         // '&' reduction op - initializer is '~0'.
8253         QualType OrigType = Type;
8254         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8255           Type = ComplexTy->getElementType();
8256         if (Type->isRealFloatingType()) {
8257           llvm::APFloat InitValue =
8258               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8259                                              /*isIEEE=*/true);
8260           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8261                                          Type, ELoc);
8262         } else if (Type->isScalarType()) {
8263           auto Size = Context.getTypeSize(Type);
8264           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8265           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8266           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8267         }
8268         if (Init && OrigType->isAnyComplexType()) {
8269           // Init = 0xFFFF + 0xFFFFi;
8270           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8271           Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8272         }
8273         Type = OrigType;
8274         break;
8275       }
8276       case BO_LT:
8277       case BO_GT: {
8278         // 'min' reduction op - initializer is 'Largest representable number in
8279         // the reduction list item type'.
8280         // 'max' reduction op - initializer is 'Least representable number in
8281         // the reduction list item type'.
8282         if (Type->isIntegerType() || Type->isPointerType()) {
8283           bool IsSigned = Type->hasSignedIntegerRepresentation();
8284           auto Size = Context.getTypeSize(Type);
8285           QualType IntTy =
8286               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8287           llvm::APInt InitValue =
8288               (BOK != BO_LT)
8289                   ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8290                              : llvm::APInt::getMinValue(Size)
8291                   : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8292                              : llvm::APInt::getMaxValue(Size);
8293           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8294           if (Type->isPointerType()) {
8295             // Cast to pointer type.
8296             auto CastExpr = BuildCStyleCastExpr(
8297                 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8298                 SourceLocation(), Init);
8299             if (CastExpr.isInvalid())
8300               continue;
8301             Init = CastExpr.get();
8302           }
8303         } else if (Type->isRealFloatingType()) {
8304           llvm::APFloat InitValue = llvm::APFloat::getLargest(
8305               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8306           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8307                                          Type, ELoc);
8308         }
8309         break;
8310       }
8311       case BO_PtrMemD:
8312       case BO_PtrMemI:
8313       case BO_MulAssign:
8314       case BO_Div:
8315       case BO_Rem:
8316       case BO_Sub:
8317       case BO_Shl:
8318       case BO_Shr:
8319       case BO_LE:
8320       case BO_GE:
8321       case BO_EQ:
8322       case BO_NE:
8323       case BO_AndAssign:
8324       case BO_XorAssign:
8325       case BO_OrAssign:
8326       case BO_Assign:
8327       case BO_AddAssign:
8328       case BO_SubAssign:
8329       case BO_DivAssign:
8330       case BO_RemAssign:
8331       case BO_ShlAssign:
8332       case BO_ShrAssign:
8333       case BO_Comma:
8334         llvm_unreachable("Unexpected reduction operation");
8335       }
8336     }
8337     if (Init && DeclareReductionRef.isUnset()) {
8338       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
8339                            /*TypeMayContainAuto=*/false);
8340     } else if (!Init)
8341       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
8342     if (RHSVD->isInvalidDecl())
8343       continue;
8344     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
8345       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8346                                                             << ReductionIdRange;
8347       bool IsDecl =
8348           !VD ||
8349           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8350       Diag(D->getLocation(),
8351            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8352           << D;
8353       continue;
8354     }
8355     // Store initializer for single element in private copy. Will be used during
8356     // codegen.
8357     PrivateVD->setInit(RHSVD->getInit());
8358     PrivateVD->setInitStyle(RHSVD->getInitStyle());
8359     auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
8360     ExprResult ReductionOp;
8361     if (DeclareReductionRef.isUsable()) {
8362       QualType RedTy = DeclareReductionRef.get()->getType();
8363       QualType PtrRedTy = Context.getPointerType(RedTy);
8364       ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8365       ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8366       if (!BasePath.empty()) {
8367         LHS = DefaultLvalueConversion(LHS.get());
8368         RHS = DefaultLvalueConversion(RHS.get());
8369         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8370                                        CK_UncheckedDerivedToBase, LHS.get(),
8371                                        &BasePath, LHS.get()->getValueKind());
8372         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8373                                        CK_UncheckedDerivedToBase, RHS.get(),
8374                                        &BasePath, RHS.get()->getValueKind());
8375       }
8376       FunctionProtoType::ExtProtoInfo EPI;
8377       QualType Params[] = {PtrRedTy, PtrRedTy};
8378       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8379       auto *OVE = new (Context) OpaqueValueExpr(
8380           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8381           DefaultLvalueConversion(DeclareReductionRef.get()).get());
8382       Expr *Args[] = {LHS.get(), RHS.get()};
8383       ReductionOp = new (Context)
8384           CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8385     } else {
8386       ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8387                                ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8388       if (ReductionOp.isUsable()) {
8389         if (BOK != BO_LT && BOK != BO_GT) {
8390           ReductionOp =
8391               BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8392                          BO_Assign, LHSDRE, ReductionOp.get());
8393         } else {
8394           auto *ConditionalOp = new (Context) ConditionalOperator(
8395               ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8396               RHSDRE, Type, VK_LValue, OK_Ordinary);
8397           ReductionOp =
8398               BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8399                          BO_Assign, LHSDRE, ConditionalOp);
8400         }
8401         ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8402       }
8403       if (ReductionOp.isInvalid())
8404         continue;
8405     }
8406 
8407     DeclRefExpr *Ref = nullptr;
8408     Expr *VarsExpr = RefExpr->IgnoreParens();
8409     if (!VD && !CurContext->isDependentContext()) {
8410       if (ASE || OASE) {
8411         TransformExprToCaptures RebuildToCapture(*this, D);
8412         VarsExpr =
8413             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8414         Ref = RebuildToCapture.getCapturedExpr();
8415       } else {
8416         VarsExpr = Ref =
8417             buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8418       }
8419       if (!IsOpenMPCapturedDecl(D)) {
8420         ExprCaptures.push_back(Ref->getDecl());
8421         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8422           ExprResult RefRes = DefaultLvalueConversion(Ref);
8423           if (!RefRes.isUsable())
8424             continue;
8425           ExprResult PostUpdateRes =
8426               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8427                          SimpleRefExpr, RefRes.get());
8428           if (!PostUpdateRes.isUsable())
8429             continue;
8430           ExprPostUpdates.push_back(
8431               IgnoredValueConversions(PostUpdateRes.get()).get());
8432         }
8433       }
8434     }
8435     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8436     Vars.push_back(VarsExpr);
8437     Privates.push_back(PrivateDRE);
8438     LHSs.push_back(LHSDRE);
8439     RHSs.push_back(RHSDRE);
8440     ReductionOps.push_back(ReductionOp.get());
8441   }
8442 
8443   if (Vars.empty())
8444     return nullptr;
8445 
8446   return OMPReductionClause::Create(
8447       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
8448       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
8449       LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
8450       buildPostUpdate(*this, ExprPostUpdates));
8451 }
8452 
8453 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8454                                      SourceLocation LinLoc) {
8455   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
8456       LinKind == OMPC_LINEAR_unknown) {
8457     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
8458     return true;
8459   }
8460   return false;
8461 }
8462 
8463 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8464                                  OpenMPLinearClauseKind LinKind,
8465                                  QualType Type) {
8466   auto *VD = dyn_cast_or_null<VarDecl>(D);
8467   // A variable must not have an incomplete type or a reference type.
8468   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
8469     return true;
8470   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
8471       !Type->isReferenceType()) {
8472     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
8473         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
8474     return true;
8475   }
8476   Type = Type.getNonReferenceType();
8477 
8478   // A list item must not be const-qualified.
8479   if (Type.isConstant(Context)) {
8480     Diag(ELoc, diag::err_omp_const_variable)
8481         << getOpenMPClauseName(OMPC_linear);
8482     if (D) {
8483       bool IsDecl =
8484           !VD ||
8485           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8486       Diag(D->getLocation(),
8487            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8488           << D;
8489     }
8490     return true;
8491   }
8492 
8493   // A list item must be of integral or pointer type.
8494   Type = Type.getUnqualifiedType().getCanonicalType();
8495   const auto *Ty = Type.getTypePtrOrNull();
8496   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
8497               !Ty->isPointerType())) {
8498     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
8499     if (D) {
8500       bool IsDecl =
8501           !VD ||
8502           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8503       Diag(D->getLocation(),
8504            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8505           << D;
8506     }
8507     return true;
8508   }
8509   return false;
8510 }
8511 
8512 OMPClause *Sema::ActOnOpenMPLinearClause(
8513     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
8514     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
8515     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8516   SmallVector<Expr *, 8> Vars;
8517   SmallVector<Expr *, 8> Privates;
8518   SmallVector<Expr *, 8> Inits;
8519   SmallVector<Decl *, 4> ExprCaptures;
8520   SmallVector<Expr *, 4> ExprPostUpdates;
8521   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
8522     LinKind = OMPC_LINEAR_val;
8523   for (auto &RefExpr : VarList) {
8524     assert(RefExpr && "NULL expr in OpenMP linear clause.");
8525     SourceLocation ELoc;
8526     SourceRange ERange;
8527     Expr *SimpleRefExpr = RefExpr;
8528     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8529                               /*AllowArraySection=*/false);
8530     if (Res.second) {
8531       // It will be analyzed later.
8532       Vars.push_back(RefExpr);
8533       Privates.push_back(nullptr);
8534       Inits.push_back(nullptr);
8535     }
8536     ValueDecl *D = Res.first;
8537     if (!D)
8538       continue;
8539 
8540     QualType Type = D->getType();
8541     auto *VD = dyn_cast<VarDecl>(D);
8542 
8543     // OpenMP [2.14.3.7, linear clause]
8544     //  A list-item cannot appear in more than one linear clause.
8545     //  A list-item that appears in a linear clause cannot appear in any
8546     //  other data-sharing attribute clause.
8547     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8548     if (DVar.RefExpr) {
8549       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8550                                           << getOpenMPClauseName(OMPC_linear);
8551       ReportOriginalDSA(*this, DSAStack, D, DVar);
8552       continue;
8553     }
8554 
8555     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
8556       continue;
8557     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8558 
8559     // Build private copy of original var.
8560     auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
8561                                  D->hasAttrs() ? &D->getAttrs() : nullptr);
8562     auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
8563     // Build var to save initial value.
8564     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
8565     Expr *InitExpr;
8566     DeclRefExpr *Ref = nullptr;
8567     if (!VD && !CurContext->isDependentContext()) {
8568       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
8569       if (!IsOpenMPCapturedDecl(D)) {
8570         ExprCaptures.push_back(Ref->getDecl());
8571         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8572           ExprResult RefRes = DefaultLvalueConversion(Ref);
8573           if (!RefRes.isUsable())
8574             continue;
8575           ExprResult PostUpdateRes =
8576               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8577                          SimpleRefExpr, RefRes.get());
8578           if (!PostUpdateRes.isUsable())
8579             continue;
8580           ExprPostUpdates.push_back(
8581               IgnoredValueConversions(PostUpdateRes.get()).get());
8582         }
8583       }
8584     }
8585     if (LinKind == OMPC_LINEAR_uval)
8586       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
8587     else
8588       InitExpr = VD ? SimpleRefExpr : Ref;
8589     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
8590                          /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
8591     auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
8592 
8593     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
8594     Vars.push_back((VD || CurContext->isDependentContext())
8595                        ? RefExpr->IgnoreParens()
8596                        : Ref);
8597     Privates.push_back(PrivateRef);
8598     Inits.push_back(InitRef);
8599   }
8600 
8601   if (Vars.empty())
8602     return nullptr;
8603 
8604   Expr *StepExpr = Step;
8605   Expr *CalcStepExpr = nullptr;
8606   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
8607       !Step->isInstantiationDependent() &&
8608       !Step->containsUnexpandedParameterPack()) {
8609     SourceLocation StepLoc = Step->getLocStart();
8610     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
8611     if (Val.isInvalid())
8612       return nullptr;
8613     StepExpr = Val.get();
8614 
8615     // Build var to save the step value.
8616     VarDecl *SaveVar =
8617         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
8618     ExprResult SaveRef =
8619         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
8620     ExprResult CalcStep =
8621         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
8622     CalcStep = ActOnFinishFullExpr(CalcStep.get());
8623 
8624     // Warn about zero linear step (it would be probably better specified as
8625     // making corresponding variables 'const').
8626     llvm::APSInt Result;
8627     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
8628     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
8629       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
8630                                                      << (Vars.size() > 1);
8631     if (!IsConstant && CalcStep.isUsable()) {
8632       // Calculate the step beforehand instead of doing this on each iteration.
8633       // (This is not used if the number of iterations may be kfold-ed).
8634       CalcStepExpr = CalcStep.get();
8635     }
8636   }
8637 
8638   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
8639                                  ColonLoc, EndLoc, Vars, Privates, Inits,
8640                                  StepExpr, CalcStepExpr,
8641                                  buildPreInits(Context, ExprCaptures),
8642                                  buildPostUpdate(*this, ExprPostUpdates));
8643 }
8644 
8645 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
8646                                      Expr *NumIterations, Sema &SemaRef,
8647                                      Scope *S, DSAStackTy *Stack) {
8648   // Walk the vars and build update/final expressions for the CodeGen.
8649   SmallVector<Expr *, 8> Updates;
8650   SmallVector<Expr *, 8> Finals;
8651   Expr *Step = Clause.getStep();
8652   Expr *CalcStep = Clause.getCalcStep();
8653   // OpenMP [2.14.3.7, linear clause]
8654   // If linear-step is not specified it is assumed to be 1.
8655   if (Step == nullptr)
8656     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
8657   else if (CalcStep) {
8658     Step = cast<BinaryOperator>(CalcStep)->getLHS();
8659   }
8660   bool HasErrors = false;
8661   auto CurInit = Clause.inits().begin();
8662   auto CurPrivate = Clause.privates().begin();
8663   auto LinKind = Clause.getModifier();
8664   for (auto &RefExpr : Clause.varlists()) {
8665     SourceLocation ELoc;
8666     SourceRange ERange;
8667     Expr *SimpleRefExpr = RefExpr;
8668     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
8669                               /*AllowArraySection=*/false);
8670     ValueDecl *D = Res.first;
8671     if (Res.second || !D) {
8672       Updates.push_back(nullptr);
8673       Finals.push_back(nullptr);
8674       HasErrors = true;
8675       continue;
8676     }
8677     if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
8678       D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
8679               ->getMemberDecl();
8680     }
8681     auto &&Info = Stack->isLoopControlVariable(D);
8682     Expr *InitExpr = *CurInit;
8683 
8684     // Build privatized reference to the current linear var.
8685     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
8686     Expr *CapturedRef;
8687     if (LinKind == OMPC_LINEAR_uval)
8688       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
8689     else
8690       CapturedRef =
8691           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
8692                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
8693                            /*RefersToCapture=*/true);
8694 
8695     // Build update: Var = InitExpr + IV * Step
8696     ExprResult Update;
8697     if (!Info.first) {
8698       Update =
8699           BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
8700                              InitExpr, IV, Step, /* Subtract */ false);
8701     } else
8702       Update = *CurPrivate;
8703     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
8704                                          /*DiscardedValue=*/true);
8705 
8706     // Build final: Var = InitExpr + NumIterations * Step
8707     ExprResult Final;
8708     if (!Info.first) {
8709       Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
8710                                  InitExpr, NumIterations, Step,
8711                                  /* Subtract */ false);
8712     } else
8713       Final = *CurPrivate;
8714     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
8715                                         /*DiscardedValue=*/true);
8716 
8717     if (!Update.isUsable() || !Final.isUsable()) {
8718       Updates.push_back(nullptr);
8719       Finals.push_back(nullptr);
8720       HasErrors = true;
8721     } else {
8722       Updates.push_back(Update.get());
8723       Finals.push_back(Final.get());
8724     }
8725     ++CurInit;
8726     ++CurPrivate;
8727   }
8728   Clause.setUpdates(Updates);
8729   Clause.setFinals(Finals);
8730   return HasErrors;
8731 }
8732 
8733 OMPClause *Sema::ActOnOpenMPAlignedClause(
8734     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
8735     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
8736 
8737   SmallVector<Expr *, 8> Vars;
8738   for (auto &RefExpr : VarList) {
8739     assert(RefExpr && "NULL expr in OpenMP linear clause.");
8740     SourceLocation ELoc;
8741     SourceRange ERange;
8742     Expr *SimpleRefExpr = RefExpr;
8743     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8744                               /*AllowArraySection=*/false);
8745     if (Res.second) {
8746       // It will be analyzed later.
8747       Vars.push_back(RefExpr);
8748     }
8749     ValueDecl *D = Res.first;
8750     if (!D)
8751       continue;
8752 
8753     QualType QType = D->getType();
8754     auto *VD = dyn_cast<VarDecl>(D);
8755 
8756     // OpenMP  [2.8.1, simd construct, Restrictions]
8757     // The type of list items appearing in the aligned clause must be
8758     // array, pointer, reference to array, or reference to pointer.
8759     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
8760     const Type *Ty = QType.getTypePtrOrNull();
8761     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
8762       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
8763           << QType << getLangOpts().CPlusPlus << ERange;
8764       bool IsDecl =
8765           !VD ||
8766           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8767       Diag(D->getLocation(),
8768            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8769           << D;
8770       continue;
8771     }
8772 
8773     // OpenMP  [2.8.1, simd construct, Restrictions]
8774     // A list-item cannot appear in more than one aligned clause.
8775     if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
8776       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
8777       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
8778           << getOpenMPClauseName(OMPC_aligned);
8779       continue;
8780     }
8781 
8782     DeclRefExpr *Ref = nullptr;
8783     if (!VD && IsOpenMPCapturedDecl(D))
8784       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
8785     Vars.push_back(DefaultFunctionArrayConversion(
8786                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
8787                        .get());
8788   }
8789 
8790   // OpenMP [2.8.1, simd construct, Description]
8791   // The parameter of the aligned clause, alignment, must be a constant
8792   // positive integer expression.
8793   // If no optional parameter is specified, implementation-defined default
8794   // alignments for SIMD instructions on the target platforms are assumed.
8795   if (Alignment != nullptr) {
8796     ExprResult AlignResult =
8797         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
8798     if (AlignResult.isInvalid())
8799       return nullptr;
8800     Alignment = AlignResult.get();
8801   }
8802   if (Vars.empty())
8803     return nullptr;
8804 
8805   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
8806                                   EndLoc, Vars, Alignment);
8807 }
8808 
8809 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8810                                          SourceLocation StartLoc,
8811                                          SourceLocation LParenLoc,
8812                                          SourceLocation EndLoc) {
8813   SmallVector<Expr *, 8> Vars;
8814   SmallVector<Expr *, 8> SrcExprs;
8815   SmallVector<Expr *, 8> DstExprs;
8816   SmallVector<Expr *, 8> AssignmentOps;
8817   for (auto &RefExpr : VarList) {
8818     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
8819     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
8820       // It will be analyzed later.
8821       Vars.push_back(RefExpr);
8822       SrcExprs.push_back(nullptr);
8823       DstExprs.push_back(nullptr);
8824       AssignmentOps.push_back(nullptr);
8825       continue;
8826     }
8827 
8828     SourceLocation ELoc = RefExpr->getExprLoc();
8829     // OpenMP [2.1, C/C++]
8830     //  A list item is a variable name.
8831     // OpenMP  [2.14.4.1, Restrictions, p.1]
8832     //  A list item that appears in a copyin clause must be threadprivate.
8833     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
8834     if (!DE || !isa<VarDecl>(DE->getDecl())) {
8835       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
8836           << 0 << RefExpr->getSourceRange();
8837       continue;
8838     }
8839 
8840     Decl *D = DE->getDecl();
8841     VarDecl *VD = cast<VarDecl>(D);
8842 
8843     QualType Type = VD->getType();
8844     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8845       // It will be analyzed later.
8846       Vars.push_back(DE);
8847       SrcExprs.push_back(nullptr);
8848       DstExprs.push_back(nullptr);
8849       AssignmentOps.push_back(nullptr);
8850       continue;
8851     }
8852 
8853     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
8854     //  A list item that appears in a copyin clause must be threadprivate.
8855     if (!DSAStack->isThreadPrivate(VD)) {
8856       Diag(ELoc, diag::err_omp_required_access)
8857           << getOpenMPClauseName(OMPC_copyin)
8858           << getOpenMPDirectiveName(OMPD_threadprivate);
8859       continue;
8860     }
8861 
8862     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8863     //  A variable of class type (or array thereof) that appears in a
8864     //  copyin clause requires an accessible, unambiguous copy assignment
8865     //  operator for the class type.
8866     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
8867     auto *SrcVD =
8868         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
8869                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8870     auto *PseudoSrcExpr = buildDeclRefExpr(
8871         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
8872     auto *DstVD =
8873         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
8874                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8875     auto *PseudoDstExpr =
8876         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
8877     // For arrays generate assignment operation for single element and replace
8878     // it by the original array element in CodeGen.
8879     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8880                                    PseudoDstExpr, PseudoSrcExpr);
8881     if (AssignmentOp.isInvalid())
8882       continue;
8883     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8884                                        /*DiscardedValue=*/true);
8885     if (AssignmentOp.isInvalid())
8886       continue;
8887 
8888     DSAStack->addDSA(VD, DE, OMPC_copyin);
8889     Vars.push_back(DE);
8890     SrcExprs.push_back(PseudoSrcExpr);
8891     DstExprs.push_back(PseudoDstExpr);
8892     AssignmentOps.push_back(AssignmentOp.get());
8893   }
8894 
8895   if (Vars.empty())
8896     return nullptr;
8897 
8898   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8899                                  SrcExprs, DstExprs, AssignmentOps);
8900 }
8901 
8902 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8903                                               SourceLocation StartLoc,
8904                                               SourceLocation LParenLoc,
8905                                               SourceLocation EndLoc) {
8906   SmallVector<Expr *, 8> Vars;
8907   SmallVector<Expr *, 8> SrcExprs;
8908   SmallVector<Expr *, 8> DstExprs;
8909   SmallVector<Expr *, 8> AssignmentOps;
8910   for (auto &RefExpr : VarList) {
8911     assert(RefExpr && "NULL expr in OpenMP linear clause.");
8912     SourceLocation ELoc;
8913     SourceRange ERange;
8914     Expr *SimpleRefExpr = RefExpr;
8915     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8916                               /*AllowArraySection=*/false);
8917     if (Res.second) {
8918       // It will be analyzed later.
8919       Vars.push_back(RefExpr);
8920       SrcExprs.push_back(nullptr);
8921       DstExprs.push_back(nullptr);
8922       AssignmentOps.push_back(nullptr);
8923     }
8924     ValueDecl *D = Res.first;
8925     if (!D)
8926       continue;
8927 
8928     QualType Type = D->getType();
8929     auto *VD = dyn_cast<VarDecl>(D);
8930 
8931     // OpenMP [2.14.4.2, Restrictions, p.2]
8932     //  A list item that appears in a copyprivate clause may not appear in a
8933     //  private or firstprivate clause on the single construct.
8934     if (!VD || !DSAStack->isThreadPrivate(VD)) {
8935       auto DVar = DSAStack->getTopDSA(D, false);
8936       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8937           DVar.RefExpr) {
8938         Diag(ELoc, diag::err_omp_wrong_dsa)
8939             << getOpenMPClauseName(DVar.CKind)
8940             << getOpenMPClauseName(OMPC_copyprivate);
8941         ReportOriginalDSA(*this, DSAStack, D, DVar);
8942         continue;
8943       }
8944 
8945       // OpenMP [2.11.4.2, Restrictions, p.1]
8946       //  All list items that appear in a copyprivate clause must be either
8947       //  threadprivate or private in the enclosing context.
8948       if (DVar.CKind == OMPC_unknown) {
8949         DVar = DSAStack->getImplicitDSA(D, false);
8950         if (DVar.CKind == OMPC_shared) {
8951           Diag(ELoc, diag::err_omp_required_access)
8952               << getOpenMPClauseName(OMPC_copyprivate)
8953               << "threadprivate or private in the enclosing context";
8954           ReportOriginalDSA(*this, DSAStack, D, DVar);
8955           continue;
8956         }
8957       }
8958     }
8959 
8960     // Variably modified types are not supported.
8961     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
8962       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8963           << getOpenMPClauseName(OMPC_copyprivate) << Type
8964           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8965       bool IsDecl =
8966           !VD ||
8967           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8968       Diag(D->getLocation(),
8969            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8970           << D;
8971       continue;
8972     }
8973 
8974     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8975     //  A variable of class type (or array thereof) that appears in a
8976     //  copyin clause requires an accessible, unambiguous copy assignment
8977     //  operator for the class type.
8978     Type = Context.getBaseElementType(Type.getNonReferenceType())
8979                .getUnqualifiedType();
8980     auto *SrcVD =
8981         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
8982                      D->hasAttrs() ? &D->getAttrs() : nullptr);
8983     auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
8984     auto *DstVD =
8985         buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
8986                      D->hasAttrs() ? &D->getAttrs() : nullptr);
8987     auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
8988     auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8989                                    PseudoDstExpr, PseudoSrcExpr);
8990     if (AssignmentOp.isInvalid())
8991       continue;
8992     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
8993                                        /*DiscardedValue=*/true);
8994     if (AssignmentOp.isInvalid())
8995       continue;
8996 
8997     // No need to mark vars as copyprivate, they are already threadprivate or
8998     // implicitly private.
8999     assert(VD || IsOpenMPCapturedDecl(D));
9000     Vars.push_back(
9001         VD ? RefExpr->IgnoreParens()
9002            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
9003     SrcExprs.push_back(PseudoSrcExpr);
9004     DstExprs.push_back(PseudoDstExpr);
9005     AssignmentOps.push_back(AssignmentOp.get());
9006   }
9007 
9008   if (Vars.empty())
9009     return nullptr;
9010 
9011   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9012                                       Vars, SrcExprs, DstExprs, AssignmentOps);
9013 }
9014 
9015 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9016                                         SourceLocation StartLoc,
9017                                         SourceLocation LParenLoc,
9018                                         SourceLocation EndLoc) {
9019   if (VarList.empty())
9020     return nullptr;
9021 
9022   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9023 }
9024 
9025 OMPClause *
9026 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9027                               SourceLocation DepLoc, SourceLocation ColonLoc,
9028                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9029                               SourceLocation LParenLoc, SourceLocation EndLoc) {
9030   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
9031       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
9032     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9033         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
9034     return nullptr;
9035   }
9036   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
9037       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9038        DepKind == OMPC_DEPEND_sink)) {
9039     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
9040     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
9041         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9042                                    /*Last=*/OMPC_DEPEND_unknown, Except)
9043         << getOpenMPClauseName(OMPC_depend);
9044     return nullptr;
9045   }
9046   SmallVector<Expr *, 8> Vars;
9047   DSAStackTy::OperatorOffsetTy OpsOffs;
9048   llvm::APSInt DepCounter(/*BitWidth=*/32);
9049   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9050   if (DepKind == OMPC_DEPEND_sink) {
9051     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9052       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9053       TotalDepCount.setIsUnsigned(/*Val=*/true);
9054     }
9055   }
9056   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9057       DSAStack->getParentOrderedRegionParam()) {
9058     for (auto &RefExpr : VarList) {
9059       assert(RefExpr && "NULL expr in OpenMP shared clause.");
9060       if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
9061         // It will be analyzed later.
9062         Vars.push_back(RefExpr);
9063         continue;
9064       }
9065 
9066       SourceLocation ELoc = RefExpr->getExprLoc();
9067       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9068       if (DepKind == OMPC_DEPEND_sink) {
9069         if (DepCounter >= TotalDepCount) {
9070           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9071           continue;
9072         }
9073         ++DepCounter;
9074         // OpenMP  [2.13.9, Summary]
9075         // depend(dependence-type : vec), where dependence-type is:
9076         // 'sink' and where vec is the iteration vector, which has the form:
9077         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9078         // where n is the value specified by the ordered clause in the loop
9079         // directive, xi denotes the loop iteration variable of the i-th nested
9080         // loop associated with the loop directive, and di is a constant
9081         // non-negative integer.
9082         if (CurContext->isDependentContext()) {
9083           // It will be analyzed later.
9084           Vars.push_back(RefExpr);
9085           continue;
9086         }
9087         SimpleExpr = SimpleExpr->IgnoreImplicit();
9088         OverloadedOperatorKind OOK = OO_None;
9089         SourceLocation OOLoc;
9090         Expr *LHS = SimpleExpr;
9091         Expr *RHS = nullptr;
9092         if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9093           OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9094           OOLoc = BO->getOperatorLoc();
9095           LHS = BO->getLHS()->IgnoreParenImpCasts();
9096           RHS = BO->getRHS()->IgnoreParenImpCasts();
9097         } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9098           OOK = OCE->getOperator();
9099           OOLoc = OCE->getOperatorLoc();
9100           LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9101           RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9102         } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9103           OOK = MCE->getMethodDecl()
9104                     ->getNameInfo()
9105                     .getName()
9106                     .getCXXOverloadedOperator();
9107           OOLoc = MCE->getCallee()->getExprLoc();
9108           LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9109           RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9110         }
9111         SourceLocation ELoc;
9112         SourceRange ERange;
9113         auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9114                                   /*AllowArraySection=*/false);
9115         if (Res.second) {
9116           // It will be analyzed later.
9117           Vars.push_back(RefExpr);
9118         }
9119         ValueDecl *D = Res.first;
9120         if (!D)
9121           continue;
9122 
9123         if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9124           Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9125           continue;
9126         }
9127         if (RHS) {
9128           ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9129               RHS, OMPC_depend, /*StrictlyPositive=*/false);
9130           if (RHSRes.isInvalid())
9131             continue;
9132         }
9133         if (!CurContext->isDependentContext() &&
9134             DSAStack->getParentOrderedRegionParam() &&
9135             DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9136           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9137               << DSAStack->getParentLoopControlVariable(
9138                      DepCounter.getZExtValue());
9139           continue;
9140         }
9141         OpsOffs.push_back({RHS, OOK});
9142       } else {
9143         // OpenMP  [2.11.1.1, Restrictions, p.3]
9144         //  A variable that is part of another variable (such as a field of a
9145         //  structure) but is not an array element or an array section cannot
9146         //  appear  in a depend clause.
9147         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9148         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9149         auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9150         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9151             (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
9152             (ASE &&
9153              !ASE->getBase()
9154                   ->getType()
9155                   .getNonReferenceType()
9156                   ->isPointerType() &&
9157              !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
9158           Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9159               << 0 << RefExpr->getSourceRange();
9160           continue;
9161         }
9162       }
9163       Vars.push_back(RefExpr->IgnoreParenImpCasts());
9164     }
9165 
9166     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9167         TotalDepCount > VarList.size() &&
9168         DSAStack->getParentOrderedRegionParam()) {
9169       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9170           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9171     }
9172     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9173         Vars.empty())
9174       return nullptr;
9175   }
9176   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9177                                     DepKind, DepLoc, ColonLoc, Vars);
9178   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9179     DSAStack->addDoacrossDependClause(C, OpsOffs);
9180   return C;
9181 }
9182 
9183 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9184                                          SourceLocation LParenLoc,
9185                                          SourceLocation EndLoc) {
9186   Expr *ValExpr = Device;
9187 
9188   // OpenMP [2.9.1, Restrictions]
9189   // The device expression must evaluate to a non-negative integer value.
9190   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9191                                  /*StrictlyPositive=*/false))
9192     return nullptr;
9193 
9194   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9195 }
9196 
9197 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9198                                    DSAStackTy *Stack, CXXRecordDecl *RD) {
9199   if (!RD || RD->isInvalidDecl())
9200     return true;
9201 
9202   auto QTy = SemaRef.Context.getRecordType(RD);
9203   if (RD->isDynamicClass()) {
9204     SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9205     SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9206     return false;
9207   }
9208   auto *DC = RD;
9209   bool IsCorrect = true;
9210   for (auto *I : DC->decls()) {
9211     if (I) {
9212       if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9213         if (MD->isStatic()) {
9214           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9215           SemaRef.Diag(MD->getLocation(),
9216                        diag::note_omp_static_member_in_target);
9217           IsCorrect = false;
9218         }
9219       } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9220         if (VD->isStaticDataMember()) {
9221           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9222           SemaRef.Diag(VD->getLocation(),
9223                        diag::note_omp_static_member_in_target);
9224           IsCorrect = false;
9225         }
9226       }
9227     }
9228   }
9229 
9230   for (auto &I : RD->bases()) {
9231     if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9232                                 I.getType()->getAsCXXRecordDecl()))
9233       IsCorrect = false;
9234   }
9235   return IsCorrect;
9236 }
9237 
9238 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9239                               DSAStackTy *Stack, QualType QTy) {
9240   NamedDecl *ND;
9241   if (QTy->isIncompleteType(&ND)) {
9242     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9243     return false;
9244   } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
9245     if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
9246       return false;
9247   }
9248   return true;
9249 }
9250 
9251 /// \brief Return true if it can be proven that the provided array expression
9252 /// (array section or array subscript) does NOT specify the whole size of the
9253 /// array whose base type is \a BaseQTy.
9254 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9255                                                         const Expr *E,
9256                                                         QualType BaseQTy) {
9257   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9258 
9259   // If this is an array subscript, it refers to the whole size if the size of
9260   // the dimension is constant and equals 1. Also, an array section assumes the
9261   // format of an array subscript if no colon is used.
9262   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9263     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9264       return ATy->getSize().getSExtValue() != 1;
9265     // Size can't be evaluated statically.
9266     return false;
9267   }
9268 
9269   assert(OASE && "Expecting array section if not an array subscript.");
9270   auto *LowerBound = OASE->getLowerBound();
9271   auto *Length = OASE->getLength();
9272 
9273   // If there is a lower bound that does not evaluates to zero, we are not
9274   // covering the whole dimension.
9275   if (LowerBound) {
9276     llvm::APSInt ConstLowerBound;
9277     if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9278       return false; // Can't get the integer value as a constant.
9279     if (ConstLowerBound.getSExtValue())
9280       return true;
9281   }
9282 
9283   // If we don't have a length we covering the whole dimension.
9284   if (!Length)
9285     return false;
9286 
9287   // If the base is a pointer, we don't have a way to get the size of the
9288   // pointee.
9289   if (BaseQTy->isPointerType())
9290     return false;
9291 
9292   // We can only check if the length is the same as the size of the dimension
9293   // if we have a constant array.
9294   auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9295   if (!CATy)
9296     return false;
9297 
9298   llvm::APSInt ConstLength;
9299   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9300     return false; // Can't get the integer value as a constant.
9301 
9302   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9303 }
9304 
9305 // Return true if it can be proven that the provided array expression (array
9306 // section or array subscript) does NOT specify a single element of the array
9307 // whose base type is \a BaseQTy.
9308 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
9309                                                         const Expr *E,
9310                                                         QualType BaseQTy) {
9311   auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9312 
9313   // An array subscript always refer to a single element. Also, an array section
9314   // assumes the format of an array subscript if no colon is used.
9315   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9316     return false;
9317 
9318   assert(OASE && "Expecting array section if not an array subscript.");
9319   auto *Length = OASE->getLength();
9320 
9321   // If we don't have a length we have to check if the array has unitary size
9322   // for this dimension. Also, we should always expect a length if the base type
9323   // is pointer.
9324   if (!Length) {
9325     if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9326       return ATy->getSize().getSExtValue() != 1;
9327     // We cannot assume anything.
9328     return false;
9329   }
9330 
9331   // Check if the length evaluates to 1.
9332   llvm::APSInt ConstLength;
9333   if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9334     return false; // Can't get the integer value as a constant.
9335 
9336   return ConstLength.getSExtValue() != 1;
9337 }
9338 
9339 // Return the expression of the base of the mappable expression or null if it
9340 // cannot be determined and do all the necessary checks to see if the expression
9341 // is valid as a standalone mappable expression. In the process, record all the
9342 // components of the expression.
9343 static Expr *CheckMapClauseExpressionBase(
9344     Sema &SemaRef, Expr *E,
9345     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9346     OpenMPClauseKind CKind) {
9347   SourceLocation ELoc = E->getExprLoc();
9348   SourceRange ERange = E->getSourceRange();
9349 
9350   // The base of elements of list in a map clause have to be either:
9351   //  - a reference to variable or field.
9352   //  - a member expression.
9353   //  - an array expression.
9354   //
9355   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9356   // reference to 'r'.
9357   //
9358   // If we have:
9359   //
9360   // struct SS {
9361   //   Bla S;
9362   //   foo() {
9363   //     #pragma omp target map (S.Arr[:12]);
9364   //   }
9365   // }
9366   //
9367   // We want to retrieve the member expression 'this->S';
9368 
9369   Expr *RelevantExpr = nullptr;
9370 
9371   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9372   //  If a list item is an array section, it must specify contiguous storage.
9373   //
9374   // For this restriction it is sufficient that we make sure only references
9375   // to variables or fields and array expressions, and that no array sections
9376   // exist except in the rightmost expression (unless they cover the whole
9377   // dimension of the array). E.g. these would be invalid:
9378   //
9379   //   r.ArrS[3:5].Arr[6:7]
9380   //
9381   //   r.ArrS[3:5].x
9382   //
9383   // but these would be valid:
9384   //   r.ArrS[3].Arr[6:7]
9385   //
9386   //   r.ArrS[3].x
9387 
9388   bool AllowUnitySizeArraySection = true;
9389   bool AllowWholeSizeArraySection = true;
9390 
9391   while (!RelevantExpr) {
9392     E = E->IgnoreParenImpCasts();
9393 
9394     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9395       if (!isa<VarDecl>(CurE->getDecl()))
9396         break;
9397 
9398       RelevantExpr = CurE;
9399 
9400       // If we got a reference to a declaration, we should not expect any array
9401       // section before that.
9402       AllowUnitySizeArraySection = false;
9403       AllowWholeSizeArraySection = false;
9404 
9405       // Record the component.
9406       CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9407           CurE, CurE->getDecl()));
9408       continue;
9409     }
9410 
9411     if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9412       auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9413 
9414       if (isa<CXXThisExpr>(BaseE))
9415         // We found a base expression: this->Val.
9416         RelevantExpr = CurE;
9417       else
9418         E = BaseE;
9419 
9420       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9421         SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9422             << CurE->getSourceRange();
9423         break;
9424       }
9425 
9426       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9427 
9428       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9429       //  A bit-field cannot appear in a map clause.
9430       //
9431       if (FD->isBitField()) {
9432         SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9433             << CurE->getSourceRange() << getOpenMPClauseName(CKind);
9434         break;
9435       }
9436 
9437       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9438       //  If the type of a list item is a reference to a type T then the type
9439       //  will be considered to be T for all purposes of this clause.
9440       QualType CurType = BaseE->getType().getNonReferenceType();
9441 
9442       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
9443       //  A list item cannot be a variable that is a member of a structure with
9444       //  a union type.
9445       //
9446       if (auto *RT = CurType->getAs<RecordType>())
9447         if (RT->isUnionType()) {
9448           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
9449               << CurE->getSourceRange();
9450           break;
9451         }
9452 
9453       // If we got a member expression, we should not expect any array section
9454       // before that:
9455       //
9456       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
9457       //  If a list item is an element of a structure, only the rightmost symbol
9458       //  of the variable reference can be an array section.
9459       //
9460       AllowUnitySizeArraySection = false;
9461       AllowWholeSizeArraySection = false;
9462 
9463       // Record the component.
9464       CurComponents.push_back(
9465           OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
9466       continue;
9467     }
9468 
9469     if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
9470       E = CurE->getBase()->IgnoreParenImpCasts();
9471 
9472       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
9473         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9474             << 0 << CurE->getSourceRange();
9475         break;
9476       }
9477 
9478       // If we got an array subscript that express the whole dimension we
9479       // can have any array expressions before. If it only expressing part of
9480       // the dimension, we can only have unitary-size array expressions.
9481       if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
9482                                                       E->getType()))
9483         AllowWholeSizeArraySection = false;
9484 
9485       // Record the component - we don't have any declaration associated.
9486       CurComponents.push_back(
9487           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9488       continue;
9489     }
9490 
9491     if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
9492       E = CurE->getBase()->IgnoreParenImpCasts();
9493 
9494       auto CurType =
9495           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9496 
9497       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9498       //  If the type of a list item is a reference to a type T then the type
9499       //  will be considered to be T for all purposes of this clause.
9500       if (CurType->isReferenceType())
9501         CurType = CurType->getPointeeType();
9502 
9503       bool IsPointer = CurType->isAnyPointerType();
9504 
9505       if (!IsPointer && !CurType->isArrayType()) {
9506         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
9507             << 0 << CurE->getSourceRange();
9508         break;
9509       }
9510 
9511       bool NotWhole =
9512           CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
9513       bool NotUnity =
9514           CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
9515 
9516       if (AllowWholeSizeArraySection) {
9517         // Any array section is currently allowed. Allowing a whole size array
9518         // section implies allowing a unity array section as well.
9519         //
9520         // If this array section refers to the whole dimension we can still
9521         // accept other array sections before this one, except if the base is a
9522         // pointer. Otherwise, only unitary sections are accepted.
9523         if (NotWhole || IsPointer)
9524           AllowWholeSizeArraySection = false;
9525       } else if (AllowUnitySizeArraySection && NotUnity) {
9526         // A unity or whole array section is not allowed and that is not
9527         // compatible with the properties of the current array section.
9528         SemaRef.Diag(
9529             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
9530             << CurE->getSourceRange();
9531         break;
9532       }
9533 
9534       // Record the component - we don't have any declaration associated.
9535       CurComponents.push_back(
9536           OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
9537       continue;
9538     }
9539 
9540     // If nothing else worked, this is not a valid map clause expression.
9541     SemaRef.Diag(ELoc,
9542                  diag::err_omp_expected_named_var_member_or_array_expression)
9543         << ERange;
9544     break;
9545   }
9546 
9547   return RelevantExpr;
9548 }
9549 
9550 // Return true if expression E associated with value VD has conflicts with other
9551 // map information.
9552 static bool CheckMapConflicts(
9553     Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
9554     bool CurrentRegionOnly,
9555     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
9556     OpenMPClauseKind CKind) {
9557   assert(VD && E);
9558   SourceLocation ELoc = E->getExprLoc();
9559   SourceRange ERange = E->getSourceRange();
9560 
9561   // In order to easily check the conflicts we need to match each component of
9562   // the expression under test with the components of the expressions that are
9563   // already in the stack.
9564 
9565   assert(!CurComponents.empty() && "Map clause expression with no components!");
9566   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
9567          "Map clause expression with unexpected base!");
9568 
9569   // Variables to help detecting enclosing problems in data environment nests.
9570   bool IsEnclosedByDataEnvironmentExpr = false;
9571   const Expr *EnclosingExpr = nullptr;
9572 
9573   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
9574       VD, CurrentRegionOnly,
9575       [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
9576               StackComponents,
9577           OpenMPClauseKind) -> bool {
9578 
9579         assert(!StackComponents.empty() &&
9580                "Map clause expression with no components!");
9581         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
9582                "Map clause expression with unexpected base!");
9583 
9584         // The whole expression in the stack.
9585         auto *RE = StackComponents.front().getAssociatedExpression();
9586 
9587         // Expressions must start from the same base. Here we detect at which
9588         // point both expressions diverge from each other and see if we can
9589         // detect if the memory referred to both expressions is contiguous and
9590         // do not overlap.
9591         auto CI = CurComponents.rbegin();
9592         auto CE = CurComponents.rend();
9593         auto SI = StackComponents.rbegin();
9594         auto SE = StackComponents.rend();
9595         for (; CI != CE && SI != SE; ++CI, ++SI) {
9596 
9597           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
9598           //  At most one list item can be an array item derived from a given
9599           //  variable in map clauses of the same construct.
9600           if (CurrentRegionOnly &&
9601               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
9602                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
9603               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
9604                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
9605             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
9606                          diag::err_omp_multiple_array_items_in_map_clause)
9607                 << CI->getAssociatedExpression()->getSourceRange();
9608             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
9609                          diag::note_used_here)
9610                 << SI->getAssociatedExpression()->getSourceRange();
9611             return true;
9612           }
9613 
9614           // Do both expressions have the same kind?
9615           if (CI->getAssociatedExpression()->getStmtClass() !=
9616               SI->getAssociatedExpression()->getStmtClass())
9617             break;
9618 
9619           // Are we dealing with different variables/fields?
9620           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
9621             break;
9622         }
9623         // Check if the extra components of the expressions in the enclosing
9624         // data environment are redundant for the current base declaration.
9625         // If they are, the maps completely overlap, which is legal.
9626         for (; SI != SE; ++SI) {
9627           QualType Type;
9628           if (auto *ASE =
9629                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
9630             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
9631           } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
9632                          SI->getAssociatedExpression())) {
9633             auto *E = OASE->getBase()->IgnoreParenImpCasts();
9634             Type =
9635                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
9636           }
9637           if (Type.isNull() || Type->isAnyPointerType() ||
9638               CheckArrayExpressionDoesNotReferToWholeSize(
9639                   SemaRef, SI->getAssociatedExpression(), Type))
9640             break;
9641         }
9642 
9643         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9644         //  List items of map clauses in the same construct must not share
9645         //  original storage.
9646         //
9647         // If the expressions are exactly the same or one is a subset of the
9648         // other, it means they are sharing storage.
9649         if (CI == CE && SI == SE) {
9650           if (CurrentRegionOnly) {
9651             if (CKind == OMPC_map)
9652               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9653             else {
9654               assert(CKind == OMPC_to || CKind == OMPC_from);
9655               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9656                   << ERange;
9657             }
9658             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9659                 << RE->getSourceRange();
9660             return true;
9661           } else {
9662             // If we find the same expression in the enclosing data environment,
9663             // that is legal.
9664             IsEnclosedByDataEnvironmentExpr = true;
9665             return false;
9666           }
9667         }
9668 
9669         QualType DerivedType =
9670             std::prev(CI)->getAssociatedDeclaration()->getType();
9671         SourceLocation DerivedLoc =
9672             std::prev(CI)->getAssociatedExpression()->getExprLoc();
9673 
9674         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9675         //  If the type of a list item is a reference to a type T then the type
9676         //  will be considered to be T for all purposes of this clause.
9677         DerivedType = DerivedType.getNonReferenceType();
9678 
9679         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
9680         //  A variable for which the type is pointer and an array section
9681         //  derived from that variable must not appear as list items of map
9682         //  clauses of the same construct.
9683         //
9684         // Also, cover one of the cases in:
9685         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9686         //  If any part of the original storage of a list item has corresponding
9687         //  storage in the device data environment, all of the original storage
9688         //  must have corresponding storage in the device data environment.
9689         //
9690         if (DerivedType->isAnyPointerType()) {
9691           if (CI == CE || SI == SE) {
9692             SemaRef.Diag(
9693                 DerivedLoc,
9694                 diag::err_omp_pointer_mapped_along_with_derived_section)
9695                 << DerivedLoc;
9696           } else {
9697             assert(CI != CE && SI != SE);
9698             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
9699                 << DerivedLoc;
9700           }
9701           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9702               << RE->getSourceRange();
9703           return true;
9704         }
9705 
9706         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
9707         //  List items of map clauses in the same construct must not share
9708         //  original storage.
9709         //
9710         // An expression is a subset of the other.
9711         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
9712           if (CKind == OMPC_map)
9713             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
9714           else {
9715             assert(CKind == OMPC_to || CKind == OMPC_from);
9716             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
9717                 << ERange;
9718           }
9719           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
9720               << RE->getSourceRange();
9721           return true;
9722         }
9723 
9724         // The current expression uses the same base as other expression in the
9725         // data environment but does not contain it completely.
9726         if (!CurrentRegionOnly && SI != SE)
9727           EnclosingExpr = RE;
9728 
9729         // The current expression is a subset of the expression in the data
9730         // environment.
9731         IsEnclosedByDataEnvironmentExpr |=
9732             (!CurrentRegionOnly && CI != CE && SI == SE);
9733 
9734         return false;
9735       });
9736 
9737   if (CurrentRegionOnly)
9738     return FoundError;
9739 
9740   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
9741   //  If any part of the original storage of a list item has corresponding
9742   //  storage in the device data environment, all of the original storage must
9743   //  have corresponding storage in the device data environment.
9744   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
9745   //  If a list item is an element of a structure, and a different element of
9746   //  the structure has a corresponding list item in the device data environment
9747   //  prior to a task encountering the construct associated with the map clause,
9748   //  then the list item must also have a corresponding list item in the device
9749   //  data environment prior to the task encountering the construct.
9750   //
9751   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
9752     SemaRef.Diag(ELoc,
9753                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
9754         << ERange;
9755     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
9756         << EnclosingExpr->getSourceRange();
9757     return true;
9758   }
9759 
9760   return FoundError;
9761 }
9762 
9763 namespace {
9764 // Utility struct that gathers all the related lists associated with a mappable
9765 // expression.
9766 struct MappableVarListInfo final {
9767   // The list of expressions.
9768   ArrayRef<Expr *> VarList;
9769   // The list of processed expressions.
9770   SmallVector<Expr *, 16> ProcessedVarList;
9771   // The mappble components for each expression.
9772   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
9773   // The base declaration of the variable.
9774   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
9775 
9776   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
9777     // We have a list of components and base declarations for each entry in the
9778     // variable list.
9779     VarComponents.reserve(VarList.size());
9780     VarBaseDeclarations.reserve(VarList.size());
9781   }
9782 };
9783 }
9784 
9785 // Check the validity of the provided variable list for the provided clause kind
9786 // \a CKind. In the check process the valid expressions, and mappable expression
9787 // components and variables are extracted and used to fill \a Vars,
9788 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
9789 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
9790 static void
9791 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
9792                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
9793                             SourceLocation StartLoc,
9794                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
9795                             bool IsMapTypeImplicit = false) {
9796   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
9797   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
9798          "Unexpected clause kind with mappable expressions!");
9799 
9800   // Keep track of the mappable components and base declarations in this clause.
9801   // Each entry in the list is going to have a list of components associated. We
9802   // record each set of the components so that we can build the clause later on.
9803   // In the end we should have the same amount of declarations and component
9804   // lists.
9805 
9806   for (auto &RE : MVLI.VarList) {
9807     assert(RE && "Null expr in omp to/from/map clause");
9808     SourceLocation ELoc = RE->getExprLoc();
9809 
9810     auto *VE = RE->IgnoreParenLValueCasts();
9811 
9812     if (VE->isValueDependent() || VE->isTypeDependent() ||
9813         VE->isInstantiationDependent() ||
9814         VE->containsUnexpandedParameterPack()) {
9815       // We can only analyze this information once the missing information is
9816       // resolved.
9817       MVLI.ProcessedVarList.push_back(RE);
9818       continue;
9819     }
9820 
9821     auto *SimpleExpr = RE->IgnoreParenCasts();
9822 
9823     if (!RE->IgnoreParenImpCasts()->isLValue()) {
9824       SemaRef.Diag(ELoc,
9825                    diag::err_omp_expected_named_var_member_or_array_expression)
9826           << RE->getSourceRange();
9827       continue;
9828     }
9829 
9830     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
9831     ValueDecl *CurDeclaration = nullptr;
9832 
9833     // Obtain the array or member expression bases if required. Also, fill the
9834     // components array with all the components identified in the process.
9835     auto *BE =
9836         CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
9837     if (!BE)
9838       continue;
9839 
9840     assert(!CurComponents.empty() &&
9841            "Invalid mappable expression information.");
9842 
9843     // For the following checks, we rely on the base declaration which is
9844     // expected to be associated with the last component. The declaration is
9845     // expected to be a variable or a field (if 'this' is being mapped).
9846     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
9847     assert(CurDeclaration && "Null decl on map clause.");
9848     assert(
9849         CurDeclaration->isCanonicalDecl() &&
9850         "Expecting components to have associated only canonical declarations.");
9851 
9852     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
9853     auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
9854 
9855     assert((VD || FD) && "Only variables or fields are expected here!");
9856     (void)FD;
9857 
9858     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
9859     // threadprivate variables cannot appear in a map clause.
9860     // OpenMP 4.5 [2.10.5, target update Construct]
9861     // threadprivate variables cannot appear in a from clause.
9862     if (VD && DSAS->isThreadPrivate(VD)) {
9863       auto DVar = DSAS->getTopDSA(VD, false);
9864       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
9865           << getOpenMPClauseName(CKind);
9866       ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
9867       continue;
9868     }
9869 
9870     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9871     //  A list item cannot appear in both a map clause and a data-sharing
9872     //  attribute clause on the same construct.
9873 
9874     // Check conflicts with other map clause expressions. We check the conflicts
9875     // with the current construct separately from the enclosing data
9876     // environment, because the restrictions are different. We only have to
9877     // check conflicts across regions for the map clauses.
9878     if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9879                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
9880       break;
9881     if (CKind == OMPC_map &&
9882         CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
9883                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
9884       break;
9885 
9886     // OpenMP 4.5 [2.10.5, target update Construct]
9887     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9888     //  If the type of a list item is a reference to a type T then the type will
9889     //  be considered to be T for all purposes of this clause.
9890     QualType Type = CurDeclaration->getType().getNonReferenceType();
9891 
9892     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
9893     // A list item in a to or from clause must have a mappable type.
9894     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
9895     //  A list item must have a mappable type.
9896     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
9897                            DSAS, Type))
9898       continue;
9899 
9900     if (CKind == OMPC_map) {
9901       // target enter data
9902       // OpenMP [2.10.2, Restrictions, p. 99]
9903       // A map-type must be specified in all map clauses and must be either
9904       // to or alloc.
9905       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
9906       if (DKind == OMPD_target_enter_data &&
9907           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
9908         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9909             << (IsMapTypeImplicit ? 1 : 0)
9910             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9911             << getOpenMPDirectiveName(DKind);
9912         continue;
9913       }
9914 
9915       // target exit_data
9916       // OpenMP [2.10.3, Restrictions, p. 102]
9917       // A map-type must be specified in all map clauses and must be either
9918       // from, release, or delete.
9919       if (DKind == OMPD_target_exit_data &&
9920           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
9921             MapType == OMPC_MAP_delete)) {
9922         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
9923             << (IsMapTypeImplicit ? 1 : 0)
9924             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
9925             << getOpenMPDirectiveName(DKind);
9926         continue;
9927       }
9928 
9929       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9930       // A list item cannot appear in both a map clause and a data-sharing
9931       // attribute clause on the same construct
9932       if (DKind == OMPD_target && VD) {
9933         auto DVar = DSAS->getTopDSA(VD, false);
9934         if (isOpenMPPrivate(DVar.CKind)) {
9935           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9936               << getOpenMPClauseName(DVar.CKind)
9937               << getOpenMPClauseName(OMPC_map)
9938               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
9939           ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
9940           continue;
9941         }
9942       }
9943     }
9944 
9945     // Save the current expression.
9946     MVLI.ProcessedVarList.push_back(RE);
9947 
9948     // Store the components in the stack so that they can be used to check
9949     // against other clauses later on.
9950     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
9951                                           /*WhereFoundClauseKind=*/OMPC_map);
9952 
9953     // Save the components and declaration to create the clause. For purposes of
9954     // the clause creation, any component list that has has base 'this' uses
9955     // null as base declaration.
9956     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
9957     MVLI.VarComponents.back().append(CurComponents.begin(),
9958                                      CurComponents.end());
9959     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
9960                                                            : CurDeclaration);
9961   }
9962 }
9963 
9964 OMPClause *
9965 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9966                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9967                            SourceLocation MapLoc, SourceLocation ColonLoc,
9968                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9969                            SourceLocation LParenLoc, SourceLocation EndLoc) {
9970   MappableVarListInfo MVLI(VarList);
9971   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
9972                               MapType, IsMapTypeImplicit);
9973 
9974   // We need to produce a map clause even if we don't have variables so that
9975   // other diagnostics related with non-existing map clauses are accurate.
9976   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9977                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
9978                               MVLI.VarComponents, MapTypeModifier, MapType,
9979                               IsMapTypeImplicit, MapLoc);
9980 }
9981 
9982 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9983                                                TypeResult ParsedType) {
9984   assert(ParsedType.isUsable());
9985 
9986   QualType ReductionType = GetTypeFromParser(ParsedType.get());
9987   if (ReductionType.isNull())
9988     return QualType();
9989 
9990   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
9991   // A type name in a declare reduction directive cannot be a function type, an
9992   // array type, a reference type, or a type qualified with const, volatile or
9993   // restrict.
9994   if (ReductionType.hasQualifiers()) {
9995     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
9996     return QualType();
9997   }
9998 
9999   if (ReductionType->isFunctionType()) {
10000     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10001     return QualType();
10002   }
10003   if (ReductionType->isReferenceType()) {
10004     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10005     return QualType();
10006   }
10007   if (ReductionType->isArrayType()) {
10008     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10009     return QualType();
10010   }
10011   return ReductionType;
10012 }
10013 
10014 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10015     Scope *S, DeclContext *DC, DeclarationName Name,
10016     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10017     AccessSpecifier AS, Decl *PrevDeclInScope) {
10018   SmallVector<Decl *, 8> Decls;
10019   Decls.reserve(ReductionTypes.size());
10020 
10021   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10022                       ForRedeclaration);
10023   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10024   // A reduction-identifier may not be re-declared in the current scope for the
10025   // same type or for a type that is compatible according to the base language
10026   // rules.
10027   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10028   OMPDeclareReductionDecl *PrevDRD = nullptr;
10029   bool InCompoundScope = true;
10030   if (S != nullptr) {
10031     // Find previous declaration with the same name not referenced in other
10032     // declarations.
10033     FunctionScopeInfo *ParentFn = getEnclosingFunction();
10034     InCompoundScope =
10035         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10036     LookupName(Lookup, S);
10037     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10038                          /*AllowInlineNamespace=*/false);
10039     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10040     auto Filter = Lookup.makeFilter();
10041     while (Filter.hasNext()) {
10042       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10043       if (InCompoundScope) {
10044         auto I = UsedAsPrevious.find(PrevDecl);
10045         if (I == UsedAsPrevious.end())
10046           UsedAsPrevious[PrevDecl] = false;
10047         if (auto *D = PrevDecl->getPrevDeclInScope())
10048           UsedAsPrevious[D] = true;
10049       }
10050       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10051           PrevDecl->getLocation();
10052     }
10053     Filter.done();
10054     if (InCompoundScope) {
10055       for (auto &PrevData : UsedAsPrevious) {
10056         if (!PrevData.second) {
10057           PrevDRD = PrevData.first;
10058           break;
10059         }
10060       }
10061     }
10062   } else if (PrevDeclInScope != nullptr) {
10063     auto *PrevDRDInScope = PrevDRD =
10064         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10065     do {
10066       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10067           PrevDRDInScope->getLocation();
10068       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10069     } while (PrevDRDInScope != nullptr);
10070   }
10071   for (auto &TyData : ReductionTypes) {
10072     auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10073     bool Invalid = false;
10074     if (I != PreviousRedeclTypes.end()) {
10075       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10076           << TyData.first;
10077       Diag(I->second, diag::note_previous_definition);
10078       Invalid = true;
10079     }
10080     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10081     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10082                                                 Name, TyData.first, PrevDRD);
10083     DC->addDecl(DRD);
10084     DRD->setAccess(AS);
10085     Decls.push_back(DRD);
10086     if (Invalid)
10087       DRD->setInvalidDecl();
10088     else
10089       PrevDRD = DRD;
10090   }
10091 
10092   return DeclGroupPtrTy::make(
10093       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10094 }
10095 
10096 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10097   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10098 
10099   // Enter new function scope.
10100   PushFunctionScope();
10101   getCurFunction()->setHasBranchProtectedScope();
10102   getCurFunction()->setHasOMPDeclareReductionCombiner();
10103 
10104   if (S != nullptr)
10105     PushDeclContext(S, DRD);
10106   else
10107     CurContext = DRD;
10108 
10109   PushExpressionEvaluationContext(PotentiallyEvaluated);
10110 
10111   QualType ReductionType = DRD->getType();
10112   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10113   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10114   // uses semantics of argument handles by value, but it should be passed by
10115   // reference. C lang does not support references, so pass all parameters as
10116   // pointers.
10117   // Create 'T omp_in;' variable.
10118   auto *OmpInParm =
10119       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
10120   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10121   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10122   // uses semantics of argument handles by value, but it should be passed by
10123   // reference. C lang does not support references, so pass all parameters as
10124   // pointers.
10125   // Create 'T omp_out;' variable.
10126   auto *OmpOutParm =
10127       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10128   if (S != nullptr) {
10129     PushOnScopeChains(OmpInParm, S);
10130     PushOnScopeChains(OmpOutParm, S);
10131   } else {
10132     DRD->addDecl(OmpInParm);
10133     DRD->addDecl(OmpOutParm);
10134   }
10135 }
10136 
10137 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10138   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10139   DiscardCleanupsInEvaluationContext();
10140   PopExpressionEvaluationContext();
10141 
10142   PopDeclContext();
10143   PopFunctionScopeInfo();
10144 
10145   if (Combiner != nullptr)
10146     DRD->setCombiner(Combiner);
10147   else
10148     DRD->setInvalidDecl();
10149 }
10150 
10151 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10152   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10153 
10154   // Enter new function scope.
10155   PushFunctionScope();
10156   getCurFunction()->setHasBranchProtectedScope();
10157 
10158   if (S != nullptr)
10159     PushDeclContext(S, DRD);
10160   else
10161     CurContext = DRD;
10162 
10163   PushExpressionEvaluationContext(PotentiallyEvaluated);
10164 
10165   QualType ReductionType = DRD->getType();
10166   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10167   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10168   // uses semantics of argument handles by value, but it should be passed by
10169   // reference. C lang does not support references, so pass all parameters as
10170   // pointers.
10171   // Create 'T omp_priv;' variable.
10172   auto *OmpPrivParm =
10173       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
10174   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10175   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10176   // uses semantics of argument handles by value, but it should be passed by
10177   // reference. C lang does not support references, so pass all parameters as
10178   // pointers.
10179   // Create 'T omp_orig;' variable.
10180   auto *OmpOrigParm =
10181       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
10182   if (S != nullptr) {
10183     PushOnScopeChains(OmpPrivParm, S);
10184     PushOnScopeChains(OmpOrigParm, S);
10185   } else {
10186     DRD->addDecl(OmpPrivParm);
10187     DRD->addDecl(OmpOrigParm);
10188   }
10189 }
10190 
10191 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10192                                                      Expr *Initializer) {
10193   auto *DRD = cast<OMPDeclareReductionDecl>(D);
10194   DiscardCleanupsInEvaluationContext();
10195   PopExpressionEvaluationContext();
10196 
10197   PopDeclContext();
10198   PopFunctionScopeInfo();
10199 
10200   if (Initializer != nullptr)
10201     DRD->setInitializer(Initializer);
10202   else
10203     DRD->setInvalidDecl();
10204 }
10205 
10206 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10207     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10208   for (auto *D : DeclReductions.get()) {
10209     if (IsValid) {
10210       auto *DRD = cast<OMPDeclareReductionDecl>(D);
10211       if (S != nullptr)
10212         PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10213     } else
10214       D->setInvalidDecl();
10215   }
10216   return DeclReductions;
10217 }
10218 
10219 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
10220                                            SourceLocation StartLoc,
10221                                            SourceLocation LParenLoc,
10222                                            SourceLocation EndLoc) {
10223   Expr *ValExpr = NumTeams;
10224 
10225   // OpenMP [teams Constrcut, Restrictions]
10226   // The num_teams expression must evaluate to a positive integer value.
10227   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10228                                  /*StrictlyPositive=*/true))
10229     return nullptr;
10230 
10231   return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10232 }
10233 
10234 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10235                                               SourceLocation StartLoc,
10236                                               SourceLocation LParenLoc,
10237                                               SourceLocation EndLoc) {
10238   Expr *ValExpr = ThreadLimit;
10239 
10240   // OpenMP [teams Constrcut, Restrictions]
10241   // The thread_limit expression must evaluate to a positive integer value.
10242   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10243                                  /*StrictlyPositive=*/true))
10244     return nullptr;
10245 
10246   return new (Context)
10247       OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10248 }
10249 
10250 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10251                                            SourceLocation StartLoc,
10252                                            SourceLocation LParenLoc,
10253                                            SourceLocation EndLoc) {
10254   Expr *ValExpr = Priority;
10255 
10256   // OpenMP [2.9.1, task Constrcut]
10257   // The priority-value is a non-negative numerical scalar expression.
10258   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10259                                  /*StrictlyPositive=*/false))
10260     return nullptr;
10261 
10262   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10263 }
10264 
10265 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10266                                             SourceLocation StartLoc,
10267                                             SourceLocation LParenLoc,
10268                                             SourceLocation EndLoc) {
10269   Expr *ValExpr = Grainsize;
10270 
10271   // OpenMP [2.9.2, taskloop Constrcut]
10272   // The parameter of the grainsize clause must be a positive integer
10273   // expression.
10274   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10275                                  /*StrictlyPositive=*/true))
10276     return nullptr;
10277 
10278   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10279 }
10280 
10281 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10282                                            SourceLocation StartLoc,
10283                                            SourceLocation LParenLoc,
10284                                            SourceLocation EndLoc) {
10285   Expr *ValExpr = NumTasks;
10286 
10287   // OpenMP [2.9.2, taskloop Constrcut]
10288   // The parameter of the num_tasks clause must be a positive integer
10289   // expression.
10290   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10291                                  /*StrictlyPositive=*/true))
10292     return nullptr;
10293 
10294   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10295 }
10296 
10297 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10298                                        SourceLocation LParenLoc,
10299                                        SourceLocation EndLoc) {
10300   // OpenMP [2.13.2, critical construct, Description]
10301   // ... where hint-expression is an integer constant expression that evaluates
10302   // to a valid lock hint.
10303   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10304   if (HintExpr.isInvalid())
10305     return nullptr;
10306   return new (Context)
10307       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10308 }
10309 
10310 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10311     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10312     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10313     SourceLocation EndLoc) {
10314   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10315     std::string Values;
10316     Values += "'";
10317     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10318     Values += "'";
10319     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10320         << Values << getOpenMPClauseName(OMPC_dist_schedule);
10321     return nullptr;
10322   }
10323   Expr *ValExpr = ChunkSize;
10324   Stmt *HelperValStmt = nullptr;
10325   if (ChunkSize) {
10326     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10327         !ChunkSize->isInstantiationDependent() &&
10328         !ChunkSize->containsUnexpandedParameterPack()) {
10329       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10330       ExprResult Val =
10331           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10332       if (Val.isInvalid())
10333         return nullptr;
10334 
10335       ValExpr = Val.get();
10336 
10337       // OpenMP [2.7.1, Restrictions]
10338       //  chunk_size must be a loop invariant integer expression with a positive
10339       //  value.
10340       llvm::APSInt Result;
10341       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10342         if (Result.isSigned() && !Result.isStrictlyPositive()) {
10343           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10344               << "dist_schedule" << ChunkSize->getSourceRange();
10345           return nullptr;
10346         }
10347       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10348                  !CurContext->isDependentContext()) {
10349         llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10350         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10351         HelperValStmt = buildPreInits(Context, Captures);
10352       }
10353     }
10354   }
10355 
10356   return new (Context)
10357       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
10358                             Kind, ValExpr, HelperValStmt);
10359 }
10360 
10361 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10362     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10363     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10364     SourceLocation KindLoc, SourceLocation EndLoc) {
10365   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
10366   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
10367     std::string Value;
10368     SourceLocation Loc;
10369     Value += "'";
10370     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10371       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10372                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
10373       Loc = MLoc;
10374     } else {
10375       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
10376                                              OMPC_DEFAULTMAP_scalar);
10377       Loc = KindLoc;
10378     }
10379     Value += "'";
10380     Diag(Loc, diag::err_omp_unexpected_clause_value)
10381         << Value << getOpenMPClauseName(OMPC_defaultmap);
10382     return nullptr;
10383   }
10384 
10385   return new (Context)
10386       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10387 }
10388 
10389 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10390   DeclContext *CurLexicalContext = getCurLexicalContext();
10391   if (!CurLexicalContext->isFileContext() &&
10392       !CurLexicalContext->isExternCContext() &&
10393       !CurLexicalContext->isExternCXXContext()) {
10394     Diag(Loc, diag::err_omp_region_not_file_context);
10395     return false;
10396   }
10397   if (IsInOpenMPDeclareTargetContext) {
10398     Diag(Loc, diag::err_omp_enclosed_declare_target);
10399     return false;
10400   }
10401 
10402   IsInOpenMPDeclareTargetContext = true;
10403   return true;
10404 }
10405 
10406 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10407   assert(IsInOpenMPDeclareTargetContext &&
10408          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10409 
10410   IsInOpenMPDeclareTargetContext = false;
10411 }
10412 
10413 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10414                                         CXXScopeSpec &ScopeSpec,
10415                                         const DeclarationNameInfo &Id,
10416                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
10417                                         NamedDeclSetType &SameDirectiveDecls) {
10418   LookupResult Lookup(*this, Id, LookupOrdinaryName);
10419   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10420 
10421   if (Lookup.isAmbiguous())
10422     return;
10423   Lookup.suppressDiagnostics();
10424 
10425   if (!Lookup.isSingleResult()) {
10426     if (TypoCorrection Corrected =
10427             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10428                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10429                         CTK_ErrorRecovery)) {
10430       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10431                                   << Id.getName());
10432       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10433       return;
10434     }
10435 
10436     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
10437     return;
10438   }
10439 
10440   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
10441   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
10442     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
10443       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
10444 
10445     if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
10446       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
10447       ND->addAttr(A);
10448       if (ASTMutationListener *ML = Context.getASTMutationListener())
10449         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
10450       checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
10451     } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
10452       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
10453           << Id.getName();
10454     }
10455   } else
10456     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
10457 }
10458 
10459 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
10460                                      Sema &SemaRef, Decl *D) {
10461   if (!D)
10462     return;
10463   Decl *LD = nullptr;
10464   if (isa<TagDecl>(D)) {
10465     LD = cast<TagDecl>(D)->getDefinition();
10466   } else if (isa<VarDecl>(D)) {
10467     LD = cast<VarDecl>(D)->getDefinition();
10468 
10469     // If this is an implicit variable that is legal and we do not need to do
10470     // anything.
10471     if (cast<VarDecl>(D)->isImplicit()) {
10472       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10473           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10474       D->addAttr(A);
10475       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10476         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10477       return;
10478     }
10479 
10480   } else if (isa<FunctionDecl>(D)) {
10481     const FunctionDecl *FD = nullptr;
10482     if (cast<FunctionDecl>(D)->hasBody(FD))
10483       LD = const_cast<FunctionDecl *>(FD);
10484 
10485     // If the definition is associated with the current declaration in the
10486     // target region (it can be e.g. a lambda) that is legal and we do not need
10487     // to do anything else.
10488     if (LD == D) {
10489       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10490           SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10491       D->addAttr(A);
10492       if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10493         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10494       return;
10495     }
10496   }
10497   if (!LD)
10498     LD = D;
10499   if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
10500       (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
10501     // Outlined declaration is not declared target.
10502     if (LD->isOutOfLine()) {
10503       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10504       SemaRef.Diag(SL, diag::note_used_here) << SR;
10505     } else {
10506       DeclContext *DC = LD->getDeclContext();
10507       while (DC) {
10508         if (isa<FunctionDecl>(DC) &&
10509             cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
10510           break;
10511         DC = DC->getParent();
10512       }
10513       if (DC)
10514         return;
10515 
10516       // Is not declared in target context.
10517       SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
10518       SemaRef.Diag(SL, diag::note_used_here) << SR;
10519     }
10520     // Mark decl as declared target to prevent further diagnostic.
10521     Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10522         SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
10523     D->addAttr(A);
10524     if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
10525       ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10526   }
10527 }
10528 
10529 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
10530                                    Sema &SemaRef, DSAStackTy *Stack,
10531                                    ValueDecl *VD) {
10532   if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
10533     return true;
10534   if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
10535     return false;
10536   return true;
10537 }
10538 
10539 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
10540   if (!D || D->isInvalidDecl())
10541     return;
10542   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
10543   SourceLocation SL = E ? E->getLocStart() : D->getLocation();
10544   // 2.10.6: threadprivate variable cannot appear in a declare target directive.
10545   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10546     if (DSAStack->isThreadPrivate(VD)) {
10547       Diag(SL, diag::err_omp_threadprivate_in_target);
10548       ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
10549       return;
10550     }
10551   }
10552   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
10553     // Problem if any with var declared with incomplete type will be reported
10554     // as normal, so no need to check it here.
10555     if ((E || !VD->getType()->isIncompleteType()) &&
10556         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
10557       // Mark decl as declared target to prevent further diagnostic.
10558       if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
10559         Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10560             Context, OMPDeclareTargetDeclAttr::MT_To);
10561         VD->addAttr(A);
10562         if (ASTMutationListener *ML = Context.getASTMutationListener())
10563           ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
10564       }
10565       return;
10566     }
10567   }
10568   if (!E) {
10569     // Checking declaration inside declare target region.
10570     if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
10571         (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
10572       Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
10573           Context, OMPDeclareTargetDeclAttr::MT_To);
10574       D->addAttr(A);
10575       if (ASTMutationListener *ML = Context.getASTMutationListener())
10576         ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
10577     }
10578     return;
10579   }
10580   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
10581 }
10582 
10583 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
10584                                      SourceLocation StartLoc,
10585                                      SourceLocation LParenLoc,
10586                                      SourceLocation EndLoc) {
10587   MappableVarListInfo MVLI(VarList);
10588   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
10589   if (MVLI.ProcessedVarList.empty())
10590     return nullptr;
10591 
10592   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10593                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10594                              MVLI.VarComponents);
10595 }
10596 
10597 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
10598                                        SourceLocation StartLoc,
10599                                        SourceLocation LParenLoc,
10600                                        SourceLocation EndLoc) {
10601   MappableVarListInfo MVLI(VarList);
10602   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
10603   if (MVLI.ProcessedVarList.empty())
10604     return nullptr;
10605 
10606   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10607                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10608                                MVLI.VarComponents);
10609 }
10610 
10611 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10612                                                SourceLocation StartLoc,
10613                                                SourceLocation LParenLoc,
10614                                                SourceLocation EndLoc) {
10615   MappableVarListInfo MVLI(VarList);
10616   SmallVector<Expr *, 8> PrivateCopies;
10617   SmallVector<Expr *, 8> Inits;
10618 
10619   for (auto &RefExpr : VarList) {
10620     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10621     SourceLocation ELoc;
10622     SourceRange ERange;
10623     Expr *SimpleRefExpr = RefExpr;
10624     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10625     if (Res.second) {
10626       // It will be analyzed later.
10627       MVLI.ProcessedVarList.push_back(RefExpr);
10628       PrivateCopies.push_back(nullptr);
10629       Inits.push_back(nullptr);
10630     }
10631     ValueDecl *D = Res.first;
10632     if (!D)
10633       continue;
10634 
10635     QualType Type = D->getType();
10636     Type = Type.getNonReferenceType().getUnqualifiedType();
10637 
10638     auto *VD = dyn_cast<VarDecl>(D);
10639 
10640     // Item should be a pointer or reference to pointer.
10641     if (!Type->isPointerType()) {
10642       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
10643           << 0 << RefExpr->getSourceRange();
10644       continue;
10645     }
10646 
10647     // Build the private variable and the expression that refers to it.
10648     auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
10649                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10650     if (VDPrivate->isInvalidDecl())
10651       continue;
10652 
10653     CurContext->addDecl(VDPrivate);
10654     auto VDPrivateRefExpr = buildDeclRefExpr(
10655         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
10656 
10657     // Add temporary variable to initialize the private copy of the pointer.
10658     auto *VDInit =
10659         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
10660     auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10661                                            RefExpr->getExprLoc());
10662     AddInitializerToDecl(VDPrivate,
10663                          DefaultLvalueConversion(VDInitRefExpr).get(),
10664                          /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
10665 
10666     // If required, build a capture to implement the privatization initialized
10667     // with the current list item value.
10668     DeclRefExpr *Ref = nullptr;
10669     if (!VD)
10670       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10671     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
10672     PrivateCopies.push_back(VDPrivateRefExpr);
10673     Inits.push_back(VDInitRefExpr);
10674 
10675     // We need to add a data sharing attribute for this variable to make sure it
10676     // is correctly captured. A variable that shows up in a use_device_ptr has
10677     // similar properties of a first private variable.
10678     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10679 
10680     // Create a mappable component for the list item. List items in this clause
10681     // only need a component.
10682     MVLI.VarBaseDeclarations.push_back(D);
10683     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10684     MVLI.VarComponents.back().push_back(
10685         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
10686   }
10687 
10688   if (MVLI.ProcessedVarList.empty())
10689     return nullptr;
10690 
10691   return OMPUseDevicePtrClause::Create(
10692       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10693       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
10694 }
10695 
10696 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10697                                               SourceLocation StartLoc,
10698                                               SourceLocation LParenLoc,
10699                                               SourceLocation EndLoc) {
10700   MappableVarListInfo MVLI(VarList);
10701   for (auto &RefExpr : VarList) {
10702     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
10703     SourceLocation ELoc;
10704     SourceRange ERange;
10705     Expr *SimpleRefExpr = RefExpr;
10706     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10707     if (Res.second) {
10708       // It will be analyzed later.
10709       MVLI.ProcessedVarList.push_back(RefExpr);
10710     }
10711     ValueDecl *D = Res.first;
10712     if (!D)
10713       continue;
10714 
10715     QualType Type = D->getType();
10716     // item should be a pointer or array or reference to pointer or array
10717     if (!Type.getNonReferenceType()->isPointerType() &&
10718         !Type.getNonReferenceType()->isArrayType()) {
10719       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
10720           << 0 << RefExpr->getSourceRange();
10721       continue;
10722     }
10723 
10724     // Check if the declaration in the clause does not show up in any data
10725     // sharing attribute.
10726     auto DVar = DSAStack->getTopDSA(D, false);
10727     if (isOpenMPPrivate(DVar.CKind)) {
10728       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10729           << getOpenMPClauseName(DVar.CKind)
10730           << getOpenMPClauseName(OMPC_is_device_ptr)
10731           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10732       ReportOriginalDSA(*this, DSAStack, D, DVar);
10733       continue;
10734     }
10735 
10736     Expr *ConflictExpr;
10737     if (DSAStack->checkMappableExprComponentListsForDecl(
10738             D, /*CurrentRegionOnly=*/true,
10739             [&ConflictExpr](
10740                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
10741                 OpenMPClauseKind) -> bool {
10742               ConflictExpr = R.front().getAssociatedExpression();
10743               return true;
10744             })) {
10745       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
10746       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
10747           << ConflictExpr->getSourceRange();
10748       continue;
10749     }
10750 
10751     // Store the components in the stack so that they can be used to check
10752     // against other clauses later on.
10753     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
10754     DSAStack->addMappableExpressionComponents(
10755         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
10756 
10757     // Record the expression we've just processed.
10758     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
10759 
10760     // Create a mappable component for the list item. List items in this clause
10761     // only need a component. We use a null declaration to signal fields in
10762     // 'this'.
10763     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
10764             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
10765            "Unexpected device pointer expression!");
10766     MVLI.VarBaseDeclarations.push_back(
10767         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
10768     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10769     MVLI.VarComponents.back().push_back(MC);
10770   }
10771 
10772   if (MVLI.ProcessedVarList.empty())
10773     return nullptr;
10774 
10775   return OMPIsDevicePtrClause::Create(
10776       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
10777       MVLI.VarBaseDeclarations, MVLI.VarComponents);
10778 }
10779