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