]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaOpenMP.cpp
Update clang to trunk r256633.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaOpenMP.cpp
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/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/OpenMPKinds.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 using namespace clang;
33
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37
38 namespace {
39 /// \brief Default data sharing attributes, which can be applied to directive.
40 enum DefaultDataSharingAttributes {
41   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
42   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
43   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
44 };
45
46 template <class T> struct MatchesAny {
47   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
48   bool operator()(T Kind) {
49     for (auto KindEl : Arr)
50       if (KindEl == Kind)
51         return true;
52     return false;
53   }
54
55 private:
56   ArrayRef<T> Arr;
57 };
58 struct MatchesAlways {
59   MatchesAlways() {}
60   template <class T> bool operator()(T) { return true; }
61 };
62
63 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
64 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
65
66 /// \brief Stack for tracking declarations used in OpenMP directives and
67 /// clauses and their data-sharing attributes.
68 class DSAStackTy {
69 public:
70   struct DSAVarData {
71     OpenMPDirectiveKind DKind;
72     OpenMPClauseKind CKind;
73     DeclRefExpr *RefExpr;
74     SourceLocation ImplicitDSALoc;
75     DSAVarData()
76         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
77           ImplicitDSALoc() {}
78   };
79
80 public:
81   struct MapInfo {
82     Expr *RefExpr;
83   };
84
85 private:
86   struct DSAInfo {
87     OpenMPClauseKind Attributes;
88     DeclRefExpr *RefExpr;
89   };
90   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
91   typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
92   typedef llvm::DenseMap<VarDecl *, unsigned> LoopControlVariablesMapTy;
93   typedef llvm::SmallDenseMap<VarDecl *, MapInfo, 64> MappedDeclsTy;
94   typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
95       CriticalsWithHintsTy;
96
97   struct SharingMapTy {
98     DeclSAMapTy SharingMap;
99     AlignedMapTy AlignedMap;
100     MappedDeclsTy MappedDecls;
101     LoopControlVariablesMapTy LCVMap;
102     DefaultDataSharingAttributes DefaultAttr;
103     SourceLocation DefaultAttrLoc;
104     OpenMPDirectiveKind Directive;
105     DeclarationNameInfo DirectiveName;
106     Scope *CurScope;
107     SourceLocation ConstructLoc;
108     /// \brief first argument (Expr *) contains optional argument of the
109     /// 'ordered' clause, the second one is true if the regions has 'ordered'
110     /// clause, false otherwise.
111     llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
112     bool NowaitRegion;
113     bool CancelRegion;
114     unsigned AssociatedLoops;
115     SourceLocation InnerTeamsRegionLoc;
116     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
117                  Scope *CurScope, SourceLocation Loc)
118         : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
119           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
120           ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
121           CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
122     SharingMapTy()
123         : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
124           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
125           ConstructLoc(), OrderedRegion(), NowaitRegion(false),
126           CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
127   };
128
129   typedef SmallVector<SharingMapTy, 64> StackTy;
130
131   /// \brief Stack of used declaration and their data-sharing attributes.
132   StackTy Stack;
133   /// \brief true, if check for DSA must be from parent directive, false, if
134   /// from current directive.
135   OpenMPClauseKind ClauseKindMode;
136   Sema &SemaRef;
137   bool ForceCapturing;
138   CriticalsWithHintsTy Criticals;
139
140   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
141
142   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
143
144   /// \brief Checks if the variable is a local for OpenMP region.
145   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
146
147 public:
148   explicit DSAStackTy(Sema &S)
149       : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
150         ForceCapturing(false) {}
151
152   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
153   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
154
155   bool isForceVarCapturing() const { return ForceCapturing; }
156   void setForceVarCapturing(bool V) { ForceCapturing = V; }
157
158   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
159             Scope *CurScope, SourceLocation Loc) {
160     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
161     Stack.back().DefaultAttrLoc = Loc;
162   }
163
164   void pop() {
165     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
166     Stack.pop_back();
167   }
168
169   void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
170     Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
171   }
172   const std::pair<OMPCriticalDirective *, llvm::APSInt>
173   getCriticalWithHint(const DeclarationNameInfo &Name) const {
174     auto I = Criticals.find(Name.getAsString());
175     if (I != Criticals.end())
176       return I->second;
177     return std::make_pair(nullptr, llvm::APSInt());
178   }
179   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
180   /// add it and return NULL; otherwise return previous occurrence's expression
181   /// for diagnostics.
182   DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
183
184   /// \brief Register specified variable as loop control variable.
185   void addLoopControlVariable(VarDecl *D);
186   /// \brief Check if the specified variable is a loop control variable for
187   /// current region.
188   /// \return The index of the loop control variable in the list of associated
189   /// for-loops (from outer to inner).
190   unsigned isLoopControlVariable(VarDecl *D);
191   /// \brief Check if the specified variable is a loop control variable for
192   /// parent region.
193   /// \return The index of the loop control variable in the list of associated
194   /// for-loops (from outer to inner).
195   unsigned isParentLoopControlVariable(VarDecl *D);
196   /// \brief Get the loop control variable for the I-th loop (or nullptr) in
197   /// parent directive.
198   VarDecl *getParentLoopControlVariable(unsigned I);
199
200   /// \brief Adds explicit data sharing attribute to the specified declaration.
201   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
202
203   /// \brief Returns data sharing attributes from top of the stack for the
204   /// specified declaration.
205   DSAVarData getTopDSA(VarDecl *D, bool FromParent);
206   /// \brief Returns data-sharing attributes for the specified declaration.
207   DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
208   /// \brief Checks if the specified variables has data-sharing attributes which
209   /// match specified \a CPred predicate in any directive which matches \a DPred
210   /// predicate.
211   template <class ClausesPredicate, class DirectivesPredicate>
212   DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
213                     DirectivesPredicate DPred, bool FromParent);
214   /// \brief Checks if the specified variables has data-sharing attributes which
215   /// match specified \a CPred predicate in any innermost directive which
216   /// matches \a DPred predicate.
217   template <class ClausesPredicate, class DirectivesPredicate>
218   DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
219                              DirectivesPredicate DPred,
220                              bool FromParent);
221   /// \brief Checks if the specified variables has explicit data-sharing
222   /// attributes which match specified \a CPred predicate at the specified
223   /// OpenMP region.
224   bool hasExplicitDSA(VarDecl *D,
225                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
226                       unsigned Level);
227
228   /// \brief Returns true if the directive at level \Level matches in the
229   /// specified \a DPred predicate.
230   bool hasExplicitDirective(
231       const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
232       unsigned Level);
233
234   /// \brief Finds a directive which matches specified \a DPred predicate.
235   template <class NamedDirectivesPredicate>
236   bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
237
238   /// \brief Returns currently analyzed directive.
239   OpenMPDirectiveKind getCurrentDirective() const {
240     return Stack.back().Directive;
241   }
242   /// \brief Returns parent directive.
243   OpenMPDirectiveKind getParentDirective() const {
244     if (Stack.size() > 2)
245       return Stack[Stack.size() - 2].Directive;
246     return OMPD_unknown;
247   }
248   /// \brief Return the directive associated with the provided scope.
249   OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
250
251   /// \brief Set default data sharing attribute to none.
252   void setDefaultDSANone(SourceLocation Loc) {
253     Stack.back().DefaultAttr = DSA_none;
254     Stack.back().DefaultAttrLoc = Loc;
255   }
256   /// \brief Set default data sharing attribute to shared.
257   void setDefaultDSAShared(SourceLocation Loc) {
258     Stack.back().DefaultAttr = DSA_shared;
259     Stack.back().DefaultAttrLoc = Loc;
260   }
261
262   DefaultDataSharingAttributes getDefaultDSA() const {
263     return Stack.back().DefaultAttr;
264   }
265   SourceLocation getDefaultDSALocation() const {
266     return Stack.back().DefaultAttrLoc;
267   }
268
269   /// \brief Checks if the specified variable is a threadprivate.
270   bool isThreadPrivate(VarDecl *D) {
271     DSAVarData DVar = getTopDSA(D, false);
272     return isOpenMPThreadPrivate(DVar.CKind);
273   }
274
275   /// \brief Marks current region as ordered (it has an 'ordered' clause).
276   void setOrderedRegion(bool IsOrdered, Expr *Param) {
277     Stack.back().OrderedRegion.setInt(IsOrdered);
278     Stack.back().OrderedRegion.setPointer(Param);
279   }
280   /// \brief Returns true, if parent region is ordered (has associated
281   /// 'ordered' clause), false - otherwise.
282   bool isParentOrderedRegion() const {
283     if (Stack.size() > 2)
284       return Stack[Stack.size() - 2].OrderedRegion.getInt();
285     return false;
286   }
287   /// \brief Returns optional parameter for the ordered region.
288   Expr *getParentOrderedRegionParam() const {
289     if (Stack.size() > 2)
290       return Stack[Stack.size() - 2].OrderedRegion.getPointer();
291     return nullptr;
292   }
293   /// \brief Marks current region as nowait (it has a 'nowait' clause).
294   void setNowaitRegion(bool IsNowait = true) {
295     Stack.back().NowaitRegion = IsNowait;
296   }
297   /// \brief Returns true, if parent region is nowait (has associated
298   /// 'nowait' clause), false - otherwise.
299   bool isParentNowaitRegion() const {
300     if (Stack.size() > 2)
301       return Stack[Stack.size() - 2].NowaitRegion;
302     return false;
303   }
304   /// \brief Marks parent region as cancel region.
305   void setParentCancelRegion(bool Cancel = true) {
306     if (Stack.size() > 2)
307       Stack[Stack.size() - 2].CancelRegion =
308           Stack[Stack.size() - 2].CancelRegion || Cancel;
309   }
310   /// \brief Return true if current region has inner cancel construct.
311   bool isCancelRegion() const {
312     return Stack.back().CancelRegion;
313   }
314
315   /// \brief Set collapse value for the region.
316   void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
317   /// \brief Return collapse value for region.
318   unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
319
320   /// \brief Marks current target region as one with closely nested teams
321   /// region.
322   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
323     if (Stack.size() > 2)
324       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
325   }
326   /// \brief Returns true, if current region has closely nested teams region.
327   bool hasInnerTeamsRegion() const {
328     return getInnerTeamsRegionLoc().isValid();
329   }
330   /// \brief Returns location of the nested teams region (if any).
331   SourceLocation getInnerTeamsRegionLoc() const {
332     if (Stack.size() > 1)
333       return Stack.back().InnerTeamsRegionLoc;
334     return SourceLocation();
335   }
336
337   Scope *getCurScope() const { return Stack.back().CurScope; }
338   Scope *getCurScope() { return Stack.back().CurScope; }
339   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
340
341   MapInfo getMapInfoForVar(VarDecl *VD) {
342     MapInfo VarMI = {0};
343     for (auto Cnt = Stack.size() - 1; Cnt > 0; --Cnt) {
344       if (Stack[Cnt].MappedDecls.count(VD)) {
345         VarMI = Stack[Cnt].MappedDecls[VD];
346         break;
347       }
348     }
349     return VarMI;
350   }
351
352   void addMapInfoForVar(VarDecl *VD, MapInfo MI) {
353     if (Stack.size() > 1) {
354       Stack.back().MappedDecls[VD] = MI;
355     }
356   }
357
358   MapInfo IsMappedInCurrentRegion(VarDecl *VD) {
359     assert(Stack.size() > 1 && "Target level is 0");
360     MapInfo VarMI = {0};
361     if (Stack.size() > 1 && Stack.back().MappedDecls.count(VD)) {
362       VarMI = Stack.back().MappedDecls[VD];
363     }
364     return VarMI;
365   }
366 };
367 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
368   return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
369          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown ||
370          isOpenMPTaskLoopDirective(DKind);
371 }
372 } // namespace
373
374 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
375                                           VarDecl *D) {
376   D = D->getCanonicalDecl();
377   DSAVarData DVar;
378   if (Iter == std::prev(Stack.rend())) {
379     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
380     // in a region but not in construct]
381     //  File-scope or namespace-scope variables referenced in called routines
382     //  in the region are shared unless they appear in a threadprivate
383     //  directive.
384     if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
385       DVar.CKind = OMPC_shared;
386
387     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
388     // in a region but not in construct]
389     //  Variables with static storage duration that are declared in called
390     //  routines in the region are shared.
391     if (D->hasGlobalStorage())
392       DVar.CKind = OMPC_shared;
393
394     return DVar;
395   }
396
397   DVar.DKind = Iter->Directive;
398   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
399   // in a Construct, C/C++, predetermined, p.1]
400   // Variables with automatic storage duration that are declared in a scope
401   // inside the construct are private.
402   if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
403       (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
404     DVar.CKind = OMPC_private;
405     return DVar;
406   }
407
408   // Explicitly specified attributes and local variables with predetermined
409   // attributes.
410   if (Iter->SharingMap.count(D)) {
411     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
412     DVar.CKind = Iter->SharingMap[D].Attributes;
413     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
414     return DVar;
415   }
416
417   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
418   // in a Construct, C/C++, implicitly determined, p.1]
419   //  In a parallel or task construct, the data-sharing attributes of these
420   //  variables are determined by the default clause, if present.
421   switch (Iter->DefaultAttr) {
422   case DSA_shared:
423     DVar.CKind = OMPC_shared;
424     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
425     return DVar;
426   case DSA_none:
427     return DVar;
428   case DSA_unspecified:
429     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
430     // in a Construct, implicitly determined, p.2]
431     //  In a parallel construct, if no default clause is present, these
432     //  variables are shared.
433     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
434     if (isOpenMPParallelDirective(DVar.DKind) ||
435         isOpenMPTeamsDirective(DVar.DKind)) {
436       DVar.CKind = OMPC_shared;
437       return DVar;
438     }
439
440     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
441     // in a Construct, implicitly determined, p.4]
442     //  In a task construct, if no default clause is present, a variable that in
443     //  the enclosing context is determined to be shared by all implicit tasks
444     //  bound to the current team is shared.
445     if (DVar.DKind == OMPD_task) {
446       DSAVarData DVarTemp;
447       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
448            I != EE; ++I) {
449         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
450         // Referenced
451         // in a Construct, implicitly determined, p.6]
452         //  In a task construct, if no default clause is present, a variable
453         //  whose data-sharing attribute is not determined by the rules above is
454         //  firstprivate.
455         DVarTemp = getDSA(I, D);
456         if (DVarTemp.CKind != OMPC_shared) {
457           DVar.RefExpr = nullptr;
458           DVar.DKind = OMPD_task;
459           DVar.CKind = OMPC_firstprivate;
460           return DVar;
461         }
462         if (isParallelOrTaskRegion(I->Directive))
463           break;
464       }
465       DVar.DKind = OMPD_task;
466       DVar.CKind =
467           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
468       return DVar;
469     }
470   }
471   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
472   // in a Construct, implicitly determined, p.3]
473   //  For constructs other than task, if no default clause is present, these
474   //  variables inherit their data-sharing attributes from the enclosing
475   //  context.
476   return getDSA(std::next(Iter), D);
477 }
478
479 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
480   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
481   D = D->getCanonicalDecl();
482   auto It = Stack.back().AlignedMap.find(D);
483   if (It == Stack.back().AlignedMap.end()) {
484     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
485     Stack.back().AlignedMap[D] = NewDE;
486     return nullptr;
487   } else {
488     assert(It->second && "Unexpected nullptr expr in the aligned map");
489     return It->second;
490   }
491   return nullptr;
492 }
493
494 void DSAStackTy::addLoopControlVariable(VarDecl *D) {
495   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
496   D = D->getCanonicalDecl();
497   Stack.back().LCVMap.insert(std::make_pair(D, Stack.back().LCVMap.size() + 1));
498 }
499
500 unsigned DSAStackTy::isLoopControlVariable(VarDecl *D) {
501   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
502   D = D->getCanonicalDecl();
503   return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] : 0;
504 }
505
506 unsigned DSAStackTy::isParentLoopControlVariable(VarDecl *D) {
507   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
508   D = D->getCanonicalDecl();
509   return Stack[Stack.size() - 2].LCVMap.count(D) > 0
510              ? Stack[Stack.size() - 2].LCVMap[D]
511              : 0;
512 }
513
514 VarDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
515   assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
516   if (Stack[Stack.size() - 2].LCVMap.size() < I)
517     return nullptr;
518   for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
519     if (Pair.second == I)
520       return Pair.first;
521   }
522   return nullptr;
523 }
524
525 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
526   D = D->getCanonicalDecl();
527   if (A == OMPC_threadprivate) {
528     Stack[0].SharingMap[D].Attributes = A;
529     Stack[0].SharingMap[D].RefExpr = E;
530   } else {
531     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
532     Stack.back().SharingMap[D].Attributes = A;
533     Stack.back().SharingMap[D].RefExpr = E;
534   }
535 }
536
537 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
538   D = D->getCanonicalDecl();
539   if (Stack.size() > 2) {
540     reverse_iterator I = Iter, E = std::prev(Stack.rend());
541     Scope *TopScope = nullptr;
542     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
543       ++I;
544     }
545     if (I == E)
546       return false;
547     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
548     Scope *CurScope = getCurScope();
549     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
550       CurScope = CurScope->getParent();
551     }
552     return CurScope != TopScope;
553   }
554   return false;
555 }
556
557 /// \brief Build a variable declaration for OpenMP loop iteration variable.
558 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
559                              StringRef Name, const AttrVec *Attrs = nullptr) {
560   DeclContext *DC = SemaRef.CurContext;
561   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
562   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
563   VarDecl *Decl =
564       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
565   if (Attrs) {
566     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
567          I != E; ++I)
568       Decl->addAttr(*I);
569   }
570   Decl->setImplicit();
571   return Decl;
572 }
573
574 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
575                                      SourceLocation Loc,
576                                      bool RefersToCapture = false) {
577   D->setReferenced();
578   D->markUsed(S.Context);
579   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
580                              SourceLocation(), D, RefersToCapture, Loc, Ty,
581                              VK_LValue);
582 }
583
584 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
585   D = D->getCanonicalDecl();
586   DSAVarData DVar;
587
588   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
589   // in a Construct, C/C++, predetermined, p.1]
590   //  Variables appearing in threadprivate directives are threadprivate.
591   if ((D->getTLSKind() != VarDecl::TLS_None &&
592        !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
593          SemaRef.getLangOpts().OpenMPUseTLS &&
594          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
595       (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
596        !D->isLocalVarDecl())) {
597     addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
598                                D->getLocation()),
599            OMPC_threadprivate);
600   }
601   if (Stack[0].SharingMap.count(D)) {
602     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
603     DVar.CKind = OMPC_threadprivate;
604     return DVar;
605   }
606
607   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
608   // in a Construct, C/C++, predetermined, p.4]
609   //  Static data members are shared.
610   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
611   // in a Construct, C/C++, predetermined, p.7]
612   //  Variables with static storage duration that are declared in a scope
613   //  inside the construct are shared.
614   if (D->isStaticDataMember()) {
615     DSAVarData DVarTemp =
616         hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
617     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
618       return DVar;
619
620     DVar.CKind = OMPC_shared;
621     return DVar;
622   }
623
624   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
625   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
626   Type = SemaRef.getASTContext().getBaseElementType(Type);
627   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
628   // in a Construct, C/C++, predetermined, p.6]
629   //  Variables with const qualified type having no mutable member are
630   //  shared.
631   CXXRecordDecl *RD =
632       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
633   if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
634     if (auto *CTD = CTSD->getSpecializedTemplate())
635       RD = CTD->getTemplatedDecl();
636   if (IsConstant &&
637       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
638     // Variables with const-qualified type having no mutable member may be
639     // listed in a firstprivate clause, even if they are static data members.
640     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
641                                  MatchesAlways(), FromParent);
642     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
643       return DVar;
644
645     DVar.CKind = OMPC_shared;
646     return DVar;
647   }
648
649   // Explicitly specified attributes and local variables with predetermined
650   // attributes.
651   auto StartI = std::next(Stack.rbegin());
652   auto EndI = std::prev(Stack.rend());
653   if (FromParent && StartI != EndI) {
654     StartI = std::next(StartI);
655   }
656   auto I = std::prev(StartI);
657   if (I->SharingMap.count(D)) {
658     DVar.RefExpr = I->SharingMap[D].RefExpr;
659     DVar.CKind = I->SharingMap[D].Attributes;
660     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
661   }
662
663   return DVar;
664 }
665
666 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
667   D = D->getCanonicalDecl();
668   auto StartI = Stack.rbegin();
669   auto EndI = std::prev(Stack.rend());
670   if (FromParent && StartI != EndI) {
671     StartI = std::next(StartI);
672   }
673   return getDSA(StartI, D);
674 }
675
676 template <class ClausesPredicate, class DirectivesPredicate>
677 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
678                                           DirectivesPredicate DPred,
679                                           bool FromParent) {
680   D = D->getCanonicalDecl();
681   auto StartI = std::next(Stack.rbegin());
682   auto EndI = std::prev(Stack.rend());
683   if (FromParent && StartI != EndI) {
684     StartI = std::next(StartI);
685   }
686   for (auto I = StartI, EE = EndI; I != EE; ++I) {
687     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
688       continue;
689     DSAVarData DVar = getDSA(I, D);
690     if (CPred(DVar.CKind))
691       return DVar;
692   }
693   return DSAVarData();
694 }
695
696 template <class ClausesPredicate, class DirectivesPredicate>
697 DSAStackTy::DSAVarData
698 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
699                             DirectivesPredicate DPred, bool FromParent) {
700   D = D->getCanonicalDecl();
701   auto StartI = std::next(Stack.rbegin());
702   auto EndI = std::prev(Stack.rend());
703   if (FromParent && StartI != EndI) {
704     StartI = std::next(StartI);
705   }
706   for (auto I = StartI, EE = EndI; I != EE; ++I) {
707     if (!DPred(I->Directive))
708       break;
709     DSAVarData DVar = getDSA(I, D);
710     if (CPred(DVar.CKind))
711       return DVar;
712     return DSAVarData();
713   }
714   return DSAVarData();
715 }
716
717 bool DSAStackTy::hasExplicitDSA(
718     VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
719     unsigned Level) {
720   if (CPred(ClauseKindMode))
721     return true;
722   if (isClauseParsingMode())
723     ++Level;
724   D = D->getCanonicalDecl();
725   auto StartI = Stack.rbegin();
726   auto EndI = std::prev(Stack.rend());
727   if (std::distance(StartI, EndI) <= (int)Level)
728     return false;
729   std::advance(StartI, Level);
730   return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
731          CPred(StartI->SharingMap[D].Attributes);
732 }
733
734 bool DSAStackTy::hasExplicitDirective(
735     const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
736     unsigned Level) {
737   if (isClauseParsingMode())
738     ++Level;
739   auto StartI = Stack.rbegin();
740   auto EndI = std::prev(Stack.rend());
741   if (std::distance(StartI, EndI) <= (int)Level)
742     return false;
743   std::advance(StartI, Level);
744   return DPred(StartI->Directive);
745 }
746
747 template <class NamedDirectivesPredicate>
748 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
749   auto StartI = std::next(Stack.rbegin());
750   auto EndI = std::prev(Stack.rend());
751   if (FromParent && StartI != EndI) {
752     StartI = std::next(StartI);
753   }
754   for (auto I = StartI, EE = EndI; I != EE; ++I) {
755     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
756       return true;
757   }
758   return false;
759 }
760
761 OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
762   for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
763     if (I->CurScope == S)
764       return I->Directive;
765   return OMPD_unknown;
766 }
767
768 void Sema::InitDataSharingAttributesStack() {
769   VarDataSharingAttributesStack = new DSAStackTy(*this);
770 }
771
772 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
773
774 bool Sema::IsOpenMPCapturedByRef(VarDecl *VD,
775                                  const CapturedRegionScopeInfo *RSI) {
776   assert(LangOpts.OpenMP && "OpenMP is not allowed");
777
778   auto &Ctx = getASTContext();
779   bool IsByRef = true;
780
781   // Find the directive that is associated with the provided scope.
782   auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
783   auto Ty = VD->getType();
784
785   if (isOpenMPTargetDirective(DKind)) {
786     // This table summarizes how a given variable should be passed to the device
787     // given its type and the clauses where it appears. This table is based on
788     // the description in OpenMP 4.5 [2.10.4, target Construct] and
789     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
790     //
791     // =========================================================================
792     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
793     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
794     // =========================================================================
795     // | scl  |               |     |       |       -       |          | bycopy|
796     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
797     // | scl  |               |  x  |   -   |       -       |     -    | null  |
798     // | scl  |       x       |     |       |       -       |          | byref |
799     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
800     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
801     // | scl  |               |  -  |   -   |       -       |     x    | byref |
802     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
803     //
804     // | agg  |      n.a.     |     |       |       -       |          | byref |
805     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
806     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
807     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
808     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
809     //
810     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
811     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
812     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
813     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
814     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
815     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
816     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
817     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
818     // =========================================================================
819     // Legend:
820     //  scl - scalar
821     //  ptr - pointer
822     //  agg - aggregate
823     //  x - applies
824     //  - - invalid in this combination
825     //  [] - mapped with an array section
826     //  byref - should be mapped by reference
827     //  byval - should be mapped by value
828     //  null - initialize a local variable to null on the device
829     //
830     // Observations:
831     //  - All scalar declarations that show up in a map clause have to be passed
832     //    by reference, because they may have been mapped in the enclosing data
833     //    environment.
834     //  - If the scalar value does not fit the size of uintptr, it has to be
835     //    passed by reference, regardless the result in the table above.
836     //  - For pointers mapped by value that have either an implicit map or an
837     //    array section, the runtime library may pass the NULL value to the
838     //    device instead of the value passed to it by the compiler.
839
840     // FIXME: Right now, only implicit maps are implemented. Properly mapping
841     // values requires having the map, private, and firstprivate clauses SEMA
842     // and parsing in place, which we don't yet.
843
844     if (Ty->isReferenceType())
845       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
846     IsByRef = !Ty->isScalarType();
847   }
848
849   // When passing data by value, we need to make sure it fits the uintptr size
850   // and alignment, because the runtime library only deals with uintptr types.
851   // If it does not fit the uintptr size, we need to pass the data by reference
852   // instead.
853   if (!IsByRef &&
854       (Ctx.getTypeSizeInChars(Ty) >
855            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
856        Ctx.getDeclAlign(VD) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
857     IsByRef = true;
858
859   return IsByRef;
860 }
861
862 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
863   assert(LangOpts.OpenMP && "OpenMP is not allowed");
864   VD = VD->getCanonicalDecl();
865
866   // If we are attempting to capture a global variable in a directive with
867   // 'target' we return true so that this global is also mapped to the device.
868   //
869   // FIXME: If the declaration is enclosed in a 'declare target' directive,
870   // then it should not be captured. Therefore, an extra check has to be
871   // inserted here once support for 'declare target' is added.
872   //
873   if (!VD->hasLocalStorage()) {
874     if (DSAStack->getCurrentDirective() == OMPD_target &&
875         !DSAStack->isClauseParsingMode()) {
876       return true;
877     }
878     if (DSAStack->getCurScope() &&
879         DSAStack->hasDirective(
880             [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
881                SourceLocation Loc) -> bool {
882               return isOpenMPTargetDirective(K);
883             },
884             false)) {
885       return true;
886     }
887   }
888
889   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
890       (!DSAStack->isClauseParsingMode() ||
891        DSAStack->getParentDirective() != OMPD_unknown)) {
892     if (DSAStack->isLoopControlVariable(VD) ||
893         (VD->hasLocalStorage() &&
894          isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
895         DSAStack->isForceVarCapturing())
896       return true;
897     auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
898     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
899       return true;
900     DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
901                                    DSAStack->isClauseParsingMode());
902     return DVarPrivate.CKind != OMPC_unknown;
903   }
904   return false;
905 }
906
907 bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
908   assert(LangOpts.OpenMP && "OpenMP is not allowed");
909   return DSAStack->hasExplicitDSA(
910       VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
911 }
912
913 bool Sema::isOpenMPTargetCapturedVar(VarDecl *VD, unsigned Level) {
914   assert(LangOpts.OpenMP && "OpenMP is not allowed");
915   // Return true if the current level is no longer enclosed in a target region.
916
917   return !VD->hasLocalStorage() &&
918          DSAStack->hasExplicitDirective(isOpenMPTargetDirective, Level);
919 }
920
921 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
922
923 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
924                                const DeclarationNameInfo &DirName,
925                                Scope *CurScope, SourceLocation Loc) {
926   DSAStack->push(DKind, DirName, CurScope, Loc);
927   PushExpressionEvaluationContext(PotentiallyEvaluated);
928 }
929
930 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
931   DSAStack->setClauseParsingMode(K);
932 }
933
934 void Sema::EndOpenMPClause() {
935   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
936 }
937
938 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
939   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
940   //  A variable of class type (or array thereof) that appears in a lastprivate
941   //  clause requires an accessible, unambiguous default constructor for the
942   //  class type, unless the list item is also specified in a firstprivate
943   //  clause.
944   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
945     for (auto *C : D->clauses()) {
946       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
947         SmallVector<Expr *, 8> PrivateCopies;
948         for (auto *DE : Clause->varlists()) {
949           if (DE->isValueDependent() || DE->isTypeDependent()) {
950             PrivateCopies.push_back(nullptr);
951             continue;
952           }
953           auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
954           QualType Type = VD->getType().getNonReferenceType();
955           auto DVar = DSAStack->getTopDSA(VD, false);
956           if (DVar.CKind == OMPC_lastprivate) {
957             // Generate helper private variable and initialize it with the
958             // default value. The address of the original variable is replaced
959             // by the address of the new private variable in CodeGen. This new
960             // variable is not added to IdResolver, so the code in the OpenMP
961             // region uses original variable for proper diagnostics.
962             auto *VDPrivate = buildVarDecl(
963                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
964                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
965             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
966             if (VDPrivate->isInvalidDecl())
967               continue;
968             PrivateCopies.push_back(buildDeclRefExpr(
969                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
970           } else {
971             // The variable is also a firstprivate, so initialization sequence
972             // for private copy is generated already.
973             PrivateCopies.push_back(nullptr);
974           }
975         }
976         // Set initializers to private copies if no errors were found.
977         if (PrivateCopies.size() == Clause->varlist_size()) {
978           Clause->setPrivateCopies(PrivateCopies);
979         }
980       }
981     }
982   }
983
984   DSAStack->pop();
985   DiscardCleanupsInEvaluationContext();
986   PopExpressionEvaluationContext();
987 }
988
989 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
990                                      Expr *NumIterations, Sema &SemaRef,
991                                      Scope *S);
992
993 namespace {
994
995 class VarDeclFilterCCC : public CorrectionCandidateCallback {
996 private:
997   Sema &SemaRef;
998
999 public:
1000   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1001   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1002     NamedDecl *ND = Candidate.getCorrectionDecl();
1003     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
1004       return VD->hasGlobalStorage() &&
1005              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1006                                    SemaRef.getCurScope());
1007     }
1008     return false;
1009   }
1010 };
1011 } // namespace
1012
1013 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1014                                          CXXScopeSpec &ScopeSpec,
1015                                          const DeclarationNameInfo &Id) {
1016   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1017   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1018
1019   if (Lookup.isAmbiguous())
1020     return ExprError();
1021
1022   VarDecl *VD;
1023   if (!Lookup.isSingleResult()) {
1024     if (TypoCorrection Corrected = CorrectTypo(
1025             Id, LookupOrdinaryName, CurScope, nullptr,
1026             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1027       diagnoseTypo(Corrected,
1028                    PDiag(Lookup.empty()
1029                              ? diag::err_undeclared_var_use_suggest
1030                              : diag::err_omp_expected_var_arg_suggest)
1031                        << Id.getName());
1032       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1033     } else {
1034       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1035                                        : diag::err_omp_expected_var_arg)
1036           << Id.getName();
1037       return ExprError();
1038     }
1039   } else {
1040     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1041       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1042       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1043       return ExprError();
1044     }
1045   }
1046   Lookup.suppressDiagnostics();
1047
1048   // OpenMP [2.9.2, Syntax, C/C++]
1049   //   Variables must be file-scope, namespace-scope, or static block-scope.
1050   if (!VD->hasGlobalStorage()) {
1051     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1052         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1053     bool IsDecl =
1054         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1055     Diag(VD->getLocation(),
1056          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1057         << VD;
1058     return ExprError();
1059   }
1060
1061   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1062   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
1063   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1064   //   A threadprivate directive for file-scope variables must appear outside
1065   //   any definition or declaration.
1066   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1067       !getCurLexicalContext()->isTranslationUnit()) {
1068     Diag(Id.getLoc(), diag::err_omp_var_scope)
1069         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1070     bool IsDecl =
1071         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1072     Diag(VD->getLocation(),
1073          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1074         << VD;
1075     return ExprError();
1076   }
1077   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1078   //   A threadprivate directive for static class member variables must appear
1079   //   in the class definition, in the same scope in which the member
1080   //   variables are declared.
1081   if (CanonicalVD->isStaticDataMember() &&
1082       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1083     Diag(Id.getLoc(), diag::err_omp_var_scope)
1084         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1085     bool IsDecl =
1086         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1087     Diag(VD->getLocation(),
1088          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1089         << VD;
1090     return ExprError();
1091   }
1092   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1093   //   A threadprivate directive for namespace-scope variables must appear
1094   //   outside any definition or declaration other than the namespace
1095   //   definition itself.
1096   if (CanonicalVD->getDeclContext()->isNamespace() &&
1097       (!getCurLexicalContext()->isFileContext() ||
1098        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1099     Diag(Id.getLoc(), diag::err_omp_var_scope)
1100         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1101     bool IsDecl =
1102         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1103     Diag(VD->getLocation(),
1104          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1105         << VD;
1106     return ExprError();
1107   }
1108   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1109   //   A threadprivate directive for static block-scope variables must appear
1110   //   in the scope of the variable and not in a nested scope.
1111   if (CanonicalVD->isStaticLocal() && CurScope &&
1112       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1113     Diag(Id.getLoc(), diag::err_omp_var_scope)
1114         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1115     bool IsDecl =
1116         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1117     Diag(VD->getLocation(),
1118          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1119         << VD;
1120     return ExprError();
1121   }
1122
1123   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1124   //   A threadprivate directive must lexically precede all references to any
1125   //   of the variables in its list.
1126   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1127     Diag(Id.getLoc(), diag::err_omp_var_used)
1128         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1129     return ExprError();
1130   }
1131
1132   QualType ExprType = VD->getType().getNonReferenceType();
1133   ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
1134   return DE;
1135 }
1136
1137 Sema::DeclGroupPtrTy
1138 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1139                                         ArrayRef<Expr *> VarList) {
1140   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1141     CurContext->addDecl(D);
1142     return DeclGroupPtrTy::make(DeclGroupRef(D));
1143   }
1144   return DeclGroupPtrTy();
1145 }
1146
1147 namespace {
1148 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1149   Sema &SemaRef;
1150
1151 public:
1152   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1153     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
1154       if (VD->hasLocalStorage()) {
1155         SemaRef.Diag(E->getLocStart(),
1156                      diag::err_omp_local_var_in_threadprivate_init)
1157             << E->getSourceRange();
1158         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1159             << VD << VD->getSourceRange();
1160         return true;
1161       }
1162     }
1163     return false;
1164   }
1165   bool VisitStmt(const Stmt *S) {
1166     for (auto Child : S->children()) {
1167       if (Child && Visit(Child))
1168         return true;
1169     }
1170     return false;
1171   }
1172   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
1173 };
1174 } // namespace
1175
1176 OMPThreadPrivateDecl *
1177 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
1178   SmallVector<Expr *, 8> Vars;
1179   for (auto &RefExpr : VarList) {
1180     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
1181     VarDecl *VD = cast<VarDecl>(DE->getDecl());
1182     SourceLocation ILoc = DE->getExprLoc();
1183
1184     QualType QType = VD->getType();
1185     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1186       // It will be analyzed later.
1187       Vars.push_back(DE);
1188       continue;
1189     }
1190
1191     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1192     //   A threadprivate variable must not have an incomplete type.
1193     if (RequireCompleteType(ILoc, VD->getType(),
1194                             diag::err_omp_threadprivate_incomplete_type)) {
1195       continue;
1196     }
1197
1198     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1199     //   A threadprivate variable must not have a reference type.
1200     if (VD->getType()->isReferenceType()) {
1201       Diag(ILoc, diag::err_omp_ref_type_arg)
1202           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1203       bool IsDecl =
1204           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1205       Diag(VD->getLocation(),
1206            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1207           << VD;
1208       continue;
1209     }
1210
1211     // Check if this is a TLS variable. If TLS is not being supported, produce
1212     // the corresponding diagnostic.
1213     if ((VD->getTLSKind() != VarDecl::TLS_None &&
1214          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1215            getLangOpts().OpenMPUseTLS &&
1216            getASTContext().getTargetInfo().isTLSSupported())) ||
1217         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1218          !VD->isLocalVarDecl())) {
1219       Diag(ILoc, diag::err_omp_var_thread_local)
1220           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
1221       bool IsDecl =
1222           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1223       Diag(VD->getLocation(),
1224            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1225           << VD;
1226       continue;
1227     }
1228
1229     // Check if initial value of threadprivate variable reference variable with
1230     // local storage (it is not supported by runtime).
1231     if (auto Init = VD->getAnyInitializer()) {
1232       LocalVarRefChecker Checker(*this);
1233       if (Checker.Visit(Init))
1234         continue;
1235     }
1236
1237     Vars.push_back(RefExpr);
1238     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
1239     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1240         Context, SourceRange(Loc, Loc)));
1241     if (auto *ML = Context.getASTMutationListener())
1242       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
1243   }
1244   OMPThreadPrivateDecl *D = nullptr;
1245   if (!Vars.empty()) {
1246     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1247                                      Vars);
1248     D->setAccess(AS_public);
1249   }
1250   return D;
1251 }
1252
1253 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1254                               const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1255                               bool IsLoopIterVar = false) {
1256   if (DVar.RefExpr) {
1257     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1258         << getOpenMPClauseName(DVar.CKind);
1259     return;
1260   }
1261   enum {
1262     PDSA_StaticMemberShared,
1263     PDSA_StaticLocalVarShared,
1264     PDSA_LoopIterVarPrivate,
1265     PDSA_LoopIterVarLinear,
1266     PDSA_LoopIterVarLastprivate,
1267     PDSA_ConstVarShared,
1268     PDSA_GlobalVarShared,
1269     PDSA_TaskVarFirstprivate,
1270     PDSA_LocalVarPrivate,
1271     PDSA_Implicit
1272   } Reason = PDSA_Implicit;
1273   bool ReportHint = false;
1274   auto ReportLoc = VD->getLocation();
1275   if (IsLoopIterVar) {
1276     if (DVar.CKind == OMPC_private)
1277       Reason = PDSA_LoopIterVarPrivate;
1278     else if (DVar.CKind == OMPC_lastprivate)
1279       Reason = PDSA_LoopIterVarLastprivate;
1280     else
1281       Reason = PDSA_LoopIterVarLinear;
1282   } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1283     Reason = PDSA_TaskVarFirstprivate;
1284     ReportLoc = DVar.ImplicitDSALoc;
1285   } else if (VD->isStaticLocal())
1286     Reason = PDSA_StaticLocalVarShared;
1287   else if (VD->isStaticDataMember())
1288     Reason = PDSA_StaticMemberShared;
1289   else if (VD->isFileVarDecl())
1290     Reason = PDSA_GlobalVarShared;
1291   else if (VD->getType().isConstant(SemaRef.getASTContext()))
1292     Reason = PDSA_ConstVarShared;
1293   else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1294     ReportHint = true;
1295     Reason = PDSA_LocalVarPrivate;
1296   }
1297   if (Reason != PDSA_Implicit) {
1298     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1299         << Reason << ReportHint
1300         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1301   } else if (DVar.ImplicitDSALoc.isValid()) {
1302     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1303         << getOpenMPClauseName(DVar.CKind);
1304   }
1305 }
1306
1307 namespace {
1308 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1309   DSAStackTy *Stack;
1310   Sema &SemaRef;
1311   bool ErrorFound;
1312   CapturedStmt *CS;
1313   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1314   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1315
1316 public:
1317   void VisitDeclRefExpr(DeclRefExpr *E) {
1318     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1319       // Skip internally declared variables.
1320       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1321         return;
1322
1323       auto DVar = Stack->getTopDSA(VD, false);
1324       // Check if the variable has explicit DSA set and stop analysis if it so.
1325       if (DVar.RefExpr) return;
1326
1327       auto ELoc = E->getExprLoc();
1328       auto DKind = Stack->getCurrentDirective();
1329       // The default(none) clause requires that each variable that is referenced
1330       // in the construct, and does not have a predetermined data-sharing
1331       // attribute, must have its data-sharing attribute explicitly determined
1332       // by being listed in a data-sharing attribute clause.
1333       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1334           isParallelOrTaskRegion(DKind) &&
1335           VarsWithInheritedDSA.count(VD) == 0) {
1336         VarsWithInheritedDSA[VD] = E;
1337         return;
1338       }
1339
1340       // OpenMP [2.9.3.6, Restrictions, p.2]
1341       //  A list item that appears in a reduction clause of the innermost
1342       //  enclosing worksharing or parallel construct may not be accessed in an
1343       //  explicit task.
1344       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1345                                     [](OpenMPDirectiveKind K) -> bool {
1346                                       return isOpenMPParallelDirective(K) ||
1347                                              isOpenMPWorksharingDirective(K) ||
1348                                              isOpenMPTeamsDirective(K);
1349                                     },
1350                                     false);
1351       if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1352         ErrorFound = true;
1353         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1354         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1355         return;
1356       }
1357
1358       // Define implicit data-sharing attributes for task.
1359       DVar = Stack->getImplicitDSA(VD, false);
1360       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1361         ImplicitFirstprivate.push_back(E);
1362     }
1363   }
1364   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1365     for (auto *C : S->clauses()) {
1366       // Skip analysis of arguments of implicitly defined firstprivate clause
1367       // for task directives.
1368       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1369         for (auto *CC : C->children()) {
1370           if (CC)
1371             Visit(CC);
1372         }
1373     }
1374   }
1375   void VisitStmt(Stmt *S) {
1376     for (auto *C : S->children()) {
1377       if (C && !isa<OMPExecutableDirective>(C))
1378         Visit(C);
1379     }
1380   }
1381
1382   bool isErrorFound() { return ErrorFound; }
1383   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1384   llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1385     return VarsWithInheritedDSA;
1386   }
1387
1388   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1389       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1390 };
1391 } // namespace
1392
1393 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1394   switch (DKind) {
1395   case OMPD_parallel: {
1396     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1397     QualType KmpInt32PtrTy =
1398         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1399     Sema::CapturedParamNameType Params[] = {
1400         std::make_pair(".global_tid.", KmpInt32PtrTy),
1401         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1402         std::make_pair(StringRef(), QualType()) // __context with shared vars
1403     };
1404     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1405                              Params);
1406     break;
1407   }
1408   case OMPD_simd: {
1409     Sema::CapturedParamNameType Params[] = {
1410         std::make_pair(StringRef(), QualType()) // __context with shared vars
1411     };
1412     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1413                              Params);
1414     break;
1415   }
1416   case OMPD_for: {
1417     Sema::CapturedParamNameType Params[] = {
1418         std::make_pair(StringRef(), QualType()) // __context with shared vars
1419     };
1420     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1421                              Params);
1422     break;
1423   }
1424   case OMPD_for_simd: {
1425     Sema::CapturedParamNameType Params[] = {
1426         std::make_pair(StringRef(), QualType()) // __context with shared vars
1427     };
1428     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1429                              Params);
1430     break;
1431   }
1432   case OMPD_sections: {
1433     Sema::CapturedParamNameType Params[] = {
1434         std::make_pair(StringRef(), QualType()) // __context with shared vars
1435     };
1436     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1437                              Params);
1438     break;
1439   }
1440   case OMPD_section: {
1441     Sema::CapturedParamNameType Params[] = {
1442         std::make_pair(StringRef(), QualType()) // __context with shared vars
1443     };
1444     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1445                              Params);
1446     break;
1447   }
1448   case OMPD_single: {
1449     Sema::CapturedParamNameType Params[] = {
1450         std::make_pair(StringRef(), QualType()) // __context with shared vars
1451     };
1452     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1453                              Params);
1454     break;
1455   }
1456   case OMPD_master: {
1457     Sema::CapturedParamNameType Params[] = {
1458         std::make_pair(StringRef(), QualType()) // __context with shared vars
1459     };
1460     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1461                              Params);
1462     break;
1463   }
1464   case OMPD_critical: {
1465     Sema::CapturedParamNameType Params[] = {
1466         std::make_pair(StringRef(), QualType()) // __context with shared vars
1467     };
1468     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1469                              Params);
1470     break;
1471   }
1472   case OMPD_parallel_for: {
1473     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1474     QualType KmpInt32PtrTy =
1475         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1476     Sema::CapturedParamNameType Params[] = {
1477         std::make_pair(".global_tid.", KmpInt32PtrTy),
1478         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1479         std::make_pair(StringRef(), QualType()) // __context with shared vars
1480     };
1481     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1482                              Params);
1483     break;
1484   }
1485   case OMPD_parallel_for_simd: {
1486     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1487     QualType KmpInt32PtrTy =
1488         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1489     Sema::CapturedParamNameType Params[] = {
1490         std::make_pair(".global_tid.", KmpInt32PtrTy),
1491         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1492         std::make_pair(StringRef(), QualType()) // __context with shared vars
1493     };
1494     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1495                              Params);
1496     break;
1497   }
1498   case OMPD_parallel_sections: {
1499     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1500     QualType KmpInt32PtrTy =
1501         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1502     Sema::CapturedParamNameType Params[] = {
1503         std::make_pair(".global_tid.", KmpInt32PtrTy),
1504         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1505         std::make_pair(StringRef(), QualType()) // __context with shared vars
1506     };
1507     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1508                              Params);
1509     break;
1510   }
1511   case OMPD_task: {
1512     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1513     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1514     FunctionProtoType::ExtProtoInfo EPI;
1515     EPI.Variadic = true;
1516     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1517     Sema::CapturedParamNameType Params[] = {
1518         std::make_pair(".global_tid.", KmpInt32Ty),
1519         std::make_pair(".part_id.", KmpInt32Ty),
1520         std::make_pair(".privates.",
1521                        Context.VoidPtrTy.withConst().withRestrict()),
1522         std::make_pair(
1523             ".copy_fn.",
1524             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1525         std::make_pair(StringRef(), QualType()) // __context with shared vars
1526     };
1527     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1528                              Params);
1529     // Mark this captured region as inlined, because we don't use outlined
1530     // function directly.
1531     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1532         AlwaysInlineAttr::CreateImplicit(
1533             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1534     break;
1535   }
1536   case OMPD_ordered: {
1537     Sema::CapturedParamNameType Params[] = {
1538         std::make_pair(StringRef(), QualType()) // __context with shared vars
1539     };
1540     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1541                              Params);
1542     break;
1543   }
1544   case OMPD_atomic: {
1545     Sema::CapturedParamNameType Params[] = {
1546         std::make_pair(StringRef(), QualType()) // __context with shared vars
1547     };
1548     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1549                              Params);
1550     break;
1551   }
1552   case OMPD_target_data:
1553   case OMPD_target: {
1554     Sema::CapturedParamNameType Params[] = {
1555         std::make_pair(StringRef(), QualType()) // __context with shared vars
1556     };
1557     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1558                              Params);
1559     break;
1560   }
1561   case OMPD_teams: {
1562     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1563     QualType KmpInt32PtrTy =
1564         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1565     Sema::CapturedParamNameType Params[] = {
1566         std::make_pair(".global_tid.", KmpInt32PtrTy),
1567         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1568         std::make_pair(StringRef(), QualType()) // __context with shared vars
1569     };
1570     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1571                              Params);
1572     break;
1573   }
1574   case OMPD_taskgroup: {
1575     Sema::CapturedParamNameType Params[] = {
1576         std::make_pair(StringRef(), QualType()) // __context with shared vars
1577     };
1578     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1579                              Params);
1580     break;
1581   }
1582   case OMPD_taskloop: {
1583     Sema::CapturedParamNameType Params[] = {
1584         std::make_pair(StringRef(), QualType()) // __context with shared vars
1585     };
1586     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1587                              Params);
1588     break;
1589   }
1590   case OMPD_taskloop_simd: {
1591     Sema::CapturedParamNameType Params[] = {
1592         std::make_pair(StringRef(), QualType()) // __context with shared vars
1593     };
1594     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1595                              Params);
1596     break;
1597   }
1598   case OMPD_distribute: {
1599     Sema::CapturedParamNameType Params[] = {
1600         std::make_pair(StringRef(), QualType()) // __context with shared vars
1601     };
1602     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1603                              Params);
1604     break;
1605   }
1606   case OMPD_threadprivate:
1607   case OMPD_taskyield:
1608   case OMPD_barrier:
1609   case OMPD_taskwait:
1610   case OMPD_cancellation_point:
1611   case OMPD_cancel:
1612   case OMPD_flush:
1613     llvm_unreachable("OpenMP Directive is not allowed");
1614   case OMPD_unknown:
1615     llvm_unreachable("Unknown OpenMP directive");
1616   }
1617 }
1618
1619 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1620                                       ArrayRef<OMPClause *> Clauses) {
1621   if (!S.isUsable()) {
1622     ActOnCapturedRegionError();
1623     return StmtError();
1624   }
1625
1626   OMPOrderedClause *OC = nullptr;
1627   OMPScheduleClause *SC = nullptr;
1628   SmallVector<OMPLinearClause *, 4> LCs;
1629   // This is required for proper codegen.
1630   for (auto *Clause : Clauses) {
1631     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1632         Clause->getClauseKind() == OMPC_copyprivate ||
1633         (getLangOpts().OpenMPUseTLS &&
1634          getASTContext().getTargetInfo().isTLSSupported() &&
1635          Clause->getClauseKind() == OMPC_copyin)) {
1636       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
1637       // Mark all variables in private list clauses as used in inner region.
1638       for (auto *VarRef : Clause->children()) {
1639         if (auto *E = cast_or_null<Expr>(VarRef)) {
1640           MarkDeclarationsReferencedInExpr(E);
1641         }
1642       }
1643       DSAStack->setForceVarCapturing(/*V=*/false);
1644     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1645                Clause->getClauseKind() == OMPC_schedule) {
1646       // Mark all variables in private list clauses as used in inner region.
1647       // Required for proper codegen of combined directives.
1648       // TODO: add processing for other clauses.
1649       if (auto *E = cast_or_null<Expr>(
1650               cast<OMPScheduleClause>(Clause)->getHelperChunkSize()))
1651         MarkDeclarationsReferencedInExpr(E);
1652     }
1653     if (Clause->getClauseKind() == OMPC_schedule)
1654       SC = cast<OMPScheduleClause>(Clause);
1655     else if (Clause->getClauseKind() == OMPC_ordered)
1656       OC = cast<OMPOrderedClause>(Clause);
1657     else if (Clause->getClauseKind() == OMPC_linear)
1658       LCs.push_back(cast<OMPLinearClause>(Clause));
1659   }
1660   bool ErrorFound = false;
1661   // OpenMP, 2.7.1 Loop Construct, Restrictions
1662   // The nonmonotonic modifier cannot be specified if an ordered clause is
1663   // specified.
1664   if (SC &&
1665       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1666        SC->getSecondScheduleModifier() ==
1667            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1668       OC) {
1669     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1670              ? SC->getFirstScheduleModifierLoc()
1671              : SC->getSecondScheduleModifierLoc(),
1672          diag::err_omp_schedule_nonmonotonic_ordered)
1673         << SourceRange(OC->getLocStart(), OC->getLocEnd());
1674     ErrorFound = true;
1675   }
1676   if (!LCs.empty() && OC && OC->getNumForLoops()) {
1677     for (auto *C : LCs) {
1678       Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1679           << SourceRange(OC->getLocStart(), OC->getLocEnd());
1680     }
1681     ErrorFound = true;
1682   }
1683   if (ErrorFound) {
1684     ActOnCapturedRegionError();
1685     return StmtError();
1686   }
1687   return ActOnCapturedRegionEnd(S.get());
1688 }
1689
1690 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1691                                   OpenMPDirectiveKind CurrentRegion,
1692                                   const DeclarationNameInfo &CurrentName,
1693                                   OpenMPDirectiveKind CancelRegion,
1694                                   SourceLocation StartLoc) {
1695   // Allowed nesting of constructs
1696   // +------------------+-----------------+------------------------------------+
1697   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1698   // +------------------+-----------------+------------------------------------+
1699   // | parallel         | parallel        | *                                  |
1700   // | parallel         | for             | *                                  |
1701   // | parallel         | for simd        | *                                  |
1702   // | parallel         | master          | *                                  |
1703   // | parallel         | critical        | *                                  |
1704   // | parallel         | simd            | *                                  |
1705   // | parallel         | sections        | *                                  |
1706   // | parallel         | section         | +                                  |
1707   // | parallel         | single          | *                                  |
1708   // | parallel         | parallel for    | *                                  |
1709   // | parallel         |parallel for simd| *                                  |
1710   // | parallel         |parallel sections| *                                  |
1711   // | parallel         | task            | *                                  |
1712   // | parallel         | taskyield       | *                                  |
1713   // | parallel         | barrier         | *                                  |
1714   // | parallel         | taskwait        | *                                  |
1715   // | parallel         | taskgroup       | *                                  |
1716   // | parallel         | flush           | *                                  |
1717   // | parallel         | ordered         | +                                  |
1718   // | parallel         | atomic          | *                                  |
1719   // | parallel         | target          | *                                  |
1720   // | parallel         | teams           | +                                  |
1721   // | parallel         | cancellation    |                                    |
1722   // |                  | point           | !                                  |
1723   // | parallel         | cancel          | !                                  |
1724   // | parallel         | taskloop        | *                                  |
1725   // | parallel         | taskloop simd   | *                                  |
1726   // | parallel         | distribute      |                                    |  
1727   // +------------------+-----------------+------------------------------------+
1728   // | for              | parallel        | *                                  |
1729   // | for              | for             | +                                  |
1730   // | for              | for simd        | +                                  |
1731   // | for              | master          | +                                  |
1732   // | for              | critical        | *                                  |
1733   // | for              | simd            | *                                  |
1734   // | for              | sections        | +                                  |
1735   // | for              | section         | +                                  |
1736   // | for              | single          | +                                  |
1737   // | for              | parallel for    | *                                  |
1738   // | for              |parallel for simd| *                                  |
1739   // | for              |parallel sections| *                                  |
1740   // | for              | task            | *                                  |
1741   // | for              | taskyield       | *                                  |
1742   // | for              | barrier         | +                                  |
1743   // | for              | taskwait        | *                                  |
1744   // | for              | taskgroup       | *                                  |
1745   // | for              | flush           | *                                  |
1746   // | for              | ordered         | * (if construct is ordered)        |
1747   // | for              | atomic          | *                                  |
1748   // | for              | target          | *                                  |
1749   // | for              | teams           | +                                  |
1750   // | for              | cancellation    |                                    |
1751   // |                  | point           | !                                  |
1752   // | for              | cancel          | !                                  |
1753   // | for              | taskloop        | *                                  |
1754   // | for              | taskloop simd   | *                                  |
1755   // | for              | distribute      |                                    |
1756   // +------------------+-----------------+------------------------------------+
1757   // | master           | parallel        | *                                  |
1758   // | master           | for             | +                                  |
1759   // | master           | for simd        | +                                  |
1760   // | master           | master          | *                                  |
1761   // | master           | critical        | *                                  |
1762   // | master           | simd            | *                                  |
1763   // | master           | sections        | +                                  |
1764   // | master           | section         | +                                  |
1765   // | master           | single          | +                                  |
1766   // | master           | parallel for    | *                                  |
1767   // | master           |parallel for simd| *                                  |
1768   // | master           |parallel sections| *                                  |
1769   // | master           | task            | *                                  |
1770   // | master           | taskyield       | *                                  |
1771   // | master           | barrier         | +                                  |
1772   // | master           | taskwait        | *                                  |
1773   // | master           | taskgroup       | *                                  |
1774   // | master           | flush           | *                                  |
1775   // | master           | ordered         | +                                  |
1776   // | master           | atomic          | *                                  |
1777   // | master           | target          | *                                  |
1778   // | master           | teams           | +                                  |
1779   // | master           | cancellation    |                                    |
1780   // |                  | point           |                                    |
1781   // | master           | cancel          |                                    |
1782   // | master           | taskloop        | *                                  |
1783   // | master           | taskloop simd   | *                                  |
1784   // | master           | distribute      |                                    |
1785   // +------------------+-----------------+------------------------------------+
1786   // | critical         | parallel        | *                                  |
1787   // | critical         | for             | +                                  |
1788   // | critical         | for simd        | +                                  |
1789   // | critical         | master          | *                                  |
1790   // | critical         | critical        | * (should have different names)    |
1791   // | critical         | simd            | *                                  |
1792   // | critical         | sections        | +                                  |
1793   // | critical         | section         | +                                  |
1794   // | critical         | single          | +                                  |
1795   // | critical         | parallel for    | *                                  |
1796   // | critical         |parallel for simd| *                                  |
1797   // | critical         |parallel sections| *                                  |
1798   // | critical         | task            | *                                  |
1799   // | critical         | taskyield       | *                                  |
1800   // | critical         | barrier         | +                                  |
1801   // | critical         | taskwait        | *                                  |
1802   // | critical         | taskgroup       | *                                  |
1803   // | critical         | ordered         | +                                  |
1804   // | critical         | atomic          | *                                  |
1805   // | critical         | target          | *                                  |
1806   // | critical         | teams           | +                                  |
1807   // | critical         | cancellation    |                                    |
1808   // |                  | point           |                                    |
1809   // | critical         | cancel          |                                    |
1810   // | critical         | taskloop        | *                                  |
1811   // | critical         | taskloop simd   | *                                  |
1812   // | critical         | distribute      |                                    |
1813   // +------------------+-----------------+------------------------------------+
1814   // | simd             | parallel        |                                    |
1815   // | simd             | for             |                                    |
1816   // | simd             | for simd        |                                    |
1817   // | simd             | master          |                                    |
1818   // | simd             | critical        |                                    |
1819   // | simd             | simd            |                                    |
1820   // | simd             | sections        |                                    |
1821   // | simd             | section         |                                    |
1822   // | simd             | single          |                                    |
1823   // | simd             | parallel for    |                                    |
1824   // | simd             |parallel for simd|                                    |
1825   // | simd             |parallel sections|                                    |
1826   // | simd             | task            |                                    |
1827   // | simd             | taskyield       |                                    |
1828   // | simd             | barrier         |                                    |
1829   // | simd             | taskwait        |                                    |
1830   // | simd             | taskgroup       |                                    |
1831   // | simd             | flush           |                                    |
1832   // | simd             | ordered         | + (with simd clause)               |
1833   // | simd             | atomic          |                                    |
1834   // | simd             | target          |                                    |
1835   // | simd             | teams           |                                    |
1836   // | simd             | cancellation    |                                    |
1837   // |                  | point           |                                    |
1838   // | simd             | cancel          |                                    |
1839   // | simd             | taskloop        |                                    |
1840   // | simd             | taskloop simd   |                                    |
1841   // | simd             | distribute      |                                    |
1842   // +------------------+-----------------+------------------------------------+
1843   // | for simd         | parallel        |                                    |
1844   // | for simd         | for             |                                    |
1845   // | for simd         | for simd        |                                    |
1846   // | for simd         | master          |                                    |
1847   // | for simd         | critical        |                                    |
1848   // | for simd         | simd            |                                    |
1849   // | for simd         | sections        |                                    |
1850   // | for simd         | section         |                                    |
1851   // | for simd         | single          |                                    |
1852   // | for simd         | parallel for    |                                    |
1853   // | for simd         |parallel for simd|                                    |
1854   // | for simd         |parallel sections|                                    |
1855   // | for simd         | task            |                                    |
1856   // | for simd         | taskyield       |                                    |
1857   // | for simd         | barrier         |                                    |
1858   // | for simd         | taskwait        |                                    |
1859   // | for simd         | taskgroup       |                                    |
1860   // | for simd         | flush           |                                    |
1861   // | for simd         | ordered         | + (with simd clause)               |
1862   // | for simd         | atomic          |                                    |
1863   // | for simd         | target          |                                    |
1864   // | for simd         | teams           |                                    |
1865   // | for simd         | cancellation    |                                    |
1866   // |                  | point           |                                    |
1867   // | for simd         | cancel          |                                    |
1868   // | for simd         | taskloop        |                                    |
1869   // | for simd         | taskloop simd   |                                    |
1870   // | for simd         | distribute      |                                    |
1871   // +------------------+-----------------+------------------------------------+
1872   // | parallel for simd| parallel        |                                    |
1873   // | parallel for simd| for             |                                    |
1874   // | parallel for simd| for simd        |                                    |
1875   // | parallel for simd| master          |                                    |
1876   // | parallel for simd| critical        |                                    |
1877   // | parallel for simd| simd            |                                    |
1878   // | parallel for simd| sections        |                                    |
1879   // | parallel for simd| section         |                                    |
1880   // | parallel for simd| single          |                                    |
1881   // | parallel for simd| parallel for    |                                    |
1882   // | parallel for simd|parallel for simd|                                    |
1883   // | parallel for simd|parallel sections|                                    |
1884   // | parallel for simd| task            |                                    |
1885   // | parallel for simd| taskyield       |                                    |
1886   // | parallel for simd| barrier         |                                    |
1887   // | parallel for simd| taskwait        |                                    |
1888   // | parallel for simd| taskgroup       |                                    |
1889   // | parallel for simd| flush           |                                    |
1890   // | parallel for simd| ordered         | + (with simd clause)               |
1891   // | parallel for simd| atomic          |                                    |
1892   // | parallel for simd| target          |                                    |
1893   // | parallel for simd| teams           |                                    |
1894   // | parallel for simd| cancellation    |                                    |
1895   // |                  | point           |                                    |
1896   // | parallel for simd| cancel          |                                    |
1897   // | parallel for simd| taskloop        |                                    |
1898   // | parallel for simd| taskloop simd   |                                    |
1899   // | parallel for simd| distribute      |                                    |
1900   // +------------------+-----------------+------------------------------------+
1901   // | sections         | parallel        | *                                  |
1902   // | sections         | for             | +                                  |
1903   // | sections         | for simd        | +                                  |
1904   // | sections         | master          | +                                  |
1905   // | sections         | critical        | *                                  |
1906   // | sections         | simd            | *                                  |
1907   // | sections         | sections        | +                                  |
1908   // | sections         | section         | *                                  |
1909   // | sections         | single          | +                                  |
1910   // | sections         | parallel for    | *                                  |
1911   // | sections         |parallel for simd| *                                  |
1912   // | sections         |parallel sections| *                                  |
1913   // | sections         | task            | *                                  |
1914   // | sections         | taskyield       | *                                  |
1915   // | sections         | barrier         | +                                  |
1916   // | sections         | taskwait        | *                                  |
1917   // | sections         | taskgroup       | *                                  |
1918   // | sections         | flush           | *                                  |
1919   // | sections         | ordered         | +                                  |
1920   // | sections         | atomic          | *                                  |
1921   // | sections         | target          | *                                  |
1922   // | sections         | teams           | +                                  |
1923   // | sections         | cancellation    |                                    |
1924   // |                  | point           | !                                  |
1925   // | sections         | cancel          | !                                  |
1926   // | sections         | taskloop        | *                                  |
1927   // | sections         | taskloop simd   | *                                  |
1928   // | sections         | distribute      |                                    |
1929   // +------------------+-----------------+------------------------------------+
1930   // | section          | parallel        | *                                  |
1931   // | section          | for             | +                                  |
1932   // | section          | for simd        | +                                  |
1933   // | section          | master          | +                                  |
1934   // | section          | critical        | *                                  |
1935   // | section          | simd            | *                                  |
1936   // | section          | sections        | +                                  |
1937   // | section          | section         | +                                  |
1938   // | section          | single          | +                                  |
1939   // | section          | parallel for    | *                                  |
1940   // | section          |parallel for simd| *                                  |
1941   // | section          |parallel sections| *                                  |
1942   // | section          | task            | *                                  |
1943   // | section          | taskyield       | *                                  |
1944   // | section          | barrier         | +                                  |
1945   // | section          | taskwait        | *                                  |
1946   // | section          | taskgroup       | *                                  |
1947   // | section          | flush           | *                                  |
1948   // | section          | ordered         | +                                  |
1949   // | section          | atomic          | *                                  |
1950   // | section          | target          | *                                  |
1951   // | section          | teams           | +                                  |
1952   // | section          | cancellation    |                                    |
1953   // |                  | point           | !                                  |
1954   // | section          | cancel          | !                                  |
1955   // | section          | taskloop        | *                                  |
1956   // | section          | taskloop simd   | *                                  |
1957   // | section          | distribute      |                                    |
1958   // +------------------+-----------------+------------------------------------+
1959   // | single           | parallel        | *                                  |
1960   // | single           | for             | +                                  |
1961   // | single           | for simd        | +                                  |
1962   // | single           | master          | +                                  |
1963   // | single           | critical        | *                                  |
1964   // | single           | simd            | *                                  |
1965   // | single           | sections        | +                                  |
1966   // | single           | section         | +                                  |
1967   // | single           | single          | +                                  |
1968   // | single           | parallel for    | *                                  |
1969   // | single           |parallel for simd| *                                  |
1970   // | single           |parallel sections| *                                  |
1971   // | single           | task            | *                                  |
1972   // | single           | taskyield       | *                                  |
1973   // | single           | barrier         | +                                  |
1974   // | single           | taskwait        | *                                  |
1975   // | single           | taskgroup       | *                                  |
1976   // | single           | flush           | *                                  |
1977   // | single           | ordered         | +                                  |
1978   // | single           | atomic          | *                                  |
1979   // | single           | target          | *                                  |
1980   // | single           | teams           | +                                  |
1981   // | single           | cancellation    |                                    |
1982   // |                  | point           |                                    |
1983   // | single           | cancel          |                                    |
1984   // | single           | taskloop        | *                                  |
1985   // | single           | taskloop simd   | *                                  |
1986   // | single           | distribute      |                                    |
1987   // +------------------+-----------------+------------------------------------+
1988   // | parallel for     | parallel        | *                                  |
1989   // | parallel for     | for             | +                                  |
1990   // | parallel for     | for simd        | +                                  |
1991   // | parallel for     | master          | +                                  |
1992   // | parallel for     | critical        | *                                  |
1993   // | parallel for     | simd            | *                                  |
1994   // | parallel for     | sections        | +                                  |
1995   // | parallel for     | section         | +                                  |
1996   // | parallel for     | single          | +                                  |
1997   // | parallel for     | parallel for    | *                                  |
1998   // | parallel for     |parallel for simd| *                                  |
1999   // | parallel for     |parallel sections| *                                  |
2000   // | parallel for     | task            | *                                  |
2001   // | parallel for     | taskyield       | *                                  |
2002   // | parallel for     | barrier         | +                                  |
2003   // | parallel for     | taskwait        | *                                  |
2004   // | parallel for     | taskgroup       | *                                  |
2005   // | parallel for     | flush           | *                                  |
2006   // | parallel for     | ordered         | * (if construct is ordered)        |
2007   // | parallel for     | atomic          | *                                  |
2008   // | parallel for     | target          | *                                  |
2009   // | parallel for     | teams           | +                                  |
2010   // | parallel for     | cancellation    |                                    |
2011   // |                  | point           | !                                  |
2012   // | parallel for     | cancel          | !                                  |
2013   // | parallel for     | taskloop        | *                                  |
2014   // | parallel for     | taskloop simd   | *                                  |
2015   // | parallel for     | distribute      |                                    |
2016   // +------------------+-----------------+------------------------------------+
2017   // | parallel sections| parallel        | *                                  |
2018   // | parallel sections| for             | +                                  |
2019   // | parallel sections| for simd        | +                                  |
2020   // | parallel sections| master          | +                                  |
2021   // | parallel sections| critical        | +                                  |
2022   // | parallel sections| simd            | *                                  |
2023   // | parallel sections| sections        | +                                  |
2024   // | parallel sections| section         | *                                  |
2025   // | parallel sections| single          | +                                  |
2026   // | parallel sections| parallel for    | *                                  |
2027   // | parallel sections|parallel for simd| *                                  |
2028   // | parallel sections|parallel sections| *                                  |
2029   // | parallel sections| task            | *                                  |
2030   // | parallel sections| taskyield       | *                                  |
2031   // | parallel sections| barrier         | +                                  |
2032   // | parallel sections| taskwait        | *                                  |
2033   // | parallel sections| taskgroup       | *                                  |
2034   // | parallel sections| flush           | *                                  |
2035   // | parallel sections| ordered         | +                                  |
2036   // | parallel sections| atomic          | *                                  |
2037   // | parallel sections| target          | *                                  |
2038   // | parallel sections| teams           | +                                  |
2039   // | parallel sections| cancellation    |                                    |
2040   // |                  | point           | !                                  |
2041   // | parallel sections| cancel          | !                                  |
2042   // | parallel sections| taskloop        | *                                  |
2043   // | parallel sections| taskloop simd   | *                                  |
2044   // | parallel sections| distribute      |                                    | 
2045   // +------------------+-----------------+------------------------------------+
2046   // | task             | parallel        | *                                  |
2047   // | task             | for             | +                                  |
2048   // | task             | for simd        | +                                  |
2049   // | task             | master          | +                                  |
2050   // | task             | critical        | *                                  |
2051   // | task             | simd            | *                                  |
2052   // | task             | sections        | +                                  |
2053   // | task             | section         | +                                  |
2054   // | task             | single          | +                                  |
2055   // | task             | parallel for    | *                                  |
2056   // | task             |parallel for simd| *                                  |
2057   // | task             |parallel sections| *                                  |
2058   // | task             | task            | *                                  |
2059   // | task             | taskyield       | *                                  |
2060   // | task             | barrier         | +                                  |
2061   // | task             | taskwait        | *                                  |
2062   // | task             | taskgroup       | *                                  |
2063   // | task             | flush           | *                                  |
2064   // | task             | ordered         | +                                  |
2065   // | task             | atomic          | *                                  |
2066   // | task             | target          | *                                  |
2067   // | task             | teams           | +                                  |
2068   // | task             | cancellation    |                                    |
2069   // |                  | point           | !                                  |
2070   // | task             | cancel          | !                                  |
2071   // | task             | taskloop        | *                                  |
2072   // | task             | taskloop simd   | *                                  |
2073   // | task             | distribute      |                                    |
2074   // +------------------+-----------------+------------------------------------+
2075   // | ordered          | parallel        | *                                  |
2076   // | ordered          | for             | +                                  |
2077   // | ordered          | for simd        | +                                  |
2078   // | ordered          | master          | *                                  |
2079   // | ordered          | critical        | *                                  |
2080   // | ordered          | simd            | *                                  |
2081   // | ordered          | sections        | +                                  |
2082   // | ordered          | section         | +                                  |
2083   // | ordered          | single          | +                                  |
2084   // | ordered          | parallel for    | *                                  |
2085   // | ordered          |parallel for simd| *                                  |
2086   // | ordered          |parallel sections| *                                  |
2087   // | ordered          | task            | *                                  |
2088   // | ordered          | taskyield       | *                                  |
2089   // | ordered          | barrier         | +                                  |
2090   // | ordered          | taskwait        | *                                  |
2091   // | ordered          | taskgroup       | *                                  |
2092   // | ordered          | flush           | *                                  |
2093   // | ordered          | ordered         | +                                  |
2094   // | ordered          | atomic          | *                                  |
2095   // | ordered          | target          | *                                  |
2096   // | ordered          | teams           | +                                  |
2097   // | ordered          | cancellation    |                                    |
2098   // |                  | point           |                                    |
2099   // | ordered          | cancel          |                                    |
2100   // | ordered          | taskloop        | *                                  |
2101   // | ordered          | taskloop simd   | *                                  |
2102   // | ordered          | distribute      |                                    |
2103   // +------------------+-----------------+------------------------------------+
2104   // | atomic           | parallel        |                                    |
2105   // | atomic           | for             |                                    |
2106   // | atomic           | for simd        |                                    |
2107   // | atomic           | master          |                                    |
2108   // | atomic           | critical        |                                    |
2109   // | atomic           | simd            |                                    |
2110   // | atomic           | sections        |                                    |
2111   // | atomic           | section         |                                    |
2112   // | atomic           | single          |                                    |
2113   // | atomic           | parallel for    |                                    |
2114   // | atomic           |parallel for simd|                                    |
2115   // | atomic           |parallel sections|                                    |
2116   // | atomic           | task            |                                    |
2117   // | atomic           | taskyield       |                                    |
2118   // | atomic           | barrier         |                                    |
2119   // | atomic           | taskwait        |                                    |
2120   // | atomic           | taskgroup       |                                    |
2121   // | atomic           | flush           |                                    |
2122   // | atomic           | ordered         |                                    |
2123   // | atomic           | atomic          |                                    |
2124   // | atomic           | target          |                                    |
2125   // | atomic           | teams           |                                    |
2126   // | atomic           | cancellation    |                                    |
2127   // |                  | point           |                                    |
2128   // | atomic           | cancel          |                                    |
2129   // | atomic           | taskloop        |                                    |
2130   // | atomic           | taskloop simd   |                                    |
2131   // | atomic           | distribute      |                                    | 
2132   // +------------------+-----------------+------------------------------------+
2133   // | target           | parallel        | *                                  |
2134   // | target           | for             | *                                  |
2135   // | target           | for simd        | *                                  |
2136   // | target           | master          | *                                  |
2137   // | target           | critical        | *                                  |
2138   // | target           | simd            | *                                  |
2139   // | target           | sections        | *                                  |
2140   // | target           | section         | *                                  |
2141   // | target           | single          | *                                  |
2142   // | target           | parallel for    | *                                  |
2143   // | target           |parallel for simd| *                                  |
2144   // | target           |parallel sections| *                                  |
2145   // | target           | task            | *                                  |
2146   // | target           | taskyield       | *                                  |
2147   // | target           | barrier         | *                                  |
2148   // | target           | taskwait        | *                                  |
2149   // | target           | taskgroup       | *                                  |
2150   // | target           | flush           | *                                  |
2151   // | target           | ordered         | *                                  |
2152   // | target           | atomic          | *                                  |
2153   // | target           | target          | *                                  |
2154   // | target           | teams           | *                                  |
2155   // | target           | cancellation    |                                    |
2156   // |                  | point           |                                    |
2157   // | target           | cancel          |                                    |
2158   // | target           | taskloop        | *                                  |
2159   // | target           | taskloop simd   | *                                  |
2160   // | target           | distribute      |                                    |
2161   // +------------------+-----------------+------------------------------------+
2162   // | teams            | parallel        | *                                  |
2163   // | teams            | for             | +                                  |
2164   // | teams            | for simd        | +                                  |
2165   // | teams            | master          | +                                  |
2166   // | teams            | critical        | +                                  |
2167   // | teams            | simd            | +                                  |
2168   // | teams            | sections        | +                                  |
2169   // | teams            | section         | +                                  |
2170   // | teams            | single          | +                                  |
2171   // | teams            | parallel for    | *                                  |
2172   // | teams            |parallel for simd| *                                  |
2173   // | teams            |parallel sections| *                                  |
2174   // | teams            | task            | +                                  |
2175   // | teams            | taskyield       | +                                  |
2176   // | teams            | barrier         | +                                  |
2177   // | teams            | taskwait        | +                                  |
2178   // | teams            | taskgroup       | +                                  |
2179   // | teams            | flush           | +                                  |
2180   // | teams            | ordered         | +                                  |
2181   // | teams            | atomic          | +                                  |
2182   // | teams            | target          | +                                  |
2183   // | teams            | teams           | +                                  |
2184   // | teams            | cancellation    |                                    |
2185   // |                  | point           |                                    |
2186   // | teams            | cancel          |                                    |
2187   // | teams            | taskloop        | +                                  |
2188   // | teams            | taskloop simd   | +                                  |
2189   // | teams            | distribute      | !                                  |
2190   // +------------------+-----------------+------------------------------------+
2191   // | taskloop         | parallel        | *                                  |
2192   // | taskloop         | for             | +                                  |
2193   // | taskloop         | for simd        | +                                  |
2194   // | taskloop         | master          | +                                  |
2195   // | taskloop         | critical        | *                                  |
2196   // | taskloop         | simd            | *                                  |
2197   // | taskloop         | sections        | +                                  |
2198   // | taskloop         | section         | +                                  |
2199   // | taskloop         | single          | +                                  |
2200   // | taskloop         | parallel for    | *                                  |
2201   // | taskloop         |parallel for simd| *                                  |
2202   // | taskloop         |parallel sections| *                                  |
2203   // | taskloop         | task            | *                                  |
2204   // | taskloop         | taskyield       | *                                  |
2205   // | taskloop         | barrier         | +                                  |
2206   // | taskloop         | taskwait        | *                                  |
2207   // | taskloop         | taskgroup       | *                                  |
2208   // | taskloop         | flush           | *                                  |
2209   // | taskloop         | ordered         | +                                  |
2210   // | taskloop         | atomic          | *                                  |
2211   // | taskloop         | target          | *                                  |
2212   // | taskloop         | teams           | +                                  |
2213   // | taskloop         | cancellation    |                                    |
2214   // |                  | point           |                                    |
2215   // | taskloop         | cancel          |                                    |
2216   // | taskloop         | taskloop        | *                                  |
2217   // | taskloop         | distribute      |                                    |
2218   // +------------------+-----------------+------------------------------------+
2219   // | taskloop simd    | parallel        |                                    |
2220   // | taskloop simd    | for             |                                    |
2221   // | taskloop simd    | for simd        |                                    |
2222   // | taskloop simd    | master          |                                    |
2223   // | taskloop simd    | critical        |                                    |
2224   // | taskloop simd    | simd            |                                    |
2225   // | taskloop simd    | sections        |                                    |
2226   // | taskloop simd    | section         |                                    |
2227   // | taskloop simd    | single          |                                    |
2228   // | taskloop simd    | parallel for    |                                    |
2229   // | taskloop simd    |parallel for simd|                                    |
2230   // | taskloop simd    |parallel sections|                                    |
2231   // | taskloop simd    | task            |                                    |
2232   // | taskloop simd    | taskyield       |                                    |
2233   // | taskloop simd    | barrier         |                                    |
2234   // | taskloop simd    | taskwait        |                                    |
2235   // | taskloop simd    | taskgroup       |                                    |
2236   // | taskloop simd    | flush           |                                    |
2237   // | taskloop simd    | ordered         | + (with simd clause)               |
2238   // | taskloop simd    | atomic          |                                    |
2239   // | taskloop simd    | target          |                                    |
2240   // | taskloop simd    | teams           |                                    |
2241   // | taskloop simd    | cancellation    |                                    |
2242   // |                  | point           |                                    |
2243   // | taskloop simd    | cancel          |                                    |
2244   // | taskloop simd    | taskloop        |                                    |
2245   // | taskloop simd    | taskloop simd   |                                    |
2246   // | taskloop simd    | distribute      |                                    |
2247   // +------------------+-----------------+------------------------------------+
2248   // | distribute       | parallel        | *                                  |
2249   // | distribute       | for             | *                                  |
2250   // | distribute       | for simd        | *                                  |
2251   // | distribute       | master          | *                                  |
2252   // | distribute       | critical        | *                                  |
2253   // | distribute       | simd            | *                                  |
2254   // | distribute       | sections        | *                                  |
2255   // | distribute       | section         | *                                  |
2256   // | distribute       | single          | *                                  |
2257   // | distribute       | parallel for    | *                                  |
2258   // | distribute       |parallel for simd| *                                  |
2259   // | distribute       |parallel sections| *                                  |
2260   // | distribute       | task            | *                                  |
2261   // | distribute       | taskyield       | *                                  |
2262   // | distribute       | barrier         | *                                  |
2263   // | distribute       | taskwait        | *                                  |
2264   // | distribute       | taskgroup       | *                                  |
2265   // | distribute       | flush           | *                                  |
2266   // | distribute       | ordered         | +                                  |
2267   // | distribute       | atomic          | *                                  |
2268   // | distribute       | target          |                                    |
2269   // | distribute       | teams           |                                    |
2270   // | distribute       | cancellation    | +                                  |
2271   // |                  | point           |                                    |
2272   // | distribute       | cancel          | +                                  |
2273   // | distribute       | taskloop        | *                                  |
2274   // | distribute       | taskloop simd   | *                                  |
2275   // | distribute       | distribute      |                                    |
2276   // +------------------+-----------------+------------------------------------+
2277   if (Stack->getCurScope()) {
2278     auto ParentRegion = Stack->getParentDirective();
2279     bool NestingProhibited = false;
2280     bool CloseNesting = true;
2281     enum {
2282       NoRecommend,
2283       ShouldBeInParallelRegion,
2284       ShouldBeInOrderedRegion,
2285       ShouldBeInTargetRegion,
2286       ShouldBeInTeamsRegion
2287     } Recommend = NoRecommend;
2288     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
2289       // OpenMP [2.16, Nesting of Regions]
2290       // OpenMP constructs may not be nested inside a simd region.
2291       // OpenMP [2.8.1,simd Construct, Restrictions]
2292       // An ordered construct with the simd clause is the only OpenMP construct
2293       // that can appear in the simd region.
2294       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
2295       return true;
2296     }
2297     if (ParentRegion == OMPD_atomic) {
2298       // OpenMP [2.16, Nesting of Regions]
2299       // OpenMP constructs may not be nested inside an atomic region.
2300       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2301       return true;
2302     }
2303     if (CurrentRegion == OMPD_section) {
2304       // OpenMP [2.7.2, sections Construct, Restrictions]
2305       // Orphaned section directives are prohibited. That is, the section
2306       // directives must appear within the sections construct and must not be
2307       // encountered elsewhere in the sections region.
2308       if (ParentRegion != OMPD_sections &&
2309           ParentRegion != OMPD_parallel_sections) {
2310         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2311             << (ParentRegion != OMPD_unknown)
2312             << getOpenMPDirectiveName(ParentRegion);
2313         return true;
2314       }
2315       return false;
2316     }
2317     // Allow some constructs to be orphaned (they could be used in functions,
2318     // called from OpenMP regions with the required preconditions).
2319     if (ParentRegion == OMPD_unknown)
2320       return false;
2321     if (CurrentRegion == OMPD_cancellation_point ||
2322         CurrentRegion == OMPD_cancel) {
2323       // OpenMP [2.16, Nesting of Regions]
2324       // A cancellation point construct for which construct-type-clause is
2325       // taskgroup must be nested inside a task construct. A cancellation
2326       // point construct for which construct-type-clause is not taskgroup must
2327       // be closely nested inside an OpenMP construct that matches the type
2328       // specified in construct-type-clause.
2329       // A cancel construct for which construct-type-clause is taskgroup must be
2330       // nested inside a task construct. A cancel construct for which
2331       // construct-type-clause is not taskgroup must be closely nested inside an
2332       // OpenMP construct that matches the type specified in
2333       // construct-type-clause.
2334       NestingProhibited =
2335           !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
2336             (CancelRegion == OMPD_for &&
2337              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
2338             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2339             (CancelRegion == OMPD_sections &&
2340              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2341               ParentRegion == OMPD_parallel_sections)));
2342     } else if (CurrentRegion == OMPD_master) {
2343       // OpenMP [2.16, Nesting of Regions]
2344       // A master region may not be closely nested inside a worksharing,
2345       // atomic, or explicit task region.
2346       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2347                           ParentRegion == OMPD_task ||
2348                           isOpenMPTaskLoopDirective(ParentRegion);
2349     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2350       // OpenMP [2.16, Nesting of Regions]
2351       // A critical region may not be nested (closely or otherwise) inside a
2352       // critical region with the same name. Note that this restriction is not
2353       // sufficient to prevent deadlock.
2354       SourceLocation PreviousCriticalLoc;
2355       bool DeadLock =
2356           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
2357                                   OpenMPDirectiveKind K,
2358                                   const DeclarationNameInfo &DNI,
2359                                   SourceLocation Loc)
2360                                   ->bool {
2361                                 if (K == OMPD_critical &&
2362                                     DNI.getName() == CurrentName.getName()) {
2363                                   PreviousCriticalLoc = Loc;
2364                                   return true;
2365                                 } else
2366                                   return false;
2367                               },
2368                               false /* skip top directive */);
2369       if (DeadLock) {
2370         SemaRef.Diag(StartLoc,
2371                      diag::err_omp_prohibited_region_critical_same_name)
2372             << CurrentName.getName();
2373         if (PreviousCriticalLoc.isValid())
2374           SemaRef.Diag(PreviousCriticalLoc,
2375                        diag::note_omp_previous_critical_region);
2376         return true;
2377       }
2378     } else if (CurrentRegion == OMPD_barrier) {
2379       // OpenMP [2.16, Nesting of Regions]
2380       // A barrier region may not be closely nested inside a worksharing,
2381       // explicit task, critical, ordered, atomic, or master region.
2382       NestingProhibited =
2383           isOpenMPWorksharingDirective(ParentRegion) ||
2384           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2385           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2386           isOpenMPTaskLoopDirective(ParentRegion);
2387     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
2388                !isOpenMPParallelDirective(CurrentRegion)) {
2389       // OpenMP [2.16, Nesting of Regions]
2390       // A worksharing region may not be closely nested inside a worksharing,
2391       // explicit task, critical, ordered, atomic, or master region.
2392       NestingProhibited =
2393           isOpenMPWorksharingDirective(ParentRegion) ||
2394           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
2395           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
2396           isOpenMPTaskLoopDirective(ParentRegion);
2397       Recommend = ShouldBeInParallelRegion;
2398     } else if (CurrentRegion == OMPD_ordered) {
2399       // OpenMP [2.16, Nesting of Regions]
2400       // An ordered region may not be closely nested inside a critical,
2401       // atomic, or explicit task region.
2402       // An ordered region must be closely nested inside a loop region (or
2403       // parallel loop region) with an ordered clause.
2404       // OpenMP [2.8.1,simd Construct, Restrictions]
2405       // An ordered construct with the simd clause is the only OpenMP construct
2406       // that can appear in the simd region.
2407       NestingProhibited = ParentRegion == OMPD_critical ||
2408                           ParentRegion == OMPD_task ||
2409                           isOpenMPTaskLoopDirective(ParentRegion) ||
2410                           !(isOpenMPSimdDirective(ParentRegion) ||
2411                             Stack->isParentOrderedRegion());
2412       Recommend = ShouldBeInOrderedRegion;
2413     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
2414       // OpenMP [2.16, Nesting of Regions]
2415       // If specified, a teams construct must be contained within a target
2416       // construct.
2417       NestingProhibited = ParentRegion != OMPD_target;
2418       Recommend = ShouldBeInTargetRegion;
2419       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2420     }
2421     if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
2422       // OpenMP [2.16, Nesting of Regions]
2423       // distribute, parallel, parallel sections, parallel workshare, and the
2424       // parallel loop and parallel loop SIMD constructs are the only OpenMP
2425       // constructs that can be closely nested in the teams region.
2426       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2427                           !isOpenMPDistributeDirective(CurrentRegion);
2428       Recommend = ShouldBeInParallelRegion;
2429     }
2430     if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
2431       // OpenMP 4.5 [2.17 Nesting of Regions]
2432       // The region associated with the distribute construct must be strictly
2433       // nested inside a teams region
2434       NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
2435       Recommend = ShouldBeInTeamsRegion;
2436     }
2437     if (NestingProhibited) {
2438       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2439           << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
2440           << getOpenMPDirectiveName(CurrentRegion);
2441       return true;
2442     }
2443   }
2444   return false;
2445 }
2446
2447 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2448                            ArrayRef<OMPClause *> Clauses,
2449                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2450   bool ErrorFound = false;
2451   unsigned NamedModifiersNumber = 0;
2452   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2453       OMPD_unknown + 1);
2454   SmallVector<SourceLocation, 4> NameModifierLoc;
2455   for (const auto *C : Clauses) {
2456     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2457       // At most one if clause without a directive-name-modifier can appear on
2458       // the directive.
2459       OpenMPDirectiveKind CurNM = IC->getNameModifier();
2460       if (FoundNameModifiers[CurNM]) {
2461         S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2462             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2463             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2464         ErrorFound = true;
2465       } else if (CurNM != OMPD_unknown) {
2466         NameModifierLoc.push_back(IC->getNameModifierLoc());
2467         ++NamedModifiersNumber;
2468       }
2469       FoundNameModifiers[CurNM] = IC;
2470       if (CurNM == OMPD_unknown)
2471         continue;
2472       // Check if the specified name modifier is allowed for the current
2473       // directive.
2474       // At most one if clause with the particular directive-name-modifier can
2475       // appear on the directive.
2476       bool MatchFound = false;
2477       for (auto NM : AllowedNameModifiers) {
2478         if (CurNM == NM) {
2479           MatchFound = true;
2480           break;
2481         }
2482       }
2483       if (!MatchFound) {
2484         S.Diag(IC->getNameModifierLoc(),
2485                diag::err_omp_wrong_if_directive_name_modifier)
2486             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2487         ErrorFound = true;
2488       }
2489     }
2490   }
2491   // If any if clause on the directive includes a directive-name-modifier then
2492   // all if clauses on the directive must include a directive-name-modifier.
2493   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2494     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2495       S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2496              diag::err_omp_no_more_if_clause);
2497     } else {
2498       std::string Values;
2499       std::string Sep(", ");
2500       unsigned AllowedCnt = 0;
2501       unsigned TotalAllowedNum =
2502           AllowedNameModifiers.size() - NamedModifiersNumber;
2503       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2504            ++Cnt) {
2505         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2506         if (!FoundNameModifiers[NM]) {
2507           Values += "'";
2508           Values += getOpenMPDirectiveName(NM);
2509           Values += "'";
2510           if (AllowedCnt + 2 == TotalAllowedNum)
2511             Values += " or ";
2512           else if (AllowedCnt + 1 != TotalAllowedNum)
2513             Values += Sep;
2514           ++AllowedCnt;
2515         }
2516       }
2517       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2518              diag::err_omp_unnamed_if_clause)
2519           << (TotalAllowedNum > 1) << Values;
2520     }
2521     for (auto Loc : NameModifierLoc) {
2522       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2523     }
2524     ErrorFound = true;
2525   }
2526   return ErrorFound;
2527 }
2528
2529 StmtResult Sema::ActOnOpenMPExecutableDirective(
2530     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2531     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2532     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
2533   StmtResult Res = StmtError();
2534   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2535                             StartLoc))
2536     return StmtError();
2537
2538   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
2539   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
2540   bool ErrorFound = false;
2541   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
2542   if (AStmt) {
2543     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2544
2545     // Check default data sharing attributes for referenced variables.
2546     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2547     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2548     if (DSAChecker.isErrorFound())
2549       return StmtError();
2550     // Generate list of implicitly defined firstprivate variables.
2551     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
2552
2553     if (!DSAChecker.getImplicitFirstprivate().empty()) {
2554       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2555               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2556               SourceLocation(), SourceLocation())) {
2557         ClausesWithImplicit.push_back(Implicit);
2558         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2559                      DSAChecker.getImplicitFirstprivate().size();
2560       } else
2561         ErrorFound = true;
2562     }
2563   }
2564
2565   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
2566   switch (Kind) {
2567   case OMPD_parallel:
2568     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2569                                        EndLoc);
2570     AllowedNameModifiers.push_back(OMPD_parallel);
2571     break;
2572   case OMPD_simd:
2573     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2574                                    VarsWithInheritedDSA);
2575     break;
2576   case OMPD_for:
2577     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2578                                   VarsWithInheritedDSA);
2579     break;
2580   case OMPD_for_simd:
2581     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2582                                       EndLoc, VarsWithInheritedDSA);
2583     break;
2584   case OMPD_sections:
2585     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2586                                        EndLoc);
2587     break;
2588   case OMPD_section:
2589     assert(ClausesWithImplicit.empty() &&
2590            "No clauses are allowed for 'omp section' directive");
2591     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2592     break;
2593   case OMPD_single:
2594     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2595                                      EndLoc);
2596     break;
2597   case OMPD_master:
2598     assert(ClausesWithImplicit.empty() &&
2599            "No clauses are allowed for 'omp master' directive");
2600     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2601     break;
2602   case OMPD_critical:
2603     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2604                                        StartLoc, EndLoc);
2605     break;
2606   case OMPD_parallel_for:
2607     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2608                                           EndLoc, VarsWithInheritedDSA);
2609     AllowedNameModifiers.push_back(OMPD_parallel);
2610     break;
2611   case OMPD_parallel_for_simd:
2612     Res = ActOnOpenMPParallelForSimdDirective(
2613         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2614     AllowedNameModifiers.push_back(OMPD_parallel);
2615     break;
2616   case OMPD_parallel_sections:
2617     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2618                                                StartLoc, EndLoc);
2619     AllowedNameModifiers.push_back(OMPD_parallel);
2620     break;
2621   case OMPD_task:
2622     Res =
2623         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2624     AllowedNameModifiers.push_back(OMPD_task);
2625     break;
2626   case OMPD_taskyield:
2627     assert(ClausesWithImplicit.empty() &&
2628            "No clauses are allowed for 'omp taskyield' directive");
2629     assert(AStmt == nullptr &&
2630            "No associated statement allowed for 'omp taskyield' directive");
2631     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2632     break;
2633   case OMPD_barrier:
2634     assert(ClausesWithImplicit.empty() &&
2635            "No clauses are allowed for 'omp barrier' directive");
2636     assert(AStmt == nullptr &&
2637            "No associated statement allowed for 'omp barrier' directive");
2638     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2639     break;
2640   case OMPD_taskwait:
2641     assert(ClausesWithImplicit.empty() &&
2642            "No clauses are allowed for 'omp taskwait' directive");
2643     assert(AStmt == nullptr &&
2644            "No associated statement allowed for 'omp taskwait' directive");
2645     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2646     break;
2647   case OMPD_taskgroup:
2648     assert(ClausesWithImplicit.empty() &&
2649            "No clauses are allowed for 'omp taskgroup' directive");
2650     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2651     break;
2652   case OMPD_flush:
2653     assert(AStmt == nullptr &&
2654            "No associated statement allowed for 'omp flush' directive");
2655     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2656     break;
2657   case OMPD_ordered:
2658     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2659                                       EndLoc);
2660     break;
2661   case OMPD_atomic:
2662     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2663                                      EndLoc);
2664     break;
2665   case OMPD_teams:
2666     Res =
2667         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2668     break;
2669   case OMPD_target:
2670     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2671                                      EndLoc);
2672     AllowedNameModifiers.push_back(OMPD_target);
2673     break;
2674   case OMPD_cancellation_point:
2675     assert(ClausesWithImplicit.empty() &&
2676            "No clauses are allowed for 'omp cancellation point' directive");
2677     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2678                                "cancellation point' directive");
2679     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2680     break;
2681   case OMPD_cancel:
2682     assert(AStmt == nullptr &&
2683            "No associated statement allowed for 'omp cancel' directive");
2684     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2685                                      CancelRegion);
2686     AllowedNameModifiers.push_back(OMPD_cancel);
2687     break;
2688   case OMPD_target_data:
2689     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2690                                          EndLoc);
2691     AllowedNameModifiers.push_back(OMPD_target_data);
2692     break;
2693   case OMPD_taskloop:
2694     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2695                                        EndLoc, VarsWithInheritedDSA);
2696     AllowedNameModifiers.push_back(OMPD_taskloop);
2697     break;
2698   case OMPD_taskloop_simd:
2699     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2700                                            EndLoc, VarsWithInheritedDSA);
2701     AllowedNameModifiers.push_back(OMPD_taskloop);
2702     break;
2703   case OMPD_distribute:
2704     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2705                                          EndLoc, VarsWithInheritedDSA);
2706     break;
2707   case OMPD_threadprivate:
2708     llvm_unreachable("OpenMP Directive is not allowed");
2709   case OMPD_unknown:
2710     llvm_unreachable("Unknown OpenMP directive");
2711   }
2712
2713   for (auto P : VarsWithInheritedDSA) {
2714     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2715         << P.first << P.second->getSourceRange();
2716   }
2717   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2718
2719   if (!AllowedNameModifiers.empty())
2720     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2721                  ErrorFound;
2722
2723   if (ErrorFound)
2724     return StmtError();
2725   return Res;
2726 }
2727
2728 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2729                                               Stmt *AStmt,
2730                                               SourceLocation StartLoc,
2731                                               SourceLocation EndLoc) {
2732   if (!AStmt)
2733     return StmtError();
2734
2735   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2736   // 1.2.2 OpenMP Language Terminology
2737   // Structured block - An executable statement with a single entry at the
2738   // top and a single exit at the bottom.
2739   // The point of exit cannot be a branch out of the structured block.
2740   // longjmp() and throw() must not violate the entry/exit criteria.
2741   CS->getCapturedDecl()->setNothrow();
2742
2743   getCurFunction()->setHasBranchProtectedScope();
2744
2745   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2746                                       DSAStack->isCancelRegion());
2747 }
2748
2749 namespace {
2750 /// \brief Helper class for checking canonical form of the OpenMP loops and
2751 /// extracting iteration space of each loop in the loop nest, that will be used
2752 /// for IR generation.
2753 class OpenMPIterationSpaceChecker {
2754   /// \brief Reference to Sema.
2755   Sema &SemaRef;
2756   /// \brief A location for diagnostics (when there is no some better location).
2757   SourceLocation DefaultLoc;
2758   /// \brief A location for diagnostics (when increment is not compatible).
2759   SourceLocation ConditionLoc;
2760   /// \brief A source location for referring to loop init later.
2761   SourceRange InitSrcRange;
2762   /// \brief A source location for referring to condition later.
2763   SourceRange ConditionSrcRange;
2764   /// \brief A source location for referring to increment later.
2765   SourceRange IncrementSrcRange;
2766   /// \brief Loop variable.
2767   VarDecl *Var;
2768   /// \brief Reference to loop variable.
2769   DeclRefExpr *VarRef;
2770   /// \brief Lower bound (initializer for the var).
2771   Expr *LB;
2772   /// \brief Upper bound.
2773   Expr *UB;
2774   /// \brief Loop step (increment).
2775   Expr *Step;
2776   /// \brief This flag is true when condition is one of:
2777   ///   Var <  UB
2778   ///   Var <= UB
2779   ///   UB  >  Var
2780   ///   UB  >= Var
2781   bool TestIsLessOp;
2782   /// \brief This flag is true when condition is strict ( < or > ).
2783   bool TestIsStrictOp;
2784   /// \brief This flag is true when step is subtracted on each iteration.
2785   bool SubtractStep;
2786
2787 public:
2788   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2789       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2790         InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2791         IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2792         LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2793         TestIsStrictOp(false), SubtractStep(false) {}
2794   /// \brief Check init-expr for canonical loop form and save loop counter
2795   /// variable - #Var and its initialization value - #LB.
2796   bool CheckInit(Stmt *S, bool EmitDiags = true);
2797   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2798   /// for less/greater and for strict/non-strict comparison.
2799   bool CheckCond(Expr *S);
2800   /// \brief Check incr-expr for canonical loop form and return true if it
2801   /// does not conform, otherwise save loop step (#Step).
2802   bool CheckInc(Expr *S);
2803   /// \brief Return the loop counter variable.
2804   VarDecl *GetLoopVar() const { return Var; }
2805   /// \brief Return the reference expression to loop counter variable.
2806   DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2807   /// \brief Source range of the loop init.
2808   SourceRange GetInitSrcRange() const { return InitSrcRange; }
2809   /// \brief Source range of the loop condition.
2810   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2811   /// \brief Source range of the loop increment.
2812   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2813   /// \brief True if the step should be subtracted.
2814   bool ShouldSubtractStep() const { return SubtractStep; }
2815   /// \brief Build the expression to calculate the number of iterations.
2816   Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2817   /// \brief Build the precondition expression for the loops.
2818   Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2819   /// \brief Build reference expression to the counter be used for codegen.
2820   Expr *BuildCounterVar() const;
2821   /// \brief Build reference expression to the private counter be used for
2822   /// codegen.
2823   Expr *BuildPrivateCounterVar() const;
2824   /// \brief Build initization of the counter be used for codegen.
2825   Expr *BuildCounterInit() const;
2826   /// \brief Build step of the counter be used for codegen.
2827   Expr *BuildCounterStep() const;
2828   /// \brief Return true if any expression is dependent.
2829   bool Dependent() const;
2830
2831 private:
2832   /// \brief Check the right-hand side of an assignment in the increment
2833   /// expression.
2834   bool CheckIncRHS(Expr *RHS);
2835   /// \brief Helper to set loop counter variable and its initializer.
2836   bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2837   /// \brief Helper to set upper bound.
2838   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
2839              SourceLocation SL);
2840   /// \brief Helper to set loop increment.
2841   bool SetStep(Expr *NewStep, bool Subtract);
2842 };
2843
2844 bool OpenMPIterationSpaceChecker::Dependent() const {
2845   if (!Var) {
2846     assert(!LB && !UB && !Step);
2847     return false;
2848   }
2849   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2850          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2851 }
2852
2853 template <typename T>
2854 static T *getExprAsWritten(T *E) {
2855   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2856     E = ExprTemp->getSubExpr();
2857
2858   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2859     E = MTE->GetTemporaryExpr();
2860
2861   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2862     E = Binder->getSubExpr();
2863
2864   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2865     E = ICE->getSubExprAsWritten();
2866   return E->IgnoreParens();
2867 }
2868
2869 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2870                                               DeclRefExpr *NewVarRefExpr,
2871                                               Expr *NewLB) {
2872   // State consistency checking to ensure correct usage.
2873   assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2874          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2875   if (!NewVar || !NewLB)
2876     return true;
2877   Var = NewVar;
2878   VarRef = NewVarRefExpr;
2879   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2880     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2881       if ((Ctor->isCopyOrMoveConstructor() ||
2882            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2883           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2884         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2885   LB = NewLB;
2886   return false;
2887 }
2888
2889 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2890                                         SourceRange SR, SourceLocation SL) {
2891   // State consistency checking to ensure correct usage.
2892   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2893          !TestIsLessOp && !TestIsStrictOp);
2894   if (!NewUB)
2895     return true;
2896   UB = NewUB;
2897   TestIsLessOp = LessOp;
2898   TestIsStrictOp = StrictOp;
2899   ConditionSrcRange = SR;
2900   ConditionLoc = SL;
2901   return false;
2902 }
2903
2904 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2905   // State consistency checking to ensure correct usage.
2906   assert(Var != nullptr && LB != nullptr && Step == nullptr);
2907   if (!NewStep)
2908     return true;
2909   if (!NewStep->isValueDependent()) {
2910     // Check that the step is integer expression.
2911     SourceLocation StepLoc = NewStep->getLocStart();
2912     ExprResult Val =
2913         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2914     if (Val.isInvalid())
2915       return true;
2916     NewStep = Val.get();
2917
2918     // OpenMP [2.6, Canonical Loop Form, Restrictions]
2919     //  If test-expr is of form var relational-op b and relational-op is < or
2920     //  <= then incr-expr must cause var to increase on each iteration of the
2921     //  loop. If test-expr is of form var relational-op b and relational-op is
2922     //  > or >= then incr-expr must cause var to decrease on each iteration of
2923     //  the loop.
2924     //  If test-expr is of form b relational-op var and relational-op is < or
2925     //  <= then incr-expr must cause var to decrease on each iteration of the
2926     //  loop. If test-expr is of form b relational-op var and relational-op is
2927     //  > or >= then incr-expr must cause var to increase on each iteration of
2928     //  the loop.
2929     llvm::APSInt Result;
2930     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2931     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2932     bool IsConstNeg =
2933         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2934     bool IsConstPos =
2935         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2936     bool IsConstZero = IsConstant && !Result.getBoolValue();
2937     if (UB && (IsConstZero ||
2938                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2939                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
2940       SemaRef.Diag(NewStep->getExprLoc(),
2941                    diag::err_omp_loop_incr_not_compatible)
2942           << Var << TestIsLessOp << NewStep->getSourceRange();
2943       SemaRef.Diag(ConditionLoc,
2944                    diag::note_omp_loop_cond_requres_compatible_incr)
2945           << TestIsLessOp << ConditionSrcRange;
2946       return true;
2947     }
2948     if (TestIsLessOp == Subtract) {
2949       NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2950                                              NewStep).get();
2951       Subtract = !Subtract;
2952     }
2953   }
2954
2955   Step = NewStep;
2956   SubtractStep = Subtract;
2957   return false;
2958 }
2959
2960 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2961   // Check init-expr for canonical loop form and save loop counter
2962   // variable - #Var and its initialization value - #LB.
2963   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2964   //   var = lb
2965   //   integer-type var = lb
2966   //   random-access-iterator-type var = lb
2967   //   pointer-type var = lb
2968   //
2969   if (!S) {
2970     if (EmitDiags) {
2971       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2972     }
2973     return true;
2974   }
2975   InitSrcRange = S->getSourceRange();
2976   if (Expr *E = dyn_cast<Expr>(S))
2977     S = E->IgnoreParens();
2978   if (auto BO = dyn_cast<BinaryOperator>(S)) {
2979     if (BO->getOpcode() == BO_Assign)
2980       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2981         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2982                            BO->getRHS());
2983   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2984     if (DS->isSingleDecl()) {
2985       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2986         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
2987           // Accept non-canonical init form here but emit ext. warning.
2988           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2989             SemaRef.Diag(S->getLocStart(),
2990                          diag::ext_omp_loop_not_canonical_init)
2991                 << S->getSourceRange();
2992           return SetVarAndLB(Var, nullptr, Var->getInit());
2993         }
2994       }
2995     }
2996   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2997     if (CE->getOperator() == OO_Equal)
2998       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2999         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
3000                            CE->getArg(1));
3001
3002   if (EmitDiags) {
3003     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3004         << S->getSourceRange();
3005   }
3006   return true;
3007 }
3008
3009 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
3010 /// variable (which may be the loop variable) if possible.
3011 static const VarDecl *GetInitVarDecl(const Expr *E) {
3012   if (!E)
3013     return nullptr;
3014   E = getExprAsWritten(E);
3015   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3016     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
3017       if ((Ctor->isCopyOrMoveConstructor() ||
3018            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3019           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
3020         E = CE->getArg(0)->IgnoreParenImpCasts();
3021   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
3022   if (!DRE)
3023     return nullptr;
3024   return dyn_cast<VarDecl>(DRE->getDecl());
3025 }
3026
3027 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3028   // Check test-expr for canonical form, save upper-bound UB, flags for
3029   // less/greater and for strict/non-strict comparison.
3030   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3031   //   var relational-op b
3032   //   b relational-op var
3033   //
3034   if (!S) {
3035     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
3036     return true;
3037   }
3038   S = getExprAsWritten(S);
3039   SourceLocation CondLoc = S->getLocStart();
3040   if (auto BO = dyn_cast<BinaryOperator>(S)) {
3041     if (BO->isRelationalOp()) {
3042       if (GetInitVarDecl(BO->getLHS()) == Var)
3043         return SetUB(BO->getRHS(),
3044                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3045                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3046                      BO->getSourceRange(), BO->getOperatorLoc());
3047       if (GetInitVarDecl(BO->getRHS()) == Var)
3048         return SetUB(BO->getLHS(),
3049                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3050                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3051                      BO->getSourceRange(), BO->getOperatorLoc());
3052     }
3053   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3054     if (CE->getNumArgs() == 2) {
3055       auto Op = CE->getOperator();
3056       switch (Op) {
3057       case OO_Greater:
3058       case OO_GreaterEqual:
3059       case OO_Less:
3060       case OO_LessEqual:
3061         if (GetInitVarDecl(CE->getArg(0)) == Var)
3062           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3063                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3064                        CE->getOperatorLoc());
3065         if (GetInitVarDecl(CE->getArg(1)) == Var)
3066           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3067                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3068                        CE->getOperatorLoc());
3069         break;
3070       default:
3071         break;
3072       }
3073     }
3074   }
3075   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
3076       << S->getSourceRange() << Var;
3077   return true;
3078 }
3079
3080 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3081   // RHS of canonical loop form increment can be:
3082   //   var + incr
3083   //   incr + var
3084   //   var - incr
3085   //
3086   RHS = RHS->IgnoreParenImpCasts();
3087   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
3088     if (BO->isAdditiveOp()) {
3089       bool IsAdd = BO->getOpcode() == BO_Add;
3090       if (GetInitVarDecl(BO->getLHS()) == Var)
3091         return SetStep(BO->getRHS(), !IsAdd);
3092       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
3093         return SetStep(BO->getLHS(), false);
3094     }
3095   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
3096     bool IsAdd = CE->getOperator() == OO_Plus;
3097     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
3098       if (GetInitVarDecl(CE->getArg(0)) == Var)
3099         return SetStep(CE->getArg(1), !IsAdd);
3100       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
3101         return SetStep(CE->getArg(0), false);
3102     }
3103   }
3104   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3105       << RHS->getSourceRange() << Var;
3106   return true;
3107 }
3108
3109 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3110   // Check incr-expr for canonical loop form and return true if it
3111   // does not conform.
3112   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3113   //   ++var
3114   //   var++
3115   //   --var
3116   //   var--
3117   //   var += incr
3118   //   var -= incr
3119   //   var = var + incr
3120   //   var = incr + var
3121   //   var = var - incr
3122   //
3123   if (!S) {
3124     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
3125     return true;
3126   }
3127   IncrementSrcRange = S->getSourceRange();
3128   S = S->IgnoreParens();
3129   if (auto UO = dyn_cast<UnaryOperator>(S)) {
3130     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
3131       return SetStep(
3132           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
3133                                        (UO->isDecrementOp() ? -1 : 1)).get(),
3134           false);
3135   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
3136     switch (BO->getOpcode()) {
3137     case BO_AddAssign:
3138     case BO_SubAssign:
3139       if (GetInitVarDecl(BO->getLHS()) == Var)
3140         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3141       break;
3142     case BO_Assign:
3143       if (GetInitVarDecl(BO->getLHS()) == Var)
3144         return CheckIncRHS(BO->getRHS());
3145       break;
3146     default:
3147       break;
3148     }
3149   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
3150     switch (CE->getOperator()) {
3151     case OO_PlusPlus:
3152     case OO_MinusMinus:
3153       if (GetInitVarDecl(CE->getArg(0)) == Var)
3154         return SetStep(
3155             SemaRef.ActOnIntegerConstant(
3156                         CE->getLocStart(),
3157                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
3158             false);
3159       break;
3160     case OO_PlusEqual:
3161     case OO_MinusEqual:
3162       if (GetInitVarDecl(CE->getArg(0)) == Var)
3163         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3164       break;
3165     case OO_Equal:
3166       if (GetInitVarDecl(CE->getArg(0)) == Var)
3167         return CheckIncRHS(CE->getArg(1));
3168       break;
3169     default:
3170       break;
3171     }
3172   }
3173   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
3174       << S->getSourceRange() << Var;
3175   return true;
3176 }
3177
3178 namespace {
3179 // Transform variables declared in GNU statement expressions to new ones to
3180 // avoid crash on codegen.
3181 class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
3182   typedef TreeTransform<TransformToNewDefs> BaseTransform;
3183
3184 public:
3185   TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
3186
3187   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
3188     if (auto *VD = cast<VarDecl>(D))
3189       if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
3190           !isa<ImplicitParamDecl>(D)) {
3191         auto *NewVD = VarDecl::Create(
3192             SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
3193             VD->getLocation(), VD->getIdentifier(), VD->getType(),
3194             VD->getTypeSourceInfo(), VD->getStorageClass());
3195         NewVD->setTSCSpec(VD->getTSCSpec());
3196         NewVD->setInit(VD->getInit());
3197         NewVD->setInitStyle(VD->getInitStyle());
3198         NewVD->setExceptionVariable(VD->isExceptionVariable());
3199         NewVD->setNRVOVariable(VD->isNRVOVariable());
3200         NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
3201         NewVD->setConstexpr(VD->isConstexpr());
3202         NewVD->setInitCapture(VD->isInitCapture());
3203         NewVD->setPreviousDeclInSameBlockScope(
3204             VD->isPreviousDeclInSameBlockScope());
3205         VD->getDeclContext()->addHiddenDecl(NewVD);
3206         if (VD->hasAttrs())
3207           NewVD->setAttrs(VD->getAttrs());
3208         transformedLocalDecl(VD, NewVD);
3209         return NewVD;
3210       }
3211     return BaseTransform::TransformDefinition(Loc, D);
3212   }
3213
3214   ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
3215     if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
3216       if (E->getDecl() != NewD) {
3217         NewD->setReferenced();
3218         NewD->markUsed(SemaRef.Context);
3219         return DeclRefExpr::Create(
3220             SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
3221             cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
3222             E->getNameInfo(), E->getType(), E->getValueKind());
3223       }
3224     return BaseTransform::TransformDeclRefExpr(E);
3225   }
3226 };
3227 }
3228
3229 /// \brief Build the expression to calculate the number of iterations.
3230 Expr *
3231 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
3232                                                 const bool LimitedType) const {
3233   TransformToNewDefs Transform(SemaRef);
3234   ExprResult Diff;
3235   auto VarType = Var->getType().getNonReferenceType();
3236   if (VarType->isIntegerType() || VarType->isPointerType() ||
3237       SemaRef.getLangOpts().CPlusPlus) {
3238     // Upper - Lower
3239     auto *UBExpr = TestIsLessOp ? UB : LB;
3240     auto *LBExpr = TestIsLessOp ? LB : UB;
3241     Expr *Upper = Transform.TransformExpr(UBExpr).get();
3242     Expr *Lower = Transform.TransformExpr(LBExpr).get();
3243     if (!Upper || !Lower)
3244       return nullptr;
3245     Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
3246                                                     Sema::AA_Converting,
3247                                                     /*AllowExplicit=*/true)
3248                       .get();
3249     Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
3250                                               Sema::AA_Converting,
3251                                               /*AllowExplicit=*/true)
3252                 .get();
3253     if (!Upper || !Lower)
3254       return nullptr;
3255
3256     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3257
3258     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
3259       // BuildBinOp already emitted error, this one is to point user to upper
3260       // and lower bound, and to tell what is passed to 'operator-'.
3261       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3262           << Upper->getSourceRange() << Lower->getSourceRange();
3263       return nullptr;
3264     }
3265   }
3266
3267   if (!Diff.isUsable())
3268     return nullptr;
3269
3270   // Upper - Lower [- 1]
3271   if (TestIsStrictOp)
3272     Diff = SemaRef.BuildBinOp(
3273         S, DefaultLoc, BO_Sub, Diff.get(),
3274         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3275   if (!Diff.isUsable())
3276     return nullptr;
3277
3278   // Upper - Lower [- 1] + Step
3279   auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3280   if (NewStep.isInvalid())
3281     return nullptr;
3282   NewStep = SemaRef.PerformImplicitConversion(
3283       NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3284       /*AllowExplicit=*/true);
3285   if (NewStep.isInvalid())
3286     return nullptr;
3287   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
3288   if (!Diff.isUsable())
3289     return nullptr;
3290
3291   // Parentheses (for dumping/debugging purposes only).
3292   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3293   if (!Diff.isUsable())
3294     return nullptr;
3295
3296   // (Upper - Lower [- 1] + Step) / Step
3297   NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
3298   if (NewStep.isInvalid())
3299     return nullptr;
3300   NewStep = SemaRef.PerformImplicitConversion(
3301       NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
3302       /*AllowExplicit=*/true);
3303   if (NewStep.isInvalid())
3304     return nullptr;
3305   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
3306   if (!Diff.isUsable())
3307     return nullptr;
3308
3309   // OpenMP runtime requires 32-bit or 64-bit loop variables.
3310   QualType Type = Diff.get()->getType();
3311   auto &C = SemaRef.Context;
3312   bool UseVarType = VarType->hasIntegerRepresentation() &&
3313                     C.getTypeSize(Type) > C.getTypeSize(VarType);
3314   if (!Type->isIntegerType() || UseVarType) {
3315     unsigned NewSize =
3316         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3317     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3318                                : Type->hasSignedIntegerRepresentation();
3319     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
3320     Diff = SemaRef.PerformImplicitConversion(
3321         Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3322     if (!Diff.isUsable())
3323       return nullptr;
3324   }
3325   if (LimitedType) {
3326     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3327     if (NewSize != C.getTypeSize(Type)) {
3328       if (NewSize < C.getTypeSize(Type)) {
3329         assert(NewSize == 64 && "incorrect loop var size");
3330         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3331             << InitSrcRange << ConditionSrcRange;
3332       }
3333       QualType NewType = C.getIntTypeForBitwidth(
3334           NewSize, Type->hasSignedIntegerRepresentation() ||
3335                        C.getTypeSize(Type) < NewSize);
3336       Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3337                                                Sema::AA_Converting, true);
3338       if (!Diff.isUsable())
3339         return nullptr;
3340     }
3341   }
3342
3343   return Diff.get();
3344 }
3345
3346 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
3347   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3348   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3349   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3350   TransformToNewDefs Transform(SemaRef);
3351
3352   auto NewLB = Transform.TransformExpr(LB);
3353   auto NewUB = Transform.TransformExpr(UB);
3354   if (NewLB.isInvalid() || NewUB.isInvalid())
3355     return Cond;
3356   NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
3357                                             Sema::AA_Converting,
3358                                             /*AllowExplicit=*/true);
3359   NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
3360                                             Sema::AA_Converting,
3361                                             /*AllowExplicit=*/true);
3362   if (NewLB.isInvalid() || NewUB.isInvalid())
3363     return Cond;
3364   auto CondExpr = SemaRef.BuildBinOp(
3365       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3366                                   : (TestIsStrictOp ? BO_GT : BO_GE),
3367       NewLB.get(), NewUB.get());
3368   if (CondExpr.isUsable()) {
3369     CondExpr = SemaRef.PerformImplicitConversion(
3370         CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3371         /*AllowExplicit=*/true);
3372   }
3373   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3374   // Otherwise use original loop conditon and evaluate it in runtime.
3375   return CondExpr.isUsable() ? CondExpr.get() : Cond;
3376 }
3377
3378 /// \brief Build reference expression to the counter be used for codegen.
3379 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
3380   return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
3381                           DefaultLoc);
3382 }
3383
3384 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
3385   if (Var && !Var->isInvalidDecl()) {
3386     auto Type = Var->getType().getNonReferenceType();
3387     auto *PrivateVar =
3388         buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
3389                      Var->hasAttrs() ? &Var->getAttrs() : nullptr);
3390     if (PrivateVar->isInvalidDecl())
3391       return nullptr;
3392     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3393   }
3394   return nullptr;
3395 }
3396
3397 /// \brief Build initization of the counter be used for codegen.
3398 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3399
3400 /// \brief Build step of the counter be used for codegen.
3401 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3402
3403 /// \brief Iteration space of a single for loop.
3404 struct LoopIterationSpace {
3405   /// \brief Condition of the loop.
3406   Expr *PreCond;
3407   /// \brief This expression calculates the number of iterations in the loop.
3408   /// It is always possible to calculate it before starting the loop.
3409   Expr *NumIterations;
3410   /// \brief The loop counter variable.
3411   Expr *CounterVar;
3412   /// \brief Private loop counter variable.
3413   Expr *PrivateCounterVar;
3414   /// \brief This is initializer for the initial value of #CounterVar.
3415   Expr *CounterInit;
3416   /// \brief This is step for the #CounterVar used to generate its update:
3417   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
3418   Expr *CounterStep;
3419   /// \brief Should step be subtracted?
3420   bool Subtract;
3421   /// \brief Source range of the loop init.
3422   SourceRange InitSrcRange;
3423   /// \brief Source range of the loop condition.
3424   SourceRange CondSrcRange;
3425   /// \brief Source range of the loop increment.
3426   SourceRange IncSrcRange;
3427 };
3428
3429 } // namespace
3430
3431 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3432   assert(getLangOpts().OpenMP && "OpenMP is not active.");
3433   assert(Init && "Expected loop in canonical form.");
3434   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3435   if (AssociatedLoops > 0 &&
3436       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3437     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
3438     if (!ISC.CheckInit(Init, /*EmitDiags=*/false))
3439       DSAStack->addLoopControlVariable(ISC.GetLoopVar());
3440     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
3441   }
3442 }
3443
3444 /// \brief Called on a for stmt to check and extract its iteration space
3445 /// for further processing (such as collapsing).
3446 static bool CheckOpenMPIterationSpace(
3447     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3448     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
3449     Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
3450     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3451     LoopIterationSpace &ResultIterSpace) {
3452   // OpenMP [2.6, Canonical Loop Form]
3453   //   for (init-expr; test-expr; incr-expr) structured-block
3454   auto For = dyn_cast_or_null<ForStmt>(S);
3455   if (!For) {
3456     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
3457         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3458         << getOpenMPDirectiveName(DKind) << NestedLoopCount
3459         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3460     if (NestedLoopCount > 1) {
3461       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3462         SemaRef.Diag(DSA.getConstructLoc(),
3463                      diag::note_omp_collapse_ordered_expr)
3464             << 2 << CollapseLoopCountExpr->getSourceRange()
3465             << OrderedLoopCountExpr->getSourceRange();
3466       else if (CollapseLoopCountExpr)
3467         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3468                      diag::note_omp_collapse_ordered_expr)
3469             << 0 << CollapseLoopCountExpr->getSourceRange();
3470       else
3471         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3472                      diag::note_omp_collapse_ordered_expr)
3473             << 1 << OrderedLoopCountExpr->getSourceRange();
3474     }
3475     return true;
3476   }
3477   assert(For->getBody());
3478
3479   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3480
3481   // Check init.
3482   auto Init = For->getInit();
3483   if (ISC.CheckInit(Init)) {
3484     return true;
3485   }
3486
3487   bool HasErrors = false;
3488
3489   // Check loop variable's type.
3490   auto Var = ISC.GetLoopVar();
3491
3492   // OpenMP [2.6, Canonical Loop Form]
3493   // Var is one of the following:
3494   //   A variable of signed or unsigned integer type.
3495   //   For C++, a variable of a random access iterator type.
3496   //   For C, a variable of a pointer type.
3497   auto VarType = Var->getType().getNonReferenceType();
3498   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3499       !VarType->isPointerType() &&
3500       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3501     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3502         << SemaRef.getLangOpts().CPlusPlus;
3503     HasErrors = true;
3504   }
3505
3506   // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
3507   // Construct
3508   // The loop iteration variable(s) in the associated for-loop(s) of a for or
3509   // parallel for construct is (are) private.
3510   // The loop iteration variable in the associated for-loop of a simd construct
3511   // with just one associated for-loop is linear with a constant-linear-step
3512   // that is the increment of the associated for-loop.
3513   // Exclude loop var from the list of variables with implicitly defined data
3514   // sharing attributes.
3515   VarsWithImplicitDSA.erase(Var);
3516
3517   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
3518   // a Construct, C/C++].
3519   // The loop iteration variable in the associated for-loop of a simd construct
3520   // with just one associated for-loop may be listed in a linear clause with a
3521   // constant-linear-step that is the increment of the associated for-loop.
3522   // The loop iteration variable(s) in the associated for-loop(s) of a for or
3523   // parallel for construct may be listed in a private or lastprivate clause.
3524   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
3525   auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
3526   // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3527   // declared in the loop and it is predetermined as a private.
3528   auto PredeterminedCKind =
3529       isOpenMPSimdDirective(DKind)
3530           ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3531           : OMPC_private;
3532   if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3533         DVar.CKind != PredeterminedCKind) ||
3534        ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3535          isOpenMPDistributeDirective(DKind)) &&
3536         !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3537         DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3538       (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3539     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3540         << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3541         << getOpenMPClauseName(PredeterminedCKind);
3542     if (DVar.RefExpr == nullptr)
3543       DVar.CKind = PredeterminedCKind;
3544     ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
3545     HasErrors = true;
3546   } else if (LoopVarRefExpr != nullptr) {
3547     // Make the loop iteration variable private (for worksharing constructs),
3548     // linear (for simd directives with the only one associated loop) or
3549     // lastprivate (for simd directives with several collapsed or ordered
3550     // loops).
3551     if (DVar.CKind == OMPC_unknown)
3552       DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
3553                         /*FromParent=*/false);
3554     DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
3555   }
3556
3557   assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3558
3559   // Check test-expr.
3560   HasErrors |= ISC.CheckCond(For->getCond());
3561
3562   // Check incr-expr.
3563   HasErrors |= ISC.CheckInc(For->getInc());
3564
3565   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
3566     return HasErrors;
3567
3568   // Build the loop's iteration space representation.
3569   ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
3570   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
3571       DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) ||
3572                           isOpenMPTaskLoopDirective(DKind) ||
3573                           isOpenMPDistributeDirective(DKind)));
3574   ResultIterSpace.CounterVar = ISC.BuildCounterVar();
3575   ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
3576   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3577   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3578   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3579   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3580   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3581   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3582
3583   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3584                 ResultIterSpace.NumIterations == nullptr ||
3585                 ResultIterSpace.CounterVar == nullptr ||
3586                 ResultIterSpace.PrivateCounterVar == nullptr ||
3587                 ResultIterSpace.CounterInit == nullptr ||
3588                 ResultIterSpace.CounterStep == nullptr);
3589
3590   return HasErrors;
3591 }
3592
3593 /// \brief Build 'VarRef = Start.
3594 static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
3595                                    ExprResult VarRef, ExprResult Start) {
3596   TransformToNewDefs Transform(SemaRef);
3597   // Build 'VarRef = Start.
3598   auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3599   if (NewStart.isInvalid())
3600     return ExprError();
3601   NewStart = SemaRef.PerformImplicitConversion(
3602       NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3603       Sema::AA_Converting,
3604       /*AllowExplicit=*/true);
3605   if (NewStart.isInvalid())
3606     return ExprError();
3607   NewStart = SemaRef.PerformImplicitConversion(
3608       NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3609       /*AllowExplicit=*/true);
3610   if (!NewStart.isUsable())
3611     return ExprError();
3612
3613   auto Init =
3614       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3615   return Init;
3616 }
3617
3618 /// \brief Build 'VarRef = Start + Iter * Step'.
3619 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
3620                                      SourceLocation Loc, ExprResult VarRef,
3621                                      ExprResult Start, ExprResult Iter,
3622                                      ExprResult Step, bool Subtract) {
3623   // Add parentheses (for debugging purposes only).
3624   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3625   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3626       !Step.isUsable())
3627     return ExprError();
3628
3629   TransformToNewDefs Transform(SemaRef);
3630   auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
3631   if (NewStep.isInvalid())
3632     return ExprError();
3633   NewStep = SemaRef.PerformImplicitConversion(
3634       NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
3635       Sema::AA_Converting,
3636       /*AllowExplicit=*/true);
3637   if (NewStep.isInvalid())
3638     return ExprError();
3639   ExprResult Update =
3640       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
3641   if (!Update.isUsable())
3642     return ExprError();
3643
3644   // Build 'VarRef = Start + Iter * Step'.
3645   auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
3646   if (NewStart.isInvalid())
3647     return ExprError();
3648   NewStart = SemaRef.PerformImplicitConversion(
3649       NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
3650       Sema::AA_Converting,
3651       /*AllowExplicit=*/true);
3652   if (NewStart.isInvalid())
3653     return ExprError();
3654   Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
3655                               NewStart.get(), Update.get());
3656   if (!Update.isUsable())
3657     return ExprError();
3658
3659   Update = SemaRef.PerformImplicitConversion(
3660       Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3661   if (!Update.isUsable())
3662     return ExprError();
3663
3664   Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3665   return Update;
3666 }
3667
3668 /// \brief Convert integer expression \a E to make it have at least \a Bits
3669 /// bits.
3670 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
3671                                       Sema &SemaRef) {
3672   if (E == nullptr)
3673     return ExprError();
3674   auto &C = SemaRef.Context;
3675   QualType OldType = E->getType();
3676   unsigned HasBits = C.getTypeSize(OldType);
3677   if (HasBits >= Bits)
3678     return ExprResult(E);
3679   // OK to convert to signed, because new type has more bits than old.
3680   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3681   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3682                                            true);
3683 }
3684
3685 /// \brief Check if the given expression \a E is a constant integer that fits
3686 /// into \a Bits bits.
3687 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3688   if (E == nullptr)
3689     return false;
3690   llvm::APSInt Result;
3691   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3692     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3693   return false;
3694 }
3695
3696 /// \brief Called on a for stmt to check itself and nested loops (if any).
3697 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3698 /// number of collapsed loops otherwise.
3699 static unsigned
3700 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3701                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3702                 DSAStackTy &DSA,
3703                 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
3704                 OMPLoopDirective::HelperExprs &Built) {
3705   unsigned NestedLoopCount = 1;
3706   if (CollapseLoopCountExpr) {
3707     // Found 'collapse' clause - calculate collapse number.
3708     llvm::APSInt Result;
3709     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
3710       NestedLoopCount = Result.getLimitedValue();
3711   }
3712   if (OrderedLoopCountExpr) {
3713     // Found 'ordered' clause - calculate collapse number.
3714     llvm::APSInt Result;
3715     if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3716       if (Result.getLimitedValue() < NestedLoopCount) {
3717         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3718                      diag::err_omp_wrong_ordered_loop_count)
3719             << OrderedLoopCountExpr->getSourceRange();
3720         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3721                      diag::note_collapse_loop_count)
3722             << CollapseLoopCountExpr->getSourceRange();
3723       }
3724       NestedLoopCount = Result.getLimitedValue();
3725     }
3726   }
3727   // This is helper routine for loop directives (e.g., 'for', 'simd',
3728   // 'for simd', etc.).
3729   SmallVector<LoopIterationSpace, 4> IterSpaces;
3730   IterSpaces.resize(NestedLoopCount);
3731   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
3732   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
3733     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
3734                                   NestedLoopCount, CollapseLoopCountExpr,
3735                                   OrderedLoopCountExpr, VarsWithImplicitDSA,
3736                                   IterSpaces[Cnt]))
3737       return 0;
3738     // Move on to the next nested for loop, or to the loop body.
3739     // OpenMP [2.8.1, simd construct, Restrictions]
3740     // All loops associated with the construct must be perfectly nested; that
3741     // is, there must be no intervening code nor any OpenMP directive between
3742     // any two loops.
3743     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
3744   }
3745
3746   Built.clear(/* size */ NestedLoopCount);
3747
3748   if (SemaRef.CurContext->isDependentContext())
3749     return NestedLoopCount;
3750
3751   // An example of what is generated for the following code:
3752   //
3753   //   #pragma omp simd collapse(2) ordered(2)
3754   //   for (i = 0; i < NI; ++i)
3755   //     for (k = 0; k < NK; ++k)
3756   //       for (j = J0; j < NJ; j+=2) {
3757   //         <loop body>
3758   //       }
3759   //
3760   // We generate the code below.
3761   // Note: the loop body may be outlined in CodeGen.
3762   // Note: some counters may be C++ classes, operator- is used to find number of
3763   // iterations and operator+= to calculate counter value.
3764   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3765   // or i64 is currently supported).
3766   //
3767   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3768   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3769   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3770   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3771   //     // similar updates for vars in clauses (e.g. 'linear')
3772   //     <loop body (using local i and j)>
3773   //   }
3774   //   i = NI; // assign final values of counters
3775   //   j = NJ;
3776   //
3777
3778   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3779   // the iteration counts of the collapsed for loops.
3780   // Precondition tests if there is at least one iteration (all conditions are
3781   // true).
3782   auto PreCond = ExprResult(IterSpaces[0].PreCond);
3783   auto N0 = IterSpaces[0].NumIterations;
3784   ExprResult LastIteration32 = WidenIterationCount(
3785       32 /* Bits */, SemaRef.PerformImplicitConversion(
3786                                 N0->IgnoreImpCasts(), N0->getType(),
3787                                 Sema::AA_Converting, /*AllowExplicit=*/true)
3788                          .get(),
3789       SemaRef);
3790   ExprResult LastIteration64 = WidenIterationCount(
3791       64 /* Bits */, SemaRef.PerformImplicitConversion(
3792                                 N0->IgnoreImpCasts(), N0->getType(),
3793                                 Sema::AA_Converting, /*AllowExplicit=*/true)
3794                          .get(),
3795       SemaRef);
3796
3797   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3798     return NestedLoopCount;
3799
3800   auto &C = SemaRef.Context;
3801   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3802
3803   Scope *CurScope = DSA.getCurScope();
3804   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3805     if (PreCond.isUsable()) {
3806       PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3807                                    PreCond.get(), IterSpaces[Cnt].PreCond);
3808     }
3809     auto N = IterSpaces[Cnt].NumIterations;
3810     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3811     if (LastIteration32.isUsable())
3812       LastIteration32 = SemaRef.BuildBinOp(
3813           CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
3814           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3815                                             Sema::AA_Converting,
3816                                             /*AllowExplicit=*/true)
3817               .get());
3818     if (LastIteration64.isUsable())
3819       LastIteration64 = SemaRef.BuildBinOp(
3820           CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
3821           SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3822                                             Sema::AA_Converting,
3823                                             /*AllowExplicit=*/true)
3824               .get());
3825   }
3826
3827   // Choose either the 32-bit or 64-bit version.
3828   ExprResult LastIteration = LastIteration64;
3829   if (LastIteration32.isUsable() &&
3830       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3831       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3832        FitsInto(
3833            32 /* Bits */,
3834            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3835            LastIteration64.get(), SemaRef)))
3836     LastIteration = LastIteration32;
3837
3838   if (!LastIteration.isUsable())
3839     return 0;
3840
3841   // Save the number of iterations.
3842   ExprResult NumIterations = LastIteration;
3843   {
3844     LastIteration = SemaRef.BuildBinOp(
3845         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3846         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3847     if (!LastIteration.isUsable())
3848       return 0;
3849   }
3850
3851   // Calculate the last iteration number beforehand instead of doing this on
3852   // each iteration. Do not do this if the number of iterations may be kfold-ed.
3853   llvm::APSInt Result;
3854   bool IsConstant =
3855       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3856   ExprResult CalcLastIteration;
3857   if (!IsConstant) {
3858     SourceLocation SaveLoc;
3859     VarDecl *SaveVar =
3860         buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
3861                      ".omp.last.iteration");
3862     ExprResult SaveRef = buildDeclRefExpr(
3863         SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
3864     CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3865                                            SaveRef.get(), LastIteration.get());
3866     LastIteration = SaveRef;
3867
3868     // Prepare SaveRef + 1.
3869     NumIterations = SemaRef.BuildBinOp(
3870         CurScope, SaveLoc, BO_Add, SaveRef.get(),
3871         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3872     if (!NumIterations.isUsable())
3873       return 0;
3874   }
3875
3876   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3877
3878   QualType VType = LastIteration.get()->getType();
3879   // Build variables passed into runtime, nesessary for worksharing directives.
3880   ExprResult LB, UB, IL, ST, EUB;
3881   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3882       isOpenMPDistributeDirective(DKind)) {
3883     // Lower bound variable, initialized with zero.
3884     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3885     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3886     SemaRef.AddInitializerToDecl(
3887         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3888         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3889
3890     // Upper bound variable, initialized with last iteration number.
3891     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3892     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3893     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3894                                  /*DirectInit*/ false,
3895                                  /*TypeMayContainAuto*/ false);
3896
3897     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3898     // This will be used to implement clause 'lastprivate'.
3899     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3900     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3901     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3902     SemaRef.AddInitializerToDecl(
3903         ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3904         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3905
3906     // Stride variable returned by runtime (we initialize it to 1 by default).
3907     VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3908     ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
3909     SemaRef.AddInitializerToDecl(
3910         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3911         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3912
3913     // Build expression: UB = min(UB, LastIteration)
3914     // It is nesessary for CodeGen of directives with static scheduling.
3915     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3916                                                 UB.get(), LastIteration.get());
3917     ExprResult CondOp = SemaRef.ActOnConditionalOp(
3918         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3919     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3920                              CondOp.get());
3921     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3922   }
3923
3924   // Build the iteration variable and its initialization before loop.
3925   ExprResult IV;
3926   ExprResult Init;
3927   {
3928     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3929     IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
3930     Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
3931                  isOpenMPTaskLoopDirective(DKind) ||
3932                  isOpenMPDistributeDirective(DKind))
3933                     ? LB.get()
3934                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3935     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3936     Init = SemaRef.ActOnFinishFullExpr(Init.get());
3937   }
3938
3939   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
3940   SourceLocation CondLoc;
3941   ExprResult Cond =
3942       (isOpenMPWorksharingDirective(DKind) ||
3943        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
3944           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3945           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3946                                NumIterations.get());
3947
3948   // Loop increment (IV = IV + 1)
3949   SourceLocation IncLoc;
3950   ExprResult Inc =
3951       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3952                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3953   if (!Inc.isUsable())
3954     return 0;
3955   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
3956   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3957   if (!Inc.isUsable())
3958     return 0;
3959
3960   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3961   // Used for directives with static scheduling.
3962   ExprResult NextLB, NextUB;
3963   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
3964       isOpenMPDistributeDirective(DKind)) {
3965     // LB + ST
3966     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3967     if (!NextLB.isUsable())
3968       return 0;
3969     // LB = LB + ST
3970     NextLB =
3971         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3972     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3973     if (!NextLB.isUsable())
3974       return 0;
3975     // UB + ST
3976     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3977     if (!NextUB.isUsable())
3978       return 0;
3979     // UB = UB + ST
3980     NextUB =
3981         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3982     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3983     if (!NextUB.isUsable())
3984       return 0;
3985   }
3986
3987   // Build updates and final values of the loop counters.
3988   bool HasErrors = false;
3989   Built.Counters.resize(NestedLoopCount);
3990   Built.Inits.resize(NestedLoopCount);
3991   Built.Updates.resize(NestedLoopCount);
3992   Built.Finals.resize(NestedLoopCount);
3993   {
3994     ExprResult Div;
3995     // Go from inner nested loop to outer.
3996     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3997       LoopIterationSpace &IS = IterSpaces[Cnt];
3998       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3999       // Build: Iter = (IV / Div) % IS.NumIters
4000       // where Div is product of previous iterations' IS.NumIters.
4001       ExprResult Iter;
4002       if (Div.isUsable()) {
4003         Iter =
4004             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4005       } else {
4006         Iter = IV;
4007         assert((Cnt == (int)NestedLoopCount - 1) &&
4008                "unusable div expected on first iteration only");
4009       }
4010
4011       if (Cnt != 0 && Iter.isUsable())
4012         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4013                                   IS.NumIterations);
4014       if (!Iter.isUsable()) {
4015         HasErrors = true;
4016         break;
4017       }
4018
4019       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
4020       auto *CounterVar = buildDeclRefExpr(
4021           SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
4022           IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
4023           /*RefersToCapture=*/true);
4024       ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
4025                                          IS.CounterInit);
4026       if (!Init.isUsable()) {
4027         HasErrors = true;
4028         break;
4029       }
4030       ExprResult Update =
4031           BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
4032                              IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
4033       if (!Update.isUsable()) {
4034         HasErrors = true;
4035         break;
4036       }
4037
4038       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4039       ExprResult Final = BuildCounterUpdate(
4040           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
4041           IS.NumIterations, IS.CounterStep, IS.Subtract);
4042       if (!Final.isUsable()) {
4043         HasErrors = true;
4044         break;
4045       }
4046
4047       // Build Div for the next iteration: Div <- Div * IS.NumIters
4048       if (Cnt != 0) {
4049         if (Div.isUnset())
4050           Div = IS.NumIterations;
4051         else
4052           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4053                                    IS.NumIterations);
4054
4055         // Add parentheses (for debugging purposes only).
4056         if (Div.isUsable())
4057           Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
4058         if (!Div.isUsable()) {
4059           HasErrors = true;
4060           break;
4061         }
4062       }
4063       if (!Update.isUsable() || !Final.isUsable()) {
4064         HasErrors = true;
4065         break;
4066       }
4067       // Save results
4068       Built.Counters[Cnt] = IS.CounterVar;
4069       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
4070       Built.Inits[Cnt] = Init.get();
4071       Built.Updates[Cnt] = Update.get();
4072       Built.Finals[Cnt] = Final.get();
4073     }
4074   }
4075
4076   if (HasErrors)
4077     return 0;
4078
4079   // Save results
4080   Built.IterationVarRef = IV.get();
4081   Built.LastIteration = LastIteration.get();
4082   Built.NumIterations = NumIterations.get();
4083   Built.CalcLastIteration =
4084       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
4085   Built.PreCond = PreCond.get();
4086   Built.Cond = Cond.get();
4087   Built.Init = Init.get();
4088   Built.Inc = Inc.get();
4089   Built.LB = LB.get();
4090   Built.UB = UB.get();
4091   Built.IL = IL.get();
4092   Built.ST = ST.get();
4093   Built.EUB = EUB.get();
4094   Built.NLB = NextLB.get();
4095   Built.NUB = NextUB.get();
4096
4097   return NestedLoopCount;
4098 }
4099
4100 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
4101   auto CollapseClauses =
4102       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4103   if (CollapseClauses.begin() != CollapseClauses.end())
4104     return (*CollapseClauses.begin())->getNumForLoops();
4105   return nullptr;
4106 }
4107
4108 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
4109   auto OrderedClauses =
4110       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4111   if (OrderedClauses.begin() != OrderedClauses.end())
4112     return (*OrderedClauses.begin())->getNumForLoops();
4113   return nullptr;
4114 }
4115
4116 static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
4117                                       const Expr *Safelen) {
4118   llvm::APSInt SimdlenRes, SafelenRes;
4119   if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
4120       Simdlen->isInstantiationDependent() ||
4121       Simdlen->containsUnexpandedParameterPack())
4122     return false;
4123   if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
4124       Safelen->isInstantiationDependent() ||
4125       Safelen->containsUnexpandedParameterPack())
4126     return false;
4127   Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
4128   Safelen->EvaluateAsInt(SafelenRes, S.Context);
4129   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4130   // If both simdlen and safelen clauses are specified, the value of the simdlen
4131   // parameter must be less than or equal to the value of the safelen parameter.
4132   if (SimdlenRes > SafelenRes) {
4133     S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
4134         << Simdlen->getSourceRange() << Safelen->getSourceRange();
4135     return true;
4136   }
4137   return false;
4138 }
4139
4140 StmtResult Sema::ActOnOpenMPSimdDirective(
4141     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4142     SourceLocation EndLoc,
4143     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4144   if (!AStmt)
4145     return StmtError();
4146
4147   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4148   OMPLoopDirective::HelperExprs B;
4149   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4150   // define the nested loops number.
4151   unsigned NestedLoopCount = CheckOpenMPLoop(
4152       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4153       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4154   if (NestedLoopCount == 0)
4155     return StmtError();
4156
4157   assert((CurContext->isDependentContext() || B.builtAll()) &&
4158          "omp simd loop exprs were not built");
4159
4160   if (!CurContext->isDependentContext()) {
4161     // Finalize the clauses that need pre-built expressions for CodeGen.
4162     for (auto C : Clauses) {
4163       if (auto LC = dyn_cast<OMPLinearClause>(C))
4164         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4165                                      B.NumIterations, *this, CurScope))
4166           return StmtError();
4167     }
4168   }
4169
4170   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4171   // If both simdlen and safelen clauses are specified, the value of the simdlen
4172   // parameter must be less than or equal to the value of the safelen parameter.
4173   OMPSafelenClause *Safelen = nullptr;
4174   OMPSimdlenClause *Simdlen = nullptr;
4175   for (auto *Clause : Clauses) {
4176     if (Clause->getClauseKind() == OMPC_safelen)
4177       Safelen = cast<OMPSafelenClause>(Clause);
4178     else if (Clause->getClauseKind() == OMPC_simdlen)
4179       Simdlen = cast<OMPSimdlenClause>(Clause);
4180     if (Safelen && Simdlen)
4181       break;
4182   }
4183   if (Simdlen && Safelen &&
4184       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4185                                 Safelen->getSafelen()))
4186     return StmtError();
4187
4188   getCurFunction()->setHasBranchProtectedScope();
4189   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4190                                   Clauses, AStmt, B);
4191 }
4192
4193 StmtResult Sema::ActOnOpenMPForDirective(
4194     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4195     SourceLocation EndLoc,
4196     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4197   if (!AStmt)
4198     return StmtError();
4199
4200   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4201   OMPLoopDirective::HelperExprs B;
4202   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4203   // define the nested loops number.
4204   unsigned NestedLoopCount = CheckOpenMPLoop(
4205       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4206       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
4207   if (NestedLoopCount == 0)
4208     return StmtError();
4209
4210   assert((CurContext->isDependentContext() || B.builtAll()) &&
4211          "omp for loop exprs were not built");
4212
4213   if (!CurContext->isDependentContext()) {
4214     // Finalize the clauses that need pre-built expressions for CodeGen.
4215     for (auto C : Clauses) {
4216       if (auto LC = dyn_cast<OMPLinearClause>(C))
4217         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4218                                      B.NumIterations, *this, CurScope))
4219           return StmtError();
4220     }
4221   }
4222
4223   getCurFunction()->setHasBranchProtectedScope();
4224   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4225                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
4226 }
4227
4228 StmtResult Sema::ActOnOpenMPForSimdDirective(
4229     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4230     SourceLocation EndLoc,
4231     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4232   if (!AStmt)
4233     return StmtError();
4234
4235   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4236   OMPLoopDirective::HelperExprs B;
4237   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4238   // define the nested loops number.
4239   unsigned NestedLoopCount =
4240       CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4241                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4242                       VarsWithImplicitDSA, B);
4243   if (NestedLoopCount == 0)
4244     return StmtError();
4245
4246   assert((CurContext->isDependentContext() || B.builtAll()) &&
4247          "omp for simd loop exprs were not built");
4248
4249   if (!CurContext->isDependentContext()) {
4250     // Finalize the clauses that need pre-built expressions for CodeGen.
4251     for (auto C : Clauses) {
4252       if (auto LC = dyn_cast<OMPLinearClause>(C))
4253         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4254                                      B.NumIterations, *this, CurScope))
4255           return StmtError();
4256     }
4257   }
4258
4259   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4260   // If both simdlen and safelen clauses are specified, the value of the simdlen
4261   // parameter must be less than or equal to the value of the safelen parameter.
4262   OMPSafelenClause *Safelen = nullptr;
4263   OMPSimdlenClause *Simdlen = nullptr;
4264   for (auto *Clause : Clauses) {
4265     if (Clause->getClauseKind() == OMPC_safelen)
4266       Safelen = cast<OMPSafelenClause>(Clause);
4267     else if (Clause->getClauseKind() == OMPC_simdlen)
4268       Simdlen = cast<OMPSimdlenClause>(Clause);
4269     if (Safelen && Simdlen)
4270       break;
4271   }
4272   if (Simdlen && Safelen &&
4273       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4274                                 Safelen->getSafelen()))
4275     return StmtError();
4276
4277   getCurFunction()->setHasBranchProtectedScope();
4278   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4279                                      Clauses, AStmt, B);
4280 }
4281
4282 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4283                                               Stmt *AStmt,
4284                                               SourceLocation StartLoc,
4285                                               SourceLocation EndLoc) {
4286   if (!AStmt)
4287     return StmtError();
4288
4289   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4290   auto BaseStmt = AStmt;
4291   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4292     BaseStmt = CS->getCapturedStmt();
4293   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4294     auto S = C->children();
4295     if (S.begin() == S.end())
4296       return StmtError();
4297     // All associated statements must be '#pragma omp section' except for
4298     // the first one.
4299     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4300       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4301         if (SectionStmt)
4302           Diag(SectionStmt->getLocStart(),
4303                diag::err_omp_sections_substmt_not_section);
4304         return StmtError();
4305       }
4306       cast<OMPSectionDirective>(SectionStmt)
4307           ->setHasCancel(DSAStack->isCancelRegion());
4308     }
4309   } else {
4310     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4311     return StmtError();
4312   }
4313
4314   getCurFunction()->setHasBranchProtectedScope();
4315
4316   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4317                                       DSAStack->isCancelRegion());
4318 }
4319
4320 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4321                                              SourceLocation StartLoc,
4322                                              SourceLocation EndLoc) {
4323   if (!AStmt)
4324     return StmtError();
4325
4326   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4327
4328   getCurFunction()->setHasBranchProtectedScope();
4329   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
4330
4331   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4332                                      DSAStack->isCancelRegion());
4333 }
4334
4335 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4336                                             Stmt *AStmt,
4337                                             SourceLocation StartLoc,
4338                                             SourceLocation EndLoc) {
4339   if (!AStmt)
4340     return StmtError();
4341
4342   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4343
4344   getCurFunction()->setHasBranchProtectedScope();
4345
4346   // OpenMP [2.7.3, single Construct, Restrictions]
4347   // The copyprivate clause must not be used with the nowait clause.
4348   OMPClause *Nowait = nullptr;
4349   OMPClause *Copyprivate = nullptr;
4350   for (auto *Clause : Clauses) {
4351     if (Clause->getClauseKind() == OMPC_nowait)
4352       Nowait = Clause;
4353     else if (Clause->getClauseKind() == OMPC_copyprivate)
4354       Copyprivate = Clause;
4355     if (Copyprivate && Nowait) {
4356       Diag(Copyprivate->getLocStart(),
4357            diag::err_omp_single_copyprivate_with_nowait);
4358       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4359       return StmtError();
4360     }
4361   }
4362
4363   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4364 }
4365
4366 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4367                                             SourceLocation StartLoc,
4368                                             SourceLocation EndLoc) {
4369   if (!AStmt)
4370     return StmtError();
4371
4372   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4373
4374   getCurFunction()->setHasBranchProtectedScope();
4375
4376   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4377 }
4378
4379 StmtResult Sema::ActOnOpenMPCriticalDirective(
4380     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4381     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4382   if (!AStmt)
4383     return StmtError();
4384
4385   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4386
4387   bool ErrorFound = false;
4388   llvm::APSInt Hint;
4389   SourceLocation HintLoc;
4390   bool DependentHint = false;
4391   for (auto *C : Clauses) {
4392     if (C->getClauseKind() == OMPC_hint) {
4393       if (!DirName.getName()) {
4394         Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4395         ErrorFound = true;
4396       }
4397       Expr *E = cast<OMPHintClause>(C)->getHint();
4398       if (E->isTypeDependent() || E->isValueDependent() ||
4399           E->isInstantiationDependent())
4400         DependentHint = true;
4401       else {
4402         Hint = E->EvaluateKnownConstInt(Context);
4403         HintLoc = C->getLocStart();
4404       }
4405     }
4406   }
4407   if (ErrorFound)
4408     return StmtError();
4409   auto Pair = DSAStack->getCriticalWithHint(DirName);
4410   if (Pair.first && DirName.getName() && !DependentHint) {
4411     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4412       Diag(StartLoc, diag::err_omp_critical_with_hint);
4413       if (HintLoc.isValid()) {
4414         Diag(HintLoc, diag::note_omp_critical_hint_here)
4415             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4416       } else
4417         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4418       if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4419         Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4420             << 1
4421             << C->getHint()->EvaluateKnownConstInt(Context).toString(
4422                    /*Radix=*/10, /*Signed=*/false);
4423       } else
4424         Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4425     }
4426   }
4427
4428   getCurFunction()->setHasBranchProtectedScope();
4429
4430   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4431                                            Clauses, AStmt);
4432   if (!Pair.first && DirName.getName() && !DependentHint)
4433     DSAStack->addCriticalWithHint(Dir, Hint);
4434   return Dir;
4435 }
4436
4437 StmtResult Sema::ActOnOpenMPParallelForDirective(
4438     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4439     SourceLocation EndLoc,
4440     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4441   if (!AStmt)
4442     return StmtError();
4443
4444   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4445   // 1.2.2 OpenMP Language Terminology
4446   // Structured block - An executable statement with a single entry at the
4447   // top and a single exit at the bottom.
4448   // The point of exit cannot be a branch out of the structured block.
4449   // longjmp() and throw() must not violate the entry/exit criteria.
4450   CS->getCapturedDecl()->setNothrow();
4451
4452   OMPLoopDirective::HelperExprs B;
4453   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4454   // define the nested loops number.
4455   unsigned NestedLoopCount =
4456       CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4457                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4458                       VarsWithImplicitDSA, B);
4459   if (NestedLoopCount == 0)
4460     return StmtError();
4461
4462   assert((CurContext->isDependentContext() || B.builtAll()) &&
4463          "omp parallel for loop exprs were not built");
4464
4465   if (!CurContext->isDependentContext()) {
4466     // Finalize the clauses that need pre-built expressions for CodeGen.
4467     for (auto C : Clauses) {
4468       if (auto LC = dyn_cast<OMPLinearClause>(C))
4469         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4470                                      B.NumIterations, *this, CurScope))
4471           return StmtError();
4472     }
4473   }
4474
4475   getCurFunction()->setHasBranchProtectedScope();
4476   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
4477                                          NestedLoopCount, Clauses, AStmt, B,
4478                                          DSAStack->isCancelRegion());
4479 }
4480
4481 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4482     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4483     SourceLocation EndLoc,
4484     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
4485   if (!AStmt)
4486     return StmtError();
4487
4488   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4489   // 1.2.2 OpenMP Language Terminology
4490   // Structured block - An executable statement with a single entry at the
4491   // top and a single exit at the bottom.
4492   // The point of exit cannot be a branch out of the structured block.
4493   // longjmp() and throw() must not violate the entry/exit criteria.
4494   CS->getCapturedDecl()->setNothrow();
4495
4496   OMPLoopDirective::HelperExprs B;
4497   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4498   // define the nested loops number.
4499   unsigned NestedLoopCount =
4500       CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4501                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4502                       VarsWithImplicitDSA, B);
4503   if (NestedLoopCount == 0)
4504     return StmtError();
4505
4506   if (!CurContext->isDependentContext()) {
4507     // Finalize the clauses that need pre-built expressions for CodeGen.
4508     for (auto C : Clauses) {
4509       if (auto LC = dyn_cast<OMPLinearClause>(C))
4510         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
4511                                      B.NumIterations, *this, CurScope))
4512           return StmtError();
4513     }
4514   }
4515
4516   // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
4517   // If both simdlen and safelen clauses are specified, the value of the simdlen
4518   // parameter must be less than or equal to the value of the safelen parameter.
4519   OMPSafelenClause *Safelen = nullptr;
4520   OMPSimdlenClause *Simdlen = nullptr;
4521   for (auto *Clause : Clauses) {
4522     if (Clause->getClauseKind() == OMPC_safelen)
4523       Safelen = cast<OMPSafelenClause>(Clause);
4524     else if (Clause->getClauseKind() == OMPC_simdlen)
4525       Simdlen = cast<OMPSimdlenClause>(Clause);
4526     if (Safelen && Simdlen)
4527       break;
4528   }
4529   if (Simdlen && Safelen &&
4530       checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
4531                                 Safelen->getSafelen()))
4532     return StmtError();
4533
4534   getCurFunction()->setHasBranchProtectedScope();
4535   return OMPParallelForSimdDirective::Create(
4536       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
4537 }
4538
4539 StmtResult
4540 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4541                                            Stmt *AStmt, SourceLocation StartLoc,
4542                                            SourceLocation EndLoc) {
4543   if (!AStmt)
4544     return StmtError();
4545
4546   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4547   auto BaseStmt = AStmt;
4548   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
4549     BaseStmt = CS->getCapturedStmt();
4550   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
4551     auto S = C->children();
4552     if (S.begin() == S.end())
4553       return StmtError();
4554     // All associated statements must be '#pragma omp section' except for
4555     // the first one.
4556     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
4557       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4558         if (SectionStmt)
4559           Diag(SectionStmt->getLocStart(),
4560                diag::err_omp_parallel_sections_substmt_not_section);
4561         return StmtError();
4562       }
4563       cast<OMPSectionDirective>(SectionStmt)
4564           ->setHasCancel(DSAStack->isCancelRegion());
4565     }
4566   } else {
4567     Diag(AStmt->getLocStart(),
4568          diag::err_omp_parallel_sections_not_compound_stmt);
4569     return StmtError();
4570   }
4571
4572   getCurFunction()->setHasBranchProtectedScope();
4573
4574   return OMPParallelSectionsDirective::Create(
4575       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
4576 }
4577
4578 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4579                                           Stmt *AStmt, SourceLocation StartLoc,
4580                                           SourceLocation EndLoc) {
4581   if (!AStmt)
4582     return StmtError();
4583
4584   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4585   // 1.2.2 OpenMP Language Terminology
4586   // Structured block - An executable statement with a single entry at the
4587   // top and a single exit at the bottom.
4588   // The point of exit cannot be a branch out of the structured block.
4589   // longjmp() and throw() must not violate the entry/exit criteria.
4590   CS->getCapturedDecl()->setNothrow();
4591
4592   getCurFunction()->setHasBranchProtectedScope();
4593
4594   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4595                                   DSAStack->isCancelRegion());
4596 }
4597
4598 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4599                                                SourceLocation EndLoc) {
4600   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4601 }
4602
4603 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4604                                              SourceLocation EndLoc) {
4605   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4606 }
4607
4608 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4609                                               SourceLocation EndLoc) {
4610   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4611 }
4612
4613 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4614                                                SourceLocation StartLoc,
4615                                                SourceLocation EndLoc) {
4616   if (!AStmt)
4617     return StmtError();
4618
4619   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4620
4621   getCurFunction()->setHasBranchProtectedScope();
4622
4623   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4624 }
4625
4626 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4627                                            SourceLocation StartLoc,
4628                                            SourceLocation EndLoc) {
4629   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4630   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4631 }
4632
4633 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4634                                              Stmt *AStmt,
4635                                              SourceLocation StartLoc,
4636                                              SourceLocation EndLoc) {
4637   OMPClause *DependFound = nullptr;
4638   OMPClause *DependSourceClause = nullptr;
4639   OMPClause *DependSinkClause = nullptr;
4640   bool ErrorFound = false;
4641   OMPThreadsClause *TC = nullptr;
4642   OMPSIMDClause *SC = nullptr;
4643   for (auto *C : Clauses) {
4644     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4645       DependFound = C;
4646       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4647         if (DependSourceClause) {
4648           Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4649               << getOpenMPDirectiveName(OMPD_ordered)
4650               << getOpenMPClauseName(OMPC_depend) << 2;
4651           ErrorFound = true;
4652         } else
4653           DependSourceClause = C;
4654         if (DependSinkClause) {
4655           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4656               << 0;
4657           ErrorFound = true;
4658         }
4659       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4660         if (DependSourceClause) {
4661           Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4662               << 1;
4663           ErrorFound = true;
4664         }
4665         DependSinkClause = C;
4666       }
4667     } else if (C->getClauseKind() == OMPC_threads)
4668       TC = cast<OMPThreadsClause>(C);
4669     else if (C->getClauseKind() == OMPC_simd)
4670       SC = cast<OMPSIMDClause>(C);
4671   }
4672   if (!ErrorFound && !SC &&
4673       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
4674     // OpenMP [2.8.1,simd Construct, Restrictions]
4675     // An ordered construct with the simd clause is the only OpenMP construct
4676     // that can appear in the simd region.
4677     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
4678     ErrorFound = true;
4679   } else if (DependFound && (TC || SC)) {
4680     Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4681         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4682     ErrorFound = true;
4683   } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4684     Diag(DependFound->getLocStart(),
4685          diag::err_omp_ordered_directive_without_param);
4686     ErrorFound = true;
4687   } else if (TC || Clauses.empty()) {
4688     if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4689       SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4690       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4691           << (TC != nullptr);
4692       Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4693       ErrorFound = true;
4694     }
4695   }
4696   if ((!AStmt && !DependFound) || ErrorFound)
4697     return StmtError();
4698
4699   if (AStmt) {
4700     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4701
4702     getCurFunction()->setHasBranchProtectedScope();
4703   }
4704
4705   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4706 }
4707
4708 namespace {
4709 /// \brief Helper class for checking expression in 'omp atomic [update]'
4710 /// construct.
4711 class OpenMPAtomicUpdateChecker {
4712   /// \brief Error results for atomic update expressions.
4713   enum ExprAnalysisErrorCode {
4714     /// \brief A statement is not an expression statement.
4715     NotAnExpression,
4716     /// \brief Expression is not builtin binary or unary operation.
4717     NotABinaryOrUnaryExpression,
4718     /// \brief Unary operation is not post-/pre- increment/decrement operation.
4719     NotAnUnaryIncDecExpression,
4720     /// \brief An expression is not of scalar type.
4721     NotAScalarType,
4722     /// \brief A binary operation is not an assignment operation.
4723     NotAnAssignmentOp,
4724     /// \brief RHS part of the binary operation is not a binary expression.
4725     NotABinaryExpression,
4726     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4727     /// expression.
4728     NotABinaryOperator,
4729     /// \brief RHS binary operation does not have reference to the updated LHS
4730     /// part.
4731     NotAnUpdateExpression,
4732     /// \brief No errors is found.
4733     NoError
4734   };
4735   /// \brief Reference to Sema.
4736   Sema &SemaRef;
4737   /// \brief A location for note diagnostics (when error is found).
4738   SourceLocation NoteLoc;
4739   /// \brief 'x' lvalue part of the source atomic expression.
4740   Expr *X;
4741   /// \brief 'expr' rvalue part of the source atomic expression.
4742   Expr *E;
4743   /// \brief Helper expression of the form
4744   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4745   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4746   Expr *UpdateExpr;
4747   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4748   /// important for non-associative operations.
4749   bool IsXLHSInRHSPart;
4750   BinaryOperatorKind Op;
4751   SourceLocation OpLoc;
4752   /// \brief true if the source expression is a postfix unary operation, false
4753   /// if it is a prefix unary operation.
4754   bool IsPostfixUpdate;
4755
4756 public:
4757   OpenMPAtomicUpdateChecker(Sema &SemaRef)
4758       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
4759         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
4760   /// \brief Check specified statement that it is suitable for 'atomic update'
4761   /// constructs and extract 'x', 'expr' and Operation from the original
4762   /// expression. If DiagId and NoteId == 0, then only check is performed
4763   /// without error notification.
4764   /// \param DiagId Diagnostic which should be emitted if error is found.
4765   /// \param NoteId Diagnostic note for the main error message.
4766   /// \return true if statement is not an update expression, false otherwise.
4767   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
4768   /// \brief Return the 'x' lvalue part of the source atomic expression.
4769   Expr *getX() const { return X; }
4770   /// \brief Return the 'expr' rvalue part of the source atomic expression.
4771   Expr *getExpr() const { return E; }
4772   /// \brief Return the update expression used in calculation of the updated
4773   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4774   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4775   Expr *getUpdateExpr() const { return UpdateExpr; }
4776   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
4777   /// false otherwise.
4778   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
4779
4780   /// \brief true if the source expression is a postfix unary operation, false
4781   /// if it is a prefix unary operation.
4782   bool isPostfixUpdate() const { return IsPostfixUpdate; }
4783
4784 private:
4785   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
4786                             unsigned NoteId = 0);
4787 };
4788 } // namespace
4789
4790 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
4791     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
4792   ExprAnalysisErrorCode ErrorFound = NoError;
4793   SourceLocation ErrorLoc, NoteLoc;
4794   SourceRange ErrorRange, NoteRange;
4795   // Allowed constructs are:
4796   //  x = x binop expr;
4797   //  x = expr binop x;
4798   if (AtomicBinOp->getOpcode() == BO_Assign) {
4799     X = AtomicBinOp->getLHS();
4800     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
4801             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
4802       if (AtomicInnerBinOp->isMultiplicativeOp() ||
4803           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
4804           AtomicInnerBinOp->isBitwiseOp()) {
4805         Op = AtomicInnerBinOp->getOpcode();
4806         OpLoc = AtomicInnerBinOp->getOperatorLoc();
4807         auto *LHS = AtomicInnerBinOp->getLHS();
4808         auto *RHS = AtomicInnerBinOp->getRHS();
4809         llvm::FoldingSetNodeID XId, LHSId, RHSId;
4810         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
4811                                           /*Canonical=*/true);
4812         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
4813                                             /*Canonical=*/true);
4814         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
4815                                             /*Canonical=*/true);
4816         if (XId == LHSId) {
4817           E = RHS;
4818           IsXLHSInRHSPart = true;
4819         } else if (XId == RHSId) {
4820           E = LHS;
4821           IsXLHSInRHSPart = false;
4822         } else {
4823           ErrorLoc = AtomicInnerBinOp->getExprLoc();
4824           ErrorRange = AtomicInnerBinOp->getSourceRange();
4825           NoteLoc = X->getExprLoc();
4826           NoteRange = X->getSourceRange();
4827           ErrorFound = NotAnUpdateExpression;
4828         }
4829       } else {
4830         ErrorLoc = AtomicInnerBinOp->getExprLoc();
4831         ErrorRange = AtomicInnerBinOp->getSourceRange();
4832         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
4833         NoteRange = SourceRange(NoteLoc, NoteLoc);
4834         ErrorFound = NotABinaryOperator;
4835       }
4836     } else {
4837       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
4838       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
4839       ErrorFound = NotABinaryExpression;
4840     }
4841   } else {
4842     ErrorLoc = AtomicBinOp->getExprLoc();
4843     ErrorRange = AtomicBinOp->getSourceRange();
4844     NoteLoc = AtomicBinOp->getOperatorLoc();
4845     NoteRange = SourceRange(NoteLoc, NoteLoc);
4846     ErrorFound = NotAnAssignmentOp;
4847   }
4848   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4849     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4850     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4851     return true;
4852   } else if (SemaRef.CurContext->isDependentContext())
4853     E = X = UpdateExpr = nullptr;
4854   return ErrorFound != NoError;
4855 }
4856
4857 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
4858                                                unsigned NoteId) {
4859   ExprAnalysisErrorCode ErrorFound = NoError;
4860   SourceLocation ErrorLoc, NoteLoc;
4861   SourceRange ErrorRange, NoteRange;
4862   // Allowed constructs are:
4863   //  x++;
4864   //  x--;
4865   //  ++x;
4866   //  --x;
4867   //  x binop= expr;
4868   //  x = x binop expr;
4869   //  x = expr binop x;
4870   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
4871     AtomicBody = AtomicBody->IgnoreParenImpCasts();
4872     if (AtomicBody->getType()->isScalarType() ||
4873         AtomicBody->isInstantiationDependent()) {
4874       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
4875               AtomicBody->IgnoreParenImpCasts())) {
4876         // Check for Compound Assignment Operation
4877         Op = BinaryOperator::getOpForCompoundAssignment(
4878             AtomicCompAssignOp->getOpcode());
4879         OpLoc = AtomicCompAssignOp->getOperatorLoc();
4880         E = AtomicCompAssignOp->getRHS();
4881         X = AtomicCompAssignOp->getLHS();
4882         IsXLHSInRHSPart = true;
4883       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
4884                      AtomicBody->IgnoreParenImpCasts())) {
4885         // Check for Binary Operation
4886         if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
4887           return true;
4888       } else if (auto *AtomicUnaryOp =
4889                  dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
4890         // Check for Unary Operation
4891         if (AtomicUnaryOp->isIncrementDecrementOp()) {
4892           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
4893           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
4894           OpLoc = AtomicUnaryOp->getOperatorLoc();
4895           X = AtomicUnaryOp->getSubExpr();
4896           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
4897           IsXLHSInRHSPart = true;
4898         } else {
4899           ErrorFound = NotAnUnaryIncDecExpression;
4900           ErrorLoc = AtomicUnaryOp->getExprLoc();
4901           ErrorRange = AtomicUnaryOp->getSourceRange();
4902           NoteLoc = AtomicUnaryOp->getOperatorLoc();
4903           NoteRange = SourceRange(NoteLoc, NoteLoc);
4904         }
4905       } else if (!AtomicBody->isInstantiationDependent()) {
4906         ErrorFound = NotABinaryOrUnaryExpression;
4907         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
4908         NoteRange = ErrorRange = AtomicBody->getSourceRange();
4909       }
4910     } else {
4911       ErrorFound = NotAScalarType;
4912       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
4913       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4914     }
4915   } else {
4916     ErrorFound = NotAnExpression;
4917     NoteLoc = ErrorLoc = S->getLocStart();
4918     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4919   }
4920   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
4921     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
4922     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
4923     return true;
4924   } else if (SemaRef.CurContext->isDependentContext())
4925     E = X = UpdateExpr = nullptr;
4926   if (ErrorFound == NoError && E && X) {
4927     // Build an update expression of form 'OpaqueValueExpr(x) binop
4928     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
4929     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
4930     auto *OVEX = new (SemaRef.getASTContext())
4931         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
4932     auto *OVEExpr = new (SemaRef.getASTContext())
4933         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
4934     auto Update =
4935         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
4936                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
4937     if (Update.isInvalid())
4938       return true;
4939     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
4940                                                Sema::AA_Casting);
4941     if (Update.isInvalid())
4942       return true;
4943     UpdateExpr = Update.get();
4944   }
4945   return ErrorFound != NoError;
4946 }
4947
4948 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
4949                                             Stmt *AStmt,
4950                                             SourceLocation StartLoc,
4951                                             SourceLocation EndLoc) {
4952   if (!AStmt)
4953     return StmtError();
4954
4955   auto CS = cast<CapturedStmt>(AStmt);
4956   // 1.2.2 OpenMP Language Terminology
4957   // Structured block - An executable statement with a single entry at the
4958   // top and a single exit at the bottom.
4959   // The point of exit cannot be a branch out of the structured block.
4960   // longjmp() and throw() must not violate the entry/exit criteria.
4961   OpenMPClauseKind AtomicKind = OMPC_unknown;
4962   SourceLocation AtomicKindLoc;
4963   for (auto *C : Clauses) {
4964     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
4965         C->getClauseKind() == OMPC_update ||
4966         C->getClauseKind() == OMPC_capture) {
4967       if (AtomicKind != OMPC_unknown) {
4968         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
4969             << SourceRange(C->getLocStart(), C->getLocEnd());
4970         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
4971             << getOpenMPClauseName(AtomicKind);
4972       } else {
4973         AtomicKind = C->getClauseKind();
4974         AtomicKindLoc = C->getLocStart();
4975       }
4976     }
4977   }
4978
4979   auto Body = CS->getCapturedStmt();
4980   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
4981     Body = EWC->getSubExpr();
4982
4983   Expr *X = nullptr;
4984   Expr *V = nullptr;
4985   Expr *E = nullptr;
4986   Expr *UE = nullptr;
4987   bool IsXLHSInRHSPart = false;
4988   bool IsPostfixUpdate = false;
4989   // OpenMP [2.12.6, atomic Construct]
4990   // In the next expressions:
4991   // * x and v (as applicable) are both l-value expressions with scalar type.
4992   // * During the execution of an atomic region, multiple syntactic
4993   // occurrences of x must designate the same storage location.
4994   // * Neither of v and expr (as applicable) may access the storage location
4995   // designated by x.
4996   // * Neither of x and expr (as applicable) may access the storage location
4997   // designated by v.
4998   // * expr is an expression with scalar type.
4999   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5000   // * binop, binop=, ++, and -- are not overloaded operators.
5001   // * The expression x binop expr must be numerically equivalent to x binop
5002   // (expr). This requirement is satisfied if the operators in expr have
5003   // precedence greater than binop, or by using parentheses around expr or
5004   // subexpressions of expr.
5005   // * The expression expr binop x must be numerically equivalent to (expr)
5006   // binop x. This requirement is satisfied if the operators in expr have
5007   // precedence equal to or greater than binop, or by using parentheses around
5008   // expr or subexpressions of expr.
5009   // * For forms that allow multiple occurrences of x, the number of times
5010   // that x is evaluated is unspecified.
5011   if (AtomicKind == OMPC_read) {
5012     enum {
5013       NotAnExpression,
5014       NotAnAssignmentOp,
5015       NotAScalarType,
5016       NotAnLValue,
5017       NoError
5018     } ErrorFound = NoError;
5019     SourceLocation ErrorLoc, NoteLoc;
5020     SourceRange ErrorRange, NoteRange;
5021     // If clause is read:
5022     //  v = x;
5023     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5024       auto AtomicBinOp =
5025           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5026       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5027         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5028         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5029         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5030             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5031           if (!X->isLValue() || !V->isLValue()) {
5032             auto NotLValueExpr = X->isLValue() ? V : X;
5033             ErrorFound = NotAnLValue;
5034             ErrorLoc = AtomicBinOp->getExprLoc();
5035             ErrorRange = AtomicBinOp->getSourceRange();
5036             NoteLoc = NotLValueExpr->getExprLoc();
5037             NoteRange = NotLValueExpr->getSourceRange();
5038           }
5039         } else if (!X->isInstantiationDependent() ||
5040                    !V->isInstantiationDependent()) {
5041           auto NotScalarExpr =
5042               (X->isInstantiationDependent() || X->getType()->isScalarType())
5043                   ? V
5044                   : X;
5045           ErrorFound = NotAScalarType;
5046           ErrorLoc = AtomicBinOp->getExprLoc();
5047           ErrorRange = AtomicBinOp->getSourceRange();
5048           NoteLoc = NotScalarExpr->getExprLoc();
5049           NoteRange = NotScalarExpr->getSourceRange();
5050         }
5051       } else if (!AtomicBody->isInstantiationDependent()) {
5052         ErrorFound = NotAnAssignmentOp;
5053         ErrorLoc = AtomicBody->getExprLoc();
5054         ErrorRange = AtomicBody->getSourceRange();
5055         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5056                               : AtomicBody->getExprLoc();
5057         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5058                                 : AtomicBody->getSourceRange();
5059       }
5060     } else {
5061       ErrorFound = NotAnExpression;
5062       NoteLoc = ErrorLoc = Body->getLocStart();
5063       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5064     }
5065     if (ErrorFound != NoError) {
5066       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5067           << ErrorRange;
5068       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5069                                                       << NoteRange;
5070       return StmtError();
5071     } else if (CurContext->isDependentContext())
5072       V = X = nullptr;
5073   } else if (AtomicKind == OMPC_write) {
5074     enum {
5075       NotAnExpression,
5076       NotAnAssignmentOp,
5077       NotAScalarType,
5078       NotAnLValue,
5079       NoError
5080     } ErrorFound = NoError;
5081     SourceLocation ErrorLoc, NoteLoc;
5082     SourceRange ErrorRange, NoteRange;
5083     // If clause is write:
5084     //  x = expr;
5085     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
5086       auto AtomicBinOp =
5087           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5088       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5089         X = AtomicBinOp->getLHS();
5090         E = AtomicBinOp->getRHS();
5091         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5092             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5093           if (!X->isLValue()) {
5094             ErrorFound = NotAnLValue;
5095             ErrorLoc = AtomicBinOp->getExprLoc();
5096             ErrorRange = AtomicBinOp->getSourceRange();
5097             NoteLoc = X->getExprLoc();
5098             NoteRange = X->getSourceRange();
5099           }
5100         } else if (!X->isInstantiationDependent() ||
5101                    !E->isInstantiationDependent()) {
5102           auto NotScalarExpr =
5103               (X->isInstantiationDependent() || X->getType()->isScalarType())
5104                   ? E
5105                   : X;
5106           ErrorFound = NotAScalarType;
5107           ErrorLoc = AtomicBinOp->getExprLoc();
5108           ErrorRange = AtomicBinOp->getSourceRange();
5109           NoteLoc = NotScalarExpr->getExprLoc();
5110           NoteRange = NotScalarExpr->getSourceRange();
5111         }
5112       } else if (!AtomicBody->isInstantiationDependent()) {
5113         ErrorFound = NotAnAssignmentOp;
5114         ErrorLoc = AtomicBody->getExprLoc();
5115         ErrorRange = AtomicBody->getSourceRange();
5116         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5117                               : AtomicBody->getExprLoc();
5118         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5119                                 : AtomicBody->getSourceRange();
5120       }
5121     } else {
5122       ErrorFound = NotAnExpression;
5123       NoteLoc = ErrorLoc = Body->getLocStart();
5124       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5125     }
5126     if (ErrorFound != NoError) {
5127       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5128           << ErrorRange;
5129       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5130                                                       << NoteRange;
5131       return StmtError();
5132     } else if (CurContext->isDependentContext())
5133       E = X = nullptr;
5134   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
5135     // If clause is update:
5136     //  x++;
5137     //  x--;
5138     //  ++x;
5139     //  --x;
5140     //  x binop= expr;
5141     //  x = x binop expr;
5142     //  x = expr binop x;
5143     OpenMPAtomicUpdateChecker Checker(*this);
5144     if (Checker.checkStatement(
5145             Body, (AtomicKind == OMPC_update)
5146                       ? diag::err_omp_atomic_update_not_expression_statement
5147                       : diag::err_omp_atomic_not_expression_statement,
5148             diag::note_omp_atomic_update))
5149       return StmtError();
5150     if (!CurContext->isDependentContext()) {
5151       E = Checker.getExpr();
5152       X = Checker.getX();
5153       UE = Checker.getUpdateExpr();
5154       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5155     }
5156   } else if (AtomicKind == OMPC_capture) {
5157     enum {
5158       NotAnAssignmentOp,
5159       NotACompoundStatement,
5160       NotTwoSubstatements,
5161       NotASpecificExpression,
5162       NoError
5163     } ErrorFound = NoError;
5164     SourceLocation ErrorLoc, NoteLoc;
5165     SourceRange ErrorRange, NoteRange;
5166     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5167       // If clause is a capture:
5168       //  v = x++;
5169       //  v = x--;
5170       //  v = ++x;
5171       //  v = --x;
5172       //  v = x binop= expr;
5173       //  v = x = x binop expr;
5174       //  v = x = expr binop x;
5175       auto *AtomicBinOp =
5176           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5177       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5178         V = AtomicBinOp->getLHS();
5179         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5180         OpenMPAtomicUpdateChecker Checker(*this);
5181         if (Checker.checkStatement(
5182                 Body, diag::err_omp_atomic_capture_not_expression_statement,
5183                 diag::note_omp_atomic_update))
5184           return StmtError();
5185         E = Checker.getExpr();
5186         X = Checker.getX();
5187         UE = Checker.getUpdateExpr();
5188         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5189         IsPostfixUpdate = Checker.isPostfixUpdate();
5190       } else if (!AtomicBody->isInstantiationDependent()) {
5191         ErrorLoc = AtomicBody->getExprLoc();
5192         ErrorRange = AtomicBody->getSourceRange();
5193         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5194                               : AtomicBody->getExprLoc();
5195         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5196                                 : AtomicBody->getSourceRange();
5197         ErrorFound = NotAnAssignmentOp;
5198       }
5199       if (ErrorFound != NoError) {
5200         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5201             << ErrorRange;
5202         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5203         return StmtError();
5204       } else if (CurContext->isDependentContext()) {
5205         UE = V = E = X = nullptr;
5206       }
5207     } else {
5208       // If clause is a capture:
5209       //  { v = x; x = expr; }
5210       //  { v = x; x++; }
5211       //  { v = x; x--; }
5212       //  { v = x; ++x; }
5213       //  { v = x; --x; }
5214       //  { v = x; x binop= expr; }
5215       //  { v = x; x = x binop expr; }
5216       //  { v = x; x = expr binop x; }
5217       //  { x++; v = x; }
5218       //  { x--; v = x; }
5219       //  { ++x; v = x; }
5220       //  { --x; v = x; }
5221       //  { x binop= expr; v = x; }
5222       //  { x = x binop expr; v = x; }
5223       //  { x = expr binop x; v = x; }
5224       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5225         // Check that this is { expr1; expr2; }
5226         if (CS->size() == 2) {
5227           auto *First = CS->body_front();
5228           auto *Second = CS->body_back();
5229           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5230             First = EWC->getSubExpr()->IgnoreParenImpCasts();
5231           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5232             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5233           // Need to find what subexpression is 'v' and what is 'x'.
5234           OpenMPAtomicUpdateChecker Checker(*this);
5235           bool IsUpdateExprFound = !Checker.checkStatement(Second);
5236           BinaryOperator *BinOp = nullptr;
5237           if (IsUpdateExprFound) {
5238             BinOp = dyn_cast<BinaryOperator>(First);
5239             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5240           }
5241           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5242             //  { v = x; x++; }
5243             //  { v = x; x--; }
5244             //  { v = x; ++x; }
5245             //  { v = x; --x; }
5246             //  { v = x; x binop= expr; }
5247             //  { v = x; x = x binop expr; }
5248             //  { v = x; x = expr binop x; }
5249             // Check that the first expression has form v = x.
5250             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5251             llvm::FoldingSetNodeID XId, PossibleXId;
5252             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5253             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5254             IsUpdateExprFound = XId == PossibleXId;
5255             if (IsUpdateExprFound) {
5256               V = BinOp->getLHS();
5257               X = Checker.getX();
5258               E = Checker.getExpr();
5259               UE = Checker.getUpdateExpr();
5260               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5261               IsPostfixUpdate = true;
5262             }
5263           }
5264           if (!IsUpdateExprFound) {
5265             IsUpdateExprFound = !Checker.checkStatement(First);
5266             BinOp = nullptr;
5267             if (IsUpdateExprFound) {
5268               BinOp = dyn_cast<BinaryOperator>(Second);
5269               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5270             }
5271             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5272               //  { x++; v = x; }
5273               //  { x--; v = x; }
5274               //  { ++x; v = x; }
5275               //  { --x; v = x; }
5276               //  { x binop= expr; v = x; }
5277               //  { x = x binop expr; v = x; }
5278               //  { x = expr binop x; v = x; }
5279               // Check that the second expression has form v = x.
5280               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5281               llvm::FoldingSetNodeID XId, PossibleXId;
5282               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5283               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5284               IsUpdateExprFound = XId == PossibleXId;
5285               if (IsUpdateExprFound) {
5286                 V = BinOp->getLHS();
5287                 X = Checker.getX();
5288                 E = Checker.getExpr();
5289                 UE = Checker.getUpdateExpr();
5290                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5291                 IsPostfixUpdate = false;
5292               }
5293             }
5294           }
5295           if (!IsUpdateExprFound) {
5296             //  { v = x; x = expr; }
5297             auto *FirstExpr = dyn_cast<Expr>(First);
5298             auto *SecondExpr = dyn_cast<Expr>(Second);
5299             if (!FirstExpr || !SecondExpr ||
5300                 !(FirstExpr->isInstantiationDependent() ||
5301                   SecondExpr->isInstantiationDependent())) {
5302               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5303               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
5304                 ErrorFound = NotAnAssignmentOp;
5305                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5306                                                 : First->getLocStart();
5307                 NoteRange = ErrorRange = FirstBinOp
5308                                              ? FirstBinOp->getSourceRange()
5309                                              : SourceRange(ErrorLoc, ErrorLoc);
5310               } else {
5311                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5312                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5313                   ErrorFound = NotAnAssignmentOp;
5314                   NoteLoc = ErrorLoc = SecondBinOp
5315                                            ? SecondBinOp->getOperatorLoc()
5316                                            : Second->getLocStart();
5317                   NoteRange = ErrorRange =
5318                       SecondBinOp ? SecondBinOp->getSourceRange()
5319                                   : SourceRange(ErrorLoc, ErrorLoc);
5320                 } else {
5321                   auto *PossibleXRHSInFirst =
5322                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
5323                   auto *PossibleXLHSInSecond =
5324                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
5325                   llvm::FoldingSetNodeID X1Id, X2Id;
5326                   PossibleXRHSInFirst->Profile(X1Id, Context,
5327                                                /*Canonical=*/true);
5328                   PossibleXLHSInSecond->Profile(X2Id, Context,
5329                                                 /*Canonical=*/true);
5330                   IsUpdateExprFound = X1Id == X2Id;
5331                   if (IsUpdateExprFound) {
5332                     V = FirstBinOp->getLHS();
5333                     X = SecondBinOp->getLHS();
5334                     E = SecondBinOp->getRHS();
5335                     UE = nullptr;
5336                     IsXLHSInRHSPart = false;
5337                     IsPostfixUpdate = true;
5338                   } else {
5339                     ErrorFound = NotASpecificExpression;
5340                     ErrorLoc = FirstBinOp->getExprLoc();
5341                     ErrorRange = FirstBinOp->getSourceRange();
5342                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5343                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
5344                   }
5345                 }
5346               }
5347             }
5348           }
5349         } else {
5350           NoteLoc = ErrorLoc = Body->getLocStart();
5351           NoteRange = ErrorRange =
5352               SourceRange(Body->getLocStart(), Body->getLocStart());
5353           ErrorFound = NotTwoSubstatements;
5354         }
5355       } else {
5356         NoteLoc = ErrorLoc = Body->getLocStart();
5357         NoteRange = ErrorRange =
5358             SourceRange(Body->getLocStart(), Body->getLocStart());
5359         ErrorFound = NotACompoundStatement;
5360       }
5361       if (ErrorFound != NoError) {
5362         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5363             << ErrorRange;
5364         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5365         return StmtError();
5366       } else if (CurContext->isDependentContext()) {
5367         UE = V = E = X = nullptr;
5368       }
5369     }
5370   }
5371
5372   getCurFunction()->setHasBranchProtectedScope();
5373
5374   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5375                                     X, V, E, UE, IsXLHSInRHSPart,
5376                                     IsPostfixUpdate);
5377 }
5378
5379 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5380                                             Stmt *AStmt,
5381                                             SourceLocation StartLoc,
5382                                             SourceLocation EndLoc) {
5383   if (!AStmt)
5384     return StmtError();
5385
5386   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5387   // 1.2.2 OpenMP Language Terminology
5388   // Structured block - An executable statement with a single entry at the
5389   // top and a single exit at the bottom.
5390   // The point of exit cannot be a branch out of the structured block.
5391   // longjmp() and throw() must not violate the entry/exit criteria.
5392   CS->getCapturedDecl()->setNothrow();
5393
5394   // OpenMP [2.16, Nesting of Regions]
5395   // If specified, a teams construct must be contained within a target
5396   // construct. That target construct must contain no statements or directives
5397   // outside of the teams construct.
5398   if (DSAStack->hasInnerTeamsRegion()) {
5399     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5400     bool OMPTeamsFound = true;
5401     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5402       auto I = CS->body_begin();
5403       while (I != CS->body_end()) {
5404         auto OED = dyn_cast<OMPExecutableDirective>(*I);
5405         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5406           OMPTeamsFound = false;
5407           break;
5408         }
5409         ++I;
5410       }
5411       assert(I != CS->body_end() && "Not found statement");
5412       S = *I;
5413     }
5414     if (!OMPTeamsFound) {
5415       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5416       Diag(DSAStack->getInnerTeamsRegionLoc(),
5417            diag::note_omp_nested_teams_construct_here);
5418       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5419           << isa<OMPExecutableDirective>(S);
5420       return StmtError();
5421     }
5422   }
5423
5424   getCurFunction()->setHasBranchProtectedScope();
5425
5426   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5427 }
5428
5429 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5430                                                 Stmt *AStmt,
5431                                                 SourceLocation StartLoc,
5432                                                 SourceLocation EndLoc) {
5433   if (!AStmt)
5434     return StmtError();
5435
5436   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5437
5438   getCurFunction()->setHasBranchProtectedScope();
5439
5440   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5441                                         AStmt);
5442 }
5443
5444 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5445                                            Stmt *AStmt, SourceLocation StartLoc,
5446                                            SourceLocation EndLoc) {
5447   if (!AStmt)
5448     return StmtError();
5449
5450   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5451   // 1.2.2 OpenMP Language Terminology
5452   // Structured block - An executable statement with a single entry at the
5453   // top and a single exit at the bottom.
5454   // The point of exit cannot be a branch out of the structured block.
5455   // longjmp() and throw() must not violate the entry/exit criteria.
5456   CS->getCapturedDecl()->setNothrow();
5457
5458   getCurFunction()->setHasBranchProtectedScope();
5459
5460   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5461 }
5462
5463 StmtResult
5464 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5465                                             SourceLocation EndLoc,
5466                                             OpenMPDirectiveKind CancelRegion) {
5467   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5468       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5469     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5470         << getOpenMPDirectiveName(CancelRegion);
5471     return StmtError();
5472   }
5473   if (DSAStack->isParentNowaitRegion()) {
5474     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5475     return StmtError();
5476   }
5477   if (DSAStack->isParentOrderedRegion()) {
5478     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5479     return StmtError();
5480   }
5481   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5482                                                CancelRegion);
5483 }
5484
5485 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5486                                             SourceLocation StartLoc,
5487                                             SourceLocation EndLoc,
5488                                             OpenMPDirectiveKind CancelRegion) {
5489   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5490       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5491     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5492         << getOpenMPDirectiveName(CancelRegion);
5493     return StmtError();
5494   }
5495   if (DSAStack->isParentNowaitRegion()) {
5496     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5497     return StmtError();
5498   }
5499   if (DSAStack->isParentOrderedRegion()) {
5500     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5501     return StmtError();
5502   }
5503   DSAStack->setParentCancelRegion(/*Cancel=*/true);
5504   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5505                                     CancelRegion);
5506 }
5507
5508 static bool checkGrainsizeNumTasksClauses(Sema &S,
5509                                           ArrayRef<OMPClause *> Clauses) {
5510   OMPClause *PrevClause = nullptr;
5511   bool ErrorFound = false;
5512   for (auto *C : Clauses) {
5513     if (C->getClauseKind() == OMPC_grainsize ||
5514         C->getClauseKind() == OMPC_num_tasks) {
5515       if (!PrevClause)
5516         PrevClause = C;
5517       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5518         S.Diag(C->getLocStart(),
5519                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5520             << getOpenMPClauseName(C->getClauseKind())
5521             << getOpenMPClauseName(PrevClause->getClauseKind());
5522         S.Diag(PrevClause->getLocStart(),
5523                diag::note_omp_previous_grainsize_num_tasks)
5524             << getOpenMPClauseName(PrevClause->getClauseKind());
5525         ErrorFound = true;
5526       }
5527     }
5528   }
5529   return ErrorFound;
5530 }
5531
5532 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5533     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5534     SourceLocation EndLoc,
5535     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5536   if (!AStmt)
5537     return StmtError();
5538
5539   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5540   OMPLoopDirective::HelperExprs B;
5541   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5542   // define the nested loops number.
5543   unsigned NestedLoopCount =
5544       CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
5545                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5546                       VarsWithImplicitDSA, B);
5547   if (NestedLoopCount == 0)
5548     return StmtError();
5549
5550   assert((CurContext->isDependentContext() || B.builtAll()) &&
5551          "omp for loop exprs were not built");
5552
5553   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5554   // The grainsize clause and num_tasks clause are mutually exclusive and may
5555   // not appear on the same taskloop directive.
5556   if (checkGrainsizeNumTasksClauses(*this, Clauses))
5557     return StmtError();
5558
5559   getCurFunction()->setHasBranchProtectedScope();
5560   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5561                                       NestedLoopCount, Clauses, AStmt, B);
5562 }
5563
5564 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5565     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5566     SourceLocation EndLoc,
5567     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5568   if (!AStmt)
5569     return StmtError();
5570
5571   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5572   OMPLoopDirective::HelperExprs B;
5573   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5574   // define the nested loops number.
5575   unsigned NestedLoopCount =
5576       CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5577                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5578                       VarsWithImplicitDSA, B);
5579   if (NestedLoopCount == 0)
5580     return StmtError();
5581
5582   assert((CurContext->isDependentContext() || B.builtAll()) &&
5583          "omp for loop exprs were not built");
5584
5585   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5586   // The grainsize clause and num_tasks clause are mutually exclusive and may
5587   // not appear on the same taskloop directive.
5588   if (checkGrainsizeNumTasksClauses(*this, Clauses))
5589     return StmtError();
5590
5591   getCurFunction()->setHasBranchProtectedScope();
5592   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5593                                           NestedLoopCount, Clauses, AStmt, B);
5594 }
5595
5596 StmtResult Sema::ActOnOpenMPDistributeDirective(
5597     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5598     SourceLocation EndLoc,
5599     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
5600   if (!AStmt)
5601     return StmtError();
5602
5603   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5604   OMPLoopDirective::HelperExprs B;
5605   // In presence of clause 'collapse' with number of loops, it will
5606   // define the nested loops number.
5607   unsigned NestedLoopCount =
5608       CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5609                       nullptr /*ordered not a clause on distribute*/, AStmt,
5610                       *this, *DSAStack, VarsWithImplicitDSA, B);
5611   if (NestedLoopCount == 0)
5612     return StmtError();
5613
5614   assert((CurContext->isDependentContext() || B.builtAll()) &&
5615          "omp for loop exprs were not built");
5616
5617   getCurFunction()->setHasBranchProtectedScope();
5618   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5619                                         NestedLoopCount, Clauses, AStmt, B);
5620 }
5621
5622 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
5623                                              SourceLocation StartLoc,
5624                                              SourceLocation LParenLoc,
5625                                              SourceLocation EndLoc) {
5626   OMPClause *Res = nullptr;
5627   switch (Kind) {
5628   case OMPC_final:
5629     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
5630     break;
5631   case OMPC_num_threads:
5632     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
5633     break;
5634   case OMPC_safelen:
5635     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
5636     break;
5637   case OMPC_simdlen:
5638     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
5639     break;
5640   case OMPC_collapse:
5641     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
5642     break;
5643   case OMPC_ordered:
5644     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
5645     break;
5646   case OMPC_device:
5647     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
5648     break;
5649   case OMPC_num_teams:
5650     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
5651     break;
5652   case OMPC_thread_limit:
5653     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
5654     break;
5655   case OMPC_priority:
5656     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
5657     break;
5658   case OMPC_grainsize:
5659     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
5660     break;
5661   case OMPC_num_tasks:
5662     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
5663     break;
5664   case OMPC_hint:
5665     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
5666     break;
5667   case OMPC_if:
5668   case OMPC_default:
5669   case OMPC_proc_bind:
5670   case OMPC_schedule:
5671   case OMPC_private:
5672   case OMPC_firstprivate:
5673   case OMPC_lastprivate:
5674   case OMPC_shared:
5675   case OMPC_reduction:
5676   case OMPC_linear:
5677   case OMPC_aligned:
5678   case OMPC_copyin:
5679   case OMPC_copyprivate:
5680   case OMPC_nowait:
5681   case OMPC_untied:
5682   case OMPC_mergeable:
5683   case OMPC_threadprivate:
5684   case OMPC_flush:
5685   case OMPC_read:
5686   case OMPC_write:
5687   case OMPC_update:
5688   case OMPC_capture:
5689   case OMPC_seq_cst:
5690   case OMPC_depend:
5691   case OMPC_threads:
5692   case OMPC_simd:
5693   case OMPC_map:
5694   case OMPC_nogroup:
5695   case OMPC_unknown:
5696     llvm_unreachable("Clause is not allowed.");
5697   }
5698   return Res;
5699 }
5700
5701 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
5702                                      Expr *Condition, SourceLocation StartLoc,
5703                                      SourceLocation LParenLoc,
5704                                      SourceLocation NameModifierLoc,
5705                                      SourceLocation ColonLoc,
5706                                      SourceLocation EndLoc) {
5707   Expr *ValExpr = Condition;
5708   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5709       !Condition->isInstantiationDependent() &&
5710       !Condition->containsUnexpandedParameterPack()) {
5711     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5712                                            Condition->getExprLoc(), Condition);
5713     if (Val.isInvalid())
5714       return nullptr;
5715
5716     ValExpr = Val.get();
5717   }
5718
5719   return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
5720                                    NameModifierLoc, ColonLoc, EndLoc);
5721 }
5722
5723 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
5724                                         SourceLocation StartLoc,
5725                                         SourceLocation LParenLoc,
5726                                         SourceLocation EndLoc) {
5727   Expr *ValExpr = Condition;
5728   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
5729       !Condition->isInstantiationDependent() &&
5730       !Condition->containsUnexpandedParameterPack()) {
5731     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
5732                                            Condition->getExprLoc(), Condition);
5733     if (Val.isInvalid())
5734       return nullptr;
5735
5736     ValExpr = Val.get();
5737   }
5738
5739   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5740 }
5741 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
5742                                                         Expr *Op) {
5743   if (!Op)
5744     return ExprError();
5745
5746   class IntConvertDiagnoser : public ICEConvertDiagnoser {
5747   public:
5748     IntConvertDiagnoser()
5749         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
5750     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
5751                                          QualType T) override {
5752       return S.Diag(Loc, diag::err_omp_not_integral) << T;
5753     }
5754     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
5755                                              QualType T) override {
5756       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
5757     }
5758     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
5759                                                QualType T,
5760                                                QualType ConvTy) override {
5761       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
5762     }
5763     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
5764                                            QualType ConvTy) override {
5765       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
5766              << ConvTy->isEnumeralType() << ConvTy;
5767     }
5768     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
5769                                             QualType T) override {
5770       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
5771     }
5772     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
5773                                         QualType ConvTy) override {
5774       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
5775              << ConvTy->isEnumeralType() << ConvTy;
5776     }
5777     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
5778                                              QualType) override {
5779       llvm_unreachable("conversion functions are permitted");
5780     }
5781   } ConvertDiagnoser;
5782   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
5783 }
5784
5785 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
5786                                       OpenMPClauseKind CKind,
5787                                       bool StrictlyPositive) {
5788   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
5789       !ValExpr->isInstantiationDependent()) {
5790     SourceLocation Loc = ValExpr->getExprLoc();
5791     ExprResult Value =
5792         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
5793     if (Value.isInvalid())
5794       return false;
5795
5796     ValExpr = Value.get();
5797     // The expression must evaluate to a non-negative integer value.
5798     llvm::APSInt Result;
5799     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
5800         Result.isSigned() &&
5801         !((!StrictlyPositive && Result.isNonNegative()) ||
5802           (StrictlyPositive && Result.isStrictlyPositive()))) {
5803       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
5804           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
5805           << ValExpr->getSourceRange();
5806       return false;
5807     }
5808   }
5809   return true;
5810 }
5811
5812 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
5813                                              SourceLocation StartLoc,
5814                                              SourceLocation LParenLoc,
5815                                              SourceLocation EndLoc) {
5816   Expr *ValExpr = NumThreads;
5817
5818   // OpenMP [2.5, Restrictions]
5819   //  The num_threads expression must evaluate to a positive integer value.
5820   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
5821                                  /*StrictlyPositive=*/true))
5822     return nullptr;
5823
5824   return new (Context)
5825       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
5826 }
5827
5828 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
5829                                                        OpenMPClauseKind CKind,
5830                                                        bool StrictlyPositive) {
5831   if (!E)
5832     return ExprError();
5833   if (E->isValueDependent() || E->isTypeDependent() ||
5834       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5835     return E;
5836   llvm::APSInt Result;
5837   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
5838   if (ICE.isInvalid())
5839     return ExprError();
5840   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
5841       (!StrictlyPositive && !Result.isNonNegative())) {
5842     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
5843         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
5844         << E->getSourceRange();
5845     return ExprError();
5846   }
5847   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
5848     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
5849         << E->getSourceRange();
5850     return ExprError();
5851   }
5852   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
5853     DSAStack->setAssociatedLoops(Result.getExtValue());
5854   else if (CKind == OMPC_ordered)
5855     DSAStack->setAssociatedLoops(Result.getExtValue());
5856   return ICE;
5857 }
5858
5859 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
5860                                           SourceLocation LParenLoc,
5861                                           SourceLocation EndLoc) {
5862   // OpenMP [2.8.1, simd construct, Description]
5863   // The parameter of the safelen clause must be a constant
5864   // positive integer expression.
5865   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
5866   if (Safelen.isInvalid())
5867     return nullptr;
5868   return new (Context)
5869       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
5870 }
5871
5872 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
5873                                           SourceLocation LParenLoc,
5874                                           SourceLocation EndLoc) {
5875   // OpenMP [2.8.1, simd construct, Description]
5876   // The parameter of the simdlen clause must be a constant
5877   // positive integer expression.
5878   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
5879   if (Simdlen.isInvalid())
5880     return nullptr;
5881   return new (Context)
5882       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
5883 }
5884
5885 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
5886                                            SourceLocation StartLoc,
5887                                            SourceLocation LParenLoc,
5888                                            SourceLocation EndLoc) {
5889   // OpenMP [2.7.1, loop construct, Description]
5890   // OpenMP [2.8.1, simd construct, Description]
5891   // OpenMP [2.9.6, distribute construct, Description]
5892   // The parameter of the collapse clause must be a constant
5893   // positive integer expression.
5894   ExprResult NumForLoopsResult =
5895       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
5896   if (NumForLoopsResult.isInvalid())
5897     return nullptr;
5898   return new (Context)
5899       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
5900 }
5901
5902 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
5903                                           SourceLocation EndLoc,
5904                                           SourceLocation LParenLoc,
5905                                           Expr *NumForLoops) {
5906   // OpenMP [2.7.1, loop construct, Description]
5907   // OpenMP [2.8.1, simd construct, Description]
5908   // OpenMP [2.9.6, distribute construct, Description]
5909   // The parameter of the ordered clause must be a constant
5910   // positive integer expression if any.
5911   if (NumForLoops && LParenLoc.isValid()) {
5912     ExprResult NumForLoopsResult =
5913         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
5914     if (NumForLoopsResult.isInvalid())
5915       return nullptr;
5916     NumForLoops = NumForLoopsResult.get();
5917   } else
5918     NumForLoops = nullptr;
5919   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
5920   return new (Context)
5921       OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
5922 }
5923
5924 OMPClause *Sema::ActOnOpenMPSimpleClause(
5925     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
5926     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
5927   OMPClause *Res = nullptr;
5928   switch (Kind) {
5929   case OMPC_default:
5930     Res =
5931         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
5932                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
5933     break;
5934   case OMPC_proc_bind:
5935     Res = ActOnOpenMPProcBindClause(
5936         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
5937         LParenLoc, EndLoc);
5938     break;
5939   case OMPC_if:
5940   case OMPC_final:
5941   case OMPC_num_threads:
5942   case OMPC_safelen:
5943   case OMPC_simdlen:
5944   case OMPC_collapse:
5945   case OMPC_schedule:
5946   case OMPC_private:
5947   case OMPC_firstprivate:
5948   case OMPC_lastprivate:
5949   case OMPC_shared:
5950   case OMPC_reduction:
5951   case OMPC_linear:
5952   case OMPC_aligned:
5953   case OMPC_copyin:
5954   case OMPC_copyprivate:
5955   case OMPC_ordered:
5956   case OMPC_nowait:
5957   case OMPC_untied:
5958   case OMPC_mergeable:
5959   case OMPC_threadprivate:
5960   case OMPC_flush:
5961   case OMPC_read:
5962   case OMPC_write:
5963   case OMPC_update:
5964   case OMPC_capture:
5965   case OMPC_seq_cst:
5966   case OMPC_depend:
5967   case OMPC_device:
5968   case OMPC_threads:
5969   case OMPC_simd:
5970   case OMPC_map:
5971   case OMPC_num_teams:
5972   case OMPC_thread_limit:
5973   case OMPC_priority:
5974   case OMPC_grainsize:
5975   case OMPC_nogroup:
5976   case OMPC_num_tasks:
5977   case OMPC_hint:
5978   case OMPC_unknown:
5979     llvm_unreachable("Clause is not allowed.");
5980   }
5981   return Res;
5982 }
5983
5984 static std::string
5985 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
5986                         ArrayRef<unsigned> Exclude = llvm::None) {
5987   std::string Values;
5988   unsigned Bound = Last >= 2 ? Last - 2 : 0;
5989   unsigned Skipped = Exclude.size();
5990   auto S = Exclude.begin(), E = Exclude.end();
5991   for (unsigned i = First; i < Last; ++i) {
5992     if (std::find(S, E, i) != E) {
5993       --Skipped;
5994       continue;
5995     }
5996     Values += "'";
5997     Values += getOpenMPSimpleClauseTypeName(K, i);
5998     Values += "'";
5999     if (i == Bound - Skipped)
6000       Values += " or ";
6001     else if (i != Bound + 1 - Skipped)
6002       Values += ", ";
6003   }
6004   return Values;
6005 }
6006
6007 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
6008                                           SourceLocation KindKwLoc,
6009                                           SourceLocation StartLoc,
6010                                           SourceLocation LParenLoc,
6011                                           SourceLocation EndLoc) {
6012   if (Kind == OMPC_DEFAULT_unknown) {
6013     static_assert(OMPC_DEFAULT_unknown > 0,
6014                   "OMPC_DEFAULT_unknown not greater than 0");
6015     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6016         << getListOfPossibleValues(OMPC_default, /*First=*/0,
6017                                    /*Last=*/OMPC_DEFAULT_unknown)
6018         << getOpenMPClauseName(OMPC_default);
6019     return nullptr;
6020   }
6021   switch (Kind) {
6022   case OMPC_DEFAULT_none:
6023     DSAStack->setDefaultDSANone(KindKwLoc);
6024     break;
6025   case OMPC_DEFAULT_shared:
6026     DSAStack->setDefaultDSAShared(KindKwLoc);
6027     break;
6028   case OMPC_DEFAULT_unknown:
6029     llvm_unreachable("Clause kind is not allowed.");
6030     break;
6031   }
6032   return new (Context)
6033       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6034 }
6035
6036 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
6037                                            SourceLocation KindKwLoc,
6038                                            SourceLocation StartLoc,
6039                                            SourceLocation LParenLoc,
6040                                            SourceLocation EndLoc) {
6041   if (Kind == OMPC_PROC_BIND_unknown) {
6042     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
6043         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
6044                                    /*Last=*/OMPC_PROC_BIND_unknown)
6045         << getOpenMPClauseName(OMPC_proc_bind);
6046     return nullptr;
6047   }
6048   return new (Context)
6049       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
6050 }
6051
6052 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
6053     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
6054     SourceLocation StartLoc, SourceLocation LParenLoc,
6055     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
6056     SourceLocation EndLoc) {
6057   OMPClause *Res = nullptr;
6058   switch (Kind) {
6059   case OMPC_schedule:
6060     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
6061     assert(Argument.size() == NumberOfElements &&
6062            ArgumentLoc.size() == NumberOfElements);
6063     Res = ActOnOpenMPScheduleClause(
6064         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
6065         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
6066         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
6067         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
6068         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
6069     break;
6070   case OMPC_if:
6071     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
6072     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
6073                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
6074                               DelimLoc, EndLoc);
6075     break;
6076   case OMPC_final:
6077   case OMPC_num_threads:
6078   case OMPC_safelen:
6079   case OMPC_simdlen:
6080   case OMPC_collapse:
6081   case OMPC_default:
6082   case OMPC_proc_bind:
6083   case OMPC_private:
6084   case OMPC_firstprivate:
6085   case OMPC_lastprivate:
6086   case OMPC_shared:
6087   case OMPC_reduction:
6088   case OMPC_linear:
6089   case OMPC_aligned:
6090   case OMPC_copyin:
6091   case OMPC_copyprivate:
6092   case OMPC_ordered:
6093   case OMPC_nowait:
6094   case OMPC_untied:
6095   case OMPC_mergeable:
6096   case OMPC_threadprivate:
6097   case OMPC_flush:
6098   case OMPC_read:
6099   case OMPC_write:
6100   case OMPC_update:
6101   case OMPC_capture:
6102   case OMPC_seq_cst:
6103   case OMPC_depend:
6104   case OMPC_device:
6105   case OMPC_threads:
6106   case OMPC_simd:
6107   case OMPC_map:
6108   case OMPC_num_teams:
6109   case OMPC_thread_limit:
6110   case OMPC_priority:
6111   case OMPC_grainsize:
6112   case OMPC_nogroup:
6113   case OMPC_num_tasks:
6114   case OMPC_hint:
6115   case OMPC_unknown:
6116     llvm_unreachable("Clause is not allowed.");
6117   }
6118   return Res;
6119 }
6120
6121 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
6122                                    OpenMPScheduleClauseModifier M2,
6123                                    SourceLocation M1Loc, SourceLocation M2Loc) {
6124   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
6125     SmallVector<unsigned, 2> Excluded;
6126     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
6127       Excluded.push_back(M2);
6128     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
6129       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
6130     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
6131       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
6132     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
6133         << getListOfPossibleValues(OMPC_schedule,
6134                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
6135                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6136                                    Excluded)
6137         << getOpenMPClauseName(OMPC_schedule);
6138     return true;
6139   }
6140   return false;
6141 }
6142
6143 OMPClause *Sema::ActOnOpenMPScheduleClause(
6144     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
6145     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
6146     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
6147     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
6148   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
6149       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
6150     return nullptr;
6151   // OpenMP, 2.7.1, Loop Construct, Restrictions
6152   // Either the monotonic modifier or the nonmonotonic modifier can be specified
6153   // but not both.
6154   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
6155       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
6156        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
6157       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
6158        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
6159     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
6160         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
6161         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
6162     return nullptr;
6163   }
6164   if (Kind == OMPC_SCHEDULE_unknown) {
6165     std::string Values;
6166     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
6167       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
6168       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6169                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
6170                                        Exclude);
6171     } else {
6172       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
6173                                        /*Last=*/OMPC_SCHEDULE_unknown);
6174     }
6175     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
6176         << Values << getOpenMPClauseName(OMPC_schedule);
6177     return nullptr;
6178   }
6179   // OpenMP, 2.7.1, Loop Construct, Restrictions
6180   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
6181   // schedule(guided).
6182   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
6183        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
6184       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
6185     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
6186          diag::err_omp_schedule_nonmonotonic_static);
6187     return nullptr;
6188   }
6189   Expr *ValExpr = ChunkSize;
6190   Expr *HelperValExpr = nullptr;
6191   if (ChunkSize) {
6192     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
6193         !ChunkSize->isInstantiationDependent() &&
6194         !ChunkSize->containsUnexpandedParameterPack()) {
6195       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
6196       ExprResult Val =
6197           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
6198       if (Val.isInvalid())
6199         return nullptr;
6200
6201       ValExpr = Val.get();
6202
6203       // OpenMP [2.7.1, Restrictions]
6204       //  chunk_size must be a loop invariant integer expression with a positive
6205       //  value.
6206       llvm::APSInt Result;
6207       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
6208         if (Result.isSigned() && !Result.isStrictlyPositive()) {
6209           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
6210               << "schedule" << 1 << ChunkSize->getSourceRange();
6211           return nullptr;
6212         }
6213       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
6214         auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
6215                                     ChunkSize->getType(), ".chunk.");
6216         auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
6217                                            ChunkSize->getExprLoc(),
6218                                            /*RefersToCapture=*/true);
6219         HelperValExpr = ImpVarRef;
6220       }
6221     }
6222   }
6223
6224   return new (Context)
6225       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
6226                         ValExpr, HelperValExpr, M1, M1Loc, M2, M2Loc);
6227 }
6228
6229 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
6230                                    SourceLocation StartLoc,
6231                                    SourceLocation EndLoc) {
6232   OMPClause *Res = nullptr;
6233   switch (Kind) {
6234   case OMPC_ordered:
6235     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
6236     break;
6237   case OMPC_nowait:
6238     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
6239     break;
6240   case OMPC_untied:
6241     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
6242     break;
6243   case OMPC_mergeable:
6244     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
6245     break;
6246   case OMPC_read:
6247     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
6248     break;
6249   case OMPC_write:
6250     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
6251     break;
6252   case OMPC_update:
6253     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
6254     break;
6255   case OMPC_capture:
6256     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
6257     break;
6258   case OMPC_seq_cst:
6259     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
6260     break;
6261   case OMPC_threads:
6262     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
6263     break;
6264   case OMPC_simd:
6265     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
6266     break;
6267   case OMPC_nogroup:
6268     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
6269     break;
6270   case OMPC_if:
6271   case OMPC_final:
6272   case OMPC_num_threads:
6273   case OMPC_safelen:
6274   case OMPC_simdlen:
6275   case OMPC_collapse:
6276   case OMPC_schedule:
6277   case OMPC_private:
6278   case OMPC_firstprivate:
6279   case OMPC_lastprivate:
6280   case OMPC_shared:
6281   case OMPC_reduction:
6282   case OMPC_linear:
6283   case OMPC_aligned:
6284   case OMPC_copyin:
6285   case OMPC_copyprivate:
6286   case OMPC_default:
6287   case OMPC_proc_bind:
6288   case OMPC_threadprivate:
6289   case OMPC_flush:
6290   case OMPC_depend:
6291   case OMPC_device:
6292   case OMPC_map:
6293   case OMPC_num_teams:
6294   case OMPC_thread_limit:
6295   case OMPC_priority:
6296   case OMPC_grainsize:
6297   case OMPC_num_tasks:
6298   case OMPC_hint:
6299   case OMPC_unknown:
6300     llvm_unreachable("Clause is not allowed.");
6301   }
6302   return Res;
6303 }
6304
6305 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
6306                                          SourceLocation EndLoc) {
6307   DSAStack->setNowaitRegion();
6308   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
6309 }
6310
6311 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
6312                                          SourceLocation EndLoc) {
6313   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
6314 }
6315
6316 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
6317                                             SourceLocation EndLoc) {
6318   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
6319 }
6320
6321 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
6322                                        SourceLocation EndLoc) {
6323   return new (Context) OMPReadClause(StartLoc, EndLoc);
6324 }
6325
6326 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
6327                                         SourceLocation EndLoc) {
6328   return new (Context) OMPWriteClause(StartLoc, EndLoc);
6329 }
6330
6331 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
6332                                          SourceLocation EndLoc) {
6333   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
6334 }
6335
6336 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
6337                                           SourceLocation EndLoc) {
6338   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
6339 }
6340
6341 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
6342                                          SourceLocation EndLoc) {
6343   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
6344 }
6345
6346 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
6347                                           SourceLocation EndLoc) {
6348   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
6349 }
6350
6351 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
6352                                        SourceLocation EndLoc) {
6353   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
6354 }
6355
6356 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
6357                                           SourceLocation EndLoc) {
6358   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
6359 }
6360
6361 OMPClause *Sema::ActOnOpenMPVarListClause(
6362     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
6363     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
6364     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
6365     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
6366     OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 
6367     OpenMPMapClauseKind MapType, SourceLocation DepLinMapLoc) {
6368   OMPClause *Res = nullptr;
6369   switch (Kind) {
6370   case OMPC_private:
6371     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6372     break;
6373   case OMPC_firstprivate:
6374     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6375     break;
6376   case OMPC_lastprivate:
6377     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6378     break;
6379   case OMPC_shared:
6380     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
6381     break;
6382   case OMPC_reduction:
6383     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
6384                                      EndLoc, ReductionIdScopeSpec, ReductionId);
6385     break;
6386   case OMPC_linear:
6387     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
6388                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
6389     break;
6390   case OMPC_aligned:
6391     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
6392                                    ColonLoc, EndLoc);
6393     break;
6394   case OMPC_copyin:
6395     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
6396     break;
6397   case OMPC_copyprivate:
6398     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
6399     break;
6400   case OMPC_flush:
6401     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
6402     break;
6403   case OMPC_depend:
6404     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 
6405                                   StartLoc, LParenLoc, EndLoc);
6406     break;
6407   case OMPC_map:
6408     Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, DepLinMapLoc, ColonLoc,
6409                                VarList, StartLoc, LParenLoc, EndLoc);
6410     break;
6411   case OMPC_if:
6412   case OMPC_final:
6413   case OMPC_num_threads:
6414   case OMPC_safelen:
6415   case OMPC_simdlen:
6416   case OMPC_collapse:
6417   case OMPC_default:
6418   case OMPC_proc_bind:
6419   case OMPC_schedule:
6420   case OMPC_ordered:
6421   case OMPC_nowait:
6422   case OMPC_untied:
6423   case OMPC_mergeable:
6424   case OMPC_threadprivate:
6425   case OMPC_read:
6426   case OMPC_write:
6427   case OMPC_update:
6428   case OMPC_capture:
6429   case OMPC_seq_cst:
6430   case OMPC_device:
6431   case OMPC_threads:
6432   case OMPC_simd:
6433   case OMPC_num_teams:
6434   case OMPC_thread_limit:
6435   case OMPC_priority:
6436   case OMPC_grainsize:
6437   case OMPC_nogroup:
6438   case OMPC_num_tasks:
6439   case OMPC_hint:
6440   case OMPC_unknown:
6441     llvm_unreachable("Clause is not allowed.");
6442   }
6443   return Res;
6444 }
6445
6446 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
6447                                           SourceLocation StartLoc,
6448                                           SourceLocation LParenLoc,
6449                                           SourceLocation EndLoc) {
6450   SmallVector<Expr *, 8> Vars;
6451   SmallVector<Expr *, 8> PrivateCopies;
6452   for (auto &RefExpr : VarList) {
6453     assert(RefExpr && "NULL expr in OpenMP private clause.");
6454     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6455       // It will be analyzed later.
6456       Vars.push_back(RefExpr);
6457       PrivateCopies.push_back(nullptr);
6458       continue;
6459     }
6460
6461     SourceLocation ELoc = RefExpr->getExprLoc();
6462     // OpenMP [2.1, C/C++]
6463     //  A list item is a variable name.
6464     // OpenMP  [2.9.3.3, Restrictions, p.1]
6465     //  A variable that is part of another variable (as an array or
6466     //  structure element) cannot appear in a private clause.
6467     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6468     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6469       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6470       continue;
6471     }
6472     Decl *D = DE->getDecl();
6473     VarDecl *VD = cast<VarDecl>(D);
6474
6475     QualType Type = VD->getType();
6476     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6477       // It will be analyzed later.
6478       Vars.push_back(DE);
6479       PrivateCopies.push_back(nullptr);
6480       continue;
6481     }
6482
6483     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6484     //  A variable that appears in a private clause must not have an incomplete
6485     //  type or a reference type.
6486     if (RequireCompleteType(ELoc, Type,
6487                             diag::err_omp_private_incomplete_type)) {
6488       continue;
6489     }
6490     Type = Type.getNonReferenceType();
6491
6492     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6493     // in a Construct]
6494     //  Variables with the predetermined data-sharing attributes may not be
6495     //  listed in data-sharing attributes clauses, except for the cases
6496     //  listed below. For these exceptions only, listing a predetermined
6497     //  variable in a data-sharing attribute clause is allowed and overrides
6498     //  the variable's predetermined data-sharing attributes.
6499     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6500     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
6501       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6502                                           << getOpenMPClauseName(OMPC_private);
6503       ReportOriginalDSA(*this, DSAStack, VD, DVar);
6504       continue;
6505     }
6506
6507     // Variably modified types are not supported for tasks.
6508     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
6509         DSAStack->getCurrentDirective() == OMPD_task) {
6510       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6511           << getOpenMPClauseName(OMPC_private) << Type
6512           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6513       bool IsDecl =
6514           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6515       Diag(VD->getLocation(),
6516            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6517           << VD;
6518       continue;
6519     }
6520
6521     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
6522     //  A variable of class type (or array thereof) that appears in a private
6523     //  clause requires an accessible, unambiguous default constructor for the
6524     //  class type.
6525     // Generate helper private variable and initialize it with the default
6526     // value. The address of the original variable is replaced by the address of
6527     // the new private variable in CodeGen. This new variable is not added to
6528     // IdResolver, so the code in the OpenMP region uses original variable for
6529     // proper diagnostics.
6530     Type = Type.getUnqualifiedType();
6531     auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName(),
6532                                   VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6533     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
6534     if (VDPrivate->isInvalidDecl())
6535       continue;
6536     auto VDPrivateRefExpr = buildDeclRefExpr(
6537         *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6538
6539     DSAStack->addDSA(VD, DE, OMPC_private);
6540     Vars.push_back(DE);
6541     PrivateCopies.push_back(VDPrivateRefExpr);
6542   }
6543
6544   if (Vars.empty())
6545     return nullptr;
6546
6547   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6548                                   PrivateCopies);
6549 }
6550
6551 namespace {
6552 class DiagsUninitializedSeveretyRAII {
6553 private:
6554   DiagnosticsEngine &Diags;
6555   SourceLocation SavedLoc;
6556   bool IsIgnored;
6557
6558 public:
6559   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
6560                                  bool IsIgnored)
6561       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
6562     if (!IsIgnored) {
6563       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
6564                         /*Map*/ diag::Severity::Ignored, Loc);
6565     }
6566   }
6567   ~DiagsUninitializedSeveretyRAII() {
6568     if (!IsIgnored)
6569       Diags.popMappings(SavedLoc);
6570   }
6571 };
6572 }
6573
6574 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
6575                                                SourceLocation StartLoc,
6576                                                SourceLocation LParenLoc,
6577                                                SourceLocation EndLoc) {
6578   SmallVector<Expr *, 8> Vars;
6579   SmallVector<Expr *, 8> PrivateCopies;
6580   SmallVector<Expr *, 8> Inits;
6581   bool IsImplicitClause =
6582       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
6583   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
6584
6585   for (auto &RefExpr : VarList) {
6586     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
6587     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6588       // It will be analyzed later.
6589       Vars.push_back(RefExpr);
6590       PrivateCopies.push_back(nullptr);
6591       Inits.push_back(nullptr);
6592       continue;
6593     }
6594
6595     SourceLocation ELoc =
6596         IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
6597     // OpenMP [2.1, C/C++]
6598     //  A list item is a variable name.
6599     // OpenMP  [2.9.3.3, Restrictions, p.1]
6600     //  A variable that is part of another variable (as an array or
6601     //  structure element) cannot appear in a private clause.
6602     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6603     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6604       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6605       continue;
6606     }
6607     Decl *D = DE->getDecl();
6608     VarDecl *VD = cast<VarDecl>(D);
6609
6610     QualType Type = VD->getType();
6611     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6612       // It will be analyzed later.
6613       Vars.push_back(DE);
6614       PrivateCopies.push_back(nullptr);
6615       Inits.push_back(nullptr);
6616       continue;
6617     }
6618
6619     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
6620     //  A variable that appears in a private clause must not have an incomplete
6621     //  type or a reference type.
6622     if (RequireCompleteType(ELoc, Type,
6623                             diag::err_omp_firstprivate_incomplete_type)) {
6624       continue;
6625     }
6626     Type = Type.getNonReferenceType();
6627
6628     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
6629     //  A variable of class type (or array thereof) that appears in a private
6630     //  clause requires an accessible, unambiguous copy constructor for the
6631     //  class type.
6632     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6633
6634     // If an implicit firstprivate variable found it was checked already.
6635     if (!IsImplicitClause) {
6636       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6637       bool IsConstant = ElemType.isConstant(Context);
6638       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
6639       //  A list item that specifies a given variable may not appear in more
6640       // than one clause on the same directive, except that a variable may be
6641       //  specified in both firstprivate and lastprivate clauses.
6642       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
6643           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
6644         Diag(ELoc, diag::err_omp_wrong_dsa)
6645             << getOpenMPClauseName(DVar.CKind)
6646             << getOpenMPClauseName(OMPC_firstprivate);
6647         ReportOriginalDSA(*this, DSAStack, VD, DVar);
6648         continue;
6649       }
6650
6651       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6652       // in a Construct]
6653       //  Variables with the predetermined data-sharing attributes may not be
6654       //  listed in data-sharing attributes clauses, except for the cases
6655       //  listed below. For these exceptions only, listing a predetermined
6656       //  variable in a data-sharing attribute clause is allowed and overrides
6657       //  the variable's predetermined data-sharing attributes.
6658       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
6659       // in a Construct, C/C++, p.2]
6660       //  Variables with const-qualified type having no mutable member may be
6661       //  listed in a firstprivate clause, even if they are static data members.
6662       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
6663           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
6664         Diag(ELoc, diag::err_omp_wrong_dsa)
6665             << getOpenMPClauseName(DVar.CKind)
6666             << getOpenMPClauseName(OMPC_firstprivate);
6667         ReportOriginalDSA(*this, DSAStack, VD, DVar);
6668         continue;
6669       }
6670
6671       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6672       // OpenMP [2.9.3.4, Restrictions, p.2]
6673       //  A list item that is private within a parallel region must not appear
6674       //  in a firstprivate clause on a worksharing construct if any of the
6675       //  worksharing regions arising from the worksharing construct ever bind
6676       //  to any of the parallel regions arising from the parallel construct.
6677       if (isOpenMPWorksharingDirective(CurrDir) &&
6678           !isOpenMPParallelDirective(CurrDir)) {
6679         DVar = DSAStack->getImplicitDSA(VD, true);
6680         if (DVar.CKind != OMPC_shared &&
6681             (isOpenMPParallelDirective(DVar.DKind) ||
6682              DVar.DKind == OMPD_unknown)) {
6683           Diag(ELoc, diag::err_omp_required_access)
6684               << getOpenMPClauseName(OMPC_firstprivate)
6685               << getOpenMPClauseName(OMPC_shared);
6686           ReportOriginalDSA(*this, DSAStack, VD, DVar);
6687           continue;
6688         }
6689       }
6690       // OpenMP [2.9.3.4, Restrictions, p.3]
6691       //  A list item that appears in a reduction clause of a parallel construct
6692       //  must not appear in a firstprivate clause on a worksharing or task
6693       //  construct if any of the worksharing or task regions arising from the
6694       //  worksharing or task construct ever bind to any of the parallel regions
6695       //  arising from the parallel construct.
6696       // OpenMP [2.9.3.4, Restrictions, p.4]
6697       //  A list item that appears in a reduction clause in worksharing
6698       //  construct must not appear in a firstprivate clause in a task construct
6699       //  encountered during execution of any of the worksharing regions arising
6700       //  from the worksharing construct.
6701       if (CurrDir == OMPD_task) {
6702         DVar =
6703             DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6704                                       [](OpenMPDirectiveKind K) -> bool {
6705                                         return isOpenMPParallelDirective(K) ||
6706                                                isOpenMPWorksharingDirective(K);
6707                                       },
6708                                       false);
6709         if (DVar.CKind == OMPC_reduction &&
6710             (isOpenMPParallelDirective(DVar.DKind) ||
6711              isOpenMPWorksharingDirective(DVar.DKind))) {
6712           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
6713               << getOpenMPDirectiveName(DVar.DKind);
6714           ReportOriginalDSA(*this, DSAStack, VD, DVar);
6715           continue;
6716         }
6717       }
6718
6719       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
6720       // A list item that is private within a teams region must not appear in a
6721       // firstprivate clause on a distribute construct if any of the distribute
6722       // regions arising from the distribute construct ever bind to any of the
6723       // teams regions arising from the teams construct.
6724       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
6725       // A list item that appears in a reduction clause of a teams construct
6726       // must not appear in a firstprivate clause on a distribute construct if
6727       // any of the distribute regions arising from the distribute construct
6728       // ever bind to any of the teams regions arising from the teams construct.
6729       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
6730       // A list item may appear in a firstprivate or lastprivate clause but not
6731       // both.
6732       if (CurrDir == OMPD_distribute) {
6733         DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_private),
6734                                          [](OpenMPDirectiveKind K) -> bool {
6735                                            return isOpenMPTeamsDirective(K);
6736                                          },
6737                                          false);
6738         if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
6739           Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
6740           ReportOriginalDSA(*this, DSAStack, VD, DVar);
6741           continue;
6742         }
6743         DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
6744                                          [](OpenMPDirectiveKind K) -> bool {
6745                                            return isOpenMPTeamsDirective(K);
6746                                          },
6747                                          false);
6748         if (DVar.CKind == OMPC_reduction &&
6749             isOpenMPTeamsDirective(DVar.DKind)) {
6750           Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
6751           ReportOriginalDSA(*this, DSAStack, VD, DVar);
6752           continue;
6753         }
6754         DVar = DSAStack->getTopDSA(VD, false);
6755         if (DVar.CKind == OMPC_lastprivate) {
6756           Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
6757           ReportOriginalDSA(*this, DSAStack, VD, DVar);
6758           continue;
6759         }
6760       }
6761     }
6762
6763     // Variably modified types are not supported for tasks.
6764     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
6765         DSAStack->getCurrentDirective() == OMPD_task) {
6766       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6767           << getOpenMPClauseName(OMPC_firstprivate) << Type
6768           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6769       bool IsDecl =
6770           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6771       Diag(VD->getLocation(),
6772            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6773           << VD;
6774       continue;
6775     }
6776
6777     Type = Type.getUnqualifiedType();
6778     auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
6779                                   VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6780     // Generate helper private variable and initialize it with the value of the
6781     // original variable. The address of the original variable is replaced by
6782     // the address of the new private variable in the CodeGen. This new variable
6783     // is not added to IdResolver, so the code in the OpenMP region uses
6784     // original variable for proper diagnostics and variable capturing.
6785     Expr *VDInitRefExpr = nullptr;
6786     // For arrays generate initializer for single element and replace it by the
6787     // original array element in CodeGen.
6788     if (Type->isArrayType()) {
6789       auto VDInit =
6790           buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
6791       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
6792       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
6793       ElemType = ElemType.getUnqualifiedType();
6794       auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
6795                                       ".firstprivate.temp");
6796       InitializedEntity Entity =
6797           InitializedEntity::InitializeVariable(VDInitTemp);
6798       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
6799
6800       InitializationSequence InitSeq(*this, Entity, Kind, Init);
6801       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
6802       if (Result.isInvalid())
6803         VDPrivate->setInvalidDecl();
6804       else
6805         VDPrivate->setInit(Result.getAs<Expr>());
6806       // Remove temp variable declaration.
6807       Context.Deallocate(VDInitTemp);
6808     } else {
6809       auto *VDInit =
6810           buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
6811       VDInitRefExpr =
6812           buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
6813       AddInitializerToDecl(VDPrivate,
6814                            DefaultLvalueConversion(VDInitRefExpr).get(),
6815                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
6816     }
6817     if (VDPrivate->isInvalidDecl()) {
6818       if (IsImplicitClause) {
6819         Diag(DE->getExprLoc(),
6820              diag::note_omp_task_predetermined_firstprivate_here);
6821       }
6822       continue;
6823     }
6824     CurContext->addDecl(VDPrivate);
6825     auto VDPrivateRefExpr = buildDeclRefExpr(
6826         *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6827     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
6828     Vars.push_back(DE);
6829     PrivateCopies.push_back(VDPrivateRefExpr);
6830     Inits.push_back(VDInitRefExpr);
6831   }
6832
6833   if (Vars.empty())
6834     return nullptr;
6835
6836   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6837                                        Vars, PrivateCopies, Inits);
6838 }
6839
6840 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
6841                                               SourceLocation StartLoc,
6842                                               SourceLocation LParenLoc,
6843                                               SourceLocation EndLoc) {
6844   SmallVector<Expr *, 8> Vars;
6845   SmallVector<Expr *, 8> SrcExprs;
6846   SmallVector<Expr *, 8> DstExprs;
6847   SmallVector<Expr *, 8> AssignmentOps;
6848   for (auto &RefExpr : VarList) {
6849     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
6850     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6851       // It will be analyzed later.
6852       Vars.push_back(RefExpr);
6853       SrcExprs.push_back(nullptr);
6854       DstExprs.push_back(nullptr);
6855       AssignmentOps.push_back(nullptr);
6856       continue;
6857     }
6858
6859     SourceLocation ELoc = RefExpr->getExprLoc();
6860     // OpenMP [2.1, C/C++]
6861     //  A list item is a variable name.
6862     // OpenMP  [2.14.3.5, Restrictions, p.1]
6863     //  A variable that is part of another variable (as an array or structure
6864     //  element) cannot appear in a lastprivate clause.
6865     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
6866     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6867       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6868       continue;
6869     }
6870     Decl *D = DE->getDecl();
6871     VarDecl *VD = cast<VarDecl>(D);
6872
6873     QualType Type = VD->getType();
6874     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6875       // It will be analyzed later.
6876       Vars.push_back(DE);
6877       SrcExprs.push_back(nullptr);
6878       DstExprs.push_back(nullptr);
6879       AssignmentOps.push_back(nullptr);
6880       continue;
6881     }
6882
6883     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
6884     //  A variable that appears in a lastprivate clause must not have an
6885     //  incomplete type or a reference type.
6886     if (RequireCompleteType(ELoc, Type,
6887                             diag::err_omp_lastprivate_incomplete_type)) {
6888       continue;
6889     }
6890     Type = Type.getNonReferenceType();
6891
6892     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
6893     // in a Construct]
6894     //  Variables with the predetermined data-sharing attributes may not be
6895     //  listed in data-sharing attributes clauses, except for the cases
6896     //  listed below.
6897     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6898     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
6899         DVar.CKind != OMPC_firstprivate &&
6900         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
6901       Diag(ELoc, diag::err_omp_wrong_dsa)
6902           << getOpenMPClauseName(DVar.CKind)
6903           << getOpenMPClauseName(OMPC_lastprivate);
6904       ReportOriginalDSA(*this, DSAStack, VD, DVar);
6905       continue;
6906     }
6907
6908     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
6909     // OpenMP [2.14.3.5, Restrictions, p.2]
6910     // A list item that is private within a parallel region, or that appears in
6911     // the reduction clause of a parallel construct, must not appear in a
6912     // lastprivate clause on a worksharing construct if any of the corresponding
6913     // worksharing regions ever binds to any of the corresponding parallel
6914     // regions.
6915     DSAStackTy::DSAVarData TopDVar = DVar;
6916     if (isOpenMPWorksharingDirective(CurrDir) &&
6917         !isOpenMPParallelDirective(CurrDir)) {
6918       DVar = DSAStack->getImplicitDSA(VD, true);
6919       if (DVar.CKind != OMPC_shared) {
6920         Diag(ELoc, diag::err_omp_required_access)
6921             << getOpenMPClauseName(OMPC_lastprivate)
6922             << getOpenMPClauseName(OMPC_shared);
6923         ReportOriginalDSA(*this, DSAStack, VD, DVar);
6924         continue;
6925       }
6926     }
6927     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
6928     //  A variable of class type (or array thereof) that appears in a
6929     //  lastprivate clause requires an accessible, unambiguous default
6930     //  constructor for the class type, unless the list item is also specified
6931     //  in a firstprivate clause.
6932     //  A variable of class type (or array thereof) that appears in a
6933     //  lastprivate clause requires an accessible, unambiguous copy assignment
6934     //  operator for the class type.
6935     Type = Context.getBaseElementType(Type).getNonReferenceType();
6936     auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6937                                Type.getUnqualifiedType(), ".lastprivate.src",
6938                                VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6939     auto *PseudoSrcExpr = buildDeclRefExpr(
6940         *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
6941     auto *DstVD =
6942         buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
6943                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
6944     auto *PseudoDstExpr =
6945         buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6946     // For arrays generate assignment operation for single element and replace
6947     // it by the original array element in CodeGen.
6948     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6949                                    PseudoDstExpr, PseudoSrcExpr);
6950     if (AssignmentOp.isInvalid())
6951       continue;
6952     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6953                                        /*DiscardedValue=*/true);
6954     if (AssignmentOp.isInvalid())
6955       continue;
6956
6957     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
6958     // A list item may appear in a firstprivate or lastprivate clause but not
6959     // both.
6960     if (CurrDir == OMPD_distribute) {
6961       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6962       if (DVar.CKind == OMPC_firstprivate) {
6963         Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
6964         ReportOriginalDSA(*this, DSAStack, VD, DVar);
6965         continue;
6966       }
6967     }
6968
6969     if (TopDVar.CKind != OMPC_firstprivate)
6970       DSAStack->addDSA(VD, DE, OMPC_lastprivate);
6971     Vars.push_back(DE);
6972     SrcExprs.push_back(PseudoSrcExpr);
6973     DstExprs.push_back(PseudoDstExpr);
6974     AssignmentOps.push_back(AssignmentOp.get());
6975   }
6976
6977   if (Vars.empty())
6978     return nullptr;
6979
6980   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6981                                       Vars, SrcExprs, DstExprs, AssignmentOps);
6982 }
6983
6984 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
6985                                          SourceLocation StartLoc,
6986                                          SourceLocation LParenLoc,
6987                                          SourceLocation EndLoc) {
6988   SmallVector<Expr *, 8> Vars;
6989   for (auto &RefExpr : VarList) {
6990     assert(RefExpr && "NULL expr in OpenMP shared clause.");
6991     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6992       // It will be analyzed later.
6993       Vars.push_back(RefExpr);
6994       continue;
6995     }
6996
6997     SourceLocation ELoc = RefExpr->getExprLoc();
6998     // OpenMP [2.1, C/C++]
6999     //  A list item is a variable name.
7000     // OpenMP  [2.14.3.2, Restrictions, p.1]
7001     //  A variable that is part of another variable (as an array or structure
7002     //  element) cannot appear in a shared unless it is a static data member
7003     //  of a C++ class.
7004     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7005     if (!DE || !isa<VarDecl>(DE->getDecl())) {
7006       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7007       continue;
7008     }
7009     Decl *D = DE->getDecl();
7010     VarDecl *VD = cast<VarDecl>(D);
7011
7012     QualType Type = VD->getType();
7013     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7014       // It will be analyzed later.
7015       Vars.push_back(DE);
7016       continue;
7017     }
7018
7019     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7020     // in a Construct]
7021     //  Variables with the predetermined data-sharing attributes may not be
7022     //  listed in data-sharing attributes clauses, except for the cases
7023     //  listed below. For these exceptions only, listing a predetermined
7024     //  variable in a data-sharing attribute clause is allowed and overrides
7025     //  the variable's predetermined data-sharing attributes.
7026     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
7027     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
7028         DVar.RefExpr) {
7029       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7030                                           << getOpenMPClauseName(OMPC_shared);
7031       ReportOriginalDSA(*this, DSAStack, VD, DVar);
7032       continue;
7033     }
7034
7035     DSAStack->addDSA(VD, DE, OMPC_shared);
7036     Vars.push_back(DE);
7037   }
7038
7039   if (Vars.empty())
7040     return nullptr;
7041
7042   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
7043 }
7044
7045 namespace {
7046 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
7047   DSAStackTy *Stack;
7048
7049 public:
7050   bool VisitDeclRefExpr(DeclRefExpr *E) {
7051     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
7052       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
7053       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
7054         return false;
7055       if (DVar.CKind != OMPC_unknown)
7056         return true;
7057       DSAStackTy::DSAVarData DVarPrivate =
7058           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
7059       if (DVarPrivate.CKind != OMPC_unknown)
7060         return true;
7061       return false;
7062     }
7063     return false;
7064   }
7065   bool VisitStmt(Stmt *S) {
7066     for (auto Child : S->children()) {
7067       if (Child && Visit(Child))
7068         return true;
7069     }
7070     return false;
7071   }
7072   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
7073 };
7074 } // namespace
7075
7076 OMPClause *Sema::ActOnOpenMPReductionClause(
7077     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
7078     SourceLocation ColonLoc, SourceLocation EndLoc,
7079     CXXScopeSpec &ReductionIdScopeSpec,
7080     const DeclarationNameInfo &ReductionId) {
7081   // TODO: Allow scope specification search when 'declare reduction' is
7082   // supported.
7083   assert(ReductionIdScopeSpec.isEmpty() &&
7084          "No support for scoped reduction identifiers yet.");
7085
7086   auto DN = ReductionId.getName();
7087   auto OOK = DN.getCXXOverloadedOperator();
7088   BinaryOperatorKind BOK = BO_Comma;
7089
7090   // OpenMP [2.14.3.6, reduction clause]
7091   // C
7092   // reduction-identifier is either an identifier or one of the following
7093   // operators: +, -, *,  &, |, ^, && and ||
7094   // C++
7095   // reduction-identifier is either an id-expression or one of the following
7096   // operators: +, -, *, &, |, ^, && and ||
7097   // FIXME: Only 'min' and 'max' identifiers are supported for now.
7098   switch (OOK) {
7099   case OO_Plus:
7100   case OO_Minus:
7101     BOK = BO_Add;
7102     break;
7103   case OO_Star:
7104     BOK = BO_Mul;
7105     break;
7106   case OO_Amp:
7107     BOK = BO_And;
7108     break;
7109   case OO_Pipe:
7110     BOK = BO_Or;
7111     break;
7112   case OO_Caret:
7113     BOK = BO_Xor;
7114     break;
7115   case OO_AmpAmp:
7116     BOK = BO_LAnd;
7117     break;
7118   case OO_PipePipe:
7119     BOK = BO_LOr;
7120     break;
7121   case OO_New:
7122   case OO_Delete:
7123   case OO_Array_New:
7124   case OO_Array_Delete:
7125   case OO_Slash:
7126   case OO_Percent:
7127   case OO_Tilde:
7128   case OO_Exclaim:
7129   case OO_Equal:
7130   case OO_Less:
7131   case OO_Greater:
7132   case OO_LessEqual:
7133   case OO_GreaterEqual:
7134   case OO_PlusEqual:
7135   case OO_MinusEqual:
7136   case OO_StarEqual:
7137   case OO_SlashEqual:
7138   case OO_PercentEqual:
7139   case OO_CaretEqual:
7140   case OO_AmpEqual:
7141   case OO_PipeEqual:
7142   case OO_LessLess:
7143   case OO_GreaterGreater:
7144   case OO_LessLessEqual:
7145   case OO_GreaterGreaterEqual:
7146   case OO_EqualEqual:
7147   case OO_ExclaimEqual:
7148   case OO_PlusPlus:
7149   case OO_MinusMinus:
7150   case OO_Comma:
7151   case OO_ArrowStar:
7152   case OO_Arrow:
7153   case OO_Call:
7154   case OO_Subscript:
7155   case OO_Conditional:
7156   case OO_Coawait:
7157   case NUM_OVERLOADED_OPERATORS:
7158     llvm_unreachable("Unexpected reduction identifier");
7159   case OO_None:
7160     if (auto II = DN.getAsIdentifierInfo()) {
7161       if (II->isStr("max"))
7162         BOK = BO_GT;
7163       else if (II->isStr("min"))
7164         BOK = BO_LT;
7165     }
7166     break;
7167   }
7168   SourceRange ReductionIdRange;
7169   if (ReductionIdScopeSpec.isValid()) {
7170     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
7171   }
7172   ReductionIdRange.setEnd(ReductionId.getEndLoc());
7173   if (BOK == BO_Comma) {
7174     // Not allowed reduction identifier is found.
7175     Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
7176         << ReductionIdRange;
7177     return nullptr;
7178   }
7179
7180   SmallVector<Expr *, 8> Vars;
7181   SmallVector<Expr *, 8> Privates;
7182   SmallVector<Expr *, 8> LHSs;
7183   SmallVector<Expr *, 8> RHSs;
7184   SmallVector<Expr *, 8> ReductionOps;
7185   for (auto RefExpr : VarList) {
7186     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
7187     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7188       // It will be analyzed later.
7189       Vars.push_back(RefExpr);
7190       Privates.push_back(nullptr);
7191       LHSs.push_back(nullptr);
7192       RHSs.push_back(nullptr);
7193       ReductionOps.push_back(nullptr);
7194       continue;
7195     }
7196
7197     if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7198         RefExpr->isInstantiationDependent() ||
7199         RefExpr->containsUnexpandedParameterPack()) {
7200       // It will be analyzed later.
7201       Vars.push_back(RefExpr);
7202       Privates.push_back(nullptr);
7203       LHSs.push_back(nullptr);
7204       RHSs.push_back(nullptr);
7205       ReductionOps.push_back(nullptr);
7206       continue;
7207     }
7208
7209     auto ELoc = RefExpr->getExprLoc();
7210     auto ERange = RefExpr->getSourceRange();
7211     // OpenMP [2.1, C/C++]
7212     //  A list item is a variable or array section, subject to the restrictions
7213     //  specified in Section 2.4 on page 42 and in each of the sections
7214     // describing clauses and directives for which a list appears.
7215     // OpenMP  [2.14.3.3, Restrictions, p.1]
7216     //  A variable that is part of another variable (as an array or
7217     //  structure element) cannot appear in a private clause.
7218     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
7219     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
7220     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
7221     if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
7222       Diag(ELoc, diag::err_omp_expected_var_name_or_array_item) << ERange;
7223       continue;
7224     }
7225     QualType Type;
7226     VarDecl *VD = nullptr;
7227     if (DE) {
7228       auto D = DE->getDecl();
7229       VD = cast<VarDecl>(D);
7230       Type = VD->getType();
7231     } else if (ASE) {
7232       Type = ASE->getType();
7233       auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7234       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7235         Base = TempASE->getBase()->IgnoreParenImpCasts();
7236       DE = dyn_cast<DeclRefExpr>(Base);
7237       if (DE)
7238         VD = dyn_cast<VarDecl>(DE->getDecl());
7239       if (!VD) {
7240         Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7241             << 0 << Base->getSourceRange();
7242         continue;
7243       }
7244     } else if (OASE) {
7245       auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
7246       if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
7247         Type = ATy->getElementType();
7248       else
7249         Type = BaseType->getPointeeType();
7250       auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7251       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7252         Base = TempOASE->getBase()->IgnoreParenImpCasts();
7253       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7254         Base = TempASE->getBase()->IgnoreParenImpCasts();
7255       DE = dyn_cast<DeclRefExpr>(Base);
7256       if (DE)
7257         VD = dyn_cast<VarDecl>(DE->getDecl());
7258       if (!VD) {
7259         Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
7260             << 1 << Base->getSourceRange();
7261         continue;
7262       }
7263     }
7264
7265     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7266     //  A variable that appears in a private clause must not have an incomplete
7267     //  type or a reference type.
7268     if (RequireCompleteType(ELoc, Type,
7269                             diag::err_omp_reduction_incomplete_type))
7270       continue;
7271     // OpenMP [2.14.3.6, reduction clause, Restrictions]
7272     // Arrays may not appear in a reduction clause.
7273     if (Type.getNonReferenceType()->isArrayType()) {
7274       Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
7275       if (!ASE && !OASE) {
7276         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7277                       VarDecl::DeclarationOnly;
7278         Diag(VD->getLocation(),
7279              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7280             << VD;
7281       }
7282       continue;
7283     }
7284     // OpenMP [2.14.3.6, reduction clause, Restrictions]
7285     // A list item that appears in a reduction clause must not be
7286     // const-qualified.
7287     if (Type.getNonReferenceType().isConstant(Context)) {
7288       Diag(ELoc, diag::err_omp_const_reduction_list_item)
7289           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
7290       if (!ASE && !OASE) {
7291         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7292                       VarDecl::DeclarationOnly;
7293         Diag(VD->getLocation(),
7294              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7295             << VD;
7296       }
7297       continue;
7298     }
7299     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
7300     //  If a list-item is a reference type then it must bind to the same object
7301     //  for all threads of the team.
7302     if (!ASE && !OASE) {
7303       VarDecl *VDDef = VD->getDefinition();
7304       if (Type->isReferenceType() && VDDef) {
7305         DSARefChecker Check(DSAStack);
7306         if (Check.Visit(VDDef->getInit())) {
7307           Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
7308           Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
7309           continue;
7310         }
7311       }
7312     }
7313     // OpenMP [2.14.3.6, reduction clause, Restrictions]
7314     // The type of a list item that appears in a reduction clause must be valid
7315     // for the reduction-identifier. For a max or min reduction in C, the type
7316     // of the list item must be an allowed arithmetic data type: char, int,
7317     // float, double, or _Bool, possibly modified with long, short, signed, or
7318     // unsigned. For a max or min reduction in C++, the type of the list item
7319     // must be an allowed arithmetic data type: char, wchar_t, int, float,
7320     // double, or bool, possibly modified with long, short, signed, or unsigned.
7321     if ((BOK == BO_GT || BOK == BO_LT) &&
7322         !(Type->isScalarType() ||
7323           (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
7324       Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
7325           << getLangOpts().CPlusPlus;
7326       if (!ASE && !OASE) {
7327         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7328                       VarDecl::DeclarationOnly;
7329         Diag(VD->getLocation(),
7330              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7331             << VD;
7332       }
7333       continue;
7334     }
7335     if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
7336         !getLangOpts().CPlusPlus && Type->isFloatingType()) {
7337       Diag(ELoc, diag::err_omp_clause_floating_type_arg);
7338       if (!ASE && !OASE) {
7339         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7340                       VarDecl::DeclarationOnly;
7341         Diag(VD->getLocation(),
7342              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7343             << VD;
7344       }
7345       continue;
7346     }
7347     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
7348     // in a Construct]
7349     //  Variables with the predetermined data-sharing attributes may not be
7350     //  listed in data-sharing attributes clauses, except for the cases
7351     //  listed below. For these exceptions only, listing a predetermined
7352     //  variable in a data-sharing attribute clause is allowed and overrides
7353     //  the variable's predetermined data-sharing attributes.
7354     // OpenMP [2.14.3.6, Restrictions, p.3]
7355     //  Any number of reduction clauses can be specified on the directive,
7356     //  but a list item can appear only once in the reduction clauses for that
7357     //  directive.
7358     DSAStackTy::DSAVarData DVar;
7359     DVar = DSAStack->getTopDSA(VD, false);
7360     if (DVar.CKind == OMPC_reduction) {
7361       Diag(ELoc, diag::err_omp_once_referenced)
7362           << getOpenMPClauseName(OMPC_reduction);
7363       if (DVar.RefExpr) {
7364         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
7365       }
7366     } else if (DVar.CKind != OMPC_unknown) {
7367       Diag(ELoc, diag::err_omp_wrong_dsa)
7368           << getOpenMPClauseName(DVar.CKind)
7369           << getOpenMPClauseName(OMPC_reduction);
7370       ReportOriginalDSA(*this, DSAStack, VD, DVar);
7371       continue;
7372     }
7373
7374     // OpenMP [2.14.3.6, Restrictions, p.1]
7375     //  A list item that appears in a reduction clause of a worksharing
7376     //  construct must be shared in the parallel regions to which any of the
7377     //  worksharing regions arising from the worksharing construct bind.
7378     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
7379     if (isOpenMPWorksharingDirective(CurrDir) &&
7380         !isOpenMPParallelDirective(CurrDir)) {
7381       DVar = DSAStack->getImplicitDSA(VD, true);
7382       if (DVar.CKind != OMPC_shared) {
7383         Diag(ELoc, diag::err_omp_required_access)
7384             << getOpenMPClauseName(OMPC_reduction)
7385             << getOpenMPClauseName(OMPC_shared);
7386         ReportOriginalDSA(*this, DSAStack, VD, DVar);
7387         continue;
7388       }
7389     }
7390
7391     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
7392     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
7393                                VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7394     auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
7395                                VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7396     auto PrivateTy = Type;
7397     if (OASE) {
7398       // For array sections only:
7399       // Create pseudo array type for private copy. The size for this array will
7400       // be generated during codegen.
7401       // For array subscripts or single variables Private Ty is the same as Type
7402       // (type of the variable or single array element).
7403       PrivateTy = Context.getVariableArrayType(
7404           Type, new (Context) OpaqueValueExpr(SourceLocation(),
7405                                               Context.getSizeType(), VK_RValue),
7406           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
7407     }
7408     // Private copy.
7409     auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
7410                                    VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7411     // Add initializer for private variable.
7412     Expr *Init = nullptr;
7413     switch (BOK) {
7414     case BO_Add:
7415     case BO_Xor:
7416     case BO_Or:
7417     case BO_LOr:
7418       // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
7419       if (Type->isScalarType() || Type->isAnyComplexType()) {
7420         Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
7421       }
7422       break;
7423     case BO_Mul:
7424     case BO_LAnd:
7425       if (Type->isScalarType() || Type->isAnyComplexType()) {
7426         // '*' and '&&' reduction ops - initializer is '1'.
7427         Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
7428       }
7429       break;
7430     case BO_And: {
7431       // '&' reduction op - initializer is '~0'.
7432       QualType OrigType = Type;
7433       if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
7434         Type = ComplexTy->getElementType();
7435       }
7436       if (Type->isRealFloatingType()) {
7437         llvm::APFloat InitValue =
7438             llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
7439                                            /*isIEEE=*/true);
7440         Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
7441                                        Type, ELoc);
7442       } else if (Type->isScalarType()) {
7443         auto Size = Context.getTypeSize(Type);
7444         QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
7445         llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
7446         Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
7447       }
7448       if (Init && OrigType->isAnyComplexType()) {
7449         // Init = 0xFFFF + 0xFFFFi;
7450         auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
7451         Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
7452       }
7453       Type = OrigType;
7454       break;
7455     }
7456     case BO_LT:
7457     case BO_GT: {
7458       // 'min' reduction op - initializer is 'Largest representable number in
7459       // the reduction list item type'.
7460       // 'max' reduction op - initializer is 'Least representable number in
7461       // the reduction list item type'.
7462       if (Type->isIntegerType() || Type->isPointerType()) {
7463         bool IsSigned = Type->hasSignedIntegerRepresentation();
7464         auto Size = Context.getTypeSize(Type);
7465         QualType IntTy =
7466             Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
7467         llvm::APInt InitValue =
7468             (BOK != BO_LT)
7469                 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
7470                            : llvm::APInt::getMinValue(Size)
7471                 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
7472                            : llvm::APInt::getMaxValue(Size);
7473         Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
7474         if (Type->isPointerType()) {
7475           // Cast to pointer type.
7476           auto CastExpr = BuildCStyleCastExpr(
7477               SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
7478               SourceLocation(), Init);
7479           if (CastExpr.isInvalid())
7480             continue;
7481           Init = CastExpr.get();
7482         }
7483       } else if (Type->isRealFloatingType()) {
7484         llvm::APFloat InitValue = llvm::APFloat::getLargest(
7485             Context.getFloatTypeSemantics(Type), BOK != BO_LT);
7486         Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
7487                                        Type, ELoc);
7488       }
7489       break;
7490     }
7491     case BO_PtrMemD:
7492     case BO_PtrMemI:
7493     case BO_MulAssign:
7494     case BO_Div:
7495     case BO_Rem:
7496     case BO_Sub:
7497     case BO_Shl:
7498     case BO_Shr:
7499     case BO_LE:
7500     case BO_GE:
7501     case BO_EQ:
7502     case BO_NE:
7503     case BO_AndAssign:
7504     case BO_XorAssign:
7505     case BO_OrAssign:
7506     case BO_Assign:
7507     case BO_AddAssign:
7508     case BO_SubAssign:
7509     case BO_DivAssign:
7510     case BO_RemAssign:
7511     case BO_ShlAssign:
7512     case BO_ShrAssign:
7513     case BO_Comma:
7514       llvm_unreachable("Unexpected reduction operation");
7515     }
7516     if (Init) {
7517       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
7518                            /*TypeMayContainAuto=*/false);
7519     } else
7520       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
7521     if (!RHSVD->hasInit()) {
7522       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
7523                                                             << ReductionIdRange;
7524       if (VD) {
7525         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
7526                       VarDecl::DeclarationOnly;
7527         Diag(VD->getLocation(),
7528              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7529             << VD;
7530       }
7531       continue;
7532     }
7533     // Store initializer for single element in private copy. Will be used during
7534     // codegen.
7535     PrivateVD->setInit(RHSVD->getInit());
7536     PrivateVD->setInitStyle(RHSVD->getInitStyle());
7537     auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
7538     auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
7539     auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
7540     ExprResult ReductionOp =
7541         BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
7542                    LHSDRE, RHSDRE);
7543     if (ReductionOp.isUsable()) {
7544       if (BOK != BO_LT && BOK != BO_GT) {
7545         ReductionOp =
7546             BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
7547                        BO_Assign, LHSDRE, ReductionOp.get());
7548       } else {
7549         auto *ConditionalOp = new (Context) ConditionalOperator(
7550             ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
7551             RHSDRE, Type, VK_LValue, OK_Ordinary);
7552         ReductionOp =
7553             BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
7554                        BO_Assign, LHSDRE, ConditionalOp);
7555       }
7556       ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
7557     }
7558     if (ReductionOp.isInvalid())
7559       continue;
7560
7561     DSAStack->addDSA(VD, DE, OMPC_reduction);
7562     Vars.push_back(RefExpr);
7563     Privates.push_back(PrivateDRE);
7564     LHSs.push_back(LHSDRE);
7565     RHSs.push_back(RHSDRE);
7566     ReductionOps.push_back(ReductionOp.get());
7567   }
7568
7569   if (Vars.empty())
7570     return nullptr;
7571
7572   return OMPReductionClause::Create(
7573       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
7574       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
7575       LHSs, RHSs, ReductionOps);
7576 }
7577
7578 OMPClause *Sema::ActOnOpenMPLinearClause(
7579     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
7580     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
7581     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7582   SmallVector<Expr *, 8> Vars;
7583   SmallVector<Expr *, 8> Privates;
7584   SmallVector<Expr *, 8> Inits;
7585   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
7586       LinKind == OMPC_LINEAR_unknown) {
7587     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
7588     LinKind = OMPC_LINEAR_val;
7589   }
7590   for (auto &RefExpr : VarList) {
7591     assert(RefExpr && "NULL expr in OpenMP linear clause.");
7592     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7593       // It will be analyzed later.
7594       Vars.push_back(RefExpr);
7595       Privates.push_back(nullptr);
7596       Inits.push_back(nullptr);
7597       continue;
7598     }
7599
7600     // OpenMP [2.14.3.7, linear clause]
7601     // A list item that appears in a linear clause is subject to the private
7602     // clause semantics described in Section 2.14.3.3 on page 159 except as
7603     // noted. In addition, the value of the new list item on each iteration
7604     // of the associated loop(s) corresponds to the value of the original
7605     // list item before entering the construct plus the logical number of
7606     // the iteration times linear-step.
7607
7608     SourceLocation ELoc = RefExpr->getExprLoc();
7609     // OpenMP [2.1, C/C++]
7610     //  A list item is a variable name.
7611     // OpenMP  [2.14.3.3, Restrictions, p.1]
7612     //  A variable that is part of another variable (as an array or
7613     //  structure element) cannot appear in a private clause.
7614     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7615     if (!DE || !isa<VarDecl>(DE->getDecl())) {
7616       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7617       continue;
7618     }
7619
7620     VarDecl *VD = cast<VarDecl>(DE->getDecl());
7621
7622     // OpenMP [2.14.3.7, linear clause]
7623     //  A list-item cannot appear in more than one linear clause.
7624     //  A list-item that appears in a linear clause cannot appear in any
7625     //  other data-sharing attribute clause.
7626     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
7627     if (DVar.RefExpr) {
7628       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7629                                           << getOpenMPClauseName(OMPC_linear);
7630       ReportOriginalDSA(*this, DSAStack, VD, DVar);
7631       continue;
7632     }
7633
7634     QualType QType = VD->getType();
7635     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
7636       // It will be analyzed later.
7637       Vars.push_back(DE);
7638       Privates.push_back(nullptr);
7639       Inits.push_back(nullptr);
7640       continue;
7641     }
7642
7643     // A variable must not have an incomplete type or a reference type.
7644     if (RequireCompleteType(ELoc, QType,
7645                             diag::err_omp_linear_incomplete_type)) {
7646       continue;
7647     }
7648     if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
7649         !QType->isReferenceType()) {
7650       Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
7651           << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
7652       continue;
7653     }
7654     QType = QType.getNonReferenceType();
7655
7656     // A list item must not be const-qualified.
7657     if (QType.isConstant(Context)) {
7658       Diag(ELoc, diag::err_omp_const_variable)
7659           << getOpenMPClauseName(OMPC_linear);
7660       bool IsDecl =
7661           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7662       Diag(VD->getLocation(),
7663            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7664           << VD;
7665       continue;
7666     }
7667
7668     // A list item must be of integral or pointer type.
7669     QType = QType.getUnqualifiedType().getCanonicalType();
7670     const Type *Ty = QType.getTypePtrOrNull();
7671     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
7672                 !Ty->isPointerType())) {
7673       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
7674       bool IsDecl =
7675           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7676       Diag(VD->getLocation(),
7677            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7678           << VD;
7679       continue;
7680     }
7681
7682     // Build private copy of original var.
7683     auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
7684                                  VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7685     auto *PrivateRef = buildDeclRefExpr(
7686         *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
7687     // Build var to save initial value.
7688     VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
7689     Expr *InitExpr;
7690     if (LinKind == OMPC_LINEAR_uval)
7691       InitExpr = VD->getInit();
7692     else
7693       InitExpr = DE;
7694     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
7695                          /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
7696     auto InitRef = buildDeclRefExpr(
7697         *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
7698     DSAStack->addDSA(VD, DE, OMPC_linear);
7699     Vars.push_back(DE);
7700     Privates.push_back(PrivateRef);
7701     Inits.push_back(InitRef);
7702   }
7703
7704   if (Vars.empty())
7705     return nullptr;
7706
7707   Expr *StepExpr = Step;
7708   Expr *CalcStepExpr = nullptr;
7709   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
7710       !Step->isInstantiationDependent() &&
7711       !Step->containsUnexpandedParameterPack()) {
7712     SourceLocation StepLoc = Step->getLocStart();
7713     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
7714     if (Val.isInvalid())
7715       return nullptr;
7716     StepExpr = Val.get();
7717
7718     // Build var to save the step value.
7719     VarDecl *SaveVar =
7720         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
7721     ExprResult SaveRef =
7722         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
7723     ExprResult CalcStep =
7724         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
7725     CalcStep = ActOnFinishFullExpr(CalcStep.get());
7726
7727     // Warn about zero linear step (it would be probably better specified as
7728     // making corresponding variables 'const').
7729     llvm::APSInt Result;
7730     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
7731     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
7732       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
7733                                                      << (Vars.size() > 1);
7734     if (!IsConstant && CalcStep.isUsable()) {
7735       // Calculate the step beforehand instead of doing this on each iteration.
7736       // (This is not used if the number of iterations may be kfold-ed).
7737       CalcStepExpr = CalcStep.get();
7738     }
7739   }
7740
7741   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
7742                                  ColonLoc, EndLoc, Vars, Privates, Inits,
7743                                  StepExpr, CalcStepExpr);
7744 }
7745
7746 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
7747                                      Expr *NumIterations, Sema &SemaRef,
7748                                      Scope *S) {
7749   // Walk the vars and build update/final expressions for the CodeGen.
7750   SmallVector<Expr *, 8> Updates;
7751   SmallVector<Expr *, 8> Finals;
7752   Expr *Step = Clause.getStep();
7753   Expr *CalcStep = Clause.getCalcStep();
7754   // OpenMP [2.14.3.7, linear clause]
7755   // If linear-step is not specified it is assumed to be 1.
7756   if (Step == nullptr)
7757     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7758   else if (CalcStep)
7759     Step = cast<BinaryOperator>(CalcStep)->getLHS();
7760   bool HasErrors = false;
7761   auto CurInit = Clause.inits().begin();
7762   auto CurPrivate = Clause.privates().begin();
7763   auto LinKind = Clause.getModifier();
7764   for (auto &RefExpr : Clause.varlists()) {
7765     Expr *InitExpr = *CurInit;
7766
7767     // Build privatized reference to the current linear var.
7768     auto DE = cast<DeclRefExpr>(RefExpr);
7769     Expr *CapturedRef;
7770     if (LinKind == OMPC_LINEAR_uval)
7771       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
7772     else
7773       CapturedRef =
7774           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
7775                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
7776                            /*RefersToCapture=*/true);
7777
7778     // Build update: Var = InitExpr + IV * Step
7779     ExprResult Update =
7780         BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
7781                            InitExpr, IV, Step, /* Subtract */ false);
7782     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
7783                                          /*DiscardedValue=*/true);
7784
7785     // Build final: Var = InitExpr + NumIterations * Step
7786     ExprResult Final =
7787         BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
7788                            InitExpr, NumIterations, Step, /* Subtract */ false);
7789     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
7790                                         /*DiscardedValue=*/true);
7791     if (!Update.isUsable() || !Final.isUsable()) {
7792       Updates.push_back(nullptr);
7793       Finals.push_back(nullptr);
7794       HasErrors = true;
7795     } else {
7796       Updates.push_back(Update.get());
7797       Finals.push_back(Final.get());
7798     }
7799     ++CurInit, ++CurPrivate;
7800   }
7801   Clause.setUpdates(Updates);
7802   Clause.setFinals(Finals);
7803   return HasErrors;
7804 }
7805
7806 OMPClause *Sema::ActOnOpenMPAlignedClause(
7807     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
7808     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
7809
7810   SmallVector<Expr *, 8> Vars;
7811   for (auto &RefExpr : VarList) {
7812     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
7813     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7814       // It will be analyzed later.
7815       Vars.push_back(RefExpr);
7816       continue;
7817     }
7818
7819     SourceLocation ELoc = RefExpr->getExprLoc();
7820     // OpenMP [2.1, C/C++]
7821     //  A list item is a variable name.
7822     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7823     if (!DE || !isa<VarDecl>(DE->getDecl())) {
7824       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7825       continue;
7826     }
7827
7828     VarDecl *VD = cast<VarDecl>(DE->getDecl());
7829
7830     // OpenMP  [2.8.1, simd construct, Restrictions]
7831     // The type of list items appearing in the aligned clause must be
7832     // array, pointer, reference to array, or reference to pointer.
7833     QualType QType = VD->getType();
7834     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
7835     const Type *Ty = QType.getTypePtrOrNull();
7836     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
7837                 !Ty->isPointerType())) {
7838       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
7839           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
7840       bool IsDecl =
7841           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
7842       Diag(VD->getLocation(),
7843            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
7844           << VD;
7845       continue;
7846     }
7847
7848     // OpenMP  [2.8.1, simd construct, Restrictions]
7849     // A list-item cannot appear in more than one aligned clause.
7850     if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
7851       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
7852       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
7853           << getOpenMPClauseName(OMPC_aligned);
7854       continue;
7855     }
7856
7857     Vars.push_back(DE);
7858   }
7859
7860   // OpenMP [2.8.1, simd construct, Description]
7861   // The parameter of the aligned clause, alignment, must be a constant
7862   // positive integer expression.
7863   // If no optional parameter is specified, implementation-defined default
7864   // alignments for SIMD instructions on the target platforms are assumed.
7865   if (Alignment != nullptr) {
7866     ExprResult AlignResult =
7867         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
7868     if (AlignResult.isInvalid())
7869       return nullptr;
7870     Alignment = AlignResult.get();
7871   }
7872   if (Vars.empty())
7873     return nullptr;
7874
7875   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
7876                                   EndLoc, Vars, Alignment);
7877 }
7878
7879 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
7880                                          SourceLocation StartLoc,
7881                                          SourceLocation LParenLoc,
7882                                          SourceLocation EndLoc) {
7883   SmallVector<Expr *, 8> Vars;
7884   SmallVector<Expr *, 8> SrcExprs;
7885   SmallVector<Expr *, 8> DstExprs;
7886   SmallVector<Expr *, 8> AssignmentOps;
7887   for (auto &RefExpr : VarList) {
7888     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
7889     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7890       // It will be analyzed later.
7891       Vars.push_back(RefExpr);
7892       SrcExprs.push_back(nullptr);
7893       DstExprs.push_back(nullptr);
7894       AssignmentOps.push_back(nullptr);
7895       continue;
7896     }
7897
7898     SourceLocation ELoc = RefExpr->getExprLoc();
7899     // OpenMP [2.1, C/C++]
7900     //  A list item is a variable name.
7901     // OpenMP  [2.14.4.1, Restrictions, p.1]
7902     //  A list item that appears in a copyin clause must be threadprivate.
7903     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7904     if (!DE || !isa<VarDecl>(DE->getDecl())) {
7905       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7906       continue;
7907     }
7908
7909     Decl *D = DE->getDecl();
7910     VarDecl *VD = cast<VarDecl>(D);
7911
7912     QualType Type = VD->getType();
7913     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
7914       // It will be analyzed later.
7915       Vars.push_back(DE);
7916       SrcExprs.push_back(nullptr);
7917       DstExprs.push_back(nullptr);
7918       AssignmentOps.push_back(nullptr);
7919       continue;
7920     }
7921
7922     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
7923     //  A list item that appears in a copyin clause must be threadprivate.
7924     if (!DSAStack->isThreadPrivate(VD)) {
7925       Diag(ELoc, diag::err_omp_required_access)
7926           << getOpenMPClauseName(OMPC_copyin)
7927           << getOpenMPDirectiveName(OMPD_threadprivate);
7928       continue;
7929     }
7930
7931     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
7932     //  A variable of class type (or array thereof) that appears in a
7933     //  copyin clause requires an accessible, unambiguous copy assignment
7934     //  operator for the class type.
7935     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
7936     auto *SrcVD =
7937         buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
7938                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7939     auto *PseudoSrcExpr = buildDeclRefExpr(
7940         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
7941     auto *DstVD =
7942         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
7943                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
7944     auto *PseudoDstExpr =
7945         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
7946     // For arrays generate assignment operation for single element and replace
7947     // it by the original array element in CodeGen.
7948     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
7949                                    PseudoDstExpr, PseudoSrcExpr);
7950     if (AssignmentOp.isInvalid())
7951       continue;
7952     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
7953                                        /*DiscardedValue=*/true);
7954     if (AssignmentOp.isInvalid())
7955       continue;
7956
7957     DSAStack->addDSA(VD, DE, OMPC_copyin);
7958     Vars.push_back(DE);
7959     SrcExprs.push_back(PseudoSrcExpr);
7960     DstExprs.push_back(PseudoDstExpr);
7961     AssignmentOps.push_back(AssignmentOp.get());
7962   }
7963
7964   if (Vars.empty())
7965     return nullptr;
7966
7967   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7968                                  SrcExprs, DstExprs, AssignmentOps);
7969 }
7970
7971 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
7972                                               SourceLocation StartLoc,
7973                                               SourceLocation LParenLoc,
7974                                               SourceLocation EndLoc) {
7975   SmallVector<Expr *, 8> Vars;
7976   SmallVector<Expr *, 8> SrcExprs;
7977   SmallVector<Expr *, 8> DstExprs;
7978   SmallVector<Expr *, 8> AssignmentOps;
7979   for (auto &RefExpr : VarList) {
7980     assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
7981     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
7982       // It will be analyzed later.
7983       Vars.push_back(RefExpr);
7984       SrcExprs.push_back(nullptr);
7985       DstExprs.push_back(nullptr);
7986       AssignmentOps.push_back(nullptr);
7987       continue;
7988     }
7989
7990     SourceLocation ELoc = RefExpr->getExprLoc();
7991     // OpenMP [2.1, C/C++]
7992     //  A list item is a variable name.
7993     // OpenMP  [2.14.4.1, Restrictions, p.1]
7994     //  A list item that appears in a copyin clause must be threadprivate.
7995     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
7996     if (!DE || !isa<VarDecl>(DE->getDecl())) {
7997       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
7998       continue;
7999     }
8000
8001     Decl *D = DE->getDecl();
8002     VarDecl *VD = cast<VarDecl>(D);
8003
8004     QualType Type = VD->getType();
8005     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
8006       // It will be analyzed later.
8007       Vars.push_back(DE);
8008       SrcExprs.push_back(nullptr);
8009       DstExprs.push_back(nullptr);
8010       AssignmentOps.push_back(nullptr);
8011       continue;
8012     }
8013
8014     // OpenMP [2.14.4.2, Restrictions, p.2]
8015     //  A list item that appears in a copyprivate clause may not appear in a
8016     //  private or firstprivate clause on the single construct.
8017     if (!DSAStack->isThreadPrivate(VD)) {
8018       auto DVar = DSAStack->getTopDSA(VD, false);
8019       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
8020           DVar.RefExpr) {
8021         Diag(ELoc, diag::err_omp_wrong_dsa)
8022             << getOpenMPClauseName(DVar.CKind)
8023             << getOpenMPClauseName(OMPC_copyprivate);
8024         ReportOriginalDSA(*this, DSAStack, VD, DVar);
8025         continue;
8026       }
8027
8028       // OpenMP [2.11.4.2, Restrictions, p.1]
8029       //  All list items that appear in a copyprivate clause must be either
8030       //  threadprivate or private in the enclosing context.
8031       if (DVar.CKind == OMPC_unknown) {
8032         DVar = DSAStack->getImplicitDSA(VD, false);
8033         if (DVar.CKind == OMPC_shared) {
8034           Diag(ELoc, diag::err_omp_required_access)
8035               << getOpenMPClauseName(OMPC_copyprivate)
8036               << "threadprivate or private in the enclosing context";
8037           ReportOriginalDSA(*this, DSAStack, VD, DVar);
8038           continue;
8039         }
8040       }
8041     }
8042
8043     // Variably modified types are not supported.
8044     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
8045       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8046           << getOpenMPClauseName(OMPC_copyprivate) << Type
8047           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8048       bool IsDecl =
8049           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8050       Diag(VD->getLocation(),
8051            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8052           << VD;
8053       continue;
8054     }
8055
8056     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
8057     //  A variable of class type (or array thereof) that appears in a
8058     //  copyin clause requires an accessible, unambiguous copy assignment
8059     //  operator for the class type.
8060     Type = Context.getBaseElementType(Type.getNonReferenceType())
8061                .getUnqualifiedType();
8062     auto *SrcVD =
8063         buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
8064                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8065     auto *PseudoSrcExpr =
8066         buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
8067     auto *DstVD =
8068         buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
8069                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
8070     auto *PseudoDstExpr =
8071         buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
8072     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
8073                                    PseudoDstExpr, PseudoSrcExpr);
8074     if (AssignmentOp.isInvalid())
8075       continue;
8076     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
8077                                        /*DiscardedValue=*/true);
8078     if (AssignmentOp.isInvalid())
8079       continue;
8080
8081     // No need to mark vars as copyprivate, they are already threadprivate or
8082     // implicitly private.
8083     Vars.push_back(DE);
8084     SrcExprs.push_back(PseudoSrcExpr);
8085     DstExprs.push_back(PseudoDstExpr);
8086     AssignmentOps.push_back(AssignmentOp.get());
8087   }
8088
8089   if (Vars.empty())
8090     return nullptr;
8091
8092   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
8093                                       Vars, SrcExprs, DstExprs, AssignmentOps);
8094 }
8095
8096 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8097                                         SourceLocation StartLoc,
8098                                         SourceLocation LParenLoc,
8099                                         SourceLocation EndLoc) {
8100   if (VarList.empty())
8101     return nullptr;
8102
8103   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
8104 }
8105
8106 OMPClause *
8107 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
8108                               SourceLocation DepLoc, SourceLocation ColonLoc,
8109                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8110                               SourceLocation LParenLoc, SourceLocation EndLoc) {
8111   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
8112       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
8113     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8114         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
8115     return nullptr;
8116   }
8117   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
8118       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
8119        DepKind == OMPC_DEPEND_sink)) {
8120     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
8121     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
8122         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
8123                                    /*Last=*/OMPC_DEPEND_unknown, Except)
8124         << getOpenMPClauseName(OMPC_depend);
8125     return nullptr;
8126   }
8127   SmallVector<Expr *, 8> Vars;
8128   llvm::APSInt DepCounter(/*BitWidth=*/32);
8129   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
8130   if (DepKind == OMPC_DEPEND_sink) {
8131     if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
8132       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
8133       TotalDepCount.setIsUnsigned(/*Val=*/true);
8134     }
8135   }
8136   if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
8137       DSAStack->getParentOrderedRegionParam()) {
8138     for (auto &RefExpr : VarList) {
8139       assert(RefExpr && "NULL expr in OpenMP shared clause.");
8140       if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
8141           (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
8142         // It will be analyzed later.
8143         Vars.push_back(RefExpr);
8144         continue;
8145       }
8146
8147       SourceLocation ELoc = RefExpr->getExprLoc();
8148       auto *SimpleExpr = RefExpr->IgnoreParenCasts();
8149       if (DepKind == OMPC_DEPEND_sink) {
8150         if (DepCounter >= TotalDepCount) {
8151           Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
8152           continue;
8153         }
8154         ++DepCounter;
8155         // OpenMP  [2.13.9, Summary]
8156         // depend(dependence-type : vec), where dependence-type is:
8157         // 'sink' and where vec is the iteration vector, which has the form:
8158         //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
8159         // where n is the value specified by the ordered clause in the loop
8160         // directive, xi denotes the loop iteration variable of the i-th nested
8161         // loop associated with the loop directive, and di is a constant
8162         // non-negative integer.
8163         SimpleExpr = SimpleExpr->IgnoreImplicit();
8164         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8165         if (!DE) {
8166           OverloadedOperatorKind OOK = OO_None;
8167           SourceLocation OOLoc;
8168           Expr *LHS, *RHS;
8169           if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
8170             OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
8171             OOLoc = BO->getOperatorLoc();
8172             LHS = BO->getLHS()->IgnoreParenImpCasts();
8173             RHS = BO->getRHS()->IgnoreParenImpCasts();
8174           } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
8175             OOK = OCE->getOperator();
8176             OOLoc = OCE->getOperatorLoc();
8177             LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8178             RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
8179           } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
8180             OOK = MCE->getMethodDecl()
8181                       ->getNameInfo()
8182                       .getName()
8183                       .getCXXOverloadedOperator();
8184             OOLoc = MCE->getCallee()->getExprLoc();
8185             LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
8186             RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
8187           } else {
8188             Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
8189             continue;
8190           }
8191           DE = dyn_cast<DeclRefExpr>(LHS);
8192           if (!DE) {
8193             Diag(LHS->getExprLoc(),
8194                  diag::err_omp_depend_sink_expected_loop_iteration)
8195                 << DSAStack->getParentLoopControlVariable(
8196                     DepCounter.getZExtValue());
8197             continue;
8198           }
8199           if (OOK != OO_Plus && OOK != OO_Minus) {
8200             Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
8201             continue;
8202           }
8203           ExprResult Res = VerifyPositiveIntegerConstantInClause(
8204               RHS, OMPC_depend, /*StrictlyPositive=*/false);
8205           if (Res.isInvalid())
8206             continue;
8207         }
8208         auto *VD = dyn_cast<VarDecl>(DE->getDecl());
8209         if (!CurContext->isDependentContext() &&
8210             DSAStack->getParentOrderedRegionParam() &&
8211             (!VD || DepCounter != DSAStack->isParentLoopControlVariable(VD))) {
8212           Diag(DE->getExprLoc(),
8213                diag::err_omp_depend_sink_expected_loop_iteration)
8214               << DSAStack->getParentLoopControlVariable(
8215                   DepCounter.getZExtValue());
8216           continue;
8217         }
8218       } else {
8219         // OpenMP  [2.11.1.1, Restrictions, p.3]
8220         //  A variable that is part of another variable (such as a field of a
8221         //  structure) but is not an array element or an array section cannot
8222         //  appear  in a depend clause.
8223         auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8224         auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8225         auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8226         if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
8227             (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
8228             (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
8229              !ASE->getBase()->getType()->isArrayType())) {
8230           Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
8231               << RefExpr->getSourceRange();
8232           continue;
8233         }
8234       }
8235
8236       Vars.push_back(RefExpr->IgnoreParenImpCasts());
8237     }
8238
8239     if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
8240         TotalDepCount > VarList.size() &&
8241         DSAStack->getParentOrderedRegionParam()) {
8242       Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
8243           << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
8244     }
8245     if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
8246         Vars.empty())
8247       return nullptr;
8248   }
8249
8250   return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
8251                                  DepLoc, ColonLoc, Vars);
8252 }
8253
8254 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8255                                          SourceLocation LParenLoc,
8256                                          SourceLocation EndLoc) {
8257   Expr *ValExpr = Device;
8258
8259   // OpenMP [2.9.1, Restrictions]
8260   // The device expression must evaluate to a non-negative integer value.
8261   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
8262                                  /*StrictlyPositive=*/false))
8263     return nullptr;
8264
8265   return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8266 }
8267
8268 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
8269                                    DSAStackTy *Stack, CXXRecordDecl *RD) {
8270   if (!RD || RD->isInvalidDecl())
8271     return true;
8272
8273   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
8274     if (auto *CTD = CTSD->getSpecializedTemplate())
8275       RD = CTD->getTemplatedDecl();
8276   auto QTy = SemaRef.Context.getRecordType(RD);
8277   if (RD->isDynamicClass()) {
8278     SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8279     SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
8280     return false;
8281   }
8282   auto *DC = RD;
8283   bool IsCorrect = true;
8284   for (auto *I : DC->decls()) {
8285     if (I) {
8286       if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
8287         if (MD->isStatic()) {
8288           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8289           SemaRef.Diag(MD->getLocation(),
8290                        diag::note_omp_static_member_in_target);
8291           IsCorrect = false;
8292         }
8293       } else if (auto *VD = dyn_cast<VarDecl>(I)) {
8294         if (VD->isStaticDataMember()) {
8295           SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
8296           SemaRef.Diag(VD->getLocation(),
8297                        diag::note_omp_static_member_in_target);
8298           IsCorrect = false;
8299         }
8300       }
8301     }
8302   }
8303
8304   for (auto &I : RD->bases()) {
8305     if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
8306                                 I.getType()->getAsCXXRecordDecl()))
8307       IsCorrect = false;
8308   }
8309   return IsCorrect;
8310 }
8311
8312 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
8313                               DSAStackTy *Stack, QualType QTy) {
8314   NamedDecl *ND;
8315   if (QTy->isIncompleteType(&ND)) {
8316     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
8317     return false;
8318   } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
8319     if (!RD->isInvalidDecl() &&
8320         !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
8321       return false;
8322   }
8323   return true;
8324 }
8325
8326 OMPClause *Sema::ActOnOpenMPMapClause(
8327     OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
8328     SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8329     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
8330   SmallVector<Expr *, 4> Vars;
8331
8332   for (auto &RE : VarList) {
8333     assert(RE && "Null expr in omp map");
8334     if (isa<DependentScopeDeclRefExpr>(RE)) {
8335       // It will be analyzed later.
8336       Vars.push_back(RE);
8337       continue;
8338     }
8339     SourceLocation ELoc = RE->getExprLoc();
8340
8341     // OpenMP [2.14.5, Restrictions]
8342     //  A variable that is part of another variable (such as field of a
8343     //  structure) but is not an array element or an array section cannot appear
8344     //  in a map clause.
8345     auto *VE = RE->IgnoreParenLValueCasts();
8346
8347     if (VE->isValueDependent() || VE->isTypeDependent() ||
8348         VE->isInstantiationDependent() ||
8349         VE->containsUnexpandedParameterPack()) {
8350       // It will be analyzed later.
8351       Vars.push_back(RE);
8352       continue;
8353     }
8354
8355     auto *SimpleExpr = RE->IgnoreParenCasts();
8356     auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
8357     auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
8358     auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
8359
8360     if (!RE->IgnoreParenImpCasts()->isLValue() ||
8361         (!OASE && !ASE && !DE) ||
8362         (DE && !isa<VarDecl>(DE->getDecl())) ||
8363         (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
8364          !ASE->getBase()->getType()->isArrayType())) {
8365       Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
8366         << RE->getSourceRange();
8367       continue;
8368     }
8369
8370     Decl *D = nullptr;
8371     if (DE) {
8372       D = DE->getDecl();
8373     } else if (ASE) {
8374       auto *B = ASE->getBase()->IgnoreParenCasts();
8375       D = dyn_cast<DeclRefExpr>(B)->getDecl();
8376     } else if (OASE) {
8377       auto *B = OASE->getBase();
8378       D = dyn_cast<DeclRefExpr>(B)->getDecl();
8379     }
8380     assert(D && "Null decl on map clause.");
8381     auto *VD = cast<VarDecl>(D);
8382
8383     // OpenMP [2.14.5, Restrictions, p.8]
8384     // threadprivate variables cannot appear in a map clause.
8385     if (DSAStack->isThreadPrivate(VD)) {
8386       auto DVar = DSAStack->getTopDSA(VD, false);
8387       Diag(ELoc, diag::err_omp_threadprivate_in_map);
8388       ReportOriginalDSA(*this, DSAStack, VD, DVar);
8389       continue;
8390     }
8391
8392     // OpenMP [2.14.5, Restrictions, p.2]
8393     //  At most one list item can be an array item derived from a given variable
8394     //  in map clauses of the same construct.
8395     // OpenMP [2.14.5, Restrictions, p.3]
8396     //  List items of map clauses in the same construct must not share original
8397     //  storage.
8398     // OpenMP [2.14.5, Restrictions, C/C++, p.2]
8399     //  A variable for which the type is pointer, reference to array, or
8400     //  reference to pointer and an array section derived from that variable
8401     //  must not appear as list items of map clauses of the same construct.
8402     DSAStackTy::MapInfo MI = DSAStack->IsMappedInCurrentRegion(VD);
8403     if (MI.RefExpr) {
8404       Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
8405       Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
8406           << MI.RefExpr->getSourceRange();
8407       continue;
8408     }
8409
8410     // OpenMP [2.14.5, Restrictions, C/C++, p.3,4]
8411     //  A variable for which the type is pointer, reference to array, or
8412     //  reference to pointer must not appear as a list item if the enclosing
8413     //  device data environment already contains an array section derived from
8414     //  that variable.
8415     //  An array section derived from a variable for which the type is pointer,
8416     //  reference to array, or reference to pointer must not appear as a list
8417     //  item if the enclosing device data environment already contains that
8418     //  variable.
8419     QualType Type = VD->getType();
8420     MI = DSAStack->getMapInfoForVar(VD);
8421     if (MI.RefExpr && (isa<DeclRefExpr>(MI.RefExpr->IgnoreParenLValueCasts()) !=
8422                        isa<DeclRefExpr>(VE)) &&
8423         (Type->isPointerType() || Type->isReferenceType())) {
8424       Diag(ELoc, diag::err_omp_map_shared_storage) << ELoc;
8425       Diag(MI.RefExpr->getExprLoc(), diag::note_used_here)
8426           << MI.RefExpr->getSourceRange();
8427       continue;
8428     }
8429
8430     // OpenMP [2.14.5, Restrictions, C/C++, p.7]
8431     //  A list item must have a mappable type.
8432     if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
8433                            DSAStack, Type))
8434       continue;
8435
8436     Vars.push_back(RE);
8437     MI.RefExpr = RE;
8438     DSAStack->addMapInfoForVar(VD, MI);
8439   }
8440   if (Vars.empty())
8441     return nullptr;
8442
8443   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8444                               MapTypeModifier, MapType, MapLoc);
8445 }
8446
8447 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 
8448                                            SourceLocation StartLoc,
8449                                            SourceLocation LParenLoc,
8450                                            SourceLocation EndLoc) {
8451   Expr *ValExpr = NumTeams;
8452
8453   // OpenMP [teams Constrcut, Restrictions]
8454   // The num_teams expression must evaluate to a positive integer value.
8455   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
8456                                  /*StrictlyPositive=*/true))
8457     return nullptr;
8458
8459   return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8460 }
8461
8462 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8463                                               SourceLocation StartLoc,
8464                                               SourceLocation LParenLoc,
8465                                               SourceLocation EndLoc) {
8466   Expr *ValExpr = ThreadLimit;
8467
8468   // OpenMP [teams Constrcut, Restrictions]
8469   // The thread_limit expression must evaluate to a positive integer value.
8470   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
8471                                  /*StrictlyPositive=*/true))
8472     return nullptr;
8473
8474   return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
8475                                             EndLoc);
8476 }
8477
8478 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
8479                                            SourceLocation StartLoc,
8480                                            SourceLocation LParenLoc,
8481                                            SourceLocation EndLoc) {
8482   Expr *ValExpr = Priority;
8483
8484   // OpenMP [2.9.1, task Constrcut]
8485   // The priority-value is a non-negative numerical scalar expression.
8486   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
8487                                  /*StrictlyPositive=*/false))
8488     return nullptr;
8489
8490   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8491 }
8492
8493 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
8494                                             SourceLocation StartLoc,
8495                                             SourceLocation LParenLoc,
8496                                             SourceLocation EndLoc) {
8497   Expr *ValExpr = Grainsize;
8498
8499   // OpenMP [2.9.2, taskloop Constrcut]
8500   // The parameter of the grainsize clause must be a positive integer
8501   // expression.
8502   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
8503                                  /*StrictlyPositive=*/true))
8504     return nullptr;
8505
8506   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8507 }
8508
8509 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
8510                                            SourceLocation StartLoc,
8511                                            SourceLocation LParenLoc,
8512                                            SourceLocation EndLoc) {
8513   Expr *ValExpr = NumTasks;
8514
8515   // OpenMP [2.9.2, taskloop Constrcut]
8516   // The parameter of the num_tasks clause must be a positive integer
8517   // expression.
8518   if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
8519                                  /*StrictlyPositive=*/true))
8520     return nullptr;
8521
8522   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8523 }
8524
8525 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8526                                        SourceLocation LParenLoc,
8527                                        SourceLocation EndLoc) {
8528   // OpenMP [2.13.2, critical construct, Description]
8529   // ... where hint-expression is an integer constant expression that evaluates
8530   // to a valid lock hint.
8531   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
8532   if (HintExpr.isInvalid())
8533     return nullptr;
8534   return new (Context)
8535       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
8536 }
8537