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 "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclOpenMP.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/AST/StmtOpenMP.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/OpenMPKinds.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaInternal.h"
31 using namespace clang;
32 
33 //===----------------------------------------------------------------------===//
34 // Stack of data-sharing attributes for variables
35 //===----------------------------------------------------------------------===//
36 
37 namespace {
38 /// \brief Default data sharing attributes, which can be applied to directive.
39 enum DefaultDataSharingAttributes {
40   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
41   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
42   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
43 };
44 
45 template <class T> struct MatchesAny {
46   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
47   bool operator()(T Kind) {
48     for (auto KindEl : Arr)
49       if (KindEl == Kind)
50         return true;
51     return false;
52   }
53 
54 private:
55   ArrayRef<T> Arr;
56 };
57 struct MatchesAlways {
58   MatchesAlways() {}
59   template <class T> bool operator()(T) { return true; }
60 };
61 
62 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
63 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
64 
65 /// \brief Stack for tracking declarations used in OpenMP directives and
66 /// clauses and their data-sharing attributes.
67 class DSAStackTy {
68 public:
69   struct DSAVarData {
70     OpenMPDirectiveKind DKind;
71     OpenMPClauseKind CKind;
72     DeclRefExpr *RefExpr;
73     SourceLocation ImplicitDSALoc;
74     DSAVarData()
75         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
76           ImplicitDSALoc() {}
77   };
78 
79 private:
80   struct DSAInfo {
81     OpenMPClauseKind Attributes;
82     DeclRefExpr *RefExpr;
83   };
84   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
85   typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
86   typedef llvm::DenseSet<VarDecl *> LoopControlVariablesSetTy;
87 
88   struct SharingMapTy {
89     DeclSAMapTy SharingMap;
90     AlignedMapTy AlignedMap;
91     LoopControlVariablesSetTy LCVSet;
92     DefaultDataSharingAttributes DefaultAttr;
93     SourceLocation DefaultAttrLoc;
94     OpenMPDirectiveKind Directive;
95     DeclarationNameInfo DirectiveName;
96     Scope *CurScope;
97     SourceLocation ConstructLoc;
98     bool OrderedRegion;
99     bool NowaitRegion;
100     unsigned CollapseNumber;
101     SourceLocation InnerTeamsRegionLoc;
102     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
103                  Scope *CurScope, SourceLocation Loc)
104         : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
105           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
106           ConstructLoc(Loc), OrderedRegion(false), NowaitRegion(false),
107           CollapseNumber(1), InnerTeamsRegionLoc() {}
108     SharingMapTy()
109         : SharingMap(), AlignedMap(), LCVSet(), DefaultAttr(DSA_unspecified),
110           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
111           ConstructLoc(), OrderedRegion(false), NowaitRegion(false),
112           CollapseNumber(1), InnerTeamsRegionLoc() {}
113   };
114 
115   typedef SmallVector<SharingMapTy, 64> StackTy;
116 
117   /// \brief Stack of used declaration and their data-sharing attributes.
118   StackTy Stack;
119   /// \brief true, if check for DSA must be from parent directive, false, if
120   /// from current directive.
121   OpenMPClauseKind ClauseKindMode;
122   Sema &SemaRef;
123 
124   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
125 
126   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
127 
128   /// \brief Checks if the variable is a local for OpenMP region.
129   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
130 
131 public:
132   explicit DSAStackTy(Sema &S)
133       : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S) {}
134 
135   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
136   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
137 
138   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
139             Scope *CurScope, SourceLocation Loc) {
140     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
141     Stack.back().DefaultAttrLoc = Loc;
142   }
143 
144   void pop() {
145     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
146     Stack.pop_back();
147   }
148 
149   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
150   /// add it and return NULL; otherwise return previous occurrence's expression
151   /// for diagnostics.
152   DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
153 
154   /// \brief Register specified variable as loop control variable.
155   void addLoopControlVariable(VarDecl *D);
156   /// \brief Check if the specified variable is a loop control variable for
157   /// current region.
158   bool isLoopControlVariable(VarDecl *D);
159 
160   /// \brief Adds explicit data sharing attribute to the specified declaration.
161   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
162 
163   /// \brief Returns data sharing attributes from top of the stack for the
164   /// specified declaration.
165   DSAVarData getTopDSA(VarDecl *D, bool FromParent);
166   /// \brief Returns data-sharing attributes for the specified declaration.
167   DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
168   /// \brief Checks if the specified variables has data-sharing attributes which
169   /// match specified \a CPred predicate in any directive which matches \a DPred
170   /// predicate.
171   template <class ClausesPredicate, class DirectivesPredicate>
172   DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
173                     DirectivesPredicate DPred, bool FromParent);
174   /// \brief Checks if the specified variables has data-sharing attributes which
175   /// match specified \a CPred predicate in any innermost directive which
176   /// matches \a DPred predicate.
177   template <class ClausesPredicate, class DirectivesPredicate>
178   DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
179                              DirectivesPredicate DPred,
180                              bool FromParent);
181   /// \brief Checks if the specified variables has explicit data-sharing
182   /// attributes which match specified \a CPred predicate at the specified
183   /// OpenMP region.
184   bool hasExplicitDSA(VarDecl *D,
185                       const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
186                       unsigned Level);
187   /// \brief Finds a directive which matches specified \a DPred predicate.
188   template <class NamedDirectivesPredicate>
189   bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
190 
191   /// \brief Returns currently analyzed directive.
192   OpenMPDirectiveKind getCurrentDirective() const {
193     return Stack.back().Directive;
194   }
195   /// \brief Returns parent directive.
196   OpenMPDirectiveKind getParentDirective() const {
197     if (Stack.size() > 2)
198       return Stack[Stack.size() - 2].Directive;
199     return OMPD_unknown;
200   }
201 
202   /// \brief Set default data sharing attribute to none.
203   void setDefaultDSANone(SourceLocation Loc) {
204     Stack.back().DefaultAttr = DSA_none;
205     Stack.back().DefaultAttrLoc = Loc;
206   }
207   /// \brief Set default data sharing attribute to shared.
208   void setDefaultDSAShared(SourceLocation Loc) {
209     Stack.back().DefaultAttr = DSA_shared;
210     Stack.back().DefaultAttrLoc = Loc;
211   }
212 
213   DefaultDataSharingAttributes getDefaultDSA() const {
214     return Stack.back().DefaultAttr;
215   }
216   SourceLocation getDefaultDSALocation() const {
217     return Stack.back().DefaultAttrLoc;
218   }
219 
220   /// \brief Checks if the specified variable is a threadprivate.
221   bool isThreadPrivate(VarDecl *D) {
222     DSAVarData DVar = getTopDSA(D, false);
223     return isOpenMPThreadPrivate(DVar.CKind);
224   }
225 
226   /// \brief Marks current region as ordered (it has an 'ordered' clause).
227   void setOrderedRegion(bool IsOrdered = true) {
228     Stack.back().OrderedRegion = IsOrdered;
229   }
230   /// \brief Returns true, if parent region is ordered (has associated
231   /// 'ordered' clause), false - otherwise.
232   bool isParentOrderedRegion() const {
233     if (Stack.size() > 2)
234       return Stack[Stack.size() - 2].OrderedRegion;
235     return false;
236   }
237   /// \brief Marks current region as nowait (it has a 'nowait' clause).
238   void setNowaitRegion(bool IsNowait = true) {
239     Stack.back().NowaitRegion = IsNowait;
240   }
241   /// \brief Returns true, if parent region is nowait (has associated
242   /// 'nowait' clause), false - otherwise.
243   bool isParentNowaitRegion() const {
244     if (Stack.size() > 2)
245       return Stack[Stack.size() - 2].NowaitRegion;
246     return false;
247   }
248 
249   /// \brief Set collapse value for the region.
250   void setCollapseNumber(unsigned Val) { Stack.back().CollapseNumber = Val; }
251   /// \brief Return collapse value for region.
252   unsigned getCollapseNumber() const {
253     return Stack.back().CollapseNumber;
254   }
255 
256   /// \brief Marks current target region as one with closely nested teams
257   /// region.
258   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
259     if (Stack.size() > 2)
260       Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
261   }
262   /// \brief Returns true, if current region has closely nested teams region.
263   bool hasInnerTeamsRegion() const {
264     return getInnerTeamsRegionLoc().isValid();
265   }
266   /// \brief Returns location of the nested teams region (if any).
267   SourceLocation getInnerTeamsRegionLoc() const {
268     if (Stack.size() > 1)
269       return Stack.back().InnerTeamsRegionLoc;
270     return SourceLocation();
271   }
272 
273   Scope *getCurScope() const { return Stack.back().CurScope; }
274   Scope *getCurScope() { return Stack.back().CurScope; }
275   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
276 };
277 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
278   return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
279          isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
280 }
281 } // namespace
282 
283 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
284                                           VarDecl *D) {
285   D = D->getCanonicalDecl();
286   DSAVarData DVar;
287   if (Iter == std::prev(Stack.rend())) {
288     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
289     // in a region but not in construct]
290     //  File-scope or namespace-scope variables referenced in called routines
291     //  in the region are shared unless they appear in a threadprivate
292     //  directive.
293     if (!D->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
294       DVar.CKind = OMPC_shared;
295 
296     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
297     // in a region but not in construct]
298     //  Variables with static storage duration that are declared in called
299     //  routines in the region are shared.
300     if (D->hasGlobalStorage())
301       DVar.CKind = OMPC_shared;
302 
303     return DVar;
304   }
305 
306   DVar.DKind = Iter->Directive;
307   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
308   // in a Construct, C/C++, predetermined, p.1]
309   // Variables with automatic storage duration that are declared in a scope
310   // inside the construct are private.
311   if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
312       (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
313     DVar.CKind = OMPC_private;
314     return DVar;
315   }
316 
317   // Explicitly specified attributes and local variables with predetermined
318   // attributes.
319   if (Iter->SharingMap.count(D)) {
320     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
321     DVar.CKind = Iter->SharingMap[D].Attributes;
322     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
323     return DVar;
324   }
325 
326   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
327   // in a Construct, C/C++, implicitly determined, p.1]
328   //  In a parallel or task construct, the data-sharing attributes of these
329   //  variables are determined by the default clause, if present.
330   switch (Iter->DefaultAttr) {
331   case DSA_shared:
332     DVar.CKind = OMPC_shared;
333     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
334     return DVar;
335   case DSA_none:
336     return DVar;
337   case DSA_unspecified:
338     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
339     // in a Construct, implicitly determined, p.2]
340     //  In a parallel construct, if no default clause is present, these
341     //  variables are shared.
342     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
343     if (isOpenMPParallelDirective(DVar.DKind) ||
344         isOpenMPTeamsDirective(DVar.DKind)) {
345       DVar.CKind = OMPC_shared;
346       return DVar;
347     }
348 
349     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
350     // in a Construct, implicitly determined, p.4]
351     //  In a task construct, if no default clause is present, a variable that in
352     //  the enclosing context is determined to be shared by all implicit tasks
353     //  bound to the current team is shared.
354     if (DVar.DKind == OMPD_task) {
355       DSAVarData DVarTemp;
356       for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
357            I != EE; ++I) {
358         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
359         // Referenced
360         // in a Construct, implicitly determined, p.6]
361         //  In a task construct, if no default clause is present, a variable
362         //  whose data-sharing attribute is not determined by the rules above is
363         //  firstprivate.
364         DVarTemp = getDSA(I, D);
365         if (DVarTemp.CKind != OMPC_shared) {
366           DVar.RefExpr = nullptr;
367           DVar.DKind = OMPD_task;
368           DVar.CKind = OMPC_firstprivate;
369           return DVar;
370         }
371         if (isParallelOrTaskRegion(I->Directive))
372           break;
373       }
374       DVar.DKind = OMPD_task;
375       DVar.CKind =
376           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
377       return DVar;
378     }
379   }
380   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
381   // in a Construct, implicitly determined, p.3]
382   //  For constructs other than task, if no default clause is present, these
383   //  variables inherit their data-sharing attributes from the enclosing
384   //  context.
385   return getDSA(std::next(Iter), D);
386 }
387 
388 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
389   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
390   D = D->getCanonicalDecl();
391   auto It = Stack.back().AlignedMap.find(D);
392   if (It == Stack.back().AlignedMap.end()) {
393     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
394     Stack.back().AlignedMap[D] = NewDE;
395     return nullptr;
396   } else {
397     assert(It->second && "Unexpected nullptr expr in the aligned map");
398     return It->second;
399   }
400   return nullptr;
401 }
402 
403 void DSAStackTy::addLoopControlVariable(VarDecl *D) {
404   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
405   D = D->getCanonicalDecl();
406   Stack.back().LCVSet.insert(D);
407 }
408 
409 bool DSAStackTy::isLoopControlVariable(VarDecl *D) {
410   assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
411   D = D->getCanonicalDecl();
412   return Stack.back().LCVSet.count(D) > 0;
413 }
414 
415 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
416   D = D->getCanonicalDecl();
417   if (A == OMPC_threadprivate) {
418     Stack[0].SharingMap[D].Attributes = A;
419     Stack[0].SharingMap[D].RefExpr = E;
420   } else {
421     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
422     Stack.back().SharingMap[D].Attributes = A;
423     Stack.back().SharingMap[D].RefExpr = E;
424   }
425 }
426 
427 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
428   D = D->getCanonicalDecl();
429   if (Stack.size() > 2) {
430     reverse_iterator I = Iter, E = std::prev(Stack.rend());
431     Scope *TopScope = nullptr;
432     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
433       ++I;
434     }
435     if (I == E)
436       return false;
437     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
438     Scope *CurScope = getCurScope();
439     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
440       CurScope = CurScope->getParent();
441     }
442     return CurScope != TopScope;
443   }
444   return false;
445 }
446 
447 /// \brief Build a variable declaration for OpenMP loop iteration variable.
448 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
449                              StringRef Name) {
450   DeclContext *DC = SemaRef.CurContext;
451   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
452   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
453   VarDecl *Decl =
454       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
455   Decl->setImplicit();
456   return Decl;
457 }
458 
459 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
460                                      SourceLocation Loc,
461                                      bool RefersToCapture = false) {
462   D->setReferenced();
463   D->markUsed(S.Context);
464   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
465                              SourceLocation(), D, RefersToCapture, Loc, Ty,
466                              VK_LValue);
467 }
468 
469 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
470   D = D->getCanonicalDecl();
471   DSAVarData DVar;
472 
473   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
474   // in a Construct, C/C++, predetermined, p.1]
475   //  Variables appearing in threadprivate directives are threadprivate.
476   if ((D->getTLSKind() != VarDecl::TLS_None &&
477        !(D->hasAttr<OMPThreadPrivateDeclAttr>() &&
478          SemaRef.getLangOpts().OpenMPUseTLS &&
479          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
480       (D->getStorageClass() == SC_Register && D->hasAttr<AsmLabelAttr>() &&
481        !D->isLocalVarDecl())) {
482     addDSA(D, buildDeclRefExpr(SemaRef, D, D->getType().getNonReferenceType(),
483                                D->getLocation()),
484            OMPC_threadprivate);
485   }
486   if (Stack[0].SharingMap.count(D)) {
487     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
488     DVar.CKind = OMPC_threadprivate;
489     return DVar;
490   }
491 
492   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
493   // in a Construct, C/C++, predetermined, p.1]
494   // Variables with automatic storage duration that are declared in a scope
495   // inside the construct are private.
496   OpenMPDirectiveKind Kind =
497       FromParent ? getParentDirective() : getCurrentDirective();
498   auto StartI = std::next(Stack.rbegin());
499   auto EndI = std::prev(Stack.rend());
500   if (FromParent && StartI != EndI) {
501     StartI = std::next(StartI);
502   }
503   if (!isParallelOrTaskRegion(Kind)) {
504     if (isOpenMPLocal(D, StartI) &&
505         ((D->isLocalVarDecl() && (D->getStorageClass() == SC_Auto ||
506                                   D->getStorageClass() == SC_None)) ||
507          isa<ParmVarDecl>(D))) {
508       DVar.CKind = OMPC_private;
509       return DVar;
510     }
511 
512     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
513     // in a Construct, C/C++, predetermined, p.4]
514     //  Static data members are shared.
515     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
516     // in a Construct, C/C++, predetermined, p.7]
517     //  Variables with static storage duration that are declared in a scope
518     //  inside the construct are shared.
519     if (D->isStaticDataMember() || D->isStaticLocal()) {
520       DSAVarData DVarTemp =
521           hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
522       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
523         return DVar;
524 
525       DVar.CKind = OMPC_shared;
526       return DVar;
527     }
528   }
529 
530   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
531   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
532   Type = SemaRef.getASTContext().getBaseElementType(Type);
533   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
534   // in a Construct, C/C++, predetermined, p.6]
535   //  Variables with const qualified type having no mutable member are
536   //  shared.
537   CXXRecordDecl *RD =
538       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
539   if (IsConstant &&
540       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
541     // Variables with const-qualified type having no mutable member may be
542     // listed in a firstprivate clause, even if they are static data members.
543     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
544                                  MatchesAlways(), FromParent);
545     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
546       return DVar;
547 
548     DVar.CKind = OMPC_shared;
549     return DVar;
550   }
551 
552   // Explicitly specified attributes and local variables with predetermined
553   // attributes.
554   auto I = std::prev(StartI);
555   if (I->SharingMap.count(D)) {
556     DVar.RefExpr = I->SharingMap[D].RefExpr;
557     DVar.CKind = I->SharingMap[D].Attributes;
558     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
559   }
560 
561   return DVar;
562 }
563 
564 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
565   D = D->getCanonicalDecl();
566   auto StartI = Stack.rbegin();
567   auto EndI = std::prev(Stack.rend());
568   if (FromParent && StartI != EndI) {
569     StartI = std::next(StartI);
570   }
571   return getDSA(StartI, D);
572 }
573 
574 template <class ClausesPredicate, class DirectivesPredicate>
575 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
576                                           DirectivesPredicate DPred,
577                                           bool FromParent) {
578   D = D->getCanonicalDecl();
579   auto StartI = std::next(Stack.rbegin());
580   auto EndI = std::prev(Stack.rend());
581   if (FromParent && StartI != EndI) {
582     StartI = std::next(StartI);
583   }
584   for (auto I = StartI, EE = EndI; I != EE; ++I) {
585     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
586       continue;
587     DSAVarData DVar = getDSA(I, D);
588     if (CPred(DVar.CKind))
589       return DVar;
590   }
591   return DSAVarData();
592 }
593 
594 template <class ClausesPredicate, class DirectivesPredicate>
595 DSAStackTy::DSAVarData
596 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
597                             DirectivesPredicate DPred, bool FromParent) {
598   D = D->getCanonicalDecl();
599   auto StartI = std::next(Stack.rbegin());
600   auto EndI = std::prev(Stack.rend());
601   if (FromParent && StartI != EndI) {
602     StartI = std::next(StartI);
603   }
604   for (auto I = StartI, EE = EndI; I != EE; ++I) {
605     if (!DPred(I->Directive))
606       break;
607     DSAVarData DVar = getDSA(I, D);
608     if (CPred(DVar.CKind))
609       return DVar;
610     return DSAVarData();
611   }
612   return DSAVarData();
613 }
614 
615 bool DSAStackTy::hasExplicitDSA(
616     VarDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
617     unsigned Level) {
618   if (CPred(ClauseKindMode))
619     return true;
620   if (isClauseParsingMode())
621     ++Level;
622   D = D->getCanonicalDecl();
623   auto StartI = Stack.rbegin();
624   auto EndI = std::prev(Stack.rend());
625   if (std::distance(StartI, EndI) <= (int)Level)
626     return false;
627   std::advance(StartI, Level);
628   return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
629          CPred(StartI->SharingMap[D].Attributes);
630 }
631 
632 template <class NamedDirectivesPredicate>
633 bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
634   auto StartI = std::next(Stack.rbegin());
635   auto EndI = std::prev(Stack.rend());
636   if (FromParent && StartI != EndI) {
637     StartI = std::next(StartI);
638   }
639   for (auto I = StartI, EE = EndI; I != EE; ++I) {
640     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
641       return true;
642   }
643   return false;
644 }
645 
646 void Sema::InitDataSharingAttributesStack() {
647   VarDataSharingAttributesStack = new DSAStackTy(*this);
648 }
649 
650 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
651 
652 bool Sema::IsOpenMPCapturedVar(VarDecl *VD) {
653   assert(LangOpts.OpenMP && "OpenMP is not allowed");
654   VD = VD->getCanonicalDecl();
655   if (DSAStack->getCurrentDirective() != OMPD_unknown) {
656     if (DSAStack->isLoopControlVariable(VD) ||
657         (VD->hasLocalStorage() &&
658          isParallelOrTaskRegion(DSAStack->getCurrentDirective())))
659       return true;
660     auto DVarPrivate = DSAStack->getTopDSA(VD, DSAStack->isClauseParsingMode());
661     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
662       return true;
663     DVarPrivate = DSAStack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(),
664                                    DSAStack->isClauseParsingMode());
665     return DVarPrivate.CKind != OMPC_unknown;
666   }
667   return false;
668 }
669 
670 bool Sema::isOpenMPPrivateVar(VarDecl *VD, unsigned Level) {
671   assert(LangOpts.OpenMP && "OpenMP is not allowed");
672   return DSAStack->hasExplicitDSA(
673       VD, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
674 }
675 
676 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
677 
678 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
679                                const DeclarationNameInfo &DirName,
680                                Scope *CurScope, SourceLocation Loc) {
681   DSAStack->push(DKind, DirName, CurScope, Loc);
682   PushExpressionEvaluationContext(PotentiallyEvaluated);
683 }
684 
685 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
686   DSAStack->setClauseParsingMode(K);
687 }
688 
689 void Sema::EndOpenMPClause() {
690   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
691 }
692 
693 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
694   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
695   //  A variable of class type (or array thereof) that appears in a lastprivate
696   //  clause requires an accessible, unambiguous default constructor for the
697   //  class type, unless the list item is also specified in a firstprivate
698   //  clause.
699   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
700     for (auto *C : D->clauses()) {
701       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
702         SmallVector<Expr *, 8> PrivateCopies;
703         for (auto *DE : Clause->varlists()) {
704           if (DE->isValueDependent() || DE->isTypeDependent()) {
705             PrivateCopies.push_back(nullptr);
706             continue;
707           }
708           auto *VD = cast<VarDecl>(cast<DeclRefExpr>(DE)->getDecl());
709           QualType Type = VD->getType();
710           auto DVar = DSAStack->getTopDSA(VD, false);
711           if (DVar.CKind == OMPC_lastprivate) {
712             // Generate helper private variable and initialize it with the
713             // default value. The address of the original variable is replaced
714             // by the address of the new private variable in CodeGen. This new
715             // variable is not added to IdResolver, so the code in the OpenMP
716             // region uses original variable for proper diagnostics.
717             auto *VDPrivate =
718                 buildVarDecl(*this, DE->getExprLoc(), Type.getUnqualifiedType(),
719                              VD->getName());
720             ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
721             if (VDPrivate->isInvalidDecl())
722               continue;
723             PrivateCopies.push_back(buildDeclRefExpr(
724                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
725           } else {
726             // The variable is also a firstprivate, so initialization sequence
727             // for private copy is generated already.
728             PrivateCopies.push_back(nullptr);
729           }
730         }
731         // Set initializers to private copies if no errors were found.
732         if (PrivateCopies.size() == Clause->varlist_size()) {
733           Clause->setPrivateCopies(PrivateCopies);
734         }
735       }
736     }
737   }
738 
739   DSAStack->pop();
740   DiscardCleanupsInEvaluationContext();
741   PopExpressionEvaluationContext();
742 }
743 
744 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
745                                      Expr *NumIterations, Sema &SemaRef,
746                                      Scope *S);
747 
748 namespace {
749 
750 class VarDeclFilterCCC : public CorrectionCandidateCallback {
751 private:
752   Sema &SemaRef;
753 
754 public:
755   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
756   bool ValidateCandidate(const TypoCorrection &Candidate) override {
757     NamedDecl *ND = Candidate.getCorrectionDecl();
758     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
759       return VD->hasGlobalStorage() &&
760              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
761                                    SemaRef.getCurScope());
762     }
763     return false;
764   }
765 };
766 } // namespace
767 
768 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
769                                          CXXScopeSpec &ScopeSpec,
770                                          const DeclarationNameInfo &Id) {
771   LookupResult Lookup(*this, Id, LookupOrdinaryName);
772   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
773 
774   if (Lookup.isAmbiguous())
775     return ExprError();
776 
777   VarDecl *VD;
778   if (!Lookup.isSingleResult()) {
779     if (TypoCorrection Corrected = CorrectTypo(
780             Id, LookupOrdinaryName, CurScope, nullptr,
781             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
782       diagnoseTypo(Corrected,
783                    PDiag(Lookup.empty()
784                              ? diag::err_undeclared_var_use_suggest
785                              : diag::err_omp_expected_var_arg_suggest)
786                        << Id.getName());
787       VD = Corrected.getCorrectionDeclAs<VarDecl>();
788     } else {
789       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
790                                        : diag::err_omp_expected_var_arg)
791           << Id.getName();
792       return ExprError();
793     }
794   } else {
795     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
796       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
797       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
798       return ExprError();
799     }
800   }
801   Lookup.suppressDiagnostics();
802 
803   // OpenMP [2.9.2, Syntax, C/C++]
804   //   Variables must be file-scope, namespace-scope, or static block-scope.
805   if (!VD->hasGlobalStorage()) {
806     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
807         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
808     bool IsDecl =
809         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
810     Diag(VD->getLocation(),
811          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
812         << VD;
813     return ExprError();
814   }
815 
816   VarDecl *CanonicalVD = VD->getCanonicalDecl();
817   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
818   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
819   //   A threadprivate directive for file-scope variables must appear outside
820   //   any definition or declaration.
821   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
822       !getCurLexicalContext()->isTranslationUnit()) {
823     Diag(Id.getLoc(), diag::err_omp_var_scope)
824         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
825     bool IsDecl =
826         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
827     Diag(VD->getLocation(),
828          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
829         << VD;
830     return ExprError();
831   }
832   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
833   //   A threadprivate directive for static class member variables must appear
834   //   in the class definition, in the same scope in which the member
835   //   variables are declared.
836   if (CanonicalVD->isStaticDataMember() &&
837       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
838     Diag(Id.getLoc(), diag::err_omp_var_scope)
839         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
840     bool IsDecl =
841         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
842     Diag(VD->getLocation(),
843          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
844         << VD;
845     return ExprError();
846   }
847   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
848   //   A threadprivate directive for namespace-scope variables must appear
849   //   outside any definition or declaration other than the namespace
850   //   definition itself.
851   if (CanonicalVD->getDeclContext()->isNamespace() &&
852       (!getCurLexicalContext()->isFileContext() ||
853        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
854     Diag(Id.getLoc(), diag::err_omp_var_scope)
855         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
856     bool IsDecl =
857         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
858     Diag(VD->getLocation(),
859          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
860         << VD;
861     return ExprError();
862   }
863   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
864   //   A threadprivate directive for static block-scope variables must appear
865   //   in the scope of the variable and not in a nested scope.
866   if (CanonicalVD->isStaticLocal() && CurScope &&
867       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
868     Diag(Id.getLoc(), diag::err_omp_var_scope)
869         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
870     bool IsDecl =
871         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
872     Diag(VD->getLocation(),
873          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
874         << VD;
875     return ExprError();
876   }
877 
878   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
879   //   A threadprivate directive must lexically precede all references to any
880   //   of the variables in its list.
881   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
882     Diag(Id.getLoc(), diag::err_omp_var_used)
883         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
884     return ExprError();
885   }
886 
887   QualType ExprType = VD->getType().getNonReferenceType();
888   ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
889   return DE;
890 }
891 
892 Sema::DeclGroupPtrTy
893 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
894                                         ArrayRef<Expr *> VarList) {
895   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
896     CurContext->addDecl(D);
897     return DeclGroupPtrTy::make(DeclGroupRef(D));
898   }
899   return DeclGroupPtrTy();
900 }
901 
902 namespace {
903 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
904   Sema &SemaRef;
905 
906 public:
907   bool VisitDeclRefExpr(const DeclRefExpr *E) {
908     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
909       if (VD->hasLocalStorage()) {
910         SemaRef.Diag(E->getLocStart(),
911                      diag::err_omp_local_var_in_threadprivate_init)
912             << E->getSourceRange();
913         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
914             << VD << VD->getSourceRange();
915         return true;
916       }
917     }
918     return false;
919   }
920   bool VisitStmt(const Stmt *S) {
921     for (auto Child : S->children()) {
922       if (Child && Visit(Child))
923         return true;
924     }
925     return false;
926   }
927   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
928 };
929 } // namespace
930 
931 OMPThreadPrivateDecl *
932 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
933   SmallVector<Expr *, 8> Vars;
934   for (auto &RefExpr : VarList) {
935     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
936     VarDecl *VD = cast<VarDecl>(DE->getDecl());
937     SourceLocation ILoc = DE->getExprLoc();
938 
939     QualType QType = VD->getType();
940     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
941       // It will be analyzed later.
942       Vars.push_back(DE);
943       continue;
944     }
945 
946     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
947     //   A threadprivate variable must not have an incomplete type.
948     if (RequireCompleteType(ILoc, VD->getType(),
949                             diag::err_omp_threadprivate_incomplete_type)) {
950       continue;
951     }
952 
953     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
954     //   A threadprivate variable must not have a reference type.
955     if (VD->getType()->isReferenceType()) {
956       Diag(ILoc, diag::err_omp_ref_type_arg)
957           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
958       bool IsDecl =
959           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
960       Diag(VD->getLocation(),
961            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
962           << VD;
963       continue;
964     }
965 
966     // Check if this is a TLS variable. If TLS is not being supported, produce
967     // the corresponding diagnostic.
968     if ((VD->getTLSKind() != VarDecl::TLS_None &&
969          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
970            getLangOpts().OpenMPUseTLS &&
971            getASTContext().getTargetInfo().isTLSSupported())) ||
972         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
973          !VD->isLocalVarDecl())) {
974       Diag(ILoc, diag::err_omp_var_thread_local)
975           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
976       bool IsDecl =
977           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
978       Diag(VD->getLocation(),
979            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
980           << VD;
981       continue;
982     }
983 
984     // Check if initial value of threadprivate variable reference variable with
985     // local storage (it is not supported by runtime).
986     if (auto Init = VD->getAnyInitializer()) {
987       LocalVarRefChecker Checker(*this);
988       if (Checker.Visit(Init))
989         continue;
990     }
991 
992     Vars.push_back(RefExpr);
993     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
994     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
995         Context, SourceRange(Loc, Loc)));
996     if (auto *ML = Context.getASTMutationListener())
997       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
998   }
999   OMPThreadPrivateDecl *D = nullptr;
1000   if (!Vars.empty()) {
1001     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1002                                      Vars);
1003     D->setAccess(AS_public);
1004   }
1005   return D;
1006 }
1007 
1008 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
1009                               const VarDecl *VD, DSAStackTy::DSAVarData DVar,
1010                               bool IsLoopIterVar = false) {
1011   if (DVar.RefExpr) {
1012     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1013         << getOpenMPClauseName(DVar.CKind);
1014     return;
1015   }
1016   enum {
1017     PDSA_StaticMemberShared,
1018     PDSA_StaticLocalVarShared,
1019     PDSA_LoopIterVarPrivate,
1020     PDSA_LoopIterVarLinear,
1021     PDSA_LoopIterVarLastprivate,
1022     PDSA_ConstVarShared,
1023     PDSA_GlobalVarShared,
1024     PDSA_TaskVarFirstprivate,
1025     PDSA_LocalVarPrivate,
1026     PDSA_Implicit
1027   } Reason = PDSA_Implicit;
1028   bool ReportHint = false;
1029   auto ReportLoc = VD->getLocation();
1030   if (IsLoopIterVar) {
1031     if (DVar.CKind == OMPC_private)
1032       Reason = PDSA_LoopIterVarPrivate;
1033     else if (DVar.CKind == OMPC_lastprivate)
1034       Reason = PDSA_LoopIterVarLastprivate;
1035     else
1036       Reason = PDSA_LoopIterVarLinear;
1037   } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
1038     Reason = PDSA_TaskVarFirstprivate;
1039     ReportLoc = DVar.ImplicitDSALoc;
1040   } else if (VD->isStaticLocal())
1041     Reason = PDSA_StaticLocalVarShared;
1042   else if (VD->isStaticDataMember())
1043     Reason = PDSA_StaticMemberShared;
1044   else if (VD->isFileVarDecl())
1045     Reason = PDSA_GlobalVarShared;
1046   else if (VD->getType().isConstant(SemaRef.getASTContext()))
1047     Reason = PDSA_ConstVarShared;
1048   else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
1049     ReportHint = true;
1050     Reason = PDSA_LocalVarPrivate;
1051   }
1052   if (Reason != PDSA_Implicit) {
1053     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
1054         << Reason << ReportHint
1055         << getOpenMPDirectiveName(Stack->getCurrentDirective());
1056   } else if (DVar.ImplicitDSALoc.isValid()) {
1057     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1058         << getOpenMPClauseName(DVar.CKind);
1059   }
1060 }
1061 
1062 namespace {
1063 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1064   DSAStackTy *Stack;
1065   Sema &SemaRef;
1066   bool ErrorFound;
1067   CapturedStmt *CS;
1068   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
1069   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1070 
1071 public:
1072   void VisitDeclRefExpr(DeclRefExpr *E) {
1073     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
1074       // Skip internally declared variables.
1075       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1076         return;
1077 
1078       auto DVar = Stack->getTopDSA(VD, false);
1079       // Check if the variable has explicit DSA set and stop analysis if it so.
1080       if (DVar.RefExpr) return;
1081 
1082       auto ELoc = E->getExprLoc();
1083       auto DKind = Stack->getCurrentDirective();
1084       // The default(none) clause requires that each variable that is referenced
1085       // in the construct, and does not have a predetermined data-sharing
1086       // attribute, must have its data-sharing attribute explicitly determined
1087       // by being listed in a data-sharing attribute clause.
1088       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
1089           isParallelOrTaskRegion(DKind) &&
1090           VarsWithInheritedDSA.count(VD) == 0) {
1091         VarsWithInheritedDSA[VD] = E;
1092         return;
1093       }
1094 
1095       // OpenMP [2.9.3.6, Restrictions, p.2]
1096       //  A list item that appears in a reduction clause of the innermost
1097       //  enclosing worksharing or parallel construct may not be accessed in an
1098       //  explicit task.
1099       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
1100                                     [](OpenMPDirectiveKind K) -> bool {
1101                                       return isOpenMPParallelDirective(K) ||
1102                                              isOpenMPWorksharingDirective(K) ||
1103                                              isOpenMPTeamsDirective(K);
1104                                     },
1105                                     false);
1106       if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
1107         ErrorFound = true;
1108         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1109         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
1110         return;
1111       }
1112 
1113       // Define implicit data-sharing attributes for task.
1114       DVar = Stack->getImplicitDSA(VD, false);
1115       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
1116         ImplicitFirstprivate.push_back(E);
1117     }
1118   }
1119   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
1120     for (auto *C : S->clauses()) {
1121       // Skip analysis of arguments of implicitly defined firstprivate clause
1122       // for task directives.
1123       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1124         for (auto *CC : C->children()) {
1125           if (CC)
1126             Visit(CC);
1127         }
1128     }
1129   }
1130   void VisitStmt(Stmt *S) {
1131     for (auto *C : S->children()) {
1132       if (C && !isa<OMPExecutableDirective>(C))
1133         Visit(C);
1134     }
1135   }
1136 
1137   bool isErrorFound() { return ErrorFound; }
1138   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
1139   llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
1140     return VarsWithInheritedDSA;
1141   }
1142 
1143   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1144       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
1145 };
1146 } // namespace
1147 
1148 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
1149   switch (DKind) {
1150   case OMPD_parallel: {
1151     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1152     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1153     Sema::CapturedParamNameType Params[] = {
1154         std::make_pair(".global_tid.", KmpInt32PtrTy),
1155         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1156         std::make_pair(StringRef(), QualType()) // __context with shared vars
1157     };
1158     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1159                              Params);
1160     break;
1161   }
1162   case OMPD_simd: {
1163     Sema::CapturedParamNameType Params[] = {
1164         std::make_pair(StringRef(), QualType()) // __context with shared vars
1165     };
1166     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1167                              Params);
1168     break;
1169   }
1170   case OMPD_for: {
1171     Sema::CapturedParamNameType Params[] = {
1172         std::make_pair(StringRef(), QualType()) // __context with shared vars
1173     };
1174     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1175                              Params);
1176     break;
1177   }
1178   case OMPD_for_simd: {
1179     Sema::CapturedParamNameType Params[] = {
1180         std::make_pair(StringRef(), QualType()) // __context with shared vars
1181     };
1182     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1183                              Params);
1184     break;
1185   }
1186   case OMPD_sections: {
1187     Sema::CapturedParamNameType Params[] = {
1188         std::make_pair(StringRef(), QualType()) // __context with shared vars
1189     };
1190     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1191                              Params);
1192     break;
1193   }
1194   case OMPD_section: {
1195     Sema::CapturedParamNameType Params[] = {
1196         std::make_pair(StringRef(), QualType()) // __context with shared vars
1197     };
1198     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1199                              Params);
1200     break;
1201   }
1202   case OMPD_single: {
1203     Sema::CapturedParamNameType Params[] = {
1204         std::make_pair(StringRef(), QualType()) // __context with shared vars
1205     };
1206     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1207                              Params);
1208     break;
1209   }
1210   case OMPD_master: {
1211     Sema::CapturedParamNameType Params[] = {
1212         std::make_pair(StringRef(), QualType()) // __context with shared vars
1213     };
1214     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1215                              Params);
1216     break;
1217   }
1218   case OMPD_critical: {
1219     Sema::CapturedParamNameType Params[] = {
1220         std::make_pair(StringRef(), QualType()) // __context with shared vars
1221     };
1222     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1223                              Params);
1224     break;
1225   }
1226   case OMPD_parallel_for: {
1227     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1228     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1229     Sema::CapturedParamNameType Params[] = {
1230         std::make_pair(".global_tid.", KmpInt32PtrTy),
1231         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1232         std::make_pair(StringRef(), QualType()) // __context with shared vars
1233     };
1234     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1235                              Params);
1236     break;
1237   }
1238   case OMPD_parallel_for_simd: {
1239     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1240     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1241     Sema::CapturedParamNameType Params[] = {
1242         std::make_pair(".global_tid.", KmpInt32PtrTy),
1243         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1244         std::make_pair(StringRef(), QualType()) // __context with shared vars
1245     };
1246     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1247                              Params);
1248     break;
1249   }
1250   case OMPD_parallel_sections: {
1251     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1252     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1253     Sema::CapturedParamNameType Params[] = {
1254         std::make_pair(".global_tid.", KmpInt32PtrTy),
1255         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1256         std::make_pair(StringRef(), QualType()) // __context with shared vars
1257     };
1258     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1259                              Params);
1260     break;
1261   }
1262   case OMPD_task: {
1263     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1264     QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1265     FunctionProtoType::ExtProtoInfo EPI;
1266     EPI.Variadic = true;
1267     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
1268     Sema::CapturedParamNameType Params[] = {
1269         std::make_pair(".global_tid.", KmpInt32Ty),
1270         std::make_pair(".part_id.", KmpInt32Ty),
1271         std::make_pair(".privates.",
1272                        Context.VoidPtrTy.withConst().withRestrict()),
1273         std::make_pair(
1274             ".copy_fn.",
1275             Context.getPointerType(CopyFnType).withConst().withRestrict()),
1276         std::make_pair(StringRef(), QualType()) // __context with shared vars
1277     };
1278     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1279                              Params);
1280     // Mark this captured region as inlined, because we don't use outlined
1281     // function directly.
1282     getCurCapturedRegion()->TheCapturedDecl->addAttr(
1283         AlwaysInlineAttr::CreateImplicit(
1284             Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
1285     break;
1286   }
1287   case OMPD_ordered: {
1288     Sema::CapturedParamNameType Params[] = {
1289         std::make_pair(StringRef(), QualType()) // __context with shared vars
1290     };
1291     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1292                              Params);
1293     break;
1294   }
1295   case OMPD_atomic: {
1296     Sema::CapturedParamNameType Params[] = {
1297         std::make_pair(StringRef(), QualType()) // __context with shared vars
1298     };
1299     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1300                              Params);
1301     break;
1302   }
1303   case OMPD_target: {
1304     Sema::CapturedParamNameType Params[] = {
1305         std::make_pair(StringRef(), QualType()) // __context with shared vars
1306     };
1307     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1308                              Params);
1309     break;
1310   }
1311   case OMPD_teams: {
1312     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1313     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1314     Sema::CapturedParamNameType Params[] = {
1315         std::make_pair(".global_tid.", KmpInt32PtrTy),
1316         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1317         std::make_pair(StringRef(), QualType()) // __context with shared vars
1318     };
1319     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1320                              Params);
1321     break;
1322   }
1323   case OMPD_taskgroup: {
1324     Sema::CapturedParamNameType Params[] = {
1325         std::make_pair(StringRef(), QualType()) // __context with shared vars
1326     };
1327     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1328                              Params);
1329     break;
1330   }
1331   case OMPD_threadprivate:
1332   case OMPD_taskyield:
1333   case OMPD_barrier:
1334   case OMPD_taskwait:
1335   case OMPD_cancellation_point:
1336   case OMPD_cancel:
1337   case OMPD_flush:
1338     llvm_unreachable("OpenMP Directive is not allowed");
1339   case OMPD_unknown:
1340     llvm_unreachable("Unknown OpenMP directive");
1341   }
1342 }
1343 
1344 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1345                                       ArrayRef<OMPClause *> Clauses) {
1346   if (!S.isUsable()) {
1347     ActOnCapturedRegionError();
1348     return StmtError();
1349   }
1350   // This is required for proper codegen.
1351   for (auto *Clause : Clauses) {
1352     if (isOpenMPPrivate(Clause->getClauseKind()) ||
1353         Clause->getClauseKind() == OMPC_copyprivate) {
1354       // Mark all variables in private list clauses as used in inner region.
1355       for (auto *VarRef : Clause->children()) {
1356         if (auto *E = cast_or_null<Expr>(VarRef)) {
1357           MarkDeclarationsReferencedInExpr(E);
1358         }
1359       }
1360     } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
1361                Clause->getClauseKind() == OMPC_schedule) {
1362       // Mark all variables in private list clauses as used in inner region.
1363       // Required for proper codegen of combined directives.
1364       // TODO: add processing for other clauses.
1365       if (auto *E = cast_or_null<Expr>(
1366               cast<OMPScheduleClause>(Clause)->getHelperChunkSize())) {
1367           MarkDeclarationsReferencedInExpr(E);
1368         }
1369     }
1370   }
1371   return ActOnCapturedRegionEnd(S.get());
1372 }
1373 
1374 static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1375                                   OpenMPDirectiveKind CurrentRegion,
1376                                   const DeclarationNameInfo &CurrentName,
1377                                   OpenMPDirectiveKind CancelRegion,
1378                                   SourceLocation StartLoc) {
1379   // Allowed nesting of constructs
1380   // +------------------+-----------------+------------------------------------+
1381   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1382   // +------------------+-----------------+------------------------------------+
1383   // | parallel         | parallel        | *                                  |
1384   // | parallel         | for             | *                                  |
1385   // | parallel         | for simd        | *                                  |
1386   // | parallel         | master          | *                                  |
1387   // | parallel         | critical        | *                                  |
1388   // | parallel         | simd            | *                                  |
1389   // | parallel         | sections        | *                                  |
1390   // | parallel         | section         | +                                  |
1391   // | parallel         | single          | *                                  |
1392   // | parallel         | parallel for    | *                                  |
1393   // | parallel         |parallel for simd| *                                  |
1394   // | parallel         |parallel sections| *                                  |
1395   // | parallel         | task            | *                                  |
1396   // | parallel         | taskyield       | *                                  |
1397   // | parallel         | barrier         | *                                  |
1398   // | parallel         | taskwait        | *                                  |
1399   // | parallel         | taskgroup       | *                                  |
1400   // | parallel         | flush           | *                                  |
1401   // | parallel         | ordered         | +                                  |
1402   // | parallel         | atomic          | *                                  |
1403   // | parallel         | target          | *                                  |
1404   // | parallel         | teams           | +                                  |
1405   // | parallel         | cancellation    |                                    |
1406   // |                  | point           | !                                  |
1407   // | parallel         | cancel          | !                                  |
1408   // +------------------+-----------------+------------------------------------+
1409   // | for              | parallel        | *                                  |
1410   // | for              | for             | +                                  |
1411   // | for              | for simd        | +                                  |
1412   // | for              | master          | +                                  |
1413   // | for              | critical        | *                                  |
1414   // | for              | simd            | *                                  |
1415   // | for              | sections        | +                                  |
1416   // | for              | section         | +                                  |
1417   // | for              | single          | +                                  |
1418   // | for              | parallel for    | *                                  |
1419   // | for              |parallel for simd| *                                  |
1420   // | for              |parallel sections| *                                  |
1421   // | for              | task            | *                                  |
1422   // | for              | taskyield       | *                                  |
1423   // | for              | barrier         | +                                  |
1424   // | for              | taskwait        | *                                  |
1425   // | for              | taskgroup       | *                                  |
1426   // | for              | flush           | *                                  |
1427   // | for              | ordered         | * (if construct is ordered)        |
1428   // | for              | atomic          | *                                  |
1429   // | for              | target          | *                                  |
1430   // | for              | teams           | +                                  |
1431   // | for              | cancellation    |                                    |
1432   // |                  | point           | !                                  |
1433   // | for              | cancel          | !                                  |
1434   // +------------------+-----------------+------------------------------------+
1435   // | master           | parallel        | *                                  |
1436   // | master           | for             | +                                  |
1437   // | master           | for simd        | +                                  |
1438   // | master           | master          | *                                  |
1439   // | master           | critical        | *                                  |
1440   // | master           | simd            | *                                  |
1441   // | master           | sections        | +                                  |
1442   // | master           | section         | +                                  |
1443   // | master           | single          | +                                  |
1444   // | master           | parallel for    | *                                  |
1445   // | master           |parallel for simd| *                                  |
1446   // | master           |parallel sections| *                                  |
1447   // | master           | task            | *                                  |
1448   // | master           | taskyield       | *                                  |
1449   // | master           | barrier         | +                                  |
1450   // | master           | taskwait        | *                                  |
1451   // | master           | taskgroup       | *                                  |
1452   // | master           | flush           | *                                  |
1453   // | master           | ordered         | +                                  |
1454   // | master           | atomic          | *                                  |
1455   // | master           | target          | *                                  |
1456   // | master           | teams           | +                                  |
1457   // | master           | cancellation    |                                    |
1458   // |                  | point           |                                    |
1459   // | master           | cancel          |                                    |
1460   // +------------------+-----------------+------------------------------------+
1461   // | critical         | parallel        | *                                  |
1462   // | critical         | for             | +                                  |
1463   // | critical         | for simd        | +                                  |
1464   // | critical         | master          | *                                  |
1465   // | critical         | critical        | * (should have different names)    |
1466   // | critical         | simd            | *                                  |
1467   // | critical         | sections        | +                                  |
1468   // | critical         | section         | +                                  |
1469   // | critical         | single          | +                                  |
1470   // | critical         | parallel for    | *                                  |
1471   // | critical         |parallel for simd| *                                  |
1472   // | critical         |parallel sections| *                                  |
1473   // | critical         | task            | *                                  |
1474   // | critical         | taskyield       | *                                  |
1475   // | critical         | barrier         | +                                  |
1476   // | critical         | taskwait        | *                                  |
1477   // | critical         | taskgroup       | *                                  |
1478   // | critical         | ordered         | +                                  |
1479   // | critical         | atomic          | *                                  |
1480   // | critical         | target          | *                                  |
1481   // | critical         | teams           | +                                  |
1482   // | critical         | cancellation    |                                    |
1483   // |                  | point           |                                    |
1484   // | critical         | cancel          |                                    |
1485   // +------------------+-----------------+------------------------------------+
1486   // | simd             | parallel        |                                    |
1487   // | simd             | for             |                                    |
1488   // | simd             | for simd        |                                    |
1489   // | simd             | master          |                                    |
1490   // | simd             | critical        |                                    |
1491   // | simd             | simd            |                                    |
1492   // | simd             | sections        |                                    |
1493   // | simd             | section         |                                    |
1494   // | simd             | single          |                                    |
1495   // | simd             | parallel for    |                                    |
1496   // | simd             |parallel for simd|                                    |
1497   // | simd             |parallel sections|                                    |
1498   // | simd             | task            |                                    |
1499   // | simd             | taskyield       |                                    |
1500   // | simd             | barrier         |                                    |
1501   // | simd             | taskwait        |                                    |
1502   // | simd             | taskgroup       |                                    |
1503   // | simd             | flush           |                                    |
1504   // | simd             | ordered         |                                    |
1505   // | simd             | atomic          |                                    |
1506   // | simd             | target          |                                    |
1507   // | simd             | teams           |                                    |
1508   // | simd             | cancellation    |                                    |
1509   // |                  | point           |                                    |
1510   // | simd             | cancel          |                                    |
1511   // +------------------+-----------------+------------------------------------+
1512   // | for simd         | parallel        |                                    |
1513   // | for simd         | for             |                                    |
1514   // | for simd         | for simd        |                                    |
1515   // | for simd         | master          |                                    |
1516   // | for simd         | critical        |                                    |
1517   // | for simd         | simd            |                                    |
1518   // | for simd         | sections        |                                    |
1519   // | for simd         | section         |                                    |
1520   // | for simd         | single          |                                    |
1521   // | for simd         | parallel for    |                                    |
1522   // | for simd         |parallel for simd|                                    |
1523   // | for simd         |parallel sections|                                    |
1524   // | for simd         | task            |                                    |
1525   // | for simd         | taskyield       |                                    |
1526   // | for simd         | barrier         |                                    |
1527   // | for simd         | taskwait        |                                    |
1528   // | for simd         | taskgroup       |                                    |
1529   // | for simd         | flush           |                                    |
1530   // | for simd         | ordered         |                                    |
1531   // | for simd         | atomic          |                                    |
1532   // | for simd         | target          |                                    |
1533   // | for simd         | teams           |                                    |
1534   // | for simd         | cancellation    |                                    |
1535   // |                  | point           |                                    |
1536   // | for simd         | cancel          |                                    |
1537   // +------------------+-----------------+------------------------------------+
1538   // | parallel for simd| parallel        |                                    |
1539   // | parallel for simd| for             |                                    |
1540   // | parallel for simd| for simd        |                                    |
1541   // | parallel for simd| master          |                                    |
1542   // | parallel for simd| critical        |                                    |
1543   // | parallel for simd| simd            |                                    |
1544   // | parallel for simd| sections        |                                    |
1545   // | parallel for simd| section         |                                    |
1546   // | parallel for simd| single          |                                    |
1547   // | parallel for simd| parallel for    |                                    |
1548   // | parallel for simd|parallel for simd|                                    |
1549   // | parallel for simd|parallel sections|                                    |
1550   // | parallel for simd| task            |                                    |
1551   // | parallel for simd| taskyield       |                                    |
1552   // | parallel for simd| barrier         |                                    |
1553   // | parallel for simd| taskwait        |                                    |
1554   // | parallel for simd| taskgroup       |                                    |
1555   // | parallel for simd| flush           |                                    |
1556   // | parallel for simd| ordered         |                                    |
1557   // | parallel for simd| atomic          |                                    |
1558   // | parallel for simd| target          |                                    |
1559   // | parallel for simd| teams           |                                    |
1560   // | parallel for simd| cancellation    |                                    |
1561   // |                  | point           |                                    |
1562   // | parallel for simd| cancel          |                                    |
1563   // +------------------+-----------------+------------------------------------+
1564   // | sections         | parallel        | *                                  |
1565   // | sections         | for             | +                                  |
1566   // | sections         | for simd        | +                                  |
1567   // | sections         | master          | +                                  |
1568   // | sections         | critical        | *                                  |
1569   // | sections         | simd            | *                                  |
1570   // | sections         | sections        | +                                  |
1571   // | sections         | section         | *                                  |
1572   // | sections         | single          | +                                  |
1573   // | sections         | parallel for    | *                                  |
1574   // | sections         |parallel for simd| *                                  |
1575   // | sections         |parallel sections| *                                  |
1576   // | sections         | task            | *                                  |
1577   // | sections         | taskyield       | *                                  |
1578   // | sections         | barrier         | +                                  |
1579   // | sections         | taskwait        | *                                  |
1580   // | sections         | taskgroup       | *                                  |
1581   // | sections         | flush           | *                                  |
1582   // | sections         | ordered         | +                                  |
1583   // | sections         | atomic          | *                                  |
1584   // | sections         | target          | *                                  |
1585   // | sections         | teams           | +                                  |
1586   // | sections         | cancellation    |                                    |
1587   // |                  | point           | !                                  |
1588   // | sections         | cancel          | !                                  |
1589   // +------------------+-----------------+------------------------------------+
1590   // | section          | parallel        | *                                  |
1591   // | section          | for             | +                                  |
1592   // | section          | for simd        | +                                  |
1593   // | section          | master          | +                                  |
1594   // | section          | critical        | *                                  |
1595   // | section          | simd            | *                                  |
1596   // | section          | sections        | +                                  |
1597   // | section          | section         | +                                  |
1598   // | section          | single          | +                                  |
1599   // | section          | parallel for    | *                                  |
1600   // | section          |parallel for simd| *                                  |
1601   // | section          |parallel sections| *                                  |
1602   // | section          | task            | *                                  |
1603   // | section          | taskyield       | *                                  |
1604   // | section          | barrier         | +                                  |
1605   // | section          | taskwait        | *                                  |
1606   // | section          | taskgroup       | *                                  |
1607   // | section          | flush           | *                                  |
1608   // | section          | ordered         | +                                  |
1609   // | section          | atomic          | *                                  |
1610   // | section          | target          | *                                  |
1611   // | section          | teams           | +                                  |
1612   // | section          | cancellation    |                                    |
1613   // |                  | point           | !                                  |
1614   // | section          | cancel          | !                                  |
1615   // +------------------+-----------------+------------------------------------+
1616   // | single           | parallel        | *                                  |
1617   // | single           | for             | +                                  |
1618   // | single           | for simd        | +                                  |
1619   // | single           | master          | +                                  |
1620   // | single           | critical        | *                                  |
1621   // | single           | simd            | *                                  |
1622   // | single           | sections        | +                                  |
1623   // | single           | section         | +                                  |
1624   // | single           | single          | +                                  |
1625   // | single           | parallel for    | *                                  |
1626   // | single           |parallel for simd| *                                  |
1627   // | single           |parallel sections| *                                  |
1628   // | single           | task            | *                                  |
1629   // | single           | taskyield       | *                                  |
1630   // | single           | barrier         | +                                  |
1631   // | single           | taskwait        | *                                  |
1632   // | single           | taskgroup       | *                                  |
1633   // | single           | flush           | *                                  |
1634   // | single           | ordered         | +                                  |
1635   // | single           | atomic          | *                                  |
1636   // | single           | target          | *                                  |
1637   // | single           | teams           | +                                  |
1638   // | single           | cancellation    |                                    |
1639   // |                  | point           |                                    |
1640   // | single           | cancel          |                                    |
1641   // +------------------+-----------------+------------------------------------+
1642   // | parallel for     | parallel        | *                                  |
1643   // | parallel for     | for             | +                                  |
1644   // | parallel for     | for simd        | +                                  |
1645   // | parallel for     | master          | +                                  |
1646   // | parallel for     | critical        | *                                  |
1647   // | parallel for     | simd            | *                                  |
1648   // | parallel for     | sections        | +                                  |
1649   // | parallel for     | section         | +                                  |
1650   // | parallel for     | single          | +                                  |
1651   // | parallel for     | parallel for    | *                                  |
1652   // | parallel for     |parallel for simd| *                                  |
1653   // | parallel for     |parallel sections| *                                  |
1654   // | parallel for     | task            | *                                  |
1655   // | parallel for     | taskyield       | *                                  |
1656   // | parallel for     | barrier         | +                                  |
1657   // | parallel for     | taskwait        | *                                  |
1658   // | parallel for     | taskgroup       | *                                  |
1659   // | parallel for     | flush           | *                                  |
1660   // | parallel for     | ordered         | * (if construct is ordered)        |
1661   // | parallel for     | atomic          | *                                  |
1662   // | parallel for     | target          | *                                  |
1663   // | parallel for     | teams           | +                                  |
1664   // | parallel for     | cancellation    |                                    |
1665   // |                  | point           | !                                  |
1666   // | parallel for     | cancel          | !                                  |
1667   // +------------------+-----------------+------------------------------------+
1668   // | parallel sections| parallel        | *                                  |
1669   // | parallel sections| for             | +                                  |
1670   // | parallel sections| for simd        | +                                  |
1671   // | parallel sections| master          | +                                  |
1672   // | parallel sections| critical        | +                                  |
1673   // | parallel sections| simd            | *                                  |
1674   // | parallel sections| sections        | +                                  |
1675   // | parallel sections| section         | *                                  |
1676   // | parallel sections| single          | +                                  |
1677   // | parallel sections| parallel for    | *                                  |
1678   // | parallel sections|parallel for simd| *                                  |
1679   // | parallel sections|parallel sections| *                                  |
1680   // | parallel sections| task            | *                                  |
1681   // | parallel sections| taskyield       | *                                  |
1682   // | parallel sections| barrier         | +                                  |
1683   // | parallel sections| taskwait        | *                                  |
1684   // | parallel sections| taskgroup       | *                                  |
1685   // | parallel sections| flush           | *                                  |
1686   // | parallel sections| ordered         | +                                  |
1687   // | parallel sections| atomic          | *                                  |
1688   // | parallel sections| target          | *                                  |
1689   // | parallel sections| teams           | +                                  |
1690   // | parallel sections| cancellation    |                                    |
1691   // |                  | point           | !                                  |
1692   // | parallel sections| cancel          | !                                  |
1693   // +------------------+-----------------+------------------------------------+
1694   // | task             | parallel        | *                                  |
1695   // | task             | for             | +                                  |
1696   // | task             | for simd        | +                                  |
1697   // | task             | master          | +                                  |
1698   // | task             | critical        | *                                  |
1699   // | task             | simd            | *                                  |
1700   // | task             | sections        | +                                  |
1701   // | task             | section         | +                                  |
1702   // | task             | single          | +                                  |
1703   // | task             | parallel for    | *                                  |
1704   // | task             |parallel for simd| *                                  |
1705   // | task             |parallel sections| *                                  |
1706   // | task             | task            | *                                  |
1707   // | task             | taskyield       | *                                  |
1708   // | task             | barrier         | +                                  |
1709   // | task             | taskwait        | *                                  |
1710   // | task             | taskgroup       | *                                  |
1711   // | task             | flush           | *                                  |
1712   // | task             | ordered         | +                                  |
1713   // | task             | atomic          | *                                  |
1714   // | task             | target          | *                                  |
1715   // | task             | teams           | +                                  |
1716   // | task             | cancellation    |                                    |
1717   // |                  | point           | !                                  |
1718   // | task             | cancel          | !                                  |
1719   // +------------------+-----------------+------------------------------------+
1720   // | ordered          | parallel        | *                                  |
1721   // | ordered          | for             | +                                  |
1722   // | ordered          | for simd        | +                                  |
1723   // | ordered          | master          | *                                  |
1724   // | ordered          | critical        | *                                  |
1725   // | ordered          | simd            | *                                  |
1726   // | ordered          | sections        | +                                  |
1727   // | ordered          | section         | +                                  |
1728   // | ordered          | single          | +                                  |
1729   // | ordered          | parallel for    | *                                  |
1730   // | ordered          |parallel for simd| *                                  |
1731   // | ordered          |parallel sections| *                                  |
1732   // | ordered          | task            | *                                  |
1733   // | ordered          | taskyield       | *                                  |
1734   // | ordered          | barrier         | +                                  |
1735   // | ordered          | taskwait        | *                                  |
1736   // | ordered          | taskgroup       | *                                  |
1737   // | ordered          | flush           | *                                  |
1738   // | ordered          | ordered         | +                                  |
1739   // | ordered          | atomic          | *                                  |
1740   // | ordered          | target          | *                                  |
1741   // | ordered          | teams           | +                                  |
1742   // | ordered          | cancellation    |                                    |
1743   // |                  | point           |                                    |
1744   // | ordered          | cancel          |                                    |
1745   // +------------------+-----------------+------------------------------------+
1746   // | atomic           | parallel        |                                    |
1747   // | atomic           | for             |                                    |
1748   // | atomic           | for simd        |                                    |
1749   // | atomic           | master          |                                    |
1750   // | atomic           | critical        |                                    |
1751   // | atomic           | simd            |                                    |
1752   // | atomic           | sections        |                                    |
1753   // | atomic           | section         |                                    |
1754   // | atomic           | single          |                                    |
1755   // | atomic           | parallel for    |                                    |
1756   // | atomic           |parallel for simd|                                    |
1757   // | atomic           |parallel sections|                                    |
1758   // | atomic           | task            |                                    |
1759   // | atomic           | taskyield       |                                    |
1760   // | atomic           | barrier         |                                    |
1761   // | atomic           | taskwait        |                                    |
1762   // | atomic           | taskgroup       |                                    |
1763   // | atomic           | flush           |                                    |
1764   // | atomic           | ordered         |                                    |
1765   // | atomic           | atomic          |                                    |
1766   // | atomic           | target          |                                    |
1767   // | atomic           | teams           |                                    |
1768   // | atomic           | cancellation    |                                    |
1769   // |                  | point           |                                    |
1770   // | atomic           | cancel          |                                    |
1771   // +------------------+-----------------+------------------------------------+
1772   // | target           | parallel        | *                                  |
1773   // | target           | for             | *                                  |
1774   // | target           | for simd        | *                                  |
1775   // | target           | master          | *                                  |
1776   // | target           | critical        | *                                  |
1777   // | target           | simd            | *                                  |
1778   // | target           | sections        | *                                  |
1779   // | target           | section         | *                                  |
1780   // | target           | single          | *                                  |
1781   // | target           | parallel for    | *                                  |
1782   // | target           |parallel for simd| *                                  |
1783   // | target           |parallel sections| *                                  |
1784   // | target           | task            | *                                  |
1785   // | target           | taskyield       | *                                  |
1786   // | target           | barrier         | *                                  |
1787   // | target           | taskwait        | *                                  |
1788   // | target           | taskgroup       | *                                  |
1789   // | target           | flush           | *                                  |
1790   // | target           | ordered         | *                                  |
1791   // | target           | atomic          | *                                  |
1792   // | target           | target          | *                                  |
1793   // | target           | teams           | *                                  |
1794   // | target           | cancellation    |                                    |
1795   // |                  | point           |                                    |
1796   // | target           | cancel          |                                    |
1797   // +------------------+-----------------+------------------------------------+
1798   // | teams            | parallel        | *                                  |
1799   // | teams            | for             | +                                  |
1800   // | teams            | for simd        | +                                  |
1801   // | teams            | master          | +                                  |
1802   // | teams            | critical        | +                                  |
1803   // | teams            | simd            | +                                  |
1804   // | teams            | sections        | +                                  |
1805   // | teams            | section         | +                                  |
1806   // | teams            | single          | +                                  |
1807   // | teams            | parallel for    | *                                  |
1808   // | teams            |parallel for simd| *                                  |
1809   // | teams            |parallel sections| *                                  |
1810   // | teams            | task            | +                                  |
1811   // | teams            | taskyield       | +                                  |
1812   // | teams            | barrier         | +                                  |
1813   // | teams            | taskwait        | +                                  |
1814   // | teams            | taskgroup       | +                                  |
1815   // | teams            | flush           | +                                  |
1816   // | teams            | ordered         | +                                  |
1817   // | teams            | atomic          | +                                  |
1818   // | teams            | target          | +                                  |
1819   // | teams            | teams           | +                                  |
1820   // | teams            | cancellation    |                                    |
1821   // |                  | point           |                                    |
1822   // | teams            | cancel          |                                    |
1823   // +------------------+-----------------+------------------------------------+
1824   if (Stack->getCurScope()) {
1825     auto ParentRegion = Stack->getParentDirective();
1826     bool NestingProhibited = false;
1827     bool CloseNesting = true;
1828     enum {
1829       NoRecommend,
1830       ShouldBeInParallelRegion,
1831       ShouldBeInOrderedRegion,
1832       ShouldBeInTargetRegion
1833     } Recommend = NoRecommend;
1834     if (isOpenMPSimdDirective(ParentRegion)) {
1835       // OpenMP [2.16, Nesting of Regions]
1836       // OpenMP constructs may not be nested inside a simd region.
1837       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1838       return true;
1839     }
1840     if (ParentRegion == OMPD_atomic) {
1841       // OpenMP [2.16, Nesting of Regions]
1842       // OpenMP constructs may not be nested inside an atomic region.
1843       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1844       return true;
1845     }
1846     if (CurrentRegion == OMPD_section) {
1847       // OpenMP [2.7.2, sections Construct, Restrictions]
1848       // Orphaned section directives are prohibited. That is, the section
1849       // directives must appear within the sections construct and must not be
1850       // encountered elsewhere in the sections region.
1851       if (ParentRegion != OMPD_sections &&
1852           ParentRegion != OMPD_parallel_sections) {
1853         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1854             << (ParentRegion != OMPD_unknown)
1855             << getOpenMPDirectiveName(ParentRegion);
1856         return true;
1857       }
1858       return false;
1859     }
1860     // Allow some constructs to be orphaned (they could be used in functions,
1861     // called from OpenMP regions with the required preconditions).
1862     if (ParentRegion == OMPD_unknown)
1863       return false;
1864     if (CurrentRegion == OMPD_cancellation_point ||
1865         CurrentRegion == OMPD_cancel) {
1866       // OpenMP [2.16, Nesting of Regions]
1867       // A cancellation point construct for which construct-type-clause is
1868       // taskgroup must be nested inside a task construct. A cancellation
1869       // point construct for which construct-type-clause is not taskgroup must
1870       // be closely nested inside an OpenMP construct that matches the type
1871       // specified in construct-type-clause.
1872       // A cancel construct for which construct-type-clause is taskgroup must be
1873       // nested inside a task construct. A cancel construct for which
1874       // construct-type-clause is not taskgroup must be closely nested inside an
1875       // OpenMP construct that matches the type specified in
1876       // construct-type-clause.
1877       NestingProhibited =
1878           !((CancelRegion == OMPD_parallel && ParentRegion == OMPD_parallel) ||
1879             (CancelRegion == OMPD_for && ParentRegion == OMPD_for) ||
1880             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
1881             (CancelRegion == OMPD_sections &&
1882              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections)));
1883     } else if (CurrentRegion == OMPD_master) {
1884       // OpenMP [2.16, Nesting of Regions]
1885       // A master region may not be closely nested inside a worksharing,
1886       // atomic, or explicit task region.
1887       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1888                           ParentRegion == OMPD_task;
1889     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
1890       // OpenMP [2.16, Nesting of Regions]
1891       // A critical region may not be nested (closely or otherwise) inside a
1892       // critical region with the same name. Note that this restriction is not
1893       // sufficient to prevent deadlock.
1894       SourceLocation PreviousCriticalLoc;
1895       bool DeadLock =
1896           Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
1897                                   OpenMPDirectiveKind K,
1898                                   const DeclarationNameInfo &DNI,
1899                                   SourceLocation Loc)
1900                                   ->bool {
1901                                 if (K == OMPD_critical &&
1902                                     DNI.getName() == CurrentName.getName()) {
1903                                   PreviousCriticalLoc = Loc;
1904                                   return true;
1905                                 } else
1906                                   return false;
1907                               },
1908                               false /* skip top directive */);
1909       if (DeadLock) {
1910         SemaRef.Diag(StartLoc,
1911                      diag::err_omp_prohibited_region_critical_same_name)
1912             << CurrentName.getName();
1913         if (PreviousCriticalLoc.isValid())
1914           SemaRef.Diag(PreviousCriticalLoc,
1915                        diag::note_omp_previous_critical_region);
1916         return true;
1917       }
1918     } else if (CurrentRegion == OMPD_barrier) {
1919       // OpenMP [2.16, Nesting of Regions]
1920       // A barrier region may not be closely nested inside a worksharing,
1921       // explicit task, critical, ordered, atomic, or master region.
1922       NestingProhibited =
1923           isOpenMPWorksharingDirective(ParentRegion) ||
1924           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1925           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1926     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1927                !isOpenMPParallelDirective(CurrentRegion)) {
1928       // OpenMP [2.16, Nesting of Regions]
1929       // A worksharing region may not be closely nested inside a worksharing,
1930       // explicit task, critical, ordered, atomic, or master region.
1931       NestingProhibited =
1932           isOpenMPWorksharingDirective(ParentRegion) ||
1933           ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
1934           ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
1935       Recommend = ShouldBeInParallelRegion;
1936     } else if (CurrentRegion == OMPD_ordered) {
1937       // OpenMP [2.16, Nesting of Regions]
1938       // An ordered region may not be closely nested inside a critical,
1939       // atomic, or explicit task region.
1940       // An ordered region must be closely nested inside a loop region (or
1941       // parallel loop region) with an ordered clause.
1942       NestingProhibited = ParentRegion == OMPD_critical ||
1943                           ParentRegion == OMPD_task ||
1944                           !Stack->isParentOrderedRegion();
1945       Recommend = ShouldBeInOrderedRegion;
1946     } else if (isOpenMPTeamsDirective(CurrentRegion)) {
1947       // OpenMP [2.16, Nesting of Regions]
1948       // If specified, a teams construct must be contained within a target
1949       // construct.
1950       NestingProhibited = ParentRegion != OMPD_target;
1951       Recommend = ShouldBeInTargetRegion;
1952       Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
1953     }
1954     if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
1955       // OpenMP [2.16, Nesting of Regions]
1956       // distribute, parallel, parallel sections, parallel workshare, and the
1957       // parallel loop and parallel loop SIMD constructs are the only OpenMP
1958       // constructs that can be closely nested in the teams region.
1959       // TODO: add distribute directive.
1960       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion);
1961       Recommend = ShouldBeInParallelRegion;
1962     }
1963     if (NestingProhibited) {
1964       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1965           << CloseNesting << getOpenMPDirectiveName(ParentRegion) << Recommend
1966           << getOpenMPDirectiveName(CurrentRegion);
1967       return true;
1968     }
1969   }
1970   return false;
1971 }
1972 
1973 StmtResult Sema::ActOnOpenMPExecutableDirective(
1974     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
1975     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
1976     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
1977   StmtResult Res = StmtError();
1978   if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
1979                             StartLoc))
1980     return StmtError();
1981 
1982   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1983   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1984   bool ErrorFound = false;
1985   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1986   if (AStmt) {
1987     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1988 
1989     // Check default data sharing attributes for referenced variables.
1990     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1991     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1992     if (DSAChecker.isErrorFound())
1993       return StmtError();
1994     // Generate list of implicitly defined firstprivate variables.
1995     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1996 
1997     if (!DSAChecker.getImplicitFirstprivate().empty()) {
1998       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1999               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2000               SourceLocation(), SourceLocation())) {
2001         ClausesWithImplicit.push_back(Implicit);
2002         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2003                      DSAChecker.getImplicitFirstprivate().size();
2004       } else
2005         ErrorFound = true;
2006     }
2007   }
2008 
2009   switch (Kind) {
2010   case OMPD_parallel:
2011     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2012                                        EndLoc);
2013     break;
2014   case OMPD_simd:
2015     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2016                                    VarsWithInheritedDSA);
2017     break;
2018   case OMPD_for:
2019     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2020                                   VarsWithInheritedDSA);
2021     break;
2022   case OMPD_for_simd:
2023     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2024                                       EndLoc, VarsWithInheritedDSA);
2025     break;
2026   case OMPD_sections:
2027     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2028                                        EndLoc);
2029     break;
2030   case OMPD_section:
2031     assert(ClausesWithImplicit.empty() &&
2032            "No clauses are allowed for 'omp section' directive");
2033     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2034     break;
2035   case OMPD_single:
2036     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2037                                      EndLoc);
2038     break;
2039   case OMPD_master:
2040     assert(ClausesWithImplicit.empty() &&
2041            "No clauses are allowed for 'omp master' directive");
2042     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2043     break;
2044   case OMPD_critical:
2045     assert(ClausesWithImplicit.empty() &&
2046            "No clauses are allowed for 'omp critical' directive");
2047     Res = ActOnOpenMPCriticalDirective(DirName, AStmt, StartLoc, EndLoc);
2048     break;
2049   case OMPD_parallel_for:
2050     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2051                                           EndLoc, VarsWithInheritedDSA);
2052     break;
2053   case OMPD_parallel_for_simd:
2054     Res = ActOnOpenMPParallelForSimdDirective(
2055         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2056     break;
2057   case OMPD_parallel_sections:
2058     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2059                                                StartLoc, EndLoc);
2060     break;
2061   case OMPD_task:
2062     Res =
2063         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2064     break;
2065   case OMPD_taskyield:
2066     assert(ClausesWithImplicit.empty() &&
2067            "No clauses are allowed for 'omp taskyield' directive");
2068     assert(AStmt == nullptr &&
2069            "No associated statement allowed for 'omp taskyield' directive");
2070     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2071     break;
2072   case OMPD_barrier:
2073     assert(ClausesWithImplicit.empty() &&
2074            "No clauses are allowed for 'omp barrier' directive");
2075     assert(AStmt == nullptr &&
2076            "No associated statement allowed for 'omp barrier' directive");
2077     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2078     break;
2079   case OMPD_taskwait:
2080     assert(ClausesWithImplicit.empty() &&
2081            "No clauses are allowed for 'omp taskwait' directive");
2082     assert(AStmt == nullptr &&
2083            "No associated statement allowed for 'omp taskwait' directive");
2084     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2085     break;
2086   case OMPD_taskgroup:
2087     assert(ClausesWithImplicit.empty() &&
2088            "No clauses are allowed for 'omp taskgroup' directive");
2089     Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2090     break;
2091   case OMPD_flush:
2092     assert(AStmt == nullptr &&
2093            "No associated statement allowed for 'omp flush' directive");
2094     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2095     break;
2096   case OMPD_ordered:
2097     assert(ClausesWithImplicit.empty() &&
2098            "No clauses are allowed for 'omp ordered' directive");
2099     Res = ActOnOpenMPOrderedDirective(AStmt, StartLoc, EndLoc);
2100     break;
2101   case OMPD_atomic:
2102     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2103                                      EndLoc);
2104     break;
2105   case OMPD_teams:
2106     Res =
2107         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2108     break;
2109   case OMPD_target:
2110     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2111                                      EndLoc);
2112     break;
2113   case OMPD_cancellation_point:
2114     assert(ClausesWithImplicit.empty() &&
2115            "No clauses are allowed for 'omp cancellation point' directive");
2116     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2117                                "cancellation point' directive");
2118     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2119     break;
2120   case OMPD_cancel:
2121     assert(ClausesWithImplicit.empty() &&
2122            "No clauses are allowed for 'omp cancel' directive");
2123     assert(AStmt == nullptr &&
2124            "No associated statement allowed for 'omp cancel' directive");
2125     Res = ActOnOpenMPCancelDirective(StartLoc, EndLoc, CancelRegion);
2126     break;
2127   case OMPD_threadprivate:
2128     llvm_unreachable("OpenMP Directive is not allowed");
2129   case OMPD_unknown:
2130     llvm_unreachable("Unknown OpenMP directive");
2131   }
2132 
2133   for (auto P : VarsWithInheritedDSA) {
2134     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2135         << P.first << P.second->getSourceRange();
2136   }
2137   if (!VarsWithInheritedDSA.empty())
2138     return StmtError();
2139 
2140   if (ErrorFound)
2141     return StmtError();
2142   return Res;
2143 }
2144 
2145 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2146                                               Stmt *AStmt,
2147                                               SourceLocation StartLoc,
2148                                               SourceLocation EndLoc) {
2149   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2150   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2151   // 1.2.2 OpenMP Language Terminology
2152   // Structured block - An executable statement with a single entry at the
2153   // top and a single exit at the bottom.
2154   // The point of exit cannot be a branch out of the structured block.
2155   // longjmp() and throw() must not violate the entry/exit criteria.
2156   CS->getCapturedDecl()->setNothrow();
2157 
2158   getCurFunction()->setHasBranchProtectedScope();
2159 
2160   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
2161                                       AStmt);
2162 }
2163 
2164 namespace {
2165 /// \brief Helper class for checking canonical form of the OpenMP loops and
2166 /// extracting iteration space of each loop in the loop nest, that will be used
2167 /// for IR generation.
2168 class OpenMPIterationSpaceChecker {
2169   /// \brief Reference to Sema.
2170   Sema &SemaRef;
2171   /// \brief A location for diagnostics (when there is no some better location).
2172   SourceLocation DefaultLoc;
2173   /// \brief A location for diagnostics (when increment is not compatible).
2174   SourceLocation ConditionLoc;
2175   /// \brief A source location for referring to loop init later.
2176   SourceRange InitSrcRange;
2177   /// \brief A source location for referring to condition later.
2178   SourceRange ConditionSrcRange;
2179   /// \brief A source location for referring to increment later.
2180   SourceRange IncrementSrcRange;
2181   /// \brief Loop variable.
2182   VarDecl *Var;
2183   /// \brief Reference to loop variable.
2184   DeclRefExpr *VarRef;
2185   /// \brief Lower bound (initializer for the var).
2186   Expr *LB;
2187   /// \brief Upper bound.
2188   Expr *UB;
2189   /// \brief Loop step (increment).
2190   Expr *Step;
2191   /// \brief This flag is true when condition is one of:
2192   ///   Var <  UB
2193   ///   Var <= UB
2194   ///   UB  >  Var
2195   ///   UB  >= Var
2196   bool TestIsLessOp;
2197   /// \brief This flag is true when condition is strict ( < or > ).
2198   bool TestIsStrictOp;
2199   /// \brief This flag is true when step is subtracted on each iteration.
2200   bool SubtractStep;
2201 
2202 public:
2203   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
2204       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
2205         InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
2206         IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
2207         LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
2208         TestIsStrictOp(false), SubtractStep(false) {}
2209   /// \brief Check init-expr for canonical loop form and save loop counter
2210   /// variable - #Var and its initialization value - #LB.
2211   bool CheckInit(Stmt *S, bool EmitDiags = true);
2212   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2213   /// for less/greater and for strict/non-strict comparison.
2214   bool CheckCond(Expr *S);
2215   /// \brief Check incr-expr for canonical loop form and return true if it
2216   /// does not conform, otherwise save loop step (#Step).
2217   bool CheckInc(Expr *S);
2218   /// \brief Return the loop counter variable.
2219   VarDecl *GetLoopVar() const { return Var; }
2220   /// \brief Return the reference expression to loop counter variable.
2221   DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
2222   /// \brief Source range of the loop init.
2223   SourceRange GetInitSrcRange() const { return InitSrcRange; }
2224   /// \brief Source range of the loop condition.
2225   SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2226   /// \brief Source range of the loop increment.
2227   SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2228   /// \brief True if the step should be subtracted.
2229   bool ShouldSubtractStep() const { return SubtractStep; }
2230   /// \brief Build the expression to calculate the number of iterations.
2231   Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
2232   /// \brief Build the precondition expression for the loops.
2233   Expr *BuildPreCond(Scope *S, Expr *Cond) const;
2234   /// \brief Build reference expression to the counter be used for codegen.
2235   Expr *BuildCounterVar() const;
2236   /// \brief Build initization of the counter be used for codegen.
2237   Expr *BuildCounterInit() const;
2238   /// \brief Build step of the counter be used for codegen.
2239   Expr *BuildCounterStep() const;
2240   /// \brief Return true if any expression is dependent.
2241   bool Dependent() const;
2242 
2243 private:
2244   /// \brief Check the right-hand side of an assignment in the increment
2245   /// expression.
2246   bool CheckIncRHS(Expr *RHS);
2247   /// \brief Helper to set loop counter variable and its initializer.
2248   bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
2249   /// \brief Helper to set upper bound.
2250   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
2251              const SourceLocation &SL);
2252   /// \brief Helper to set loop increment.
2253   bool SetStep(Expr *NewStep, bool Subtract);
2254 };
2255 
2256 bool OpenMPIterationSpaceChecker::Dependent() const {
2257   if (!Var) {
2258     assert(!LB && !UB && !Step);
2259     return false;
2260   }
2261   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
2262          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
2263 }
2264 
2265 template <typename T>
2266 static T *getExprAsWritten(T *E) {
2267   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2268     E = ExprTemp->getSubExpr();
2269 
2270   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2271     E = MTE->GetTemporaryExpr();
2272 
2273   while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2274     E = Binder->getSubExpr();
2275 
2276   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2277     E = ICE->getSubExprAsWritten();
2278   return E->IgnoreParens();
2279 }
2280 
2281 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
2282                                               DeclRefExpr *NewVarRefExpr,
2283                                               Expr *NewLB) {
2284   // State consistency checking to ensure correct usage.
2285   assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
2286          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
2287   if (!NewVar || !NewLB)
2288     return true;
2289   Var = NewVar;
2290   VarRef = NewVarRefExpr;
2291   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2292     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2293       if ((Ctor->isCopyOrMoveConstructor() ||
2294            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2295           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2296         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
2297   LB = NewLB;
2298   return false;
2299 }
2300 
2301 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
2302                                         const SourceRange &SR,
2303                                         const SourceLocation &SL) {
2304   // State consistency checking to ensure correct usage.
2305   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
2306          !TestIsLessOp && !TestIsStrictOp);
2307   if (!NewUB)
2308     return true;
2309   UB = NewUB;
2310   TestIsLessOp = LessOp;
2311   TestIsStrictOp = StrictOp;
2312   ConditionSrcRange = SR;
2313   ConditionLoc = SL;
2314   return false;
2315 }
2316 
2317 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2318   // State consistency checking to ensure correct usage.
2319   assert(Var != nullptr && LB != nullptr && Step == nullptr);
2320   if (!NewStep)
2321     return true;
2322   if (!NewStep->isValueDependent()) {
2323     // Check that the step is integer expression.
2324     SourceLocation StepLoc = NewStep->getLocStart();
2325     ExprResult Val =
2326         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2327     if (Val.isInvalid())
2328       return true;
2329     NewStep = Val.get();
2330 
2331     // OpenMP [2.6, Canonical Loop Form, Restrictions]
2332     //  If test-expr is of form var relational-op b and relational-op is < or
2333     //  <= then incr-expr must cause var to increase on each iteration of the
2334     //  loop. If test-expr is of form var relational-op b and relational-op is
2335     //  > or >= then incr-expr must cause var to decrease on each iteration of
2336     //  the loop.
2337     //  If test-expr is of form b relational-op var and relational-op is < or
2338     //  <= then incr-expr must cause var to decrease on each iteration of the
2339     //  loop. If test-expr is of form b relational-op var and relational-op is
2340     //  > or >= then incr-expr must cause var to increase on each iteration of
2341     //  the loop.
2342     llvm::APSInt Result;
2343     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
2344     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
2345     bool IsConstNeg =
2346         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
2347     bool IsConstPos =
2348         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
2349     bool IsConstZero = IsConstant && !Result.getBoolValue();
2350     if (UB && (IsConstZero ||
2351                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
2352                              : (IsConstPos || (IsUnsigned && !Subtract))))) {
2353       SemaRef.Diag(NewStep->getExprLoc(),
2354                    diag::err_omp_loop_incr_not_compatible)
2355           << Var << TestIsLessOp << NewStep->getSourceRange();
2356       SemaRef.Diag(ConditionLoc,
2357                    diag::note_omp_loop_cond_requres_compatible_incr)
2358           << TestIsLessOp << ConditionSrcRange;
2359       return true;
2360     }
2361     if (TestIsLessOp == Subtract) {
2362       NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
2363                                              NewStep).get();
2364       Subtract = !Subtract;
2365     }
2366   }
2367 
2368   Step = NewStep;
2369   SubtractStep = Subtract;
2370   return false;
2371 }
2372 
2373 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
2374   // Check init-expr for canonical loop form and save loop counter
2375   // variable - #Var and its initialization value - #LB.
2376   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
2377   //   var = lb
2378   //   integer-type var = lb
2379   //   random-access-iterator-type var = lb
2380   //   pointer-type var = lb
2381   //
2382   if (!S) {
2383     if (EmitDiags) {
2384       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
2385     }
2386     return true;
2387   }
2388   InitSrcRange = S->getSourceRange();
2389   if (Expr *E = dyn_cast<Expr>(S))
2390     S = E->IgnoreParens();
2391   if (auto BO = dyn_cast<BinaryOperator>(S)) {
2392     if (BO->getOpcode() == BO_Assign)
2393       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
2394         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2395                            BO->getRHS());
2396   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
2397     if (DS->isSingleDecl()) {
2398       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
2399         if (Var->hasInit()) {
2400           // Accept non-canonical init form here but emit ext. warning.
2401           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
2402             SemaRef.Diag(S->getLocStart(),
2403                          diag::ext_omp_loop_not_canonical_init)
2404                 << S->getSourceRange();
2405           return SetVarAndLB(Var, nullptr, Var->getInit());
2406         }
2407       }
2408     }
2409   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
2410     if (CE->getOperator() == OO_Equal)
2411       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
2412         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
2413                            CE->getArg(1));
2414 
2415   if (EmitDiags) {
2416     SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
2417         << S->getSourceRange();
2418   }
2419   return true;
2420 }
2421 
2422 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
2423 /// variable (which may be the loop variable) if possible.
2424 static const VarDecl *GetInitVarDecl(const Expr *E) {
2425   if (!E)
2426     return nullptr;
2427   E = getExprAsWritten(E);
2428   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
2429     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
2430       if ((Ctor->isCopyOrMoveConstructor() ||
2431            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2432           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
2433         E = CE->getArg(0)->IgnoreParenImpCasts();
2434   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
2435   if (!DRE)
2436     return nullptr;
2437   return dyn_cast<VarDecl>(DRE->getDecl());
2438 }
2439 
2440 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
2441   // Check test-expr for canonical form, save upper-bound UB, flags for
2442   // less/greater and for strict/non-strict comparison.
2443   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2444   //   var relational-op b
2445   //   b relational-op var
2446   //
2447   if (!S) {
2448     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
2449     return true;
2450   }
2451   S = getExprAsWritten(S);
2452   SourceLocation CondLoc = S->getLocStart();
2453   if (auto BO = dyn_cast<BinaryOperator>(S)) {
2454     if (BO->isRelationalOp()) {
2455       if (GetInitVarDecl(BO->getLHS()) == Var)
2456         return SetUB(BO->getRHS(),
2457                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
2458                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2459                      BO->getSourceRange(), BO->getOperatorLoc());
2460       if (GetInitVarDecl(BO->getRHS()) == Var)
2461         return SetUB(BO->getLHS(),
2462                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
2463                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
2464                      BO->getSourceRange(), BO->getOperatorLoc());
2465     }
2466   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2467     if (CE->getNumArgs() == 2) {
2468       auto Op = CE->getOperator();
2469       switch (Op) {
2470       case OO_Greater:
2471       case OO_GreaterEqual:
2472       case OO_Less:
2473       case OO_LessEqual:
2474         if (GetInitVarDecl(CE->getArg(0)) == Var)
2475           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
2476                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2477                        CE->getOperatorLoc());
2478         if (GetInitVarDecl(CE->getArg(1)) == Var)
2479           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
2480                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
2481                        CE->getOperatorLoc());
2482         break;
2483       default:
2484         break;
2485       }
2486     }
2487   }
2488   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
2489       << S->getSourceRange() << Var;
2490   return true;
2491 }
2492 
2493 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
2494   // RHS of canonical loop form increment can be:
2495   //   var + incr
2496   //   incr + var
2497   //   var - incr
2498   //
2499   RHS = RHS->IgnoreParenImpCasts();
2500   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
2501     if (BO->isAdditiveOp()) {
2502       bool IsAdd = BO->getOpcode() == BO_Add;
2503       if (GetInitVarDecl(BO->getLHS()) == Var)
2504         return SetStep(BO->getRHS(), !IsAdd);
2505       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
2506         return SetStep(BO->getLHS(), false);
2507     }
2508   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
2509     bool IsAdd = CE->getOperator() == OO_Plus;
2510     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
2511       if (GetInitVarDecl(CE->getArg(0)) == Var)
2512         return SetStep(CE->getArg(1), !IsAdd);
2513       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
2514         return SetStep(CE->getArg(0), false);
2515     }
2516   }
2517   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2518       << RHS->getSourceRange() << Var;
2519   return true;
2520 }
2521 
2522 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
2523   // Check incr-expr for canonical loop form and return true if it
2524   // does not conform.
2525   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
2526   //   ++var
2527   //   var++
2528   //   --var
2529   //   var--
2530   //   var += incr
2531   //   var -= incr
2532   //   var = var + incr
2533   //   var = incr + var
2534   //   var = var - incr
2535   //
2536   if (!S) {
2537     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
2538     return true;
2539   }
2540   IncrementSrcRange = S->getSourceRange();
2541   S = S->IgnoreParens();
2542   if (auto UO = dyn_cast<UnaryOperator>(S)) {
2543     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
2544       return SetStep(
2545           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
2546                                        (UO->isDecrementOp() ? -1 : 1)).get(),
2547           false);
2548   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
2549     switch (BO->getOpcode()) {
2550     case BO_AddAssign:
2551     case BO_SubAssign:
2552       if (GetInitVarDecl(BO->getLHS()) == Var)
2553         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
2554       break;
2555     case BO_Assign:
2556       if (GetInitVarDecl(BO->getLHS()) == Var)
2557         return CheckIncRHS(BO->getRHS());
2558       break;
2559     default:
2560       break;
2561     }
2562   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
2563     switch (CE->getOperator()) {
2564     case OO_PlusPlus:
2565     case OO_MinusMinus:
2566       if (GetInitVarDecl(CE->getArg(0)) == Var)
2567         return SetStep(
2568             SemaRef.ActOnIntegerConstant(
2569                         CE->getLocStart(),
2570                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
2571             false);
2572       break;
2573     case OO_PlusEqual:
2574     case OO_MinusEqual:
2575       if (GetInitVarDecl(CE->getArg(0)) == Var)
2576         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
2577       break;
2578     case OO_Equal:
2579       if (GetInitVarDecl(CE->getArg(0)) == Var)
2580         return CheckIncRHS(CE->getArg(1));
2581       break;
2582     default:
2583       break;
2584     }
2585   }
2586   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
2587       << S->getSourceRange() << Var;
2588   return true;
2589 }
2590 
2591 /// \brief Build the expression to calculate the number of iterations.
2592 Expr *
2593 OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
2594                                                 const bool LimitedType) const {
2595   ExprResult Diff;
2596   if (Var->getType()->isIntegerType() || Var->getType()->isPointerType() ||
2597       SemaRef.getLangOpts().CPlusPlus) {
2598     // Upper - Lower
2599     Expr *Upper = TestIsLessOp ? UB : LB;
2600     Expr *Lower = TestIsLessOp ? LB : UB;
2601 
2602     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
2603 
2604     if (!Diff.isUsable() && Var->getType()->getAsCXXRecordDecl()) {
2605       // BuildBinOp already emitted error, this one is to point user to upper
2606       // and lower bound, and to tell what is passed to 'operator-'.
2607       SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
2608           << Upper->getSourceRange() << Lower->getSourceRange();
2609       return nullptr;
2610     }
2611   }
2612 
2613   if (!Diff.isUsable())
2614     return nullptr;
2615 
2616   // Upper - Lower [- 1]
2617   if (TestIsStrictOp)
2618     Diff = SemaRef.BuildBinOp(
2619         S, DefaultLoc, BO_Sub, Diff.get(),
2620         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
2621   if (!Diff.isUsable())
2622     return nullptr;
2623 
2624   // Upper - Lower [- 1] + Step
2625   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
2626                             Step->IgnoreImplicit());
2627   if (!Diff.isUsable())
2628     return nullptr;
2629 
2630   // Parentheses (for dumping/debugging purposes only).
2631   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
2632   if (!Diff.isUsable())
2633     return nullptr;
2634 
2635   // (Upper - Lower [- 1] + Step) / Step
2636   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(),
2637                             Step->IgnoreImplicit());
2638   if (!Diff.isUsable())
2639     return nullptr;
2640 
2641   // OpenMP runtime requires 32-bit or 64-bit loop variables.
2642   if (LimitedType) {
2643     auto &C = SemaRef.Context;
2644     QualType Type = Diff.get()->getType();
2645     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
2646     if (NewSize != C.getTypeSize(Type)) {
2647       if (NewSize < C.getTypeSize(Type)) {
2648         assert(NewSize == 64 && "incorrect loop var size");
2649         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
2650             << InitSrcRange << ConditionSrcRange;
2651       }
2652       QualType NewType = C.getIntTypeForBitwidth(
2653           NewSize, Type->hasSignedIntegerRepresentation());
2654       Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
2655                                                Sema::AA_Converting, true);
2656       if (!Diff.isUsable())
2657         return nullptr;
2658     }
2659   }
2660 
2661   return Diff.get();
2662 }
2663 
2664 Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
2665   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
2666   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
2667   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2668   auto CondExpr = SemaRef.BuildBinOp(
2669       S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
2670                                   : (TestIsStrictOp ? BO_GT : BO_GE),
2671       LB, UB);
2672   if (CondExpr.isUsable()) {
2673     CondExpr = SemaRef.PerformImplicitConversion(
2674         CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
2675         /*AllowExplicit=*/true);
2676   }
2677   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2678   // Otherwise use original loop conditon and evaluate it in runtime.
2679   return CondExpr.isUsable() ? CondExpr.get() : Cond;
2680 }
2681 
2682 /// \brief Build reference expression to the counter be used for codegen.
2683 Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
2684   return buildDeclRefExpr(SemaRef, Var, Var->getType(), DefaultLoc);
2685 }
2686 
2687 /// \brief Build initization of the counter be used for codegen.
2688 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
2689 
2690 /// \brief Build step of the counter be used for codegen.
2691 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
2692 
2693 /// \brief Iteration space of a single for loop.
2694 struct LoopIterationSpace {
2695   /// \brief Condition of the loop.
2696   Expr *PreCond;
2697   /// \brief This expression calculates the number of iterations in the loop.
2698   /// It is always possible to calculate it before starting the loop.
2699   Expr *NumIterations;
2700   /// \brief The loop counter variable.
2701   Expr *CounterVar;
2702   /// \brief This is initializer for the initial value of #CounterVar.
2703   Expr *CounterInit;
2704   /// \brief This is step for the #CounterVar used to generate its update:
2705   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
2706   Expr *CounterStep;
2707   /// \brief Should step be subtracted?
2708   bool Subtract;
2709   /// \brief Source range of the loop init.
2710   SourceRange InitSrcRange;
2711   /// \brief Source range of the loop condition.
2712   SourceRange CondSrcRange;
2713   /// \brief Source range of the loop increment.
2714   SourceRange IncSrcRange;
2715 };
2716 
2717 } // namespace
2718 
2719 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
2720   assert(getLangOpts().OpenMP && "OpenMP is not active.");
2721   assert(Init && "Expected loop in canonical form.");
2722   unsigned CollapseIteration = DSAStack->getCollapseNumber();
2723   if (CollapseIteration > 0 &&
2724       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2725     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
2726     if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
2727       DSAStack->addLoopControlVariable(ISC.GetLoopVar());
2728     }
2729     DSAStack->setCollapseNumber(CollapseIteration - 1);
2730   }
2731 }
2732 
2733 /// \brief Called on a for stmt to check and extract its iteration space
2734 /// for further processing (such as collapsing).
2735 static bool CheckOpenMPIterationSpace(
2736     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
2737     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
2738     Expr *NestedLoopCountExpr,
2739     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2740     LoopIterationSpace &ResultIterSpace) {
2741   // OpenMP [2.6, Canonical Loop Form]
2742   //   for (init-expr; test-expr; incr-expr) structured-block
2743   auto For = dyn_cast_or_null<ForStmt>(S);
2744   if (!For) {
2745     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
2746         << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
2747         << NestedLoopCount << (CurrentNestedLoopCount > 0)
2748         << CurrentNestedLoopCount;
2749     if (NestedLoopCount > 1)
2750       SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
2751                    diag::note_omp_collapse_expr)
2752           << NestedLoopCountExpr->getSourceRange();
2753     return true;
2754   }
2755   assert(For->getBody());
2756 
2757   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
2758 
2759   // Check init.
2760   auto Init = For->getInit();
2761   if (ISC.CheckInit(Init)) {
2762     return true;
2763   }
2764 
2765   bool HasErrors = false;
2766 
2767   // Check loop variable's type.
2768   auto Var = ISC.GetLoopVar();
2769 
2770   // OpenMP [2.6, Canonical Loop Form]
2771   // Var is one of the following:
2772   //   A variable of signed or unsigned integer type.
2773   //   For C++, a variable of a random access iterator type.
2774   //   For C, a variable of a pointer type.
2775   auto VarType = Var->getType();
2776   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
2777       !VarType->isPointerType() &&
2778       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
2779     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
2780         << SemaRef.getLangOpts().CPlusPlus;
2781     HasErrors = true;
2782   }
2783 
2784   // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
2785   // Construct
2786   // The loop iteration variable(s) in the associated for-loop(s) of a for or
2787   // parallel for construct is (are) private.
2788   // The loop iteration variable in the associated for-loop of a simd construct
2789   // with just one associated for-loop is linear with a constant-linear-step
2790   // that is the increment of the associated for-loop.
2791   // Exclude loop var from the list of variables with implicitly defined data
2792   // sharing attributes.
2793   VarsWithImplicitDSA.erase(Var);
2794 
2795   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
2796   // a Construct, C/C++].
2797   // The loop iteration variable in the associated for-loop of a simd construct
2798   // with just one associated for-loop may be listed in a linear clause with a
2799   // constant-linear-step that is the increment of the associated for-loop.
2800   // The loop iteration variable(s) in the associated for-loop(s) of a for or
2801   // parallel for construct may be listed in a private or lastprivate clause.
2802   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
2803   auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
2804   // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
2805   // declared in the loop and it is predetermined as a private.
2806   auto PredeterminedCKind =
2807       isOpenMPSimdDirective(DKind)
2808           ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
2809           : OMPC_private;
2810   if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
2811         DVar.CKind != OMPC_threadprivate && DVar.CKind != PredeterminedCKind) ||
2812        (isOpenMPWorksharingDirective(DKind) && !isOpenMPSimdDirective(DKind) &&
2813         DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private &&
2814         DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_threadprivate)) &&
2815       ((DVar.CKind != OMPC_private && DVar.CKind != OMPC_threadprivate) ||
2816        DVar.RefExpr != nullptr)) {
2817     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
2818         << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
2819         << getOpenMPClauseName(PredeterminedCKind);
2820     if (DVar.RefExpr == nullptr)
2821       DVar.CKind = PredeterminedCKind;
2822     ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
2823     HasErrors = true;
2824   } else if (LoopVarRefExpr != nullptr) {
2825     // Make the loop iteration variable private (for worksharing constructs),
2826     // linear (for simd directives with the only one associated loop) or
2827     // lastprivate (for simd directives with several collapsed loops).
2828     if (DVar.CKind == OMPC_unknown)
2829       DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
2830                         /*FromParent=*/false);
2831     DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
2832   }
2833 
2834   assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
2835 
2836   // Check test-expr.
2837   HasErrors |= ISC.CheckCond(For->getCond());
2838 
2839   // Check incr-expr.
2840   HasErrors |= ISC.CheckInc(For->getInc());
2841 
2842   if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
2843     return HasErrors;
2844 
2845   // Build the loop's iteration space representation.
2846   ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
2847   ResultIterSpace.NumIterations = ISC.BuildNumIterations(
2848       DSA.getCurScope(), /* LimitedType */ isOpenMPWorksharingDirective(DKind));
2849   ResultIterSpace.CounterVar = ISC.BuildCounterVar();
2850   ResultIterSpace.CounterInit = ISC.BuildCounterInit();
2851   ResultIterSpace.CounterStep = ISC.BuildCounterStep();
2852   ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
2853   ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
2854   ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
2855   ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
2856 
2857   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
2858                 ResultIterSpace.NumIterations == nullptr ||
2859                 ResultIterSpace.CounterVar == nullptr ||
2860                 ResultIterSpace.CounterInit == nullptr ||
2861                 ResultIterSpace.CounterStep == nullptr);
2862 
2863   return HasErrors;
2864 }
2865 
2866 /// \brief Build 'VarRef = Start + Iter * Step'.
2867 static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
2868                                      SourceLocation Loc, ExprResult VarRef,
2869                                      ExprResult Start, ExprResult Iter,
2870                                      ExprResult Step, bool Subtract) {
2871   // Add parentheses (for debugging purposes only).
2872   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
2873   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
2874       !Step.isUsable())
2875     return ExprError();
2876 
2877   ExprResult Update = SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(),
2878                                          Step.get()->IgnoreImplicit());
2879   if (!Update.isUsable())
2880     return ExprError();
2881 
2882   // Build 'VarRef = Start + Iter * Step'.
2883   Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
2884                               Start.get()->IgnoreImplicit(), Update.get());
2885   if (!Update.isUsable())
2886     return ExprError();
2887 
2888   Update = SemaRef.PerformImplicitConversion(
2889       Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
2890   if (!Update.isUsable())
2891     return ExprError();
2892 
2893   Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
2894   return Update;
2895 }
2896 
2897 /// \brief Convert integer expression \a E to make it have at least \a Bits
2898 /// bits.
2899 static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
2900                                       Sema &SemaRef) {
2901   if (E == nullptr)
2902     return ExprError();
2903   auto &C = SemaRef.Context;
2904   QualType OldType = E->getType();
2905   unsigned HasBits = C.getTypeSize(OldType);
2906   if (HasBits >= Bits)
2907     return ExprResult(E);
2908   // OK to convert to signed, because new type has more bits than old.
2909   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
2910   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
2911                                            true);
2912 }
2913 
2914 /// \brief Check if the given expression \a E is a constant integer that fits
2915 /// into \a Bits bits.
2916 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
2917   if (E == nullptr)
2918     return false;
2919   llvm::APSInt Result;
2920   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
2921     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
2922   return false;
2923 }
2924 
2925 /// \brief Called on a for stmt to check itself and nested loops (if any).
2926 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
2927 /// number of collapsed loops otherwise.
2928 static unsigned
2929 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
2930                 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
2931                 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA,
2932                 OMPLoopDirective::HelperExprs &Built) {
2933   unsigned NestedLoopCount = 1;
2934   if (NestedLoopCountExpr) {
2935     // Found 'collapse' clause - calculate collapse number.
2936     llvm::APSInt Result;
2937     if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
2938       NestedLoopCount = Result.getLimitedValue();
2939   }
2940   // This is helper routine for loop directives (e.g., 'for', 'simd',
2941   // 'for simd', etc.).
2942   SmallVector<LoopIterationSpace, 4> IterSpaces;
2943   IterSpaces.resize(NestedLoopCount);
2944   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
2945   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
2946     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
2947                                   NestedLoopCount, NestedLoopCountExpr,
2948                                   VarsWithImplicitDSA, IterSpaces[Cnt]))
2949       return 0;
2950     // Move on to the next nested for loop, or to the loop body.
2951     // OpenMP [2.8.1, simd construct, Restrictions]
2952     // All loops associated with the construct must be perfectly nested; that
2953     // is, there must be no intervening code nor any OpenMP directive between
2954     // any two loops.
2955     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
2956   }
2957 
2958   Built.clear(/* size */ NestedLoopCount);
2959 
2960   if (SemaRef.CurContext->isDependentContext())
2961     return NestedLoopCount;
2962 
2963   // An example of what is generated for the following code:
2964   //
2965   //   #pragma omp simd collapse(2)
2966   //   for (i = 0; i < NI; ++i)
2967   //     for (j = J0; j < NJ; j+=2) {
2968   //     <loop body>
2969   //   }
2970   //
2971   // We generate the code below.
2972   // Note: the loop body may be outlined in CodeGen.
2973   // Note: some counters may be C++ classes, operator- is used to find number of
2974   // iterations and operator+= to calculate counter value.
2975   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
2976   // or i64 is currently supported).
2977   //
2978   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
2979   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
2980   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
2981   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
2982   //     // similar updates for vars in clauses (e.g. 'linear')
2983   //     <loop body (using local i and j)>
2984   //   }
2985   //   i = NI; // assign final values of counters
2986   //   j = NJ;
2987   //
2988 
2989   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
2990   // the iteration counts of the collapsed for loops.
2991   // Precondition tests if there is at least one iteration (all conditions are
2992   // true).
2993   auto PreCond = ExprResult(IterSpaces[0].PreCond);
2994   auto N0 = IterSpaces[0].NumIterations;
2995   ExprResult LastIteration32 = WidenIterationCount(32 /* Bits */, N0, SemaRef);
2996   ExprResult LastIteration64 = WidenIterationCount(64 /* Bits */, N0, SemaRef);
2997 
2998   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
2999     return NestedLoopCount;
3000 
3001   auto &C = SemaRef.Context;
3002   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3003 
3004   Scope *CurScope = DSA.getCurScope();
3005   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
3006     if (PreCond.isUsable()) {
3007       PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
3008                                    PreCond.get(), IterSpaces[Cnt].PreCond);
3009     }
3010     auto N = IterSpaces[Cnt].NumIterations;
3011     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3012     if (LastIteration32.isUsable())
3013       LastIteration32 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
3014                                            LastIteration32.get(), N);
3015     if (LastIteration64.isUsable())
3016       LastIteration64 = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
3017                                            LastIteration64.get(), N);
3018   }
3019 
3020   // Choose either the 32-bit or 64-bit version.
3021   ExprResult LastIteration = LastIteration64;
3022   if (LastIteration32.isUsable() &&
3023       C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3024       (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3025        FitsInto(
3026            32 /* Bits */,
3027            LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3028            LastIteration64.get(), SemaRef)))
3029     LastIteration = LastIteration32;
3030 
3031   if (!LastIteration.isUsable())
3032     return 0;
3033 
3034   // Save the number of iterations.
3035   ExprResult NumIterations = LastIteration;
3036   {
3037     LastIteration = SemaRef.BuildBinOp(
3038         CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
3039         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3040     if (!LastIteration.isUsable())
3041       return 0;
3042   }
3043 
3044   // Calculate the last iteration number beforehand instead of doing this on
3045   // each iteration. Do not do this if the number of iterations may be kfold-ed.
3046   llvm::APSInt Result;
3047   bool IsConstant =
3048       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
3049   ExprResult CalcLastIteration;
3050   if (!IsConstant) {
3051     SourceLocation SaveLoc;
3052     VarDecl *SaveVar =
3053         buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
3054                      ".omp.last.iteration");
3055     ExprResult SaveRef = buildDeclRefExpr(
3056         SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
3057     CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
3058                                            SaveRef.get(), LastIteration.get());
3059     LastIteration = SaveRef;
3060 
3061     // Prepare SaveRef + 1.
3062     NumIterations = SemaRef.BuildBinOp(
3063         CurScope, SaveLoc, BO_Add, SaveRef.get(),
3064         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3065     if (!NumIterations.isUsable())
3066       return 0;
3067   }
3068 
3069   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
3070 
3071   QualType VType = LastIteration.get()->getType();
3072   // Build variables passed into runtime, nesessary for worksharing directives.
3073   ExprResult LB, UB, IL, ST, EUB;
3074   if (isOpenMPWorksharingDirective(DKind)) {
3075     // Lower bound variable, initialized with zero.
3076     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
3077     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
3078     SemaRef.AddInitializerToDecl(
3079         LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3080         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3081 
3082     // Upper bound variable, initialized with last iteration number.
3083     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
3084     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
3085     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
3086                                  /*DirectInit*/ false,
3087                                  /*TypeMayContainAuto*/ false);
3088 
3089     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
3090     // This will be used to implement clause 'lastprivate'.
3091     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
3092     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
3093     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
3094     SemaRef.AddInitializerToDecl(
3095         ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
3096         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3097 
3098     // Stride variable returned by runtime (we initialize it to 1 by default).
3099     VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
3100     ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
3101     SemaRef.AddInitializerToDecl(
3102         STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
3103         /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
3104 
3105     // Build expression: UB = min(UB, LastIteration)
3106     // It is nesessary for CodeGen of directives with static scheduling.
3107     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
3108                                                 UB.get(), LastIteration.get());
3109     ExprResult CondOp = SemaRef.ActOnConditionalOp(
3110         InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
3111     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
3112                              CondOp.get());
3113     EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
3114   }
3115 
3116   // Build the iteration variable and its initialization before loop.
3117   ExprResult IV;
3118   ExprResult Init;
3119   {
3120     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
3121     IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
3122     Expr *RHS = isOpenMPWorksharingDirective(DKind)
3123                     ? LB.get()
3124                     : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
3125     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
3126     Init = SemaRef.ActOnFinishFullExpr(Init.get());
3127   }
3128 
3129   // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
3130   SourceLocation CondLoc;
3131   ExprResult Cond =
3132       isOpenMPWorksharingDirective(DKind)
3133           ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
3134           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
3135                                NumIterations.get());
3136 
3137   // Loop increment (IV = IV + 1)
3138   SourceLocation IncLoc;
3139   ExprResult Inc =
3140       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
3141                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
3142   if (!Inc.isUsable())
3143     return 0;
3144   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
3145   Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
3146   if (!Inc.isUsable())
3147     return 0;
3148 
3149   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
3150   // Used for directives with static scheduling.
3151   ExprResult NextLB, NextUB;
3152   if (isOpenMPWorksharingDirective(DKind)) {
3153     // LB + ST
3154     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
3155     if (!NextLB.isUsable())
3156       return 0;
3157     // LB = LB + ST
3158     NextLB =
3159         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
3160     NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
3161     if (!NextLB.isUsable())
3162       return 0;
3163     // UB + ST
3164     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
3165     if (!NextUB.isUsable())
3166       return 0;
3167     // UB = UB + ST
3168     NextUB =
3169         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
3170     NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
3171     if (!NextUB.isUsable())
3172       return 0;
3173   }
3174 
3175   // Build updates and final values of the loop counters.
3176   bool HasErrors = false;
3177   Built.Counters.resize(NestedLoopCount);
3178   Built.Updates.resize(NestedLoopCount);
3179   Built.Finals.resize(NestedLoopCount);
3180   {
3181     ExprResult Div;
3182     // Go from inner nested loop to outer.
3183     for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
3184       LoopIterationSpace &IS = IterSpaces[Cnt];
3185       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
3186       // Build: Iter = (IV / Div) % IS.NumIters
3187       // where Div is product of previous iterations' IS.NumIters.
3188       ExprResult Iter;
3189       if (Div.isUsable()) {
3190         Iter =
3191             SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
3192       } else {
3193         Iter = IV;
3194         assert((Cnt == (int)NestedLoopCount - 1) &&
3195                "unusable div expected on first iteration only");
3196       }
3197 
3198       if (Cnt != 0 && Iter.isUsable())
3199         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
3200                                   IS.NumIterations);
3201       if (!Iter.isUsable()) {
3202         HasErrors = true;
3203         break;
3204       }
3205 
3206       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
3207       auto *CounterVar = buildDeclRefExpr(
3208           SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
3209           IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
3210           /*RefersToCapture=*/true);
3211       ExprResult Update =
3212           BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
3213                              IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
3214       if (!Update.isUsable()) {
3215         HasErrors = true;
3216         break;
3217       }
3218 
3219       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
3220       ExprResult Final = BuildCounterUpdate(
3221           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
3222           IS.NumIterations, IS.CounterStep, IS.Subtract);
3223       if (!Final.isUsable()) {
3224         HasErrors = true;
3225         break;
3226       }
3227 
3228       // Build Div for the next iteration: Div <- Div * IS.NumIters
3229       if (Cnt != 0) {
3230         if (Div.isUnset())
3231           Div = IS.NumIterations;
3232         else
3233           Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
3234                                    IS.NumIterations);
3235 
3236         // Add parentheses (for debugging purposes only).
3237         if (Div.isUsable())
3238           Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
3239         if (!Div.isUsable()) {
3240           HasErrors = true;
3241           break;
3242         }
3243       }
3244       if (!Update.isUsable() || !Final.isUsable()) {
3245         HasErrors = true;
3246         break;
3247       }
3248       // Save results
3249       Built.Counters[Cnt] = IS.CounterVar;
3250       Built.Updates[Cnt] = Update.get();
3251       Built.Finals[Cnt] = Final.get();
3252     }
3253   }
3254 
3255   if (HasErrors)
3256     return 0;
3257 
3258   // Save results
3259   Built.IterationVarRef = IV.get();
3260   Built.LastIteration = LastIteration.get();
3261   Built.NumIterations = NumIterations.get();
3262   Built.CalcLastIteration =
3263       SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
3264   Built.PreCond = PreCond.get();
3265   Built.Cond = Cond.get();
3266   Built.Init = Init.get();
3267   Built.Inc = Inc.get();
3268   Built.LB = LB.get();
3269   Built.UB = UB.get();
3270   Built.IL = IL.get();
3271   Built.ST = ST.get();
3272   Built.EUB = EUB.get();
3273   Built.NLB = NextLB.get();
3274   Built.NUB = NextUB.get();
3275 
3276   return NestedLoopCount;
3277 }
3278 
3279 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
3280   auto &&CollapseFilter = [](const OMPClause *C) -> bool {
3281     return C->getClauseKind() == OMPC_collapse;
3282   };
3283   OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
3284       Clauses, std::move(CollapseFilter));
3285   if (I)
3286     return cast<OMPCollapseClause>(*I)->getNumForLoops();
3287   return nullptr;
3288 }
3289 
3290 StmtResult Sema::ActOnOpenMPSimdDirective(
3291     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3292     SourceLocation EndLoc,
3293     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3294   OMPLoopDirective::HelperExprs B;
3295   // In presence of clause 'collapse', it will define the nested loops number.
3296   unsigned NestedLoopCount =
3297       CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
3298                       *DSAStack, VarsWithImplicitDSA, B);
3299   if (NestedLoopCount == 0)
3300     return StmtError();
3301 
3302   assert((CurContext->isDependentContext() || B.builtAll()) &&
3303          "omp simd loop exprs were not built");
3304 
3305   if (!CurContext->isDependentContext()) {
3306     // Finalize the clauses that need pre-built expressions for CodeGen.
3307     for (auto C : Clauses) {
3308       if (auto LC = dyn_cast<OMPLinearClause>(C))
3309         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3310                                      B.NumIterations, *this, CurScope))
3311           return StmtError();
3312     }
3313   }
3314 
3315   getCurFunction()->setHasBranchProtectedScope();
3316   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3317                                   Clauses, AStmt, B);
3318 }
3319 
3320 StmtResult Sema::ActOnOpenMPForDirective(
3321     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3322     SourceLocation EndLoc,
3323     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3324   OMPLoopDirective::HelperExprs B;
3325   // In presence of clause 'collapse', it will define the nested loops number.
3326   unsigned NestedLoopCount =
3327       CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
3328                       *DSAStack, VarsWithImplicitDSA, B);
3329   if (NestedLoopCount == 0)
3330     return StmtError();
3331 
3332   assert((CurContext->isDependentContext() || B.builtAll()) &&
3333          "omp for loop exprs were not built");
3334 
3335   getCurFunction()->setHasBranchProtectedScope();
3336   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3337                                  Clauses, AStmt, B);
3338 }
3339 
3340 StmtResult Sema::ActOnOpenMPForSimdDirective(
3341     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3342     SourceLocation EndLoc,
3343     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3344   OMPLoopDirective::HelperExprs B;
3345   // In presence of clause 'collapse', it will define the nested loops number.
3346   unsigned NestedLoopCount =
3347       CheckOpenMPLoop(OMPD_for_simd, GetCollapseNumberExpr(Clauses), AStmt,
3348                       *this, *DSAStack, VarsWithImplicitDSA, B);
3349   if (NestedLoopCount == 0)
3350     return StmtError();
3351 
3352   assert((CurContext->isDependentContext() || B.builtAll()) &&
3353          "omp for simd loop exprs were not built");
3354 
3355   if (!CurContext->isDependentContext()) {
3356     // Finalize the clauses that need pre-built expressions for CodeGen.
3357     for (auto C : Clauses) {
3358       if (auto LC = dyn_cast<OMPLinearClause>(C))
3359         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3360                                      B.NumIterations, *this, CurScope))
3361           return StmtError();
3362     }
3363   }
3364 
3365   getCurFunction()->setHasBranchProtectedScope();
3366   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
3367                                      Clauses, AStmt, B);
3368 }
3369 
3370 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
3371                                               Stmt *AStmt,
3372                                               SourceLocation StartLoc,
3373                                               SourceLocation EndLoc) {
3374   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3375   auto BaseStmt = AStmt;
3376   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3377     BaseStmt = CS->getCapturedStmt();
3378   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3379     auto S = C->children();
3380     if (!S)
3381       return StmtError();
3382     // All associated statements must be '#pragma omp section' except for
3383     // the first one.
3384     for (Stmt *SectionStmt : ++S) {
3385       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3386         if (SectionStmt)
3387           Diag(SectionStmt->getLocStart(),
3388                diag::err_omp_sections_substmt_not_section);
3389         return StmtError();
3390       }
3391     }
3392   } else {
3393     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
3394     return StmtError();
3395   }
3396 
3397   getCurFunction()->setHasBranchProtectedScope();
3398 
3399   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
3400                                       AStmt);
3401 }
3402 
3403 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
3404                                              SourceLocation StartLoc,
3405                                              SourceLocation EndLoc) {
3406   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3407 
3408   getCurFunction()->setHasBranchProtectedScope();
3409 
3410   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
3411 }
3412 
3413 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
3414                                             Stmt *AStmt,
3415                                             SourceLocation StartLoc,
3416                                             SourceLocation EndLoc) {
3417   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3418 
3419   getCurFunction()->setHasBranchProtectedScope();
3420 
3421   // OpenMP [2.7.3, single Construct, Restrictions]
3422   // The copyprivate clause must not be used with the nowait clause.
3423   OMPClause *Nowait = nullptr;
3424   OMPClause *Copyprivate = nullptr;
3425   for (auto *Clause : Clauses) {
3426     if (Clause->getClauseKind() == OMPC_nowait)
3427       Nowait = Clause;
3428     else if (Clause->getClauseKind() == OMPC_copyprivate)
3429       Copyprivate = Clause;
3430     if (Copyprivate && Nowait) {
3431       Diag(Copyprivate->getLocStart(),
3432            diag::err_omp_single_copyprivate_with_nowait);
3433       Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
3434       return StmtError();
3435     }
3436   }
3437 
3438   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3439 }
3440 
3441 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
3442                                             SourceLocation StartLoc,
3443                                             SourceLocation EndLoc) {
3444   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3445 
3446   getCurFunction()->setHasBranchProtectedScope();
3447 
3448   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
3449 }
3450 
3451 StmtResult
3452 Sema::ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
3453                                    Stmt *AStmt, SourceLocation StartLoc,
3454                                    SourceLocation EndLoc) {
3455   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3456 
3457   getCurFunction()->setHasBranchProtectedScope();
3458 
3459   return OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
3460                                       AStmt);
3461 }
3462 
3463 StmtResult Sema::ActOnOpenMPParallelForDirective(
3464     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3465     SourceLocation EndLoc,
3466     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3467   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3468   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3469   // 1.2.2 OpenMP Language Terminology
3470   // Structured block - An executable statement with a single entry at the
3471   // top and a single exit at the bottom.
3472   // The point of exit cannot be a branch out of the structured block.
3473   // longjmp() and throw() must not violate the entry/exit criteria.
3474   CS->getCapturedDecl()->setNothrow();
3475 
3476   OMPLoopDirective::HelperExprs B;
3477   // In presence of clause 'collapse', it will define the nested loops number.
3478   unsigned NestedLoopCount =
3479       CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
3480                       *this, *DSAStack, VarsWithImplicitDSA, B);
3481   if (NestedLoopCount == 0)
3482     return StmtError();
3483 
3484   assert((CurContext->isDependentContext() || B.builtAll()) &&
3485          "omp parallel for loop exprs were not built");
3486 
3487   getCurFunction()->setHasBranchProtectedScope();
3488   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
3489                                          NestedLoopCount, Clauses, AStmt, B);
3490 }
3491 
3492 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
3493     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
3494     SourceLocation EndLoc,
3495     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
3496   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3497   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3498   // 1.2.2 OpenMP Language Terminology
3499   // Structured block - An executable statement with a single entry at the
3500   // top and a single exit at the bottom.
3501   // The point of exit cannot be a branch out of the structured block.
3502   // longjmp() and throw() must not violate the entry/exit criteria.
3503   CS->getCapturedDecl()->setNothrow();
3504 
3505   OMPLoopDirective::HelperExprs B;
3506   // In presence of clause 'collapse', it will define the nested loops number.
3507   unsigned NestedLoopCount =
3508       CheckOpenMPLoop(OMPD_parallel_for_simd, GetCollapseNumberExpr(Clauses),
3509                       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
3510   if (NestedLoopCount == 0)
3511     return StmtError();
3512 
3513   if (!CurContext->isDependentContext()) {
3514     // Finalize the clauses that need pre-built expressions for CodeGen.
3515     for (auto C : Clauses) {
3516       if (auto LC = dyn_cast<OMPLinearClause>(C))
3517         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3518                                      B.NumIterations, *this, CurScope))
3519           return StmtError();
3520     }
3521   }
3522 
3523   getCurFunction()->setHasBranchProtectedScope();
3524   return OMPParallelForSimdDirective::Create(
3525       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
3526 }
3527 
3528 StmtResult
3529 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
3530                                            Stmt *AStmt, SourceLocation StartLoc,
3531                                            SourceLocation EndLoc) {
3532   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3533   auto BaseStmt = AStmt;
3534   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
3535     BaseStmt = CS->getCapturedStmt();
3536   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
3537     auto S = C->children();
3538     if (!S)
3539       return StmtError();
3540     // All associated statements must be '#pragma omp section' except for
3541     // the first one.
3542     for (Stmt *SectionStmt : ++S) {
3543       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
3544         if (SectionStmt)
3545           Diag(SectionStmt->getLocStart(),
3546                diag::err_omp_parallel_sections_substmt_not_section);
3547         return StmtError();
3548       }
3549     }
3550   } else {
3551     Diag(AStmt->getLocStart(),
3552          diag::err_omp_parallel_sections_not_compound_stmt);
3553     return StmtError();
3554   }
3555 
3556   getCurFunction()->setHasBranchProtectedScope();
3557 
3558   return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
3559                                               Clauses, AStmt);
3560 }
3561 
3562 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
3563                                           Stmt *AStmt, SourceLocation StartLoc,
3564                                           SourceLocation EndLoc) {
3565   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3566   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3567   // 1.2.2 OpenMP Language Terminology
3568   // Structured block - An executable statement with a single entry at the
3569   // top and a single exit at the bottom.
3570   // The point of exit cannot be a branch out of the structured block.
3571   // longjmp() and throw() must not violate the entry/exit criteria.
3572   CS->getCapturedDecl()->setNothrow();
3573 
3574   getCurFunction()->setHasBranchProtectedScope();
3575 
3576   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
3577 }
3578 
3579 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
3580                                                SourceLocation EndLoc) {
3581   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
3582 }
3583 
3584 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
3585                                              SourceLocation EndLoc) {
3586   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
3587 }
3588 
3589 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
3590                                               SourceLocation EndLoc) {
3591   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
3592 }
3593 
3594 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
3595                                                SourceLocation StartLoc,
3596                                                SourceLocation EndLoc) {
3597   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3598 
3599   getCurFunction()->setHasBranchProtectedScope();
3600 
3601   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
3602 }
3603 
3604 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
3605                                            SourceLocation StartLoc,
3606                                            SourceLocation EndLoc) {
3607   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
3608   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
3609 }
3610 
3611 StmtResult Sema::ActOnOpenMPOrderedDirective(Stmt *AStmt,
3612                                              SourceLocation StartLoc,
3613                                              SourceLocation EndLoc) {
3614   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3615 
3616   getCurFunction()->setHasBranchProtectedScope();
3617 
3618   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, AStmt);
3619 }
3620 
3621 namespace {
3622 /// \brief Helper class for checking expression in 'omp atomic [update]'
3623 /// construct.
3624 class OpenMPAtomicUpdateChecker {
3625   /// \brief Error results for atomic update expressions.
3626   enum ExprAnalysisErrorCode {
3627     /// \brief A statement is not an expression statement.
3628     NotAnExpression,
3629     /// \brief Expression is not builtin binary or unary operation.
3630     NotABinaryOrUnaryExpression,
3631     /// \brief Unary operation is not post-/pre- increment/decrement operation.
3632     NotAnUnaryIncDecExpression,
3633     /// \brief An expression is not of scalar type.
3634     NotAScalarType,
3635     /// \brief A binary operation is not an assignment operation.
3636     NotAnAssignmentOp,
3637     /// \brief RHS part of the binary operation is not a binary expression.
3638     NotABinaryExpression,
3639     /// \brief RHS part is not additive/multiplicative/shift/biwise binary
3640     /// expression.
3641     NotABinaryOperator,
3642     /// \brief RHS binary operation does not have reference to the updated LHS
3643     /// part.
3644     NotAnUpdateExpression,
3645     /// \brief No errors is found.
3646     NoError
3647   };
3648   /// \brief Reference to Sema.
3649   Sema &SemaRef;
3650   /// \brief A location for note diagnostics (when error is found).
3651   SourceLocation NoteLoc;
3652   /// \brief 'x' lvalue part of the source atomic expression.
3653   Expr *X;
3654   /// \brief 'expr' rvalue part of the source atomic expression.
3655   Expr *E;
3656   /// \brief Helper expression of the form
3657   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3658   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3659   Expr *UpdateExpr;
3660   /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
3661   /// important for non-associative operations.
3662   bool IsXLHSInRHSPart;
3663   BinaryOperatorKind Op;
3664   SourceLocation OpLoc;
3665   /// \brief true if the source expression is a postfix unary operation, false
3666   /// if it is a prefix unary operation.
3667   bool IsPostfixUpdate;
3668 
3669 public:
3670   OpenMPAtomicUpdateChecker(Sema &SemaRef)
3671       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
3672         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
3673   /// \brief Check specified statement that it is suitable for 'atomic update'
3674   /// constructs and extract 'x', 'expr' and Operation from the original
3675   /// expression. If DiagId and NoteId == 0, then only check is performed
3676   /// without error notification.
3677   /// \param DiagId Diagnostic which should be emitted if error is found.
3678   /// \param NoteId Diagnostic note for the main error message.
3679   /// \return true if statement is not an update expression, false otherwise.
3680   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
3681   /// \brief Return the 'x' lvalue part of the source atomic expression.
3682   Expr *getX() const { return X; }
3683   /// \brief Return the 'expr' rvalue part of the source atomic expression.
3684   Expr *getExpr() const { return E; }
3685   /// \brief Return the update expression used in calculation of the updated
3686   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
3687   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
3688   Expr *getUpdateExpr() const { return UpdateExpr; }
3689   /// \brief Return true if 'x' is LHS in RHS part of full update expression,
3690   /// false otherwise.
3691   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
3692 
3693   /// \brief true if the source expression is a postfix unary operation, false
3694   /// if it is a prefix unary operation.
3695   bool isPostfixUpdate() const { return IsPostfixUpdate; }
3696 
3697 private:
3698   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
3699                             unsigned NoteId = 0);
3700 };
3701 } // namespace
3702 
3703 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
3704     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
3705   ExprAnalysisErrorCode ErrorFound = NoError;
3706   SourceLocation ErrorLoc, NoteLoc;
3707   SourceRange ErrorRange, NoteRange;
3708   // Allowed constructs are:
3709   //  x = x binop expr;
3710   //  x = expr binop x;
3711   if (AtomicBinOp->getOpcode() == BO_Assign) {
3712     X = AtomicBinOp->getLHS();
3713     if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
3714             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
3715       if (AtomicInnerBinOp->isMultiplicativeOp() ||
3716           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
3717           AtomicInnerBinOp->isBitwiseOp()) {
3718         Op = AtomicInnerBinOp->getOpcode();
3719         OpLoc = AtomicInnerBinOp->getOperatorLoc();
3720         auto *LHS = AtomicInnerBinOp->getLHS();
3721         auto *RHS = AtomicInnerBinOp->getRHS();
3722         llvm::FoldingSetNodeID XId, LHSId, RHSId;
3723         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
3724                                           /*Canonical=*/true);
3725         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
3726                                             /*Canonical=*/true);
3727         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
3728                                             /*Canonical=*/true);
3729         if (XId == LHSId) {
3730           E = RHS;
3731           IsXLHSInRHSPart = true;
3732         } else if (XId == RHSId) {
3733           E = LHS;
3734           IsXLHSInRHSPart = false;
3735         } else {
3736           ErrorLoc = AtomicInnerBinOp->getExprLoc();
3737           ErrorRange = AtomicInnerBinOp->getSourceRange();
3738           NoteLoc = X->getExprLoc();
3739           NoteRange = X->getSourceRange();
3740           ErrorFound = NotAnUpdateExpression;
3741         }
3742       } else {
3743         ErrorLoc = AtomicInnerBinOp->getExprLoc();
3744         ErrorRange = AtomicInnerBinOp->getSourceRange();
3745         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
3746         NoteRange = SourceRange(NoteLoc, NoteLoc);
3747         ErrorFound = NotABinaryOperator;
3748       }
3749     } else {
3750       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
3751       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
3752       ErrorFound = NotABinaryExpression;
3753     }
3754   } else {
3755     ErrorLoc = AtomicBinOp->getExprLoc();
3756     ErrorRange = AtomicBinOp->getSourceRange();
3757     NoteLoc = AtomicBinOp->getOperatorLoc();
3758     NoteRange = SourceRange(NoteLoc, NoteLoc);
3759     ErrorFound = NotAnAssignmentOp;
3760   }
3761   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3762     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3763     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3764     return true;
3765   } else if (SemaRef.CurContext->isDependentContext())
3766     E = X = UpdateExpr = nullptr;
3767   return ErrorFound != NoError;
3768 }
3769 
3770 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
3771                                                unsigned NoteId) {
3772   ExprAnalysisErrorCode ErrorFound = NoError;
3773   SourceLocation ErrorLoc, NoteLoc;
3774   SourceRange ErrorRange, NoteRange;
3775   // Allowed constructs are:
3776   //  x++;
3777   //  x--;
3778   //  ++x;
3779   //  --x;
3780   //  x binop= expr;
3781   //  x = x binop expr;
3782   //  x = expr binop x;
3783   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
3784     AtomicBody = AtomicBody->IgnoreParenImpCasts();
3785     if (AtomicBody->getType()->isScalarType() ||
3786         AtomicBody->isInstantiationDependent()) {
3787       if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
3788               AtomicBody->IgnoreParenImpCasts())) {
3789         // Check for Compound Assignment Operation
3790         Op = BinaryOperator::getOpForCompoundAssignment(
3791             AtomicCompAssignOp->getOpcode());
3792         OpLoc = AtomicCompAssignOp->getOperatorLoc();
3793         E = AtomicCompAssignOp->getRHS();
3794         X = AtomicCompAssignOp->getLHS();
3795         IsXLHSInRHSPart = true;
3796       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
3797                      AtomicBody->IgnoreParenImpCasts())) {
3798         // Check for Binary Operation
3799         if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
3800           return true;
3801       } else if (auto *AtomicUnaryOp =
3802                  dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
3803         // Check for Unary Operation
3804         if (AtomicUnaryOp->isIncrementDecrementOp()) {
3805           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
3806           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
3807           OpLoc = AtomicUnaryOp->getOperatorLoc();
3808           X = AtomicUnaryOp->getSubExpr();
3809           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
3810           IsXLHSInRHSPart = true;
3811         } else {
3812           ErrorFound = NotAnUnaryIncDecExpression;
3813           ErrorLoc = AtomicUnaryOp->getExprLoc();
3814           ErrorRange = AtomicUnaryOp->getSourceRange();
3815           NoteLoc = AtomicUnaryOp->getOperatorLoc();
3816           NoteRange = SourceRange(NoteLoc, NoteLoc);
3817         }
3818       } else {
3819         ErrorFound = NotABinaryOrUnaryExpression;
3820         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
3821         NoteRange = ErrorRange = AtomicBody->getSourceRange();
3822       }
3823     } else {
3824       ErrorFound = NotAScalarType;
3825       NoteLoc = ErrorLoc = AtomicBody->getLocStart();
3826       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3827     }
3828   } else {
3829     ErrorFound = NotAnExpression;
3830     NoteLoc = ErrorLoc = S->getLocStart();
3831     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3832   }
3833   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
3834     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
3835     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
3836     return true;
3837   } else if (SemaRef.CurContext->isDependentContext())
3838     E = X = UpdateExpr = nullptr;
3839   if (ErrorFound == NoError && E && X) {
3840     // Build an update expression of form 'OpaqueValueExpr(x) binop
3841     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
3842     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
3843     auto *OVEX = new (SemaRef.getASTContext())
3844         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
3845     auto *OVEExpr = new (SemaRef.getASTContext())
3846         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
3847     auto Update =
3848         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
3849                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
3850     if (Update.isInvalid())
3851       return true;
3852     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
3853                                                Sema::AA_Casting);
3854     if (Update.isInvalid())
3855       return true;
3856     UpdateExpr = Update.get();
3857   }
3858   return ErrorFound != NoError;
3859 }
3860 
3861 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
3862                                             Stmt *AStmt,
3863                                             SourceLocation StartLoc,
3864                                             SourceLocation EndLoc) {
3865   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
3866   auto CS = cast<CapturedStmt>(AStmt);
3867   // 1.2.2 OpenMP Language Terminology
3868   // Structured block - An executable statement with a single entry at the
3869   // top and a single exit at the bottom.
3870   // The point of exit cannot be a branch out of the structured block.
3871   // longjmp() and throw() must not violate the entry/exit criteria.
3872   OpenMPClauseKind AtomicKind = OMPC_unknown;
3873   SourceLocation AtomicKindLoc;
3874   for (auto *C : Clauses) {
3875     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
3876         C->getClauseKind() == OMPC_update ||
3877         C->getClauseKind() == OMPC_capture) {
3878       if (AtomicKind != OMPC_unknown) {
3879         Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
3880             << SourceRange(C->getLocStart(), C->getLocEnd());
3881         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
3882             << getOpenMPClauseName(AtomicKind);
3883       } else {
3884         AtomicKind = C->getClauseKind();
3885         AtomicKindLoc = C->getLocStart();
3886       }
3887     }
3888   }
3889 
3890   auto Body = CS->getCapturedStmt();
3891   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
3892     Body = EWC->getSubExpr();
3893 
3894   Expr *X = nullptr;
3895   Expr *V = nullptr;
3896   Expr *E = nullptr;
3897   Expr *UE = nullptr;
3898   bool IsXLHSInRHSPart = false;
3899   bool IsPostfixUpdate = false;
3900   // OpenMP [2.12.6, atomic Construct]
3901   // In the next expressions:
3902   // * x and v (as applicable) are both l-value expressions with scalar type.
3903   // * During the execution of an atomic region, multiple syntactic
3904   // occurrences of x must designate the same storage location.
3905   // * Neither of v and expr (as applicable) may access the storage location
3906   // designated by x.
3907   // * Neither of x and expr (as applicable) may access the storage location
3908   // designated by v.
3909   // * expr is an expression with scalar type.
3910   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
3911   // * binop, binop=, ++, and -- are not overloaded operators.
3912   // * The expression x binop expr must be numerically equivalent to x binop
3913   // (expr). This requirement is satisfied if the operators in expr have
3914   // precedence greater than binop, or by using parentheses around expr or
3915   // subexpressions of expr.
3916   // * The expression expr binop x must be numerically equivalent to (expr)
3917   // binop x. This requirement is satisfied if the operators in expr have
3918   // precedence equal to or greater than binop, or by using parentheses around
3919   // expr or subexpressions of expr.
3920   // * For forms that allow multiple occurrences of x, the number of times
3921   // that x is evaluated is unspecified.
3922   if (AtomicKind == OMPC_read) {
3923     enum {
3924       NotAnExpression,
3925       NotAnAssignmentOp,
3926       NotAScalarType,
3927       NotAnLValue,
3928       NoError
3929     } ErrorFound = NoError;
3930     SourceLocation ErrorLoc, NoteLoc;
3931     SourceRange ErrorRange, NoteRange;
3932     // If clause is read:
3933     //  v = x;
3934     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3935       auto AtomicBinOp =
3936           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3937       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
3938         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
3939         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
3940         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
3941             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
3942           if (!X->isLValue() || !V->isLValue()) {
3943             auto NotLValueExpr = X->isLValue() ? V : X;
3944             ErrorFound = NotAnLValue;
3945             ErrorLoc = AtomicBinOp->getExprLoc();
3946             ErrorRange = AtomicBinOp->getSourceRange();
3947             NoteLoc = NotLValueExpr->getExprLoc();
3948             NoteRange = NotLValueExpr->getSourceRange();
3949           }
3950         } else if (!X->isInstantiationDependent() ||
3951                    !V->isInstantiationDependent()) {
3952           auto NotScalarExpr =
3953               (X->isInstantiationDependent() || X->getType()->isScalarType())
3954                   ? V
3955                   : X;
3956           ErrorFound = NotAScalarType;
3957           ErrorLoc = AtomicBinOp->getExprLoc();
3958           ErrorRange = AtomicBinOp->getSourceRange();
3959           NoteLoc = NotScalarExpr->getExprLoc();
3960           NoteRange = NotScalarExpr->getSourceRange();
3961         }
3962       } else {
3963         ErrorFound = NotAnAssignmentOp;
3964         ErrorLoc = AtomicBody->getExprLoc();
3965         ErrorRange = AtomicBody->getSourceRange();
3966         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
3967                               : AtomicBody->getExprLoc();
3968         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
3969                                 : AtomicBody->getSourceRange();
3970       }
3971     } else {
3972       ErrorFound = NotAnExpression;
3973       NoteLoc = ErrorLoc = Body->getLocStart();
3974       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
3975     }
3976     if (ErrorFound != NoError) {
3977       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
3978           << ErrorRange;
3979       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
3980                                                       << NoteRange;
3981       return StmtError();
3982     } else if (CurContext->isDependentContext())
3983       V = X = nullptr;
3984   } else if (AtomicKind == OMPC_write) {
3985     enum {
3986       NotAnExpression,
3987       NotAnAssignmentOp,
3988       NotAScalarType,
3989       NotAnLValue,
3990       NoError
3991     } ErrorFound = NoError;
3992     SourceLocation ErrorLoc, NoteLoc;
3993     SourceRange ErrorRange, NoteRange;
3994     // If clause is write:
3995     //  x = expr;
3996     if (auto AtomicBody = dyn_cast<Expr>(Body)) {
3997       auto AtomicBinOp =
3998           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
3999       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4000         X = AtomicBinOp->getLHS();
4001         E = AtomicBinOp->getRHS();
4002         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
4003             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
4004           if (!X->isLValue()) {
4005             ErrorFound = NotAnLValue;
4006             ErrorLoc = AtomicBinOp->getExprLoc();
4007             ErrorRange = AtomicBinOp->getSourceRange();
4008             NoteLoc = X->getExprLoc();
4009             NoteRange = X->getSourceRange();
4010           }
4011         } else if (!X->isInstantiationDependent() ||
4012                    !E->isInstantiationDependent()) {
4013           auto NotScalarExpr =
4014               (X->isInstantiationDependent() || X->getType()->isScalarType())
4015                   ? E
4016                   : X;
4017           ErrorFound = NotAScalarType;
4018           ErrorLoc = AtomicBinOp->getExprLoc();
4019           ErrorRange = AtomicBinOp->getSourceRange();
4020           NoteLoc = NotScalarExpr->getExprLoc();
4021           NoteRange = NotScalarExpr->getSourceRange();
4022         }
4023       } else {
4024         ErrorFound = NotAnAssignmentOp;
4025         ErrorLoc = AtomicBody->getExprLoc();
4026         ErrorRange = AtomicBody->getSourceRange();
4027         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4028                               : AtomicBody->getExprLoc();
4029         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4030                                 : AtomicBody->getSourceRange();
4031       }
4032     } else {
4033       ErrorFound = NotAnExpression;
4034       NoteLoc = ErrorLoc = Body->getLocStart();
4035       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
4036     }
4037     if (ErrorFound != NoError) {
4038       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
4039           << ErrorRange;
4040       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
4041                                                       << NoteRange;
4042       return StmtError();
4043     } else if (CurContext->isDependentContext())
4044       E = X = nullptr;
4045   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
4046     // If clause is update:
4047     //  x++;
4048     //  x--;
4049     //  ++x;
4050     //  --x;
4051     //  x binop= expr;
4052     //  x = x binop expr;
4053     //  x = expr binop x;
4054     OpenMPAtomicUpdateChecker Checker(*this);
4055     if (Checker.checkStatement(
4056             Body, (AtomicKind == OMPC_update)
4057                       ? diag::err_omp_atomic_update_not_expression_statement
4058                       : diag::err_omp_atomic_not_expression_statement,
4059             diag::note_omp_atomic_update))
4060       return StmtError();
4061     if (!CurContext->isDependentContext()) {
4062       E = Checker.getExpr();
4063       X = Checker.getX();
4064       UE = Checker.getUpdateExpr();
4065       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4066     }
4067   } else if (AtomicKind == OMPC_capture) {
4068     enum {
4069       NotAnAssignmentOp,
4070       NotACompoundStatement,
4071       NotTwoSubstatements,
4072       NotASpecificExpression,
4073       NoError
4074     } ErrorFound = NoError;
4075     SourceLocation ErrorLoc, NoteLoc;
4076     SourceRange ErrorRange, NoteRange;
4077     if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
4078       // If clause is a capture:
4079       //  v = x++;
4080       //  v = x--;
4081       //  v = ++x;
4082       //  v = --x;
4083       //  v = x binop= expr;
4084       //  v = x = x binop expr;
4085       //  v = x = expr binop x;
4086       auto *AtomicBinOp =
4087           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
4088       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
4089         V = AtomicBinOp->getLHS();
4090         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
4091         OpenMPAtomicUpdateChecker Checker(*this);
4092         if (Checker.checkStatement(
4093                 Body, diag::err_omp_atomic_capture_not_expression_statement,
4094                 diag::note_omp_atomic_update))
4095           return StmtError();
4096         E = Checker.getExpr();
4097         X = Checker.getX();
4098         UE = Checker.getUpdateExpr();
4099         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4100         IsPostfixUpdate = Checker.isPostfixUpdate();
4101       } else {
4102         ErrorLoc = AtomicBody->getExprLoc();
4103         ErrorRange = AtomicBody->getSourceRange();
4104         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
4105                               : AtomicBody->getExprLoc();
4106         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
4107                                 : AtomicBody->getSourceRange();
4108         ErrorFound = NotAnAssignmentOp;
4109       }
4110       if (ErrorFound != NoError) {
4111         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
4112             << ErrorRange;
4113         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4114         return StmtError();
4115       } else if (CurContext->isDependentContext()) {
4116         UE = V = E = X = nullptr;
4117       }
4118     } else {
4119       // If clause is a capture:
4120       //  { v = x; x = expr; }
4121       //  { v = x; x++; }
4122       //  { v = x; x--; }
4123       //  { v = x; ++x; }
4124       //  { v = x; --x; }
4125       //  { v = x; x binop= expr; }
4126       //  { v = x; x = x binop expr; }
4127       //  { v = x; x = expr binop x; }
4128       //  { x++; v = x; }
4129       //  { x--; v = x; }
4130       //  { ++x; v = x; }
4131       //  { --x; v = x; }
4132       //  { x binop= expr; v = x; }
4133       //  { x = x binop expr; v = x; }
4134       //  { x = expr binop x; v = x; }
4135       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
4136         // Check that this is { expr1; expr2; }
4137         if (CS->size() == 2) {
4138           auto *First = CS->body_front();
4139           auto *Second = CS->body_back();
4140           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
4141             First = EWC->getSubExpr()->IgnoreParenImpCasts();
4142           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
4143             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
4144           // Need to find what subexpression is 'v' and what is 'x'.
4145           OpenMPAtomicUpdateChecker Checker(*this);
4146           bool IsUpdateExprFound = !Checker.checkStatement(Second);
4147           BinaryOperator *BinOp = nullptr;
4148           if (IsUpdateExprFound) {
4149             BinOp = dyn_cast<BinaryOperator>(First);
4150             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4151           }
4152           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4153             //  { v = x; x++; }
4154             //  { v = x; x--; }
4155             //  { v = x; ++x; }
4156             //  { v = x; --x; }
4157             //  { v = x; x binop= expr; }
4158             //  { v = x; x = x binop expr; }
4159             //  { v = x; x = expr binop x; }
4160             // Check that the first expression has form v = x.
4161             auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4162             llvm::FoldingSetNodeID XId, PossibleXId;
4163             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4164             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4165             IsUpdateExprFound = XId == PossibleXId;
4166             if (IsUpdateExprFound) {
4167               V = BinOp->getLHS();
4168               X = Checker.getX();
4169               E = Checker.getExpr();
4170               UE = Checker.getUpdateExpr();
4171               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4172               IsPostfixUpdate = true;
4173             }
4174           }
4175           if (!IsUpdateExprFound) {
4176             IsUpdateExprFound = !Checker.checkStatement(First);
4177             BinOp = nullptr;
4178             if (IsUpdateExprFound) {
4179               BinOp = dyn_cast<BinaryOperator>(Second);
4180               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
4181             }
4182             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
4183               //  { x++; v = x; }
4184               //  { x--; v = x; }
4185               //  { ++x; v = x; }
4186               //  { --x; v = x; }
4187               //  { x binop= expr; v = x; }
4188               //  { x = x binop expr; v = x; }
4189               //  { x = expr binop x; v = x; }
4190               // Check that the second expression has form v = x.
4191               auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
4192               llvm::FoldingSetNodeID XId, PossibleXId;
4193               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
4194               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
4195               IsUpdateExprFound = XId == PossibleXId;
4196               if (IsUpdateExprFound) {
4197                 V = BinOp->getLHS();
4198                 X = Checker.getX();
4199                 E = Checker.getExpr();
4200                 UE = Checker.getUpdateExpr();
4201                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
4202                 IsPostfixUpdate = false;
4203               }
4204             }
4205           }
4206           if (!IsUpdateExprFound) {
4207             //  { v = x; x = expr; }
4208             auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
4209             if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
4210               ErrorFound = NotAnAssignmentOp;
4211               NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
4212                                               : First->getLocStart();
4213               NoteRange = ErrorRange = FirstBinOp
4214                                            ? FirstBinOp->getSourceRange()
4215                                            : SourceRange(ErrorLoc, ErrorLoc);
4216             } else {
4217               auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
4218               if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
4219                 ErrorFound = NotAnAssignmentOp;
4220                 NoteLoc = ErrorLoc = SecondBinOp ? SecondBinOp->getOperatorLoc()
4221                                                  : Second->getLocStart();
4222                 NoteRange = ErrorRange = SecondBinOp
4223                                              ? SecondBinOp->getSourceRange()
4224                                              : SourceRange(ErrorLoc, ErrorLoc);
4225               } else {
4226                 auto *PossibleXRHSInFirst =
4227                     FirstBinOp->getRHS()->IgnoreParenImpCasts();
4228                 auto *PossibleXLHSInSecond =
4229                     SecondBinOp->getLHS()->IgnoreParenImpCasts();
4230                 llvm::FoldingSetNodeID X1Id, X2Id;
4231                 PossibleXRHSInFirst->Profile(X1Id, Context, /*Canonical=*/true);
4232                 PossibleXLHSInSecond->Profile(X2Id, Context,
4233                                               /*Canonical=*/true);
4234                 IsUpdateExprFound = X1Id == X2Id;
4235                 if (IsUpdateExprFound) {
4236                   V = FirstBinOp->getLHS();
4237                   X = SecondBinOp->getLHS();
4238                   E = SecondBinOp->getRHS();
4239                   UE = nullptr;
4240                   IsXLHSInRHSPart = false;
4241                   IsPostfixUpdate = true;
4242                 } else {
4243                   ErrorFound = NotASpecificExpression;
4244                   ErrorLoc = FirstBinOp->getExprLoc();
4245                   ErrorRange = FirstBinOp->getSourceRange();
4246                   NoteLoc = SecondBinOp->getLHS()->getExprLoc();
4247                   NoteRange = SecondBinOp->getRHS()->getSourceRange();
4248                 }
4249               }
4250             }
4251           }
4252         } else {
4253           NoteLoc = ErrorLoc = Body->getLocStart();
4254           NoteRange = ErrorRange =
4255               SourceRange(Body->getLocStart(), Body->getLocStart());
4256           ErrorFound = NotTwoSubstatements;
4257         }
4258       } else {
4259         NoteLoc = ErrorLoc = Body->getLocStart();
4260         NoteRange = ErrorRange =
4261             SourceRange(Body->getLocStart(), Body->getLocStart());
4262         ErrorFound = NotACompoundStatement;
4263       }
4264       if (ErrorFound != NoError) {
4265         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
4266             << ErrorRange;
4267         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
4268         return StmtError();
4269       } else if (CurContext->isDependentContext()) {
4270         UE = V = E = X = nullptr;
4271       }
4272     }
4273   }
4274 
4275   getCurFunction()->setHasBranchProtectedScope();
4276 
4277   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4278                                     X, V, E, UE, IsXLHSInRHSPart,
4279                                     IsPostfixUpdate);
4280 }
4281 
4282 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
4283                                             Stmt *AStmt,
4284                                             SourceLocation StartLoc,
4285                                             SourceLocation EndLoc) {
4286   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4287 
4288   // OpenMP [2.16, Nesting of Regions]
4289   // If specified, a teams construct must be contained within a target
4290   // construct. That target construct must contain no statements or directives
4291   // outside of the teams construct.
4292   if (DSAStack->hasInnerTeamsRegion()) {
4293     auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
4294     bool OMPTeamsFound = true;
4295     if (auto *CS = dyn_cast<CompoundStmt>(S)) {
4296       auto I = CS->body_begin();
4297       while (I != CS->body_end()) {
4298         auto OED = dyn_cast<OMPExecutableDirective>(*I);
4299         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
4300           OMPTeamsFound = false;
4301           break;
4302         }
4303         ++I;
4304       }
4305       assert(I != CS->body_end() && "Not found statement");
4306       S = *I;
4307     }
4308     if (!OMPTeamsFound) {
4309       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
4310       Diag(DSAStack->getInnerTeamsRegionLoc(),
4311            diag::note_omp_nested_teams_construct_here);
4312       Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
4313           << isa<OMPExecutableDirective>(S);
4314       return StmtError();
4315     }
4316   }
4317 
4318   getCurFunction()->setHasBranchProtectedScope();
4319 
4320   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4321 }
4322 
4323 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
4324                                            Stmt *AStmt, SourceLocation StartLoc,
4325                                            SourceLocation EndLoc) {
4326   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
4327   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4328   // 1.2.2 OpenMP Language Terminology
4329   // Structured block - An executable statement with a single entry at the
4330   // top and a single exit at the bottom.
4331   // The point of exit cannot be a branch out of the structured block.
4332   // longjmp() and throw() must not violate the entry/exit criteria.
4333   CS->getCapturedDecl()->setNothrow();
4334 
4335   getCurFunction()->setHasBranchProtectedScope();
4336 
4337   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4338 }
4339 
4340 StmtResult
4341 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
4342                                             SourceLocation EndLoc,
4343                                             OpenMPDirectiveKind CancelRegion) {
4344   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4345       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4346     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4347         << getOpenMPDirectiveName(CancelRegion);
4348     return StmtError();
4349   }
4350   if (DSAStack->isParentNowaitRegion()) {
4351     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
4352     return StmtError();
4353   }
4354   if (DSAStack->isParentOrderedRegion()) {
4355     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
4356     return StmtError();
4357   }
4358   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
4359                                                CancelRegion);
4360 }
4361 
4362 StmtResult Sema::ActOnOpenMPCancelDirective(SourceLocation StartLoc,
4363                                             SourceLocation EndLoc,
4364                                             OpenMPDirectiveKind CancelRegion) {
4365   if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
4366       CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
4367     Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4368         << getOpenMPDirectiveName(CancelRegion);
4369     return StmtError();
4370   }
4371   if (DSAStack->isParentNowaitRegion()) {
4372     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
4373     return StmtError();
4374   }
4375   if (DSAStack->isParentOrderedRegion()) {
4376     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
4377     return StmtError();
4378   }
4379   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, CancelRegion);
4380 }
4381 
4382 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
4383                                              SourceLocation StartLoc,
4384                                              SourceLocation LParenLoc,
4385                                              SourceLocation EndLoc) {
4386   OMPClause *Res = nullptr;
4387   switch (Kind) {
4388   case OMPC_if:
4389     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
4390     break;
4391   case OMPC_final:
4392     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
4393     break;
4394   case OMPC_num_threads:
4395     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
4396     break;
4397   case OMPC_safelen:
4398     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
4399     break;
4400   case OMPC_collapse:
4401     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
4402     break;
4403   case OMPC_default:
4404   case OMPC_proc_bind:
4405   case OMPC_schedule:
4406   case OMPC_private:
4407   case OMPC_firstprivate:
4408   case OMPC_lastprivate:
4409   case OMPC_shared:
4410   case OMPC_reduction:
4411   case OMPC_linear:
4412   case OMPC_aligned:
4413   case OMPC_copyin:
4414   case OMPC_copyprivate:
4415   case OMPC_ordered:
4416   case OMPC_nowait:
4417   case OMPC_untied:
4418   case OMPC_mergeable:
4419   case OMPC_threadprivate:
4420   case OMPC_flush:
4421   case OMPC_read:
4422   case OMPC_write:
4423   case OMPC_update:
4424   case OMPC_capture:
4425   case OMPC_seq_cst:
4426   case OMPC_depend:
4427   case OMPC_unknown:
4428     llvm_unreachable("Clause is not allowed.");
4429   }
4430   return Res;
4431 }
4432 
4433 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
4434                                      SourceLocation LParenLoc,
4435                                      SourceLocation EndLoc) {
4436   Expr *ValExpr = Condition;
4437   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4438       !Condition->isInstantiationDependent() &&
4439       !Condition->containsUnexpandedParameterPack()) {
4440     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4441                                            Condition->getExprLoc(), Condition);
4442     if (Val.isInvalid())
4443       return nullptr;
4444 
4445     ValExpr = Val.get();
4446   }
4447 
4448   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4449 }
4450 
4451 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
4452                                         SourceLocation StartLoc,
4453                                         SourceLocation LParenLoc,
4454                                         SourceLocation EndLoc) {
4455   Expr *ValExpr = Condition;
4456   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
4457       !Condition->isInstantiationDependent() &&
4458       !Condition->containsUnexpandedParameterPack()) {
4459     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
4460                                            Condition->getExprLoc(), Condition);
4461     if (Val.isInvalid())
4462       return nullptr;
4463 
4464     ValExpr = Val.get();
4465   }
4466 
4467   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4468 }
4469 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
4470                                                         Expr *Op) {
4471   if (!Op)
4472     return ExprError();
4473 
4474   class IntConvertDiagnoser : public ICEConvertDiagnoser {
4475   public:
4476     IntConvertDiagnoser()
4477         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
4478     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
4479                                          QualType T) override {
4480       return S.Diag(Loc, diag::err_omp_not_integral) << T;
4481     }
4482     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4483                                              QualType T) override {
4484       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
4485     }
4486     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4487                                                QualType T,
4488                                                QualType ConvTy) override {
4489       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
4490     }
4491     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4492                                            QualType ConvTy) override {
4493       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4494              << ConvTy->isEnumeralType() << ConvTy;
4495     }
4496     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4497                                             QualType T) override {
4498       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
4499     }
4500     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4501                                         QualType ConvTy) override {
4502       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
4503              << ConvTy->isEnumeralType() << ConvTy;
4504     }
4505     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
4506                                              QualType) override {
4507       llvm_unreachable("conversion functions are permitted");
4508     }
4509   } ConvertDiagnoser;
4510   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
4511 }
4512 
4513 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
4514                                              SourceLocation StartLoc,
4515                                              SourceLocation LParenLoc,
4516                                              SourceLocation EndLoc) {
4517   Expr *ValExpr = NumThreads;
4518   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
4519       !NumThreads->containsUnexpandedParameterPack()) {
4520     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
4521     ExprResult Val =
4522         PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
4523     if (Val.isInvalid())
4524       return nullptr;
4525 
4526     ValExpr = Val.get();
4527 
4528     // OpenMP [2.5, Restrictions]
4529     //  The num_threads expression must evaluate to a positive integer value.
4530     llvm::APSInt Result;
4531     if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
4532         !Result.isStrictlyPositive()) {
4533       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
4534           << "num_threads" << NumThreads->getSourceRange();
4535       return nullptr;
4536     }
4537   }
4538 
4539   return new (Context)
4540       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
4541 }
4542 
4543 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
4544                                                        OpenMPClauseKind CKind) {
4545   if (!E)
4546     return ExprError();
4547   if (E->isValueDependent() || E->isTypeDependent() ||
4548       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4549     return E;
4550   llvm::APSInt Result;
4551   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
4552   if (ICE.isInvalid())
4553     return ExprError();
4554   if (!Result.isStrictlyPositive()) {
4555     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
4556         << getOpenMPClauseName(CKind) << E->getSourceRange();
4557     return ExprError();
4558   }
4559   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
4560     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
4561         << E->getSourceRange();
4562     return ExprError();
4563   }
4564   if (CKind == OMPC_collapse) {
4565     DSAStack->setCollapseNumber(Result.getExtValue());
4566   }
4567   return ICE;
4568 }
4569 
4570 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
4571                                           SourceLocation LParenLoc,
4572                                           SourceLocation EndLoc) {
4573   // OpenMP [2.8.1, simd construct, Description]
4574   // The parameter of the safelen clause must be a constant
4575   // positive integer expression.
4576   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
4577   if (Safelen.isInvalid())
4578     return nullptr;
4579   return new (Context)
4580       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
4581 }
4582 
4583 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
4584                                            SourceLocation StartLoc,
4585                                            SourceLocation LParenLoc,
4586                                            SourceLocation EndLoc) {
4587   // OpenMP [2.7.1, loop construct, Description]
4588   // OpenMP [2.8.1, simd construct, Description]
4589   // OpenMP [2.9.6, distribute construct, Description]
4590   // The parameter of the collapse clause must be a constant
4591   // positive integer expression.
4592   ExprResult NumForLoopsResult =
4593       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
4594   if (NumForLoopsResult.isInvalid())
4595     return nullptr;
4596   return new (Context)
4597       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
4598 }
4599 
4600 OMPClause *Sema::ActOnOpenMPSimpleClause(
4601     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
4602     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
4603   OMPClause *Res = nullptr;
4604   switch (Kind) {
4605   case OMPC_default:
4606     Res =
4607         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
4608                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
4609     break;
4610   case OMPC_proc_bind:
4611     Res = ActOnOpenMPProcBindClause(
4612         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
4613         LParenLoc, EndLoc);
4614     break;
4615   case OMPC_if:
4616   case OMPC_final:
4617   case OMPC_num_threads:
4618   case OMPC_safelen:
4619   case OMPC_collapse:
4620   case OMPC_schedule:
4621   case OMPC_private:
4622   case OMPC_firstprivate:
4623   case OMPC_lastprivate:
4624   case OMPC_shared:
4625   case OMPC_reduction:
4626   case OMPC_linear:
4627   case OMPC_aligned:
4628   case OMPC_copyin:
4629   case OMPC_copyprivate:
4630   case OMPC_ordered:
4631   case OMPC_nowait:
4632   case OMPC_untied:
4633   case OMPC_mergeable:
4634   case OMPC_threadprivate:
4635   case OMPC_flush:
4636   case OMPC_read:
4637   case OMPC_write:
4638   case OMPC_update:
4639   case OMPC_capture:
4640   case OMPC_seq_cst:
4641   case OMPC_depend:
4642   case OMPC_unknown:
4643     llvm_unreachable("Clause is not allowed.");
4644   }
4645   return Res;
4646 }
4647 
4648 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
4649                                           SourceLocation KindKwLoc,
4650                                           SourceLocation StartLoc,
4651                                           SourceLocation LParenLoc,
4652                                           SourceLocation EndLoc) {
4653   if (Kind == OMPC_DEFAULT_unknown) {
4654     std::string Values;
4655     static_assert(OMPC_DEFAULT_unknown > 0,
4656                   "OMPC_DEFAULT_unknown not greater than 0");
4657     std::string Sep(", ");
4658     for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
4659       Values += "'";
4660       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
4661       Values += "'";
4662       switch (i) {
4663       case OMPC_DEFAULT_unknown - 2:
4664         Values += " or ";
4665         break;
4666       case OMPC_DEFAULT_unknown - 1:
4667         break;
4668       default:
4669         Values += Sep;
4670         break;
4671       }
4672     }
4673     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4674         << Values << getOpenMPClauseName(OMPC_default);
4675     return nullptr;
4676   }
4677   switch (Kind) {
4678   case OMPC_DEFAULT_none:
4679     DSAStack->setDefaultDSANone(KindKwLoc);
4680     break;
4681   case OMPC_DEFAULT_shared:
4682     DSAStack->setDefaultDSAShared(KindKwLoc);
4683     break;
4684   case OMPC_DEFAULT_unknown:
4685     llvm_unreachable("Clause kind is not allowed.");
4686     break;
4687   }
4688   return new (Context)
4689       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4690 }
4691 
4692 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
4693                                            SourceLocation KindKwLoc,
4694                                            SourceLocation StartLoc,
4695                                            SourceLocation LParenLoc,
4696                                            SourceLocation EndLoc) {
4697   if (Kind == OMPC_PROC_BIND_unknown) {
4698     std::string Values;
4699     std::string Sep(", ");
4700     for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
4701       Values += "'";
4702       Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
4703       Values += "'";
4704       switch (i) {
4705       case OMPC_PROC_BIND_unknown - 2:
4706         Values += " or ";
4707         break;
4708       case OMPC_PROC_BIND_unknown - 1:
4709         break;
4710       default:
4711         Values += Sep;
4712         break;
4713       }
4714     }
4715     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
4716         << Values << getOpenMPClauseName(OMPC_proc_bind);
4717     return nullptr;
4718   }
4719   return new (Context)
4720       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
4721 }
4722 
4723 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
4724     OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
4725     SourceLocation StartLoc, SourceLocation LParenLoc,
4726     SourceLocation ArgumentLoc, SourceLocation CommaLoc,
4727     SourceLocation EndLoc) {
4728   OMPClause *Res = nullptr;
4729   switch (Kind) {
4730   case OMPC_schedule:
4731     Res = ActOnOpenMPScheduleClause(
4732         static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
4733         LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
4734     break;
4735   case OMPC_if:
4736   case OMPC_final:
4737   case OMPC_num_threads:
4738   case OMPC_safelen:
4739   case OMPC_collapse:
4740   case OMPC_default:
4741   case OMPC_proc_bind:
4742   case OMPC_private:
4743   case OMPC_firstprivate:
4744   case OMPC_lastprivate:
4745   case OMPC_shared:
4746   case OMPC_reduction:
4747   case OMPC_linear:
4748   case OMPC_aligned:
4749   case OMPC_copyin:
4750   case OMPC_copyprivate:
4751   case OMPC_ordered:
4752   case OMPC_nowait:
4753   case OMPC_untied:
4754   case OMPC_mergeable:
4755   case OMPC_threadprivate:
4756   case OMPC_flush:
4757   case OMPC_read:
4758   case OMPC_write:
4759   case OMPC_update:
4760   case OMPC_capture:
4761   case OMPC_seq_cst:
4762   case OMPC_depend:
4763   case OMPC_unknown:
4764     llvm_unreachable("Clause is not allowed.");
4765   }
4766   return Res;
4767 }
4768 
4769 OMPClause *Sema::ActOnOpenMPScheduleClause(
4770     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
4771     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
4772     SourceLocation EndLoc) {
4773   if (Kind == OMPC_SCHEDULE_unknown) {
4774     std::string Values;
4775     std::string Sep(", ");
4776     for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
4777       Values += "'";
4778       Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
4779       Values += "'";
4780       switch (i) {
4781       case OMPC_SCHEDULE_unknown - 2:
4782         Values += " or ";
4783         break;
4784       case OMPC_SCHEDULE_unknown - 1:
4785         break;
4786       default:
4787         Values += Sep;
4788         break;
4789       }
4790     }
4791     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
4792         << Values << getOpenMPClauseName(OMPC_schedule);
4793     return nullptr;
4794   }
4795   Expr *ValExpr = ChunkSize;
4796   Expr *HelperValExpr = nullptr;
4797   if (ChunkSize) {
4798     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
4799         !ChunkSize->isInstantiationDependent() &&
4800         !ChunkSize->containsUnexpandedParameterPack()) {
4801       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
4802       ExprResult Val =
4803           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
4804       if (Val.isInvalid())
4805         return nullptr;
4806 
4807       ValExpr = Val.get();
4808 
4809       // OpenMP [2.7.1, Restrictions]
4810       //  chunk_size must be a loop invariant integer expression with a positive
4811       //  value.
4812       llvm::APSInt Result;
4813       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
4814         if (Result.isSigned() && !Result.isStrictlyPositive()) {
4815           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
4816               << "schedule" << ChunkSize->getSourceRange();
4817           return nullptr;
4818         }
4819       } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
4820         auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
4821                                     ChunkSize->getType(), ".chunk.");
4822         auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
4823                                            ChunkSize->getExprLoc(),
4824                                            /*RefersToCapture=*/true);
4825         HelperValExpr = ImpVarRef;
4826       }
4827     }
4828   }
4829 
4830   return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
4831                                          EndLoc, Kind, ValExpr, HelperValExpr);
4832 }
4833 
4834 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
4835                                    SourceLocation StartLoc,
4836                                    SourceLocation EndLoc) {
4837   OMPClause *Res = nullptr;
4838   switch (Kind) {
4839   case OMPC_ordered:
4840     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
4841     break;
4842   case OMPC_nowait:
4843     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
4844     break;
4845   case OMPC_untied:
4846     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
4847     break;
4848   case OMPC_mergeable:
4849     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
4850     break;
4851   case OMPC_read:
4852     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
4853     break;
4854   case OMPC_write:
4855     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
4856     break;
4857   case OMPC_update:
4858     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
4859     break;
4860   case OMPC_capture:
4861     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
4862     break;
4863   case OMPC_seq_cst:
4864     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
4865     break;
4866   case OMPC_if:
4867   case OMPC_final:
4868   case OMPC_num_threads:
4869   case OMPC_safelen:
4870   case OMPC_collapse:
4871   case OMPC_schedule:
4872   case OMPC_private:
4873   case OMPC_firstprivate:
4874   case OMPC_lastprivate:
4875   case OMPC_shared:
4876   case OMPC_reduction:
4877   case OMPC_linear:
4878   case OMPC_aligned:
4879   case OMPC_copyin:
4880   case OMPC_copyprivate:
4881   case OMPC_default:
4882   case OMPC_proc_bind:
4883   case OMPC_threadprivate:
4884   case OMPC_flush:
4885   case OMPC_depend:
4886   case OMPC_unknown:
4887     llvm_unreachable("Clause is not allowed.");
4888   }
4889   return Res;
4890 }
4891 
4892 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
4893                                           SourceLocation EndLoc) {
4894   DSAStack->setOrderedRegion();
4895   return new (Context) OMPOrderedClause(StartLoc, EndLoc);
4896 }
4897 
4898 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
4899                                          SourceLocation EndLoc) {
4900   DSAStack->setNowaitRegion();
4901   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
4902 }
4903 
4904 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
4905                                          SourceLocation EndLoc) {
4906   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
4907 }
4908 
4909 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
4910                                             SourceLocation EndLoc) {
4911   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
4912 }
4913 
4914 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
4915                                        SourceLocation EndLoc) {
4916   return new (Context) OMPReadClause(StartLoc, EndLoc);
4917 }
4918 
4919 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
4920                                         SourceLocation EndLoc) {
4921   return new (Context) OMPWriteClause(StartLoc, EndLoc);
4922 }
4923 
4924 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
4925                                          SourceLocation EndLoc) {
4926   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
4927 }
4928 
4929 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
4930                                           SourceLocation EndLoc) {
4931   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
4932 }
4933 
4934 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
4935                                          SourceLocation EndLoc) {
4936   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
4937 }
4938 
4939 OMPClause *Sema::ActOnOpenMPVarListClause(
4940     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
4941     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
4942     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
4943     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
4944     SourceLocation DepLoc) {
4945   OMPClause *Res = nullptr;
4946   switch (Kind) {
4947   case OMPC_private:
4948     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4949     break;
4950   case OMPC_firstprivate:
4951     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4952     break;
4953   case OMPC_lastprivate:
4954     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4955     break;
4956   case OMPC_shared:
4957     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
4958     break;
4959   case OMPC_reduction:
4960     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
4961                                      EndLoc, ReductionIdScopeSpec, ReductionId);
4962     break;
4963   case OMPC_linear:
4964     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
4965                                   ColonLoc, EndLoc);
4966     break;
4967   case OMPC_aligned:
4968     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
4969                                    ColonLoc, EndLoc);
4970     break;
4971   case OMPC_copyin:
4972     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
4973     break;
4974   case OMPC_copyprivate:
4975     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
4976     break;
4977   case OMPC_flush:
4978     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
4979     break;
4980   case OMPC_depend:
4981     Res = ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList, StartLoc,
4982                                   LParenLoc, EndLoc);
4983     break;
4984   case OMPC_if:
4985   case OMPC_final:
4986   case OMPC_num_threads:
4987   case OMPC_safelen:
4988   case OMPC_collapse:
4989   case OMPC_default:
4990   case OMPC_proc_bind:
4991   case OMPC_schedule:
4992   case OMPC_ordered:
4993   case OMPC_nowait:
4994   case OMPC_untied:
4995   case OMPC_mergeable:
4996   case OMPC_threadprivate:
4997   case OMPC_read:
4998   case OMPC_write:
4999   case OMPC_update:
5000   case OMPC_capture:
5001   case OMPC_seq_cst:
5002   case OMPC_unknown:
5003     llvm_unreachable("Clause is not allowed.");
5004   }
5005   return Res;
5006 }
5007 
5008 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
5009                                           SourceLocation StartLoc,
5010                                           SourceLocation LParenLoc,
5011                                           SourceLocation EndLoc) {
5012   SmallVector<Expr *, 8> Vars;
5013   SmallVector<Expr *, 8> PrivateCopies;
5014   for (auto &RefExpr : VarList) {
5015     assert(RefExpr && "NULL expr in OpenMP private clause.");
5016     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5017       // It will be analyzed later.
5018       Vars.push_back(RefExpr);
5019       PrivateCopies.push_back(nullptr);
5020       continue;
5021     }
5022 
5023     SourceLocation ELoc = RefExpr->getExprLoc();
5024     // OpenMP [2.1, C/C++]
5025     //  A list item is a variable name.
5026     // OpenMP  [2.9.3.3, Restrictions, p.1]
5027     //  A variable that is part of another variable (as an array or
5028     //  structure element) cannot appear in a private clause.
5029     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5030     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5031       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5032       continue;
5033     }
5034     Decl *D = DE->getDecl();
5035     VarDecl *VD = cast<VarDecl>(D);
5036 
5037     QualType Type = VD->getType();
5038     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5039       // It will be analyzed later.
5040       Vars.push_back(DE);
5041       PrivateCopies.push_back(nullptr);
5042       continue;
5043     }
5044 
5045     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5046     //  A variable that appears in a private clause must not have an incomplete
5047     //  type or a reference type.
5048     if (RequireCompleteType(ELoc, Type,
5049                             diag::err_omp_private_incomplete_type)) {
5050       continue;
5051     }
5052     if (Type->isReferenceType()) {
5053       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5054           << getOpenMPClauseName(OMPC_private) << Type;
5055       bool IsDecl =
5056           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5057       Diag(VD->getLocation(),
5058            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5059           << VD;
5060       continue;
5061     }
5062 
5063     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5064     // in a Construct]
5065     //  Variables with the predetermined data-sharing attributes may not be
5066     //  listed in data-sharing attributes clauses, except for the cases
5067     //  listed below. For these exceptions only, listing a predetermined
5068     //  variable in a data-sharing attribute clause is allowed and overrides
5069     //  the variable's predetermined data-sharing attributes.
5070     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5071     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
5072       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5073                                           << getOpenMPClauseName(OMPC_private);
5074       ReportOriginalDSA(*this, DSAStack, VD, DVar);
5075       continue;
5076     }
5077 
5078     // Variably modified types are not supported for tasks.
5079     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5080         DSAStack->getCurrentDirective() == OMPD_task) {
5081       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5082           << getOpenMPClauseName(OMPC_private) << Type
5083           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5084       bool IsDecl =
5085           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5086       Diag(VD->getLocation(),
5087            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5088           << VD;
5089       continue;
5090     }
5091 
5092     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
5093     //  A variable of class type (or array thereof) that appears in a private
5094     //  clause requires an accessible, unambiguous default constructor for the
5095     //  class type.
5096     // Generate helper private variable and initialize it with the default
5097     // value. The address of the original variable is replaced by the address of
5098     // the new private variable in CodeGen. This new variable is not added to
5099     // IdResolver, so the code in the OpenMP region uses original variable for
5100     // proper diagnostics.
5101     Type = Type.getUnqualifiedType();
5102     auto VDPrivate = buildVarDecl(*this, DE->getExprLoc(), Type, VD->getName());
5103     ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
5104     if (VDPrivate->isInvalidDecl())
5105       continue;
5106     auto VDPrivateRefExpr = buildDeclRefExpr(
5107         *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5108 
5109     DSAStack->addDSA(VD, DE, OMPC_private);
5110     Vars.push_back(DE);
5111     PrivateCopies.push_back(VDPrivateRefExpr);
5112   }
5113 
5114   if (Vars.empty())
5115     return nullptr;
5116 
5117   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
5118                                   PrivateCopies);
5119 }
5120 
5121 namespace {
5122 class DiagsUninitializedSeveretyRAII {
5123 private:
5124   DiagnosticsEngine &Diags;
5125   SourceLocation SavedLoc;
5126   bool IsIgnored;
5127 
5128 public:
5129   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
5130                                  bool IsIgnored)
5131       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
5132     if (!IsIgnored) {
5133       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
5134                         /*Map*/ diag::Severity::Ignored, Loc);
5135     }
5136   }
5137   ~DiagsUninitializedSeveretyRAII() {
5138     if (!IsIgnored)
5139       Diags.popMappings(SavedLoc);
5140   }
5141 };
5142 }
5143 
5144 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
5145                                                SourceLocation StartLoc,
5146                                                SourceLocation LParenLoc,
5147                                                SourceLocation EndLoc) {
5148   SmallVector<Expr *, 8> Vars;
5149   SmallVector<Expr *, 8> PrivateCopies;
5150   SmallVector<Expr *, 8> Inits;
5151   bool IsImplicitClause =
5152       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
5153   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
5154 
5155   for (auto &RefExpr : VarList) {
5156     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
5157     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5158       // It will be analyzed later.
5159       Vars.push_back(RefExpr);
5160       PrivateCopies.push_back(nullptr);
5161       Inits.push_back(nullptr);
5162       continue;
5163     }
5164 
5165     SourceLocation ELoc =
5166         IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
5167     // OpenMP [2.1, C/C++]
5168     //  A list item is a variable name.
5169     // OpenMP  [2.9.3.3, Restrictions, p.1]
5170     //  A variable that is part of another variable (as an array or
5171     //  structure element) cannot appear in a private clause.
5172     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5173     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5174       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5175       continue;
5176     }
5177     Decl *D = DE->getDecl();
5178     VarDecl *VD = cast<VarDecl>(D);
5179 
5180     QualType Type = VD->getType();
5181     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5182       // It will be analyzed later.
5183       Vars.push_back(DE);
5184       PrivateCopies.push_back(nullptr);
5185       Inits.push_back(nullptr);
5186       continue;
5187     }
5188 
5189     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5190     //  A variable that appears in a private clause must not have an incomplete
5191     //  type or a reference type.
5192     if (RequireCompleteType(ELoc, Type,
5193                             diag::err_omp_firstprivate_incomplete_type)) {
5194       continue;
5195     }
5196     if (Type->isReferenceType()) {
5197       if (IsImplicitClause) {
5198         Diag(ImplicitClauseLoc,
5199              diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
5200             << Type;
5201         Diag(RefExpr->getExprLoc(), diag::note_used_here);
5202       } else {
5203         Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5204             << getOpenMPClauseName(OMPC_firstprivate) << Type;
5205       }
5206       bool IsDecl =
5207           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5208       Diag(VD->getLocation(),
5209            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5210           << VD;
5211       continue;
5212     }
5213 
5214     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
5215     //  A variable of class type (or array thereof) that appears in a private
5216     //  clause requires an accessible, unambiguous copy constructor for the
5217     //  class type.
5218     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
5219 
5220     // If an implicit firstprivate variable found it was checked already.
5221     if (!IsImplicitClause) {
5222       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5223       bool IsConstant = ElemType.isConstant(Context);
5224       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
5225       //  A list item that specifies a given variable may not appear in more
5226       // than one clause on the same directive, except that a variable may be
5227       //  specified in both firstprivate and lastprivate clauses.
5228       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
5229           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
5230         Diag(ELoc, diag::err_omp_wrong_dsa)
5231             << getOpenMPClauseName(DVar.CKind)
5232             << getOpenMPClauseName(OMPC_firstprivate);
5233         ReportOriginalDSA(*this, DSAStack, VD, DVar);
5234         continue;
5235       }
5236 
5237       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5238       // in a Construct]
5239       //  Variables with the predetermined data-sharing attributes may not be
5240       //  listed in data-sharing attributes clauses, except for the cases
5241       //  listed below. For these exceptions only, listing a predetermined
5242       //  variable in a data-sharing attribute clause is allowed and overrides
5243       //  the variable's predetermined data-sharing attributes.
5244       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5245       // in a Construct, C/C++, p.2]
5246       //  Variables with const-qualified type having no mutable member may be
5247       //  listed in a firstprivate clause, even if they are static data members.
5248       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
5249           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
5250         Diag(ELoc, diag::err_omp_wrong_dsa)
5251             << getOpenMPClauseName(DVar.CKind)
5252             << getOpenMPClauseName(OMPC_firstprivate);
5253         ReportOriginalDSA(*this, DSAStack, VD, DVar);
5254         continue;
5255       }
5256 
5257       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5258       // OpenMP [2.9.3.4, Restrictions, p.2]
5259       //  A list item that is private within a parallel region must not appear
5260       //  in a firstprivate clause on a worksharing construct if any of the
5261       //  worksharing regions arising from the worksharing construct ever bind
5262       //  to any of the parallel regions arising from the parallel construct.
5263       if (isOpenMPWorksharingDirective(CurrDir) &&
5264           !isOpenMPParallelDirective(CurrDir)) {
5265         DVar = DSAStack->getImplicitDSA(VD, true);
5266         if (DVar.CKind != OMPC_shared &&
5267             (isOpenMPParallelDirective(DVar.DKind) ||
5268              DVar.DKind == OMPD_unknown)) {
5269           Diag(ELoc, diag::err_omp_required_access)
5270               << getOpenMPClauseName(OMPC_firstprivate)
5271               << getOpenMPClauseName(OMPC_shared);
5272           ReportOriginalDSA(*this, DSAStack, VD, DVar);
5273           continue;
5274         }
5275       }
5276       // OpenMP [2.9.3.4, Restrictions, p.3]
5277       //  A list item that appears in a reduction clause of a parallel construct
5278       //  must not appear in a firstprivate clause on a worksharing or task
5279       //  construct if any of the worksharing or task regions arising from the
5280       //  worksharing or task construct ever bind to any of the parallel regions
5281       //  arising from the parallel construct.
5282       // OpenMP [2.9.3.4, Restrictions, p.4]
5283       //  A list item that appears in a reduction clause in worksharing
5284       //  construct must not appear in a firstprivate clause in a task construct
5285       //  encountered during execution of any of the worksharing regions arising
5286       //  from the worksharing construct.
5287       if (CurrDir == OMPD_task) {
5288         DVar =
5289             DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
5290                                       [](OpenMPDirectiveKind K) -> bool {
5291                                         return isOpenMPParallelDirective(K) ||
5292                                                isOpenMPWorksharingDirective(K);
5293                                       },
5294                                       false);
5295         if (DVar.CKind == OMPC_reduction &&
5296             (isOpenMPParallelDirective(DVar.DKind) ||
5297              isOpenMPWorksharingDirective(DVar.DKind))) {
5298           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
5299               << getOpenMPDirectiveName(DVar.DKind);
5300           ReportOriginalDSA(*this, DSAStack, VD, DVar);
5301           continue;
5302         }
5303       }
5304     }
5305 
5306     // Variably modified types are not supported for tasks.
5307     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
5308         DSAStack->getCurrentDirective() == OMPD_task) {
5309       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
5310           << getOpenMPClauseName(OMPC_firstprivate) << Type
5311           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
5312       bool IsDecl =
5313           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5314       Diag(VD->getLocation(),
5315            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5316           << VD;
5317       continue;
5318     }
5319 
5320     Type = Type.getUnqualifiedType();
5321     auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName());
5322     // Generate helper private variable and initialize it with the value of the
5323     // original variable. The address of the original variable is replaced by
5324     // the address of the new private variable in the CodeGen. This new variable
5325     // is not added to IdResolver, so the code in the OpenMP region uses
5326     // original variable for proper diagnostics and variable capturing.
5327     Expr *VDInitRefExpr = nullptr;
5328     // For arrays generate initializer for single element and replace it by the
5329     // original array element in CodeGen.
5330     if (Type->isArrayType()) {
5331       auto VDInit =
5332           buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
5333       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
5334       auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
5335       ElemType = ElemType.getUnqualifiedType();
5336       auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
5337                                       ".firstprivate.temp");
5338       InitializedEntity Entity =
5339           InitializedEntity::InitializeVariable(VDInitTemp);
5340       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
5341 
5342       InitializationSequence InitSeq(*this, Entity, Kind, Init);
5343       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
5344       if (Result.isInvalid())
5345         VDPrivate->setInvalidDecl();
5346       else
5347         VDPrivate->setInit(Result.getAs<Expr>());
5348     } else {
5349       auto *VDInit =
5350           buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
5351       VDInitRefExpr =
5352           buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
5353       AddInitializerToDecl(VDPrivate,
5354                            DefaultLvalueConversion(VDInitRefExpr).get(),
5355                            /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
5356     }
5357     if (VDPrivate->isInvalidDecl()) {
5358       if (IsImplicitClause) {
5359         Diag(DE->getExprLoc(),
5360              diag::note_omp_task_predetermined_firstprivate_here);
5361       }
5362       continue;
5363     }
5364     CurContext->addDecl(VDPrivate);
5365     auto VDPrivateRefExpr = buildDeclRefExpr(
5366         *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
5367     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
5368     Vars.push_back(DE);
5369     PrivateCopies.push_back(VDPrivateRefExpr);
5370     Inits.push_back(VDInitRefExpr);
5371   }
5372 
5373   if (Vars.empty())
5374     return nullptr;
5375 
5376   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5377                                        Vars, PrivateCopies, Inits);
5378 }
5379 
5380 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
5381                                               SourceLocation StartLoc,
5382                                               SourceLocation LParenLoc,
5383                                               SourceLocation EndLoc) {
5384   SmallVector<Expr *, 8> Vars;
5385   SmallVector<Expr *, 8> SrcExprs;
5386   SmallVector<Expr *, 8> DstExprs;
5387   SmallVector<Expr *, 8> AssignmentOps;
5388   for (auto &RefExpr : VarList) {
5389     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
5390     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5391       // It will be analyzed later.
5392       Vars.push_back(RefExpr);
5393       SrcExprs.push_back(nullptr);
5394       DstExprs.push_back(nullptr);
5395       AssignmentOps.push_back(nullptr);
5396       continue;
5397     }
5398 
5399     SourceLocation ELoc = RefExpr->getExprLoc();
5400     // OpenMP [2.1, C/C++]
5401     //  A list item is a variable name.
5402     // OpenMP  [2.14.3.5, Restrictions, p.1]
5403     //  A variable that is part of another variable (as an array or structure
5404     //  element) cannot appear in a lastprivate clause.
5405     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5406     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5407       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5408       continue;
5409     }
5410     Decl *D = DE->getDecl();
5411     VarDecl *VD = cast<VarDecl>(D);
5412 
5413     QualType Type = VD->getType();
5414     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5415       // It will be analyzed later.
5416       Vars.push_back(DE);
5417       SrcExprs.push_back(nullptr);
5418       DstExprs.push_back(nullptr);
5419       AssignmentOps.push_back(nullptr);
5420       continue;
5421     }
5422 
5423     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
5424     //  A variable that appears in a lastprivate clause must not have an
5425     //  incomplete type or a reference type.
5426     if (RequireCompleteType(ELoc, Type,
5427                             diag::err_omp_lastprivate_incomplete_type)) {
5428       continue;
5429     }
5430     if (Type->isReferenceType()) {
5431       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
5432           << getOpenMPClauseName(OMPC_lastprivate) << Type;
5433       bool IsDecl =
5434           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5435       Diag(VD->getLocation(),
5436            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5437           << VD;
5438       continue;
5439     }
5440 
5441     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5442     // in a Construct]
5443     //  Variables with the predetermined data-sharing attributes may not be
5444     //  listed in data-sharing attributes clauses, except for the cases
5445     //  listed below.
5446     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5447     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
5448         DVar.CKind != OMPC_firstprivate &&
5449         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
5450       Diag(ELoc, diag::err_omp_wrong_dsa)
5451           << getOpenMPClauseName(DVar.CKind)
5452           << getOpenMPClauseName(OMPC_lastprivate);
5453       ReportOriginalDSA(*this, DSAStack, VD, DVar);
5454       continue;
5455     }
5456 
5457     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5458     // OpenMP [2.14.3.5, Restrictions, p.2]
5459     // A list item that is private within a parallel region, or that appears in
5460     // the reduction clause of a parallel construct, must not appear in a
5461     // lastprivate clause on a worksharing construct if any of the corresponding
5462     // worksharing regions ever binds to any of the corresponding parallel
5463     // regions.
5464     DSAStackTy::DSAVarData TopDVar = DVar;
5465     if (isOpenMPWorksharingDirective(CurrDir) &&
5466         !isOpenMPParallelDirective(CurrDir)) {
5467       DVar = DSAStack->getImplicitDSA(VD, true);
5468       if (DVar.CKind != OMPC_shared) {
5469         Diag(ELoc, diag::err_omp_required_access)
5470             << getOpenMPClauseName(OMPC_lastprivate)
5471             << getOpenMPClauseName(OMPC_shared);
5472         ReportOriginalDSA(*this, DSAStack, VD, DVar);
5473         continue;
5474       }
5475     }
5476     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
5477     //  A variable of class type (or array thereof) that appears in a
5478     //  lastprivate clause requires an accessible, unambiguous default
5479     //  constructor for the class type, unless the list item is also specified
5480     //  in a firstprivate clause.
5481     //  A variable of class type (or array thereof) that appears in a
5482     //  lastprivate clause requires an accessible, unambiguous copy assignment
5483     //  operator for the class type.
5484     Type = Context.getBaseElementType(Type).getNonReferenceType();
5485     auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
5486                                Type.getUnqualifiedType(), ".lastprivate.src");
5487     auto *PseudoSrcExpr = buildDeclRefExpr(
5488         *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
5489     auto *DstVD =
5490         buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst");
5491     auto *PseudoDstExpr =
5492         buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
5493     // For arrays generate assignment operation for single element and replace
5494     // it by the original array element in CodeGen.
5495     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
5496                                    PseudoDstExpr, PseudoSrcExpr);
5497     if (AssignmentOp.isInvalid())
5498       continue;
5499     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
5500                                        /*DiscardedValue=*/true);
5501     if (AssignmentOp.isInvalid())
5502       continue;
5503 
5504     if (TopDVar.CKind != OMPC_firstprivate)
5505       DSAStack->addDSA(VD, DE, OMPC_lastprivate);
5506     Vars.push_back(DE);
5507     SrcExprs.push_back(PseudoSrcExpr);
5508     DstExprs.push_back(PseudoDstExpr);
5509     AssignmentOps.push_back(AssignmentOp.get());
5510   }
5511 
5512   if (Vars.empty())
5513     return nullptr;
5514 
5515   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
5516                                       Vars, SrcExprs, DstExprs, AssignmentOps);
5517 }
5518 
5519 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
5520                                          SourceLocation StartLoc,
5521                                          SourceLocation LParenLoc,
5522                                          SourceLocation EndLoc) {
5523   SmallVector<Expr *, 8> Vars;
5524   for (auto &RefExpr : VarList) {
5525     assert(RefExpr && "NULL expr in OpenMP shared clause.");
5526     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5527       // It will be analyzed later.
5528       Vars.push_back(RefExpr);
5529       continue;
5530     }
5531 
5532     SourceLocation ELoc = RefExpr->getExprLoc();
5533     // OpenMP [2.1, C/C++]
5534     //  A list item is a variable name.
5535     // OpenMP  [2.14.3.2, Restrictions, p.1]
5536     //  A variable that is part of another variable (as an array or structure
5537     //  element) cannot appear in a shared unless it is a static data member
5538     //  of a C++ class.
5539     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
5540     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5541       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
5542       continue;
5543     }
5544     Decl *D = DE->getDecl();
5545     VarDecl *VD = cast<VarDecl>(D);
5546 
5547     QualType Type = VD->getType();
5548     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
5549       // It will be analyzed later.
5550       Vars.push_back(DE);
5551       continue;
5552     }
5553 
5554     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
5555     // in a Construct]
5556     //  Variables with the predetermined data-sharing attributes may not be
5557     //  listed in data-sharing attributes clauses, except for the cases
5558     //  listed below. For these exceptions only, listing a predetermined
5559     //  variable in a data-sharing attribute clause is allowed and overrides
5560     //  the variable's predetermined data-sharing attributes.
5561     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5562     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
5563         DVar.RefExpr) {
5564       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
5565                                           << getOpenMPClauseName(OMPC_shared);
5566       ReportOriginalDSA(*this, DSAStack, VD, DVar);
5567       continue;
5568     }
5569 
5570     DSAStack->addDSA(VD, DE, OMPC_shared);
5571     Vars.push_back(DE);
5572   }
5573 
5574   if (Vars.empty())
5575     return nullptr;
5576 
5577   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
5578 }
5579 
5580 namespace {
5581 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
5582   DSAStackTy *Stack;
5583 
5584 public:
5585   bool VisitDeclRefExpr(DeclRefExpr *E) {
5586     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
5587       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
5588       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
5589         return false;
5590       if (DVar.CKind != OMPC_unknown)
5591         return true;
5592       DSAStackTy::DSAVarData DVarPrivate =
5593           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
5594       if (DVarPrivate.CKind != OMPC_unknown)
5595         return true;
5596       return false;
5597     }
5598     return false;
5599   }
5600   bool VisitStmt(Stmt *S) {
5601     for (auto Child : S->children()) {
5602       if (Child && Visit(Child))
5603         return true;
5604     }
5605     return false;
5606   }
5607   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
5608 };
5609 } // namespace
5610 
5611 OMPClause *Sema::ActOnOpenMPReductionClause(
5612     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
5613     SourceLocation ColonLoc, SourceLocation EndLoc,
5614     CXXScopeSpec &ReductionIdScopeSpec,
5615     const DeclarationNameInfo &ReductionId) {
5616   // TODO: Allow scope specification search when 'declare reduction' is
5617   // supported.
5618   assert(ReductionIdScopeSpec.isEmpty() &&
5619          "No support for scoped reduction identifiers yet.");
5620 
5621   auto DN = ReductionId.getName();
5622   auto OOK = DN.getCXXOverloadedOperator();
5623   BinaryOperatorKind BOK = BO_Comma;
5624 
5625   // OpenMP [2.14.3.6, reduction clause]
5626   // C
5627   // reduction-identifier is either an identifier or one of the following
5628   // operators: +, -, *,  &, |, ^, && and ||
5629   // C++
5630   // reduction-identifier is either an id-expression or one of the following
5631   // operators: +, -, *, &, |, ^, && and ||
5632   // FIXME: Only 'min' and 'max' identifiers are supported for now.
5633   switch (OOK) {
5634   case OO_Plus:
5635   case OO_Minus:
5636     BOK = BO_Add;
5637     break;
5638   case OO_Star:
5639     BOK = BO_Mul;
5640     break;
5641   case OO_Amp:
5642     BOK = BO_And;
5643     break;
5644   case OO_Pipe:
5645     BOK = BO_Or;
5646     break;
5647   case OO_Caret:
5648     BOK = BO_Xor;
5649     break;
5650   case OO_AmpAmp:
5651     BOK = BO_LAnd;
5652     break;
5653   case OO_PipePipe:
5654     BOK = BO_LOr;
5655     break;
5656   case OO_New:
5657   case OO_Delete:
5658   case OO_Array_New:
5659   case OO_Array_Delete:
5660   case OO_Slash:
5661   case OO_Percent:
5662   case OO_Tilde:
5663   case OO_Exclaim:
5664   case OO_Equal:
5665   case OO_Less:
5666   case OO_Greater:
5667   case OO_LessEqual:
5668   case OO_GreaterEqual:
5669   case OO_PlusEqual:
5670   case OO_MinusEqual:
5671   case OO_StarEqual:
5672   case OO_SlashEqual:
5673   case OO_PercentEqual:
5674   case OO_CaretEqual:
5675   case OO_AmpEqual:
5676   case OO_PipeEqual:
5677   case OO_LessLess:
5678   case OO_GreaterGreater:
5679   case OO_LessLessEqual:
5680   case OO_GreaterGreaterEqual:
5681   case OO_EqualEqual:
5682   case OO_ExclaimEqual:
5683   case OO_PlusPlus:
5684   case OO_MinusMinus:
5685   case OO_Comma:
5686   case OO_ArrowStar:
5687   case OO_Arrow:
5688   case OO_Call:
5689   case OO_Subscript:
5690   case OO_Conditional:
5691   case NUM_OVERLOADED_OPERATORS:
5692     llvm_unreachable("Unexpected reduction identifier");
5693   case OO_None:
5694     if (auto II = DN.getAsIdentifierInfo()) {
5695       if (II->isStr("max"))
5696         BOK = BO_GT;
5697       else if (II->isStr("min"))
5698         BOK = BO_LT;
5699     }
5700     break;
5701   }
5702   SourceRange ReductionIdRange;
5703   if (ReductionIdScopeSpec.isValid()) {
5704     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
5705   }
5706   ReductionIdRange.setEnd(ReductionId.getEndLoc());
5707   if (BOK == BO_Comma) {
5708     // Not allowed reduction identifier is found.
5709     Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
5710         << ReductionIdRange;
5711     return nullptr;
5712   }
5713 
5714   SmallVector<Expr *, 8> Vars;
5715   SmallVector<Expr *, 8> LHSs;
5716   SmallVector<Expr *, 8> RHSs;
5717   SmallVector<Expr *, 8> ReductionOps;
5718   for (auto RefExpr : VarList) {
5719     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
5720     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
5721       // It will be analyzed later.
5722       Vars.push_back(RefExpr);
5723       LHSs.push_back(nullptr);
5724       RHSs.push_back(nullptr);
5725       ReductionOps.push_back(nullptr);
5726       continue;
5727     }
5728 
5729     if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5730         RefExpr->isInstantiationDependent() ||
5731         RefExpr->containsUnexpandedParameterPack()) {
5732       // It will be analyzed later.
5733       Vars.push_back(RefExpr);
5734       LHSs.push_back(nullptr);
5735       RHSs.push_back(nullptr);
5736       ReductionOps.push_back(nullptr);
5737       continue;
5738     }
5739 
5740     auto ELoc = RefExpr->getExprLoc();
5741     auto ERange = RefExpr->getSourceRange();
5742     // OpenMP [2.1, C/C++]
5743     //  A list item is a variable or array section, subject to the restrictions
5744     //  specified in Section 2.4 on page 42 and in each of the sections
5745     // describing clauses and directives for which a list appears.
5746     // OpenMP  [2.14.3.3, Restrictions, p.1]
5747     //  A variable that is part of another variable (as an array or
5748     //  structure element) cannot appear in a private clause.
5749     auto DE = dyn_cast<DeclRefExpr>(RefExpr);
5750     if (!DE || !isa<VarDecl>(DE->getDecl())) {
5751       Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
5752       continue;
5753     }
5754     auto D = DE->getDecl();
5755     auto VD = cast<VarDecl>(D);
5756     auto Type = VD->getType();
5757     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
5758     //  A variable that appears in a private clause must not have an incomplete
5759     //  type or a reference type.
5760     if (RequireCompleteType(ELoc, Type,
5761                             diag::err_omp_reduction_incomplete_type))
5762       continue;
5763     // OpenMP [2.14.3.6, reduction clause, Restrictions]
5764     // Arrays may not appear in a reduction clause.
5765     if (Type.getNonReferenceType()->isArrayType()) {
5766       Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
5767       bool IsDecl =
5768           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5769       Diag(VD->getLocation(),
5770            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5771           << VD;
5772       continue;
5773     }
5774     // OpenMP [2.14.3.6, reduction clause, Restrictions]
5775     // A list item that appears in a reduction clause must not be
5776     // const-qualified.
5777     if (Type.getNonReferenceType().isConstant(Context)) {
5778       Diag(ELoc, diag::err_omp_const_variable)
5779           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
5780       bool IsDecl =
5781           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5782       Diag(VD->getLocation(),
5783            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5784           << VD;
5785       continue;
5786     }
5787     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
5788     //  If a list-item is a reference type then it must bind to the same object
5789     //  for all threads of the team.
5790     VarDecl *VDDef = VD->getDefinition();
5791     if (Type->isReferenceType() && VDDef) {
5792       DSARefChecker Check(DSAStack);
5793       if (Check.Visit(VDDef->getInit())) {
5794         Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
5795         Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
5796         continue;
5797       }
5798     }
5799     // OpenMP [2.14.3.6, reduction clause, Restrictions]
5800     // The type of a list item that appears in a reduction clause must be valid
5801     // for the reduction-identifier. For a max or min reduction in C, the type
5802     // of the list item must be an allowed arithmetic data type: char, int,
5803     // float, double, or _Bool, possibly modified with long, short, signed, or
5804     // unsigned. For a max or min reduction in C++, the type of the list item
5805     // must be an allowed arithmetic data type: char, wchar_t, int, float,
5806     // double, or bool, possibly modified with long, short, signed, or unsigned.
5807     if ((BOK == BO_GT || BOK == BO_LT) &&
5808         !(Type->isScalarType() ||
5809           (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
5810       Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
5811           << getLangOpts().CPlusPlus;
5812       bool IsDecl =
5813           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5814       Diag(VD->getLocation(),
5815            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5816           << VD;
5817       continue;
5818     }
5819     if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
5820         !getLangOpts().CPlusPlus && Type->isFloatingType()) {
5821       Diag(ELoc, diag::err_omp_clause_floating_type_arg);
5822       bool IsDecl =
5823           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5824       Diag(VD->getLocation(),
5825            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5826           << VD;
5827       continue;
5828     }
5829     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5830     // in a Construct]
5831     //  Variables with the predetermined data-sharing attributes may not be
5832     //  listed in data-sharing attributes clauses, except for the cases
5833     //  listed below. For these exceptions only, listing a predetermined
5834     //  variable in a data-sharing attribute clause is allowed and overrides
5835     //  the variable's predetermined data-sharing attributes.
5836     // OpenMP [2.14.3.6, Restrictions, p.3]
5837     //  Any number of reduction clauses can be specified on the directive,
5838     //  but a list item can appear only once in the reduction clauses for that
5839     //  directive.
5840     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
5841     if (DVar.CKind == OMPC_reduction) {
5842       Diag(ELoc, diag::err_omp_once_referenced)
5843           << getOpenMPClauseName(OMPC_reduction);
5844       if (DVar.RefExpr) {
5845         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
5846       }
5847     } else if (DVar.CKind != OMPC_unknown) {
5848       Diag(ELoc, diag::err_omp_wrong_dsa)
5849           << getOpenMPClauseName(DVar.CKind)
5850           << getOpenMPClauseName(OMPC_reduction);
5851       ReportOriginalDSA(*this, DSAStack, VD, DVar);
5852       continue;
5853     }
5854 
5855     // OpenMP [2.14.3.6, Restrictions, p.1]
5856     //  A list item that appears in a reduction clause of a worksharing
5857     //  construct must be shared in the parallel regions to which any of the
5858     //  worksharing regions arising from the worksharing construct bind.
5859     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
5860     if (isOpenMPWorksharingDirective(CurrDir) &&
5861         !isOpenMPParallelDirective(CurrDir)) {
5862       DVar = DSAStack->getImplicitDSA(VD, true);
5863       if (DVar.CKind != OMPC_shared) {
5864         Diag(ELoc, diag::err_omp_required_access)
5865             << getOpenMPClauseName(OMPC_reduction)
5866             << getOpenMPClauseName(OMPC_shared);
5867         ReportOriginalDSA(*this, DSAStack, VD, DVar);
5868         continue;
5869       }
5870     }
5871     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
5872     auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs");
5873     auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName());
5874     // Add initializer for private variable.
5875     Expr *Init = nullptr;
5876     switch (BOK) {
5877     case BO_Add:
5878     case BO_Xor:
5879     case BO_Or:
5880     case BO_LOr:
5881       // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
5882       if (Type->isScalarType() || Type->isAnyComplexType()) {
5883         Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
5884       }
5885       break;
5886     case BO_Mul:
5887     case BO_LAnd:
5888       if (Type->isScalarType() || Type->isAnyComplexType()) {
5889         // '*' and '&&' reduction ops - initializer is '1'.
5890         Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
5891       }
5892       break;
5893     case BO_And: {
5894       // '&' reduction op - initializer is '~0'.
5895       QualType OrigType = Type;
5896       if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
5897         Type = ComplexTy->getElementType();
5898       }
5899       if (Type->isRealFloatingType()) {
5900         llvm::APFloat InitValue =
5901             llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
5902                                            /*isIEEE=*/true);
5903         Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5904                                        Type, ELoc);
5905       } else if (Type->isScalarType()) {
5906         auto Size = Context.getTypeSize(Type);
5907         QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
5908         llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
5909         Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5910       }
5911       if (Init && OrigType->isAnyComplexType()) {
5912         // Init = 0xFFFF + 0xFFFFi;
5913         auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
5914         Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
5915       }
5916       Type = OrigType;
5917       break;
5918     }
5919     case BO_LT:
5920     case BO_GT: {
5921       // 'min' reduction op - initializer is 'Largest representable number in
5922       // the reduction list item type'.
5923       // 'max' reduction op - initializer is 'Least representable number in
5924       // the reduction list item type'.
5925       if (Type->isIntegerType() || Type->isPointerType()) {
5926         bool IsSigned = Type->hasSignedIntegerRepresentation();
5927         auto Size = Context.getTypeSize(Type);
5928         QualType IntTy =
5929             Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
5930         llvm::APInt InitValue =
5931             (BOK != BO_LT)
5932                 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
5933                            : llvm::APInt::getMinValue(Size)
5934                 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
5935                            : llvm::APInt::getMaxValue(Size);
5936         Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
5937         if (Type->isPointerType()) {
5938           // Cast to pointer type.
5939           auto CastExpr = BuildCStyleCastExpr(
5940               SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
5941               SourceLocation(), Init);
5942           if (CastExpr.isInvalid())
5943             continue;
5944           Init = CastExpr.get();
5945         }
5946       } else if (Type->isRealFloatingType()) {
5947         llvm::APFloat InitValue = llvm::APFloat::getLargest(
5948             Context.getFloatTypeSemantics(Type), BOK != BO_LT);
5949         Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
5950                                        Type, ELoc);
5951       }
5952       break;
5953     }
5954     case BO_PtrMemD:
5955     case BO_PtrMemI:
5956     case BO_MulAssign:
5957     case BO_Div:
5958     case BO_Rem:
5959     case BO_Sub:
5960     case BO_Shl:
5961     case BO_Shr:
5962     case BO_LE:
5963     case BO_GE:
5964     case BO_EQ:
5965     case BO_NE:
5966     case BO_AndAssign:
5967     case BO_XorAssign:
5968     case BO_OrAssign:
5969     case BO_Assign:
5970     case BO_AddAssign:
5971     case BO_SubAssign:
5972     case BO_DivAssign:
5973     case BO_RemAssign:
5974     case BO_ShlAssign:
5975     case BO_ShrAssign:
5976     case BO_Comma:
5977       llvm_unreachable("Unexpected reduction operation");
5978     }
5979     if (Init) {
5980       AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
5981                            /*TypeMayContainAuto=*/false);
5982     } else {
5983       ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
5984     }
5985     if (!RHSVD->hasInit()) {
5986       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
5987                                                             << ReductionIdRange;
5988       bool IsDecl =
5989           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
5990       Diag(VD->getLocation(),
5991            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
5992           << VD;
5993       continue;
5994     }
5995     auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
5996     auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
5997     ExprResult ReductionOp =
5998         BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
5999                    LHSDRE, RHSDRE);
6000     if (ReductionOp.isUsable()) {
6001       if (BOK != BO_LT && BOK != BO_GT) {
6002         ReductionOp =
6003             BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6004                        BO_Assign, LHSDRE, ReductionOp.get());
6005       } else {
6006         auto *ConditionalOp = new (Context) ConditionalOperator(
6007             ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
6008             RHSDRE, Type, VK_LValue, OK_Ordinary);
6009         ReductionOp =
6010             BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
6011                        BO_Assign, LHSDRE, ConditionalOp);
6012       }
6013       if (ReductionOp.isUsable()) {
6014         ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
6015       }
6016     }
6017     if (ReductionOp.isInvalid())
6018       continue;
6019 
6020     DSAStack->addDSA(VD, DE, OMPC_reduction);
6021     Vars.push_back(DE);
6022     LHSs.push_back(LHSDRE);
6023     RHSs.push_back(RHSDRE);
6024     ReductionOps.push_back(ReductionOp.get());
6025   }
6026 
6027   if (Vars.empty())
6028     return nullptr;
6029 
6030   return OMPReductionClause::Create(
6031       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
6032       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, LHSs,
6033       RHSs, ReductionOps);
6034 }
6035 
6036 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
6037                                          SourceLocation StartLoc,
6038                                          SourceLocation LParenLoc,
6039                                          SourceLocation ColonLoc,
6040                                          SourceLocation EndLoc) {
6041   SmallVector<Expr *, 8> Vars;
6042   SmallVector<Expr *, 8> Inits;
6043   for (auto &RefExpr : VarList) {
6044     assert(RefExpr && "NULL expr in OpenMP linear clause.");
6045     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6046       // It will be analyzed later.
6047       Vars.push_back(RefExpr);
6048       Inits.push_back(nullptr);
6049       continue;
6050     }
6051 
6052     // OpenMP [2.14.3.7, linear clause]
6053     // A list item that appears in a linear clause is subject to the private
6054     // clause semantics described in Section 2.14.3.3 on page 159 except as
6055     // noted. In addition, the value of the new list item on each iteration
6056     // of the associated loop(s) corresponds to the value of the original
6057     // list item before entering the construct plus the logical number of
6058     // the iteration times linear-step.
6059 
6060     SourceLocation ELoc = RefExpr->getExprLoc();
6061     // OpenMP [2.1, C/C++]
6062     //  A list item is a variable name.
6063     // OpenMP  [2.14.3.3, Restrictions, p.1]
6064     //  A variable that is part of another variable (as an array or
6065     //  structure element) cannot appear in a private clause.
6066     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6067     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6068       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6069       continue;
6070     }
6071 
6072     VarDecl *VD = cast<VarDecl>(DE->getDecl());
6073 
6074     // OpenMP [2.14.3.7, linear clause]
6075     //  A list-item cannot appear in more than one linear clause.
6076     //  A list-item that appears in a linear clause cannot appear in any
6077     //  other data-sharing attribute clause.
6078     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
6079     if (DVar.RefExpr) {
6080       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
6081                                           << getOpenMPClauseName(OMPC_linear);
6082       ReportOriginalDSA(*this, DSAStack, VD, DVar);
6083       continue;
6084     }
6085 
6086     QualType QType = VD->getType();
6087     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
6088       // It will be analyzed later.
6089       Vars.push_back(DE);
6090       Inits.push_back(nullptr);
6091       continue;
6092     }
6093 
6094     // A variable must not have an incomplete type or a reference type.
6095     if (RequireCompleteType(ELoc, QType,
6096                             diag::err_omp_linear_incomplete_type)) {
6097       continue;
6098     }
6099     if (QType->isReferenceType()) {
6100       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
6101           << getOpenMPClauseName(OMPC_linear) << QType;
6102       bool IsDecl =
6103           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6104       Diag(VD->getLocation(),
6105            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6106           << VD;
6107       continue;
6108     }
6109 
6110     // A list item must not be const-qualified.
6111     if (QType.isConstant(Context)) {
6112       Diag(ELoc, diag::err_omp_const_variable)
6113           << getOpenMPClauseName(OMPC_linear);
6114       bool IsDecl =
6115           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6116       Diag(VD->getLocation(),
6117            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6118           << VD;
6119       continue;
6120     }
6121 
6122     // A list item must be of integral or pointer type.
6123     QType = QType.getUnqualifiedType().getCanonicalType();
6124     const Type *Ty = QType.getTypePtrOrNull();
6125     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
6126                 !Ty->isPointerType())) {
6127       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
6128       bool IsDecl =
6129           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6130       Diag(VD->getLocation(),
6131            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6132           << VD;
6133       continue;
6134     }
6135 
6136     // Build var to save initial value.
6137     VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
6138     AddInitializerToDecl(Init, DefaultLvalueConversion(DE).get(),
6139                          /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
6140     auto InitRef = buildDeclRefExpr(
6141         *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
6142     DSAStack->addDSA(VD, DE, OMPC_linear);
6143     Vars.push_back(DE);
6144     Inits.push_back(InitRef);
6145   }
6146 
6147   if (Vars.empty())
6148     return nullptr;
6149 
6150   Expr *StepExpr = Step;
6151   Expr *CalcStepExpr = nullptr;
6152   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
6153       !Step->isInstantiationDependent() &&
6154       !Step->containsUnexpandedParameterPack()) {
6155     SourceLocation StepLoc = Step->getLocStart();
6156     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
6157     if (Val.isInvalid())
6158       return nullptr;
6159     StepExpr = Val.get();
6160 
6161     // Build var to save the step value.
6162     VarDecl *SaveVar =
6163         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
6164     ExprResult SaveRef =
6165         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
6166     ExprResult CalcStep =
6167         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
6168 
6169     // Warn about zero linear step (it would be probably better specified as
6170     // making corresponding variables 'const').
6171     llvm::APSInt Result;
6172     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
6173     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
6174       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
6175                                                      << (Vars.size() > 1);
6176     if (!IsConstant && CalcStep.isUsable()) {
6177       // Calculate the step beforehand instead of doing this on each iteration.
6178       // (This is not used if the number of iterations may be kfold-ed).
6179       CalcStepExpr = CalcStep.get();
6180     }
6181   }
6182 
6183   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
6184                                  Vars, Inits, StepExpr, CalcStepExpr);
6185 }
6186 
6187 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
6188                                      Expr *NumIterations, Sema &SemaRef,
6189                                      Scope *S) {
6190   // Walk the vars and build update/final expressions for the CodeGen.
6191   SmallVector<Expr *, 8> Updates;
6192   SmallVector<Expr *, 8> Finals;
6193   Expr *Step = Clause.getStep();
6194   Expr *CalcStep = Clause.getCalcStep();
6195   // OpenMP [2.14.3.7, linear clause]
6196   // If linear-step is not specified it is assumed to be 1.
6197   if (Step == nullptr)
6198     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6199   else if (CalcStep)
6200     Step = cast<BinaryOperator>(CalcStep)->getLHS();
6201   bool HasErrors = false;
6202   auto CurInit = Clause.inits().begin();
6203   for (auto &RefExpr : Clause.varlists()) {
6204     Expr *InitExpr = *CurInit;
6205 
6206     // Build privatized reference to the current linear var.
6207     auto DE = cast<DeclRefExpr>(RefExpr);
6208     auto PrivateRef =
6209         buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
6210                          DE->getType().getUnqualifiedType(), DE->getExprLoc(),
6211                          /*RefersToCapture=*/true);
6212 
6213     // Build update: Var = InitExpr + IV * Step
6214     ExprResult Update =
6215         BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6216                            InitExpr, IV, Step, /* Subtract */ false);
6217     Update = SemaRef.ActOnFinishFullExpr(Update.get());
6218 
6219     // Build final: Var = InitExpr + NumIterations * Step
6220     ExprResult Final =
6221         BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), PrivateRef,
6222                            InitExpr, NumIterations, Step, /* Subtract */ false);
6223     Final = SemaRef.ActOnFinishFullExpr(Final.get());
6224     if (!Update.isUsable() || !Final.isUsable()) {
6225       Updates.push_back(nullptr);
6226       Finals.push_back(nullptr);
6227       HasErrors = true;
6228     } else {
6229       Updates.push_back(Update.get());
6230       Finals.push_back(Final.get());
6231     }
6232     ++CurInit;
6233   }
6234   Clause.setUpdates(Updates);
6235   Clause.setFinals(Finals);
6236   return HasErrors;
6237 }
6238 
6239 OMPClause *Sema::ActOnOpenMPAlignedClause(
6240     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
6241     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
6242 
6243   SmallVector<Expr *, 8> Vars;
6244   for (auto &RefExpr : VarList) {
6245     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
6246     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6247       // It will be analyzed later.
6248       Vars.push_back(RefExpr);
6249       continue;
6250     }
6251 
6252     SourceLocation ELoc = RefExpr->getExprLoc();
6253     // OpenMP [2.1, C/C++]
6254     //  A list item is a variable name.
6255     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6256     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6257       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6258       continue;
6259     }
6260 
6261     VarDecl *VD = cast<VarDecl>(DE->getDecl());
6262 
6263     // OpenMP  [2.8.1, simd construct, Restrictions]
6264     // The type of list items appearing in the aligned clause must be
6265     // array, pointer, reference to array, or reference to pointer.
6266     QualType QType = VD->getType();
6267     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
6268     const Type *Ty = QType.getTypePtrOrNull();
6269     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
6270                 !Ty->isPointerType())) {
6271       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
6272           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
6273       bool IsDecl =
6274           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6275       Diag(VD->getLocation(),
6276            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6277           << VD;
6278       continue;
6279     }
6280 
6281     // OpenMP  [2.8.1, simd construct, Restrictions]
6282     // A list-item cannot appear in more than one aligned clause.
6283     if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
6284       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
6285       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
6286           << getOpenMPClauseName(OMPC_aligned);
6287       continue;
6288     }
6289 
6290     Vars.push_back(DE);
6291   }
6292 
6293   // OpenMP [2.8.1, simd construct, Description]
6294   // The parameter of the aligned clause, alignment, must be a constant
6295   // positive integer expression.
6296   // If no optional parameter is specified, implementation-defined default
6297   // alignments for SIMD instructions on the target platforms are assumed.
6298   if (Alignment != nullptr) {
6299     ExprResult AlignResult =
6300         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
6301     if (AlignResult.isInvalid())
6302       return nullptr;
6303     Alignment = AlignResult.get();
6304   }
6305   if (Vars.empty())
6306     return nullptr;
6307 
6308   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
6309                                   EndLoc, Vars, Alignment);
6310 }
6311 
6312 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
6313                                          SourceLocation StartLoc,
6314                                          SourceLocation LParenLoc,
6315                                          SourceLocation EndLoc) {
6316   SmallVector<Expr *, 8> Vars;
6317   SmallVector<Expr *, 8> SrcExprs;
6318   SmallVector<Expr *, 8> DstExprs;
6319   SmallVector<Expr *, 8> AssignmentOps;
6320   for (auto &RefExpr : VarList) {
6321     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
6322     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6323       // It will be analyzed later.
6324       Vars.push_back(RefExpr);
6325       SrcExprs.push_back(nullptr);
6326       DstExprs.push_back(nullptr);
6327       AssignmentOps.push_back(nullptr);
6328       continue;
6329     }
6330 
6331     SourceLocation ELoc = RefExpr->getExprLoc();
6332     // OpenMP [2.1, C/C++]
6333     //  A list item is a variable name.
6334     // OpenMP  [2.14.4.1, Restrictions, p.1]
6335     //  A list item that appears in a copyin clause must be threadprivate.
6336     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6337     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6338       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6339       continue;
6340     }
6341 
6342     Decl *D = DE->getDecl();
6343     VarDecl *VD = cast<VarDecl>(D);
6344 
6345     QualType Type = VD->getType();
6346     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6347       // It will be analyzed later.
6348       Vars.push_back(DE);
6349       SrcExprs.push_back(nullptr);
6350       DstExprs.push_back(nullptr);
6351       AssignmentOps.push_back(nullptr);
6352       continue;
6353     }
6354 
6355     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
6356     //  A list item that appears in a copyin clause must be threadprivate.
6357     if (!DSAStack->isThreadPrivate(VD)) {
6358       Diag(ELoc, diag::err_omp_required_access)
6359           << getOpenMPClauseName(OMPC_copyin)
6360           << getOpenMPDirectiveName(OMPD_threadprivate);
6361       continue;
6362     }
6363 
6364     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6365     //  A variable of class type (or array thereof) that appears in a
6366     //  copyin clause requires an accessible, unambiguous copy assignment
6367     //  operator for the class type.
6368     auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
6369     auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
6370                                ElemType.getUnqualifiedType(), ".copyin.src");
6371     auto *PseudoSrcExpr = buildDeclRefExpr(
6372         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
6373     auto *DstVD =
6374         buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst");
6375     auto *PseudoDstExpr =
6376         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
6377     // For arrays generate assignment operation for single element and replace
6378     // it by the original array element in CodeGen.
6379     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6380                                    PseudoDstExpr, PseudoSrcExpr);
6381     if (AssignmentOp.isInvalid())
6382       continue;
6383     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6384                                        /*DiscardedValue=*/true);
6385     if (AssignmentOp.isInvalid())
6386       continue;
6387 
6388     DSAStack->addDSA(VD, DE, OMPC_copyin);
6389     Vars.push_back(DE);
6390     SrcExprs.push_back(PseudoSrcExpr);
6391     DstExprs.push_back(PseudoDstExpr);
6392     AssignmentOps.push_back(AssignmentOp.get());
6393   }
6394 
6395   if (Vars.empty())
6396     return nullptr;
6397 
6398   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
6399                                  SrcExprs, DstExprs, AssignmentOps);
6400 }
6401 
6402 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
6403                                               SourceLocation StartLoc,
6404                                               SourceLocation LParenLoc,
6405                                               SourceLocation EndLoc) {
6406   SmallVector<Expr *, 8> Vars;
6407   SmallVector<Expr *, 8> SrcExprs;
6408   SmallVector<Expr *, 8> DstExprs;
6409   SmallVector<Expr *, 8> AssignmentOps;
6410   for (auto &RefExpr : VarList) {
6411     assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
6412     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6413       // It will be analyzed later.
6414       Vars.push_back(RefExpr);
6415       SrcExprs.push_back(nullptr);
6416       DstExprs.push_back(nullptr);
6417       AssignmentOps.push_back(nullptr);
6418       continue;
6419     }
6420 
6421     SourceLocation ELoc = RefExpr->getExprLoc();
6422     // OpenMP [2.1, C/C++]
6423     //  A list item is a variable name.
6424     // OpenMP  [2.14.4.1, Restrictions, p.1]
6425     //  A list item that appears in a copyin clause must be threadprivate.
6426     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
6427     if (!DE || !isa<VarDecl>(DE->getDecl())) {
6428       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
6429       continue;
6430     }
6431 
6432     Decl *D = DE->getDecl();
6433     VarDecl *VD = cast<VarDecl>(D);
6434 
6435     QualType Type = VD->getType();
6436     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
6437       // It will be analyzed later.
6438       Vars.push_back(DE);
6439       SrcExprs.push_back(nullptr);
6440       DstExprs.push_back(nullptr);
6441       AssignmentOps.push_back(nullptr);
6442       continue;
6443     }
6444 
6445     // OpenMP [2.14.4.2, Restrictions, p.2]
6446     //  A list item that appears in a copyprivate clause may not appear in a
6447     //  private or firstprivate clause on the single construct.
6448     if (!DSAStack->isThreadPrivate(VD)) {
6449       auto DVar = DSAStack->getTopDSA(VD, false);
6450       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
6451           DVar.RefExpr) {
6452         Diag(ELoc, diag::err_omp_wrong_dsa)
6453             << getOpenMPClauseName(DVar.CKind)
6454             << getOpenMPClauseName(OMPC_copyprivate);
6455         ReportOriginalDSA(*this, DSAStack, VD, DVar);
6456         continue;
6457       }
6458 
6459       // OpenMP [2.11.4.2, Restrictions, p.1]
6460       //  All list items that appear in a copyprivate clause must be either
6461       //  threadprivate or private in the enclosing context.
6462       if (DVar.CKind == OMPC_unknown) {
6463         DVar = DSAStack->getImplicitDSA(VD, false);
6464         if (DVar.CKind == OMPC_shared) {
6465           Diag(ELoc, diag::err_omp_required_access)
6466               << getOpenMPClauseName(OMPC_copyprivate)
6467               << "threadprivate or private in the enclosing context";
6468           ReportOriginalDSA(*this, DSAStack, VD, DVar);
6469           continue;
6470         }
6471       }
6472     }
6473 
6474     // Variably modified types are not supported.
6475     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
6476       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
6477           << getOpenMPClauseName(OMPC_copyprivate) << Type
6478           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
6479       bool IsDecl =
6480           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
6481       Diag(VD->getLocation(),
6482            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
6483           << VD;
6484       continue;
6485     }
6486 
6487     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
6488     //  A variable of class type (or array thereof) that appears in a
6489     //  copyin clause requires an accessible, unambiguous copy assignment
6490     //  operator for the class type.
6491     Type = Context.getBaseElementType(Type).getUnqualifiedType();
6492     auto *SrcVD =
6493         buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src");
6494     auto *PseudoSrcExpr =
6495         buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
6496     auto *DstVD =
6497         buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst");
6498     auto *PseudoDstExpr =
6499         buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
6500     auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
6501                                    PseudoDstExpr, PseudoSrcExpr);
6502     if (AssignmentOp.isInvalid())
6503       continue;
6504     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
6505                                        /*DiscardedValue=*/true);
6506     if (AssignmentOp.isInvalid())
6507       continue;
6508 
6509     // No need to mark vars as copyprivate, they are already threadprivate or
6510     // implicitly private.
6511     Vars.push_back(DE);
6512     SrcExprs.push_back(PseudoSrcExpr);
6513     DstExprs.push_back(PseudoDstExpr);
6514     AssignmentOps.push_back(AssignmentOp.get());
6515   }
6516 
6517   if (Vars.empty())
6518     return nullptr;
6519 
6520   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
6521                                       Vars, SrcExprs, DstExprs, AssignmentOps);
6522 }
6523 
6524 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
6525                                         SourceLocation StartLoc,
6526                                         SourceLocation LParenLoc,
6527                                         SourceLocation EndLoc) {
6528   if (VarList.empty())
6529     return nullptr;
6530 
6531   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
6532 }
6533 
6534 OMPClause *
6535 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
6536                               SourceLocation DepLoc, SourceLocation ColonLoc,
6537                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
6538                               SourceLocation LParenLoc, SourceLocation EndLoc) {
6539   if (DepKind == OMPC_DEPEND_unknown) {
6540     std::string Values;
6541     std::string Sep(", ");
6542     for (unsigned i = 0; i < OMPC_DEPEND_unknown; ++i) {
6543       Values += "'";
6544       Values += getOpenMPSimpleClauseTypeName(OMPC_depend, i);
6545       Values += "'";
6546       switch (i) {
6547       case OMPC_DEPEND_unknown - 2:
6548         Values += " or ";
6549         break;
6550       case OMPC_DEPEND_unknown - 1:
6551         break;
6552       default:
6553         Values += Sep;
6554         break;
6555       }
6556     }
6557     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
6558         << Values << getOpenMPClauseName(OMPC_depend);
6559     return nullptr;
6560   }
6561   SmallVector<Expr *, 8> Vars;
6562   for (auto &RefExpr : VarList) {
6563     assert(RefExpr && "NULL expr in OpenMP shared clause.");
6564     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
6565       // It will be analyzed later.
6566       Vars.push_back(RefExpr);
6567       continue;
6568     }
6569 
6570     SourceLocation ELoc = RefExpr->getExprLoc();
6571     // OpenMP  [2.11.1.1, Restrictions, p.3]
6572     //  A variable that is part of another variable (such as a field of a
6573     //  structure) but is not an array element or an array section cannot appear
6574     //  in a depend clause.
6575     auto *SimpleExpr = RefExpr->IgnoreParenCasts();
6576     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
6577     ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
6578     if (!RefExpr->IgnoreParenImpCasts()->isLValue() || (!ASE && !DE) ||
6579         (DE && !isa<VarDecl>(DE->getDecl())) ||
6580         (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
6581          !ASE->getBase()->getType()->isArrayType())) {
6582       Diag(ELoc, diag::err_omp_expected_var_name_or_array_item)
6583           << RefExpr->getSourceRange();
6584       continue;
6585     }
6586 
6587     Vars.push_back(RefExpr->IgnoreParenImpCasts());
6588   }
6589 
6590   if (Vars.empty())
6591     return nullptr;
6592 
6593   return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
6594                                  DepLoc, ColonLoc, Vars);
6595 }
6596 
6597