1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// \brief This file implements semantic analysis for OpenMP directives and
11 /// clauses.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclOpenMP.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/OpenMPKinds.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaInternal.h"
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Stack of data-sharing attributes for variables
33 //===----------------------------------------------------------------------===//
34 
35 namespace {
36 /// \brief Default data sharing attributes, which can be applied to directive.
37 enum DefaultDataSharingAttributes {
38   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
39   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
40   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
41 };
42 
43 template <class T> struct MatchesAny {
44   explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
45   bool operator()(T Kind) {
46     for (auto KindEl : Arr)
47       if (KindEl == Kind)
48         return true;
49     return false;
50   }
51 
52 private:
53   ArrayRef<T> Arr;
54 };
55 struct MatchesAlways {
56   MatchesAlways() {}
57   template <class T> bool operator()(T) { return true; }
58 };
59 
60 typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
61 typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
62 
63 /// \brief Stack for tracking declarations used in OpenMP directives and
64 /// clauses and their data-sharing attributes.
65 class DSAStackTy {
66 public:
67   struct DSAVarData {
68     OpenMPDirectiveKind DKind;
69     OpenMPClauseKind CKind;
70     DeclRefExpr *RefExpr;
71     SourceLocation ImplicitDSALoc;
72     DSAVarData()
73         : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
74           ImplicitDSALoc() {}
75   };
76 
77 private:
78   struct DSAInfo {
79     OpenMPClauseKind Attributes;
80     DeclRefExpr *RefExpr;
81   };
82   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
83   typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
84 
85   struct SharingMapTy {
86     DeclSAMapTy SharingMap;
87     AlignedMapTy AlignedMap;
88     DefaultDataSharingAttributes DefaultAttr;
89     SourceLocation DefaultAttrLoc;
90     OpenMPDirectiveKind Directive;
91     DeclarationNameInfo DirectiveName;
92     Scope *CurScope;
93     SourceLocation ConstructLoc;
94     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
95                  Scope *CurScope, SourceLocation Loc)
96         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
97           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
98           ConstructLoc(Loc) {}
99     SharingMapTy()
100         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
101           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
102           ConstructLoc() {}
103   };
104 
105   typedef SmallVector<SharingMapTy, 64> StackTy;
106 
107   /// \brief Stack of used declaration and their data-sharing attributes.
108   StackTy Stack;
109   Sema &SemaRef;
110 
111   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
112 
113   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
114 
115   /// \brief Checks if the variable is a local for OpenMP region.
116   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
117 
118 public:
119   explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
120 
121   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
122             Scope *CurScope, SourceLocation Loc) {
123     Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
124     Stack.back().DefaultAttrLoc = Loc;
125   }
126 
127   void pop() {
128     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
129     Stack.pop_back();
130   }
131 
132   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
133   /// add it and return NULL; otherwise return previous occurrence's expression
134   /// for diagnostics.
135   DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
136 
137   /// \brief Adds explicit data sharing attribute to the specified declaration.
138   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
139 
140   /// \brief Returns data sharing attributes from top of the stack for the
141   /// specified declaration.
142   DSAVarData getTopDSA(VarDecl *D, bool FromParent);
143   /// \brief Returns data-sharing attributes for the specified declaration.
144   DSAVarData getImplicitDSA(VarDecl *D, bool FromParent);
145   /// \brief Checks if the specified variables has data-sharing attributes which
146   /// match specified \a CPred predicate in any directive which matches \a DPred
147   /// predicate.
148   template <class ClausesPredicate, class DirectivesPredicate>
149   DSAVarData hasDSA(VarDecl *D, ClausesPredicate CPred,
150                     DirectivesPredicate DPred, bool FromParent);
151   /// \brief Checks if the specified variables has data-sharing attributes which
152   /// match specified \a CPred predicate in any innermost directive which
153   /// matches \a DPred predicate.
154   template <class ClausesPredicate, class DirectivesPredicate>
155   DSAVarData hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
156                              DirectivesPredicate DPred,
157                              bool FromParent);
158 
159   /// \brief Returns currently analyzed directive.
160   OpenMPDirectiveKind getCurrentDirective() const {
161     return Stack.back().Directive;
162   }
163   /// \brief Returns parent directive.
164   OpenMPDirectiveKind getParentDirective() const {
165     if (Stack.size() > 2)
166       return Stack[Stack.size() - 2].Directive;
167     return OMPD_unknown;
168   }
169 
170   /// \brief Set default data sharing attribute to none.
171   void setDefaultDSANone(SourceLocation Loc) {
172     Stack.back().DefaultAttr = DSA_none;
173     Stack.back().DefaultAttrLoc = Loc;
174   }
175   /// \brief Set default data sharing attribute to shared.
176   void setDefaultDSAShared(SourceLocation Loc) {
177     Stack.back().DefaultAttr = DSA_shared;
178     Stack.back().DefaultAttrLoc = Loc;
179   }
180 
181   DefaultDataSharingAttributes getDefaultDSA() const {
182     return Stack.back().DefaultAttr;
183   }
184   SourceLocation getDefaultDSALocation() const {
185     return Stack.back().DefaultAttrLoc;
186   }
187 
188   /// \brief Checks if the specified variable is a threadprivate.
189   bool isThreadPrivate(VarDecl *D) {
190     DSAVarData DVar = getTopDSA(D, false);
191     return isOpenMPThreadPrivate(DVar.CKind);
192   }
193 
194   Scope *getCurScope() const { return Stack.back().CurScope; }
195   Scope *getCurScope() { return Stack.back().CurScope; }
196   SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
197 };
198 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
199   return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
200          DKind == OMPD_unknown;
201 }
202 } // namespace
203 
204 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
205                                           VarDecl *D) {
206   DSAVarData DVar;
207   if (Iter == std::prev(Stack.rend())) {
208     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
209     // in a region but not in construct]
210     //  File-scope or namespace-scope variables referenced in called routines
211     //  in the region are shared unless they appear in a threadprivate
212     //  directive.
213     if (!D->isFunctionOrMethodVarDecl())
214       DVar.CKind = OMPC_shared;
215 
216     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
217     // in a region but not in construct]
218     //  Variables with static storage duration that are declared in called
219     //  routines in the region are shared.
220     if (D->hasGlobalStorage())
221       DVar.CKind = OMPC_shared;
222 
223     return DVar;
224   }
225 
226   DVar.DKind = Iter->Directive;
227   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
228   // in a Construct, C/C++, predetermined, p.1]
229   // Variables with automatic storage duration that are declared in a scope
230   // inside the construct are private.
231   if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
232       (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
233     DVar.CKind = OMPC_private;
234     return DVar;
235   }
236 
237   // Explicitly specified attributes and local variables with predetermined
238   // attributes.
239   if (Iter->SharingMap.count(D)) {
240     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
241     DVar.CKind = Iter->SharingMap[D].Attributes;
242     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
243     return DVar;
244   }
245 
246   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
247   // in a Construct, C/C++, implicitly determined, p.1]
248   //  In a parallel or task construct, the data-sharing attributes of these
249   //  variables are determined by the default clause, if present.
250   switch (Iter->DefaultAttr) {
251   case DSA_shared:
252     DVar.CKind = OMPC_shared;
253     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
254     return DVar;
255   case DSA_none:
256     return DVar;
257   case DSA_unspecified:
258     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
259     // in a Construct, implicitly determined, p.2]
260     //  In a parallel construct, if no default clause is present, these
261     //  variables are shared.
262     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
263     if (isOpenMPParallelDirective(DVar.DKind)) {
264       DVar.CKind = OMPC_shared;
265       return DVar;
266     }
267 
268     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
269     // in a Construct, implicitly determined, p.4]
270     //  In a task construct, if no default clause is present, a variable that in
271     //  the enclosing context is determined to be shared by all implicit tasks
272     //  bound to the current team is shared.
273     if (DVar.DKind == OMPD_task) {
274       DSAVarData DVarTemp;
275       for (StackTy::reverse_iterator I = std::next(Iter),
276                                      EE = std::prev(Stack.rend());
277            I != EE; ++I) {
278         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
279         // Referenced
280         // in a Construct, implicitly determined, p.6]
281         //  In a task construct, if no default clause is present, a variable
282         //  whose data-sharing attribute is not determined by the rules above is
283         //  firstprivate.
284         DVarTemp = getDSA(I, D);
285         if (DVarTemp.CKind != OMPC_shared) {
286           DVar.RefExpr = nullptr;
287           DVar.DKind = OMPD_task;
288           DVar.CKind = OMPC_firstprivate;
289           return DVar;
290         }
291         if (isParallelOrTaskRegion(I->Directive))
292           break;
293       }
294       DVar.DKind = OMPD_task;
295       DVar.CKind =
296           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
297       return DVar;
298     }
299   }
300   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
301   // in a Construct, implicitly determined, p.3]
302   //  For constructs other than task, if no default clause is present, these
303   //  variables inherit their data-sharing attributes from the enclosing
304   //  context.
305   return getDSA(std::next(Iter), D);
306 }
307 
308 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
309   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
310   auto It = Stack.back().AlignedMap.find(D);
311   if (It == Stack.back().AlignedMap.end()) {
312     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
313     Stack.back().AlignedMap[D] = NewDE;
314     return nullptr;
315   } else {
316     assert(It->second && "Unexpected nullptr expr in the aligned map");
317     return It->second;
318   }
319   return nullptr;
320 }
321 
322 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
323   if (A == OMPC_threadprivate) {
324     Stack[0].SharingMap[D].Attributes = A;
325     Stack[0].SharingMap[D].RefExpr = E;
326   } else {
327     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
328     Stack.back().SharingMap[D].Attributes = A;
329     Stack.back().SharingMap[D].RefExpr = E;
330   }
331 }
332 
333 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
334   if (Stack.size() > 2) {
335     reverse_iterator I = Iter, E = std::prev(Stack.rend());
336     Scope *TopScope = nullptr;
337     while (I != E && !isParallelOrTaskRegion(I->Directive)) {
338       ++I;
339     }
340     if (I == E)
341       return false;
342     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
343     Scope *CurScope = getCurScope();
344     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
345       CurScope = CurScope->getParent();
346     }
347     return CurScope != TopScope;
348   }
349   return false;
350 }
351 
352 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D, bool FromParent) {
353   DSAVarData DVar;
354 
355   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
356   // in a Construct, C/C++, predetermined, p.1]
357   //  Variables appearing in threadprivate directives are threadprivate.
358   if (D->getTLSKind() != VarDecl::TLS_None) {
359     DVar.CKind = OMPC_threadprivate;
360     return DVar;
361   }
362   if (Stack[0].SharingMap.count(D)) {
363     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
364     DVar.CKind = OMPC_threadprivate;
365     return DVar;
366   }
367 
368   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
369   // in a Construct, C/C++, predetermined, p.1]
370   // Variables with automatic storage duration that are declared in a scope
371   // inside the construct are private.
372   OpenMPDirectiveKind Kind =
373       FromParent ? getParentDirective() : getCurrentDirective();
374   auto StartI = std::next(Stack.rbegin());
375   auto EndI = std::prev(Stack.rend());
376   if (FromParent && StartI != EndI) {
377     StartI = std::next(StartI);
378   }
379   if (!isParallelOrTaskRegion(Kind)) {
380     if (isOpenMPLocal(D, StartI) && D->isLocalVarDecl() &&
381         (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
382       DVar.CKind = OMPC_private;
383       return DVar;
384     }
385   }
386 
387   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
388   // in a Construct, C/C++, predetermined, p.4]
389   //  Static data members are shared.
390   if (D->isStaticDataMember()) {
391     // Variables with const-qualified type having no mutable member may be
392     // listed in a firstprivate clause, even if they are static data members.
393     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
394                                  MatchesAlways(), FromParent);
395     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
396       return DVar;
397 
398     DVar.CKind = OMPC_shared;
399     return DVar;
400   }
401 
402   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
403   bool IsConstant = Type.isConstant(SemaRef.getASTContext());
404   while (Type->isArrayType()) {
405     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
406     Type = ElemType.getNonReferenceType().getCanonicalType();
407   }
408   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
409   // in a Construct, C/C++, predetermined, p.6]
410   //  Variables with const qualified type having no mutable member are
411   //  shared.
412   CXXRecordDecl *RD =
413       SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
414   if (IsConstant &&
415       !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
416     // Variables with const-qualified type having no mutable member may be
417     // listed in a firstprivate clause, even if they are static data members.
418     DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
419                                  MatchesAlways(), FromParent);
420     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
421       return DVar;
422 
423     DVar.CKind = OMPC_shared;
424     return DVar;
425   }
426 
427   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
428   // in a Construct, C/C++, predetermined, p.7]
429   //  Variables with static storage duration that are declared in a scope
430   //  inside the construct are shared.
431   if (D->isStaticLocal()) {
432     DVar.CKind = OMPC_shared;
433     return DVar;
434   }
435 
436   // Explicitly specified attributes and local variables with predetermined
437   // attributes.
438   auto I = std::prev(StartI);
439   if (I->SharingMap.count(D)) {
440     DVar.RefExpr = I->SharingMap[D].RefExpr;
441     DVar.CKind = I->SharingMap[D].Attributes;
442     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
443   }
444 
445   return DVar;
446 }
447 
448 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D, bool FromParent) {
449   auto StartI = Stack.rbegin();
450   auto EndI = std::prev(Stack.rend());
451   if (FromParent && StartI != EndI) {
452     StartI = std::next(StartI);
453   }
454   return getDSA(StartI, D);
455 }
456 
457 template <class ClausesPredicate, class DirectivesPredicate>
458 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, ClausesPredicate CPred,
459                                           DirectivesPredicate DPred,
460                                           bool FromParent) {
461   auto StartI = std::next(Stack.rbegin());
462   auto EndI = std::prev(Stack.rend());
463   if (FromParent && StartI != EndI) {
464     StartI = std::next(StartI);
465   }
466   for (auto I = StartI, EE = EndI; I != EE; ++I) {
467     if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
468       continue;
469     DSAVarData DVar = getDSA(I, D);
470     if (CPred(DVar.CKind))
471       return DVar;
472   }
473   return DSAVarData();
474 }
475 
476 template <class ClausesPredicate, class DirectivesPredicate>
477 DSAStackTy::DSAVarData
478 DSAStackTy::hasInnermostDSA(VarDecl *D, ClausesPredicate CPred,
479                             DirectivesPredicate DPred, bool FromParent) {
480   auto StartI = std::next(Stack.rbegin());
481   auto EndI = std::prev(Stack.rend());
482   if (FromParent && StartI != EndI) {
483     StartI = std::next(StartI);
484   }
485   for (auto I = StartI, EE = EndI; I != EE; ++I) {
486     if (!DPred(I->Directive))
487       break;
488     DSAVarData DVar = getDSA(I, D);
489     if (CPred(DVar.CKind))
490       return DVar;
491     return DSAVarData();
492   }
493   return DSAVarData();
494 }
495 
496 void Sema::InitDataSharingAttributesStack() {
497   VarDataSharingAttributesStack = new DSAStackTy(*this);
498 }
499 
500 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
501 
502 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
503 
504 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
505                                const DeclarationNameInfo &DirName,
506                                Scope *CurScope, SourceLocation Loc) {
507   DSAStack->push(DKind, DirName, CurScope, Loc);
508   PushExpressionEvaluationContext(PotentiallyEvaluated);
509 }
510 
511 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
512   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
513   //  A variable of class type (or array thereof) that appears in a lastprivate
514   //  clause requires an accessible, unambiguous default constructor for the
515   //  class type, unless the list item is also specified in a firstprivate
516   //  clause.
517   if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
518     for (auto C : D->clauses()) {
519       if (auto Clause = dyn_cast<OMPLastprivateClause>(C)) {
520         for (auto VarRef : Clause->varlists()) {
521           if (VarRef->isValueDependent() || VarRef->isTypeDependent())
522             continue;
523           auto VD = cast<VarDecl>(cast<DeclRefExpr>(VarRef)->getDecl());
524           auto DVar = DSAStack->getTopDSA(VD, false);
525           if (DVar.CKind == OMPC_lastprivate) {
526             SourceLocation ELoc = VarRef->getExprLoc();
527             auto Type = VarRef->getType();
528             if (Type->isArrayType())
529               Type = QualType(Type->getArrayElementTypeNoTypeQual(), 0);
530             CXXRecordDecl *RD =
531                 getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
532             // FIXME This code must be replaced by actual constructing of the
533             // lastprivate variable.
534             if (RD) {
535               CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
536               PartialDiagnostic PD =
537                   PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
538               if (!CD ||
539                   CheckConstructorAccess(
540                       ELoc, CD, InitializedEntity::InitializeTemporary(Type),
541                       CD->getAccess(), PD) == AR_inaccessible ||
542                   CD->isDeleted()) {
543                 Diag(ELoc, diag::err_omp_required_method)
544                     << getOpenMPClauseName(OMPC_lastprivate) << 0;
545                 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
546                               VarDecl::DeclarationOnly;
547                 Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl
548                                                : diag::note_defined_here)
549                     << VD;
550                 Diag(RD->getLocation(), diag::note_previous_decl) << RD;
551                 continue;
552               }
553               MarkFunctionReferenced(ELoc, CD);
554               DiagnoseUseOfDecl(CD, ELoc);
555             }
556           }
557         }
558       }
559     }
560   }
561 
562   DSAStack->pop();
563   DiscardCleanupsInEvaluationContext();
564   PopExpressionEvaluationContext();
565 }
566 
567 namespace {
568 
569 class VarDeclFilterCCC : public CorrectionCandidateCallback {
570 private:
571   Sema &SemaRef;
572 
573 public:
574   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
575   bool ValidateCandidate(const TypoCorrection &Candidate) override {
576     NamedDecl *ND = Candidate.getCorrectionDecl();
577     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
578       return VD->hasGlobalStorage() &&
579              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
580                                    SemaRef.getCurScope());
581     }
582     return false;
583   }
584 };
585 } // namespace
586 
587 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
588                                          CXXScopeSpec &ScopeSpec,
589                                          const DeclarationNameInfo &Id) {
590   LookupResult Lookup(*this, Id, LookupOrdinaryName);
591   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
592 
593   if (Lookup.isAmbiguous())
594     return ExprError();
595 
596   VarDecl *VD;
597   if (!Lookup.isSingleResult()) {
598     VarDeclFilterCCC Validator(*this);
599     if (TypoCorrection Corrected =
600             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, Validator,
601                         CTK_ErrorRecovery)) {
602       diagnoseTypo(Corrected,
603                    PDiag(Lookup.empty()
604                              ? diag::err_undeclared_var_use_suggest
605                              : diag::err_omp_expected_var_arg_suggest)
606                        << Id.getName());
607       VD = Corrected.getCorrectionDeclAs<VarDecl>();
608     } else {
609       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
610                                        : diag::err_omp_expected_var_arg)
611           << Id.getName();
612       return ExprError();
613     }
614   } else {
615     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
616       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
617       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
618       return ExprError();
619     }
620   }
621   Lookup.suppressDiagnostics();
622 
623   // OpenMP [2.9.2, Syntax, C/C++]
624   //   Variables must be file-scope, namespace-scope, or static block-scope.
625   if (!VD->hasGlobalStorage()) {
626     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
627         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
628     bool IsDecl =
629         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
630     Diag(VD->getLocation(),
631          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
632         << VD;
633     return ExprError();
634   }
635 
636   VarDecl *CanonicalVD = VD->getCanonicalDecl();
637   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
638   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
639   //   A threadprivate directive for file-scope variables must appear outside
640   //   any definition or declaration.
641   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
642       !getCurLexicalContext()->isTranslationUnit()) {
643     Diag(Id.getLoc(), diag::err_omp_var_scope)
644         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
645     bool IsDecl =
646         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
647     Diag(VD->getLocation(),
648          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
649         << VD;
650     return ExprError();
651   }
652   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
653   //   A threadprivate directive for static class member variables must appear
654   //   in the class definition, in the same scope in which the member
655   //   variables are declared.
656   if (CanonicalVD->isStaticDataMember() &&
657       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
658     Diag(Id.getLoc(), diag::err_omp_var_scope)
659         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
660     bool IsDecl =
661         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
662     Diag(VD->getLocation(),
663          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
664         << VD;
665     return ExprError();
666   }
667   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
668   //   A threadprivate directive for namespace-scope variables must appear
669   //   outside any definition or declaration other than the namespace
670   //   definition itself.
671   if (CanonicalVD->getDeclContext()->isNamespace() &&
672       (!getCurLexicalContext()->isFileContext() ||
673        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
674     Diag(Id.getLoc(), diag::err_omp_var_scope)
675         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
676     bool IsDecl =
677         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
678     Diag(VD->getLocation(),
679          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
680         << VD;
681     return ExprError();
682   }
683   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
684   //   A threadprivate directive for static block-scope variables must appear
685   //   in the scope of the variable and not in a nested scope.
686   if (CanonicalVD->isStaticLocal() && CurScope &&
687       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
688     Diag(Id.getLoc(), diag::err_omp_var_scope)
689         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
690     bool IsDecl =
691         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
692     Diag(VD->getLocation(),
693          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
694         << VD;
695     return ExprError();
696   }
697 
698   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
699   //   A threadprivate directive must lexically precede all references to any
700   //   of the variables in its list.
701   if (VD->isUsed()) {
702     Diag(Id.getLoc(), diag::err_omp_var_used)
703         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
704     return ExprError();
705   }
706 
707   QualType ExprType = VD->getType().getNonReferenceType();
708   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
709   return DE;
710 }
711 
712 Sema::DeclGroupPtrTy
713 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
714                                         ArrayRef<Expr *> VarList) {
715   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
716     CurContext->addDecl(D);
717     return DeclGroupPtrTy::make(DeclGroupRef(D));
718   }
719   return DeclGroupPtrTy();
720 }
721 
722 namespace {
723 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
724   Sema &SemaRef;
725 
726 public:
727   bool VisitDeclRefExpr(const DeclRefExpr *E) {
728     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
729       if (VD->hasLocalStorage()) {
730         SemaRef.Diag(E->getLocStart(),
731                      diag::err_omp_local_var_in_threadprivate_init)
732             << E->getSourceRange();
733         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
734             << VD << VD->getSourceRange();
735         return true;
736       }
737     }
738     return false;
739   }
740   bool VisitStmt(const Stmt *S) {
741     for (auto Child : S->children()) {
742       if (Child && Visit(Child))
743         return true;
744     }
745     return false;
746   }
747   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
748 };
749 } // namespace
750 
751 OMPThreadPrivateDecl *
752 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
753   SmallVector<Expr *, 8> Vars;
754   for (auto &RefExpr : VarList) {
755     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
756     VarDecl *VD = cast<VarDecl>(DE->getDecl());
757     SourceLocation ILoc = DE->getExprLoc();
758 
759     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
760     //   A threadprivate variable must not have an incomplete type.
761     if (RequireCompleteType(ILoc, VD->getType(),
762                             diag::err_omp_threadprivate_incomplete_type)) {
763       continue;
764     }
765 
766     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
767     //   A threadprivate variable must not have a reference type.
768     if (VD->getType()->isReferenceType()) {
769       Diag(ILoc, diag::err_omp_ref_type_arg)
770           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
771       bool IsDecl =
772           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
773       Diag(VD->getLocation(),
774            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
775           << VD;
776       continue;
777     }
778 
779     // Check if this is a TLS variable.
780     if (VD->getTLSKind()) {
781       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
782       bool IsDecl =
783           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
784       Diag(VD->getLocation(),
785            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
786           << VD;
787       continue;
788     }
789 
790     // Check if initial value of threadprivate variable reference variable with
791     // local storage (it is not supported by runtime).
792     if (auto Init = VD->getAnyInitializer()) {
793       LocalVarRefChecker Checker(*this);
794       if (Checker.Visit(Init))
795         continue;
796     }
797 
798     Vars.push_back(RefExpr);
799     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
800   }
801   OMPThreadPrivateDecl *D = nullptr;
802   if (!Vars.empty()) {
803     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
804                                      Vars);
805     D->setAccess(AS_public);
806   }
807   return D;
808 }
809 
810 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
811                               const VarDecl *VD, DSAStackTy::DSAVarData DVar,
812                               bool IsLoopIterVar = false) {
813   if (DVar.RefExpr) {
814     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
815         << getOpenMPClauseName(DVar.CKind);
816     return;
817   }
818   enum {
819     PDSA_StaticMemberShared,
820     PDSA_StaticLocalVarShared,
821     PDSA_LoopIterVarPrivate,
822     PDSA_LoopIterVarLinear,
823     PDSA_LoopIterVarLastprivate,
824     PDSA_ConstVarShared,
825     PDSA_GlobalVarShared,
826     PDSA_TaskVarFirstprivate,
827     PDSA_LocalVarPrivate,
828     PDSA_Implicit
829   } Reason = PDSA_Implicit;
830   bool ReportHint = false;
831   auto ReportLoc = VD->getLocation();
832   if (IsLoopIterVar) {
833     if (DVar.CKind == OMPC_private)
834       Reason = PDSA_LoopIterVarPrivate;
835     else if (DVar.CKind == OMPC_lastprivate)
836       Reason = PDSA_LoopIterVarLastprivate;
837     else
838       Reason = PDSA_LoopIterVarLinear;
839   } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
840     Reason = PDSA_TaskVarFirstprivate;
841     ReportLoc = DVar.ImplicitDSALoc;
842   } else if (VD->isStaticLocal())
843     Reason = PDSA_StaticLocalVarShared;
844   else if (VD->isStaticDataMember())
845     Reason = PDSA_StaticMemberShared;
846   else if (VD->isFileVarDecl())
847     Reason = PDSA_GlobalVarShared;
848   else if (VD->getType().isConstant(SemaRef.getASTContext()))
849     Reason = PDSA_ConstVarShared;
850   else if (VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
851     ReportHint = true;
852     Reason = PDSA_LocalVarPrivate;
853   }
854   if (Reason != PDSA_Implicit) {
855     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
856         << Reason << ReportHint
857         << getOpenMPDirectiveName(Stack->getCurrentDirective());
858   } else if (DVar.ImplicitDSALoc.isValid()) {
859     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
860         << getOpenMPClauseName(DVar.CKind);
861   }
862 }
863 
864 namespace {
865 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
866   DSAStackTy *Stack;
867   Sema &SemaRef;
868   bool ErrorFound;
869   CapturedStmt *CS;
870   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
871   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
872 
873 public:
874   void VisitDeclRefExpr(DeclRefExpr *E) {
875     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
876       // Skip internally declared variables.
877       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
878         return;
879 
880       auto DVar = Stack->getTopDSA(VD, false);
881       // Check if the variable has explicit DSA set and stop analysis if it so.
882       if (DVar.RefExpr) return;
883 
884       auto ELoc = E->getExprLoc();
885       auto DKind = Stack->getCurrentDirective();
886       // The default(none) clause requires that each variable that is referenced
887       // in the construct, and does not have a predetermined data-sharing
888       // attribute, must have its data-sharing attribute explicitly determined
889       // by being listed in a data-sharing attribute clause.
890       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
891           isParallelOrTaskRegion(DKind) &&
892           VarsWithInheritedDSA.count(VD) == 0) {
893         VarsWithInheritedDSA[VD] = E;
894         return;
895       }
896 
897       // OpenMP [2.9.3.6, Restrictions, p.2]
898       //  A list item that appears in a reduction clause of the innermost
899       //  enclosing worksharing or parallel construct may not be accessed in an
900       //  explicit task.
901       DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
902                                     [](OpenMPDirectiveKind K) -> bool {
903                                       return isOpenMPParallelDirective(K) ||
904                                              isOpenMPWorksharingDirective(K);
905                                     },
906                                     false);
907       if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
908         ErrorFound = true;
909         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
910         ReportOriginalDSA(SemaRef, Stack, VD, DVar);
911         return;
912       }
913 
914       // Define implicit data-sharing attributes for task.
915       DVar = Stack->getImplicitDSA(VD, false);
916       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
917         ImplicitFirstprivate.push_back(E);
918     }
919   }
920   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
921     for (auto *C : S->clauses()) {
922       // Skip analysis of arguments of implicitly defined firstprivate clause
923       // for task directives.
924       if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
925         for (auto *CC : C->children()) {
926           if (CC)
927             Visit(CC);
928         }
929     }
930   }
931   void VisitStmt(Stmt *S) {
932     for (auto *C : S->children()) {
933       if (C && !isa<OMPExecutableDirective>(C))
934         Visit(C);
935     }
936   }
937 
938   bool isErrorFound() { return ErrorFound; }
939   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
940   llvm::DenseMap<VarDecl *, Expr *> &getVarsWithInheritedDSA() {
941     return VarsWithInheritedDSA;
942   }
943 
944   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
945       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
946 };
947 } // namespace
948 
949 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
950   switch (DKind) {
951   case OMPD_parallel: {
952     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
953     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
954     Sema::CapturedParamNameType Params[] = {
955         std::make_pair(".global_tid.", KmpInt32PtrTy),
956         std::make_pair(".bound_tid.", KmpInt32PtrTy),
957         std::make_pair(StringRef(), QualType()) // __context with shared vars
958     };
959     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
960                              Params);
961     break;
962   }
963   case OMPD_simd: {
964     Sema::CapturedParamNameType Params[] = {
965         std::make_pair(StringRef(), QualType()) // __context with shared vars
966     };
967     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
968                              Params);
969     break;
970   }
971   case OMPD_for: {
972     Sema::CapturedParamNameType Params[] = {
973         std::make_pair(StringRef(), QualType()) // __context with shared vars
974     };
975     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
976                              Params);
977     break;
978   }
979   case OMPD_sections: {
980     Sema::CapturedParamNameType Params[] = {
981         std::make_pair(StringRef(), QualType()) // __context with shared vars
982     };
983     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
984                              Params);
985     break;
986   }
987   case OMPD_section: {
988     Sema::CapturedParamNameType Params[] = {
989         std::make_pair(StringRef(), QualType()) // __context with shared vars
990     };
991     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
992                              Params);
993     break;
994   }
995   case OMPD_single: {
996     Sema::CapturedParamNameType Params[] = {
997         std::make_pair(StringRef(), QualType()) // __context with shared vars
998     };
999     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1000                              Params);
1001     break;
1002   }
1003   case OMPD_master: {
1004     Sema::CapturedParamNameType Params[] = {
1005         std::make_pair(StringRef(), QualType()) // __context with shared vars
1006     };
1007     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1008                              Params);
1009     break;
1010   }
1011   case OMPD_parallel_for: {
1012     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1013     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
1014     Sema::CapturedParamNameType Params[] = {
1015         std::make_pair(".global_tid.", KmpInt32PtrTy),
1016         std::make_pair(".bound_tid.", KmpInt32PtrTy),
1017         std::make_pair(StringRef(), QualType()) // __context with shared vars
1018     };
1019     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1020                              Params);
1021     break;
1022   }
1023   case OMPD_parallel_sections: {
1024     Sema::CapturedParamNameType Params[] = {
1025         std::make_pair(StringRef(), QualType()) // __context with shared vars
1026     };
1027     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1028                              Params);
1029     break;
1030   }
1031   case OMPD_task: {
1032     Sema::CapturedParamNameType Params[] = {
1033         std::make_pair(StringRef(), QualType()) // __context with shared vars
1034     };
1035     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1036                              Params);
1037     break;
1038   }
1039   case OMPD_taskyield: {
1040     Sema::CapturedParamNameType Params[] = {
1041         std::make_pair(StringRef(), QualType()) // __context with shared vars
1042     };
1043     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1044                              Params);
1045     break;
1046   }
1047   case OMPD_barrier: {
1048     Sema::CapturedParamNameType Params[] = {
1049         std::make_pair(StringRef(), QualType()) // __context with shared vars
1050     };
1051     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1052                              Params);
1053     break;
1054   }
1055   case OMPD_taskwait: {
1056     Sema::CapturedParamNameType Params[] = {
1057         std::make_pair(StringRef(), QualType()) // __context with shared vars
1058     };
1059     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1060                              Params);
1061     break;
1062   }
1063   case OMPD_threadprivate:
1064     llvm_unreachable("OpenMP Directive is not allowed");
1065   case OMPD_unknown:
1066     llvm_unreachable("Unknown OpenMP directive");
1067   }
1068 }
1069 
1070 bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1071                            OpenMPDirectiveKind CurrentRegion,
1072                            SourceLocation StartLoc) {
1073   // Allowed nesting of constructs
1074   // +------------------+-----------------+------------------------------------+
1075   // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
1076   // +------------------+-----------------+------------------------------------+
1077   // | parallel         | parallel        | *                                  |
1078   // | parallel         | for             | *                                  |
1079   // | parallel         | master          | *                                  |
1080   // | parallel         | simd            | *                                  |
1081   // | parallel         | sections        | *                                  |
1082   // | parallel         | section         | +                                  |
1083   // | parallel         | single          | *                                  |
1084   // | parallel         | parallel for    | *                                  |
1085   // | parallel         |parallel sections| *                                  |
1086   // | parallel         | task            | *                                  |
1087   // | parallel         | taskyield       | *                                  |
1088   // | parallel         | barrier         | *                                  |
1089   // | parallel         | taskwait        | *                                  |
1090   // +------------------+-----------------+------------------------------------+
1091   // | for              | parallel        | *                                  |
1092   // | for              | for             | +                                  |
1093   // | for              | master          | +                                  |
1094   // | for              | simd            | *                                  |
1095   // | for              | sections        | +                                  |
1096   // | for              | section         | +                                  |
1097   // | for              | single          | +                                  |
1098   // | for              | parallel for    | *                                  |
1099   // | for              |parallel sections| *                                  |
1100   // | for              | task            | *                                  |
1101   // | for              | taskyield       | *                                  |
1102   // | for              | barrier         | +                                  |
1103   // | for              | taskwait        | *                                  |
1104   // +------------------+-----------------+------------------------------------+
1105   // | master           | parallel        | *                                  |
1106   // | master           | for             | +                                  |
1107   // | master           | master          | *                                  |
1108   // | master           | simd            | *                                  |
1109   // | master           | sections        | +                                  |
1110   // | master           | section         | +                                  |
1111   // | master           | single          | +                                  |
1112   // | master           | parallel for    | *                                  |
1113   // | master           |parallel sections| *                                  |
1114   // | master           | task            | *                                  |
1115   // | master           | taskyield       | *                                  |
1116   // | master           | barrier         | +                                  |
1117   // | master           | taskwait        | *                                  |
1118   // +------------------+-----------------+------------------------------------+
1119   // | simd             | parallel        |                                    |
1120   // | simd             | for             |                                    |
1121   // | simd             | master          |                                    |
1122   // | simd             | simd            |                                    |
1123   // | simd             | sections        |                                    |
1124   // | simd             | section         |                                    |
1125   // | simd             | single          |                                    |
1126   // | simd             | parallel for    |                                    |
1127   // | simd             |parallel sections|                                    |
1128   // | simd             | task            |                                    |
1129   // | simd             | taskyield       |                                    |
1130   // | simd             | barrier         |                                    |
1131   // | simd             | taskwait        |                                    |
1132   // +------------------+-----------------+------------------------------------+
1133   // | sections         | parallel        | *                                  |
1134   // | sections         | for             | +                                  |
1135   // | sections         | master          | +                                  |
1136   // | sections         | simd            | *                                  |
1137   // | sections         | sections        | +                                  |
1138   // | sections         | section         | *                                  |
1139   // | sections         | single          | +                                  |
1140   // | sections         | parallel for    | *                                  |
1141   // | sections         |parallel sections| *                                  |
1142   // | sections         | task            | *                                  |
1143   // | sections         | taskyield       | *                                  |
1144   // | sections         | barrier         | +                                  |
1145   // | sections         | taskwait        | *                                  |
1146   // +------------------+-----------------+------------------------------------+
1147   // | section          | parallel        | *                                  |
1148   // | section          | for             | +                                  |
1149   // | section          | master          | +                                  |
1150   // | section          | simd            | *                                  |
1151   // | section          | sections        | +                                  |
1152   // | section          | section         | +                                  |
1153   // | section          | single          | +                                  |
1154   // | section          | parallel for    | *                                  |
1155   // | section          |parallel sections| *                                  |
1156   // | section          | task            | *                                  |
1157   // | section          | taskyield       | *                                  |
1158   // | section          | barrier         | +                                  |
1159   // | section          | taskwait        | *                                  |
1160   // +------------------+-----------------+------------------------------------+
1161   // | single           | parallel        | *                                  |
1162   // | single           | for             | +                                  |
1163   // | single           | master          | +                                  |
1164   // | single           | simd            | *                                  |
1165   // | single           | sections        | +                                  |
1166   // | single           | section         | +                                  |
1167   // | single           | single          | +                                  |
1168   // | single           | parallel for    | *                                  |
1169   // | single           |parallel sections| *                                  |
1170   // | single           | task            | *                                  |
1171   // | single           | taskyield       | *                                  |
1172   // | single           | barrier         | +                                  |
1173   // | single           | taskwait        | *                                  |
1174   // +------------------+-----------------+------------------------------------+
1175   // | parallel for     | parallel        | *                                  |
1176   // | parallel for     | for             | +                                  |
1177   // | parallel for     | master          | +                                  |
1178   // | parallel for     | simd            | *                                  |
1179   // | parallel for     | sections        | +                                  |
1180   // | parallel for     | section         | +                                  |
1181   // | parallel for     | single          | +                                  |
1182   // | parallel for     | parallel for    | *                                  |
1183   // | parallel for     |parallel sections| *                                  |
1184   // | parallel for     | task            | *                                  |
1185   // | parallel for     | taskyield       | *                                  |
1186   // | parallel for     | barrier         | +                                  |
1187   // | parallel for     | taskwait        | *                                  |
1188   // +------------------+-----------------+------------------------------------+
1189   // | parallel sections| parallel        | *                                  |
1190   // | parallel sections| for             | +                                  |
1191   // | parallel sections| master          | +                                  |
1192   // | parallel sections| simd            | *                                  |
1193   // | parallel sections| sections        | +                                  |
1194   // | parallel sections| section         | *                                  |
1195   // | parallel sections| single          | +                                  |
1196   // | parallel sections| parallel for    | *                                  |
1197   // | parallel sections|parallel sections| *                                  |
1198   // | parallel sections| task            | *                                  |
1199   // | parallel sections| taskyield       | *                                  |
1200   // | parallel sections| barrier         | +                                  |
1201   // | parallel sections| taskwait        | *                                  |
1202   // +------------------+-----------------+------------------------------------+
1203   // | task             | parallel        | *                                  |
1204   // | task             | for             | +                                  |
1205   // | task             | master          | +                                  |
1206   // | task             | simd            | *                                  |
1207   // | task             | sections        | +                                  |
1208   // | task             | section         | +                                  |
1209   // | task             | single          | +                                  |
1210   // | task             | parallel for    | *                                  |
1211   // | task             |parallel sections| *                                  |
1212   // | task             | task            | *                                  |
1213   // | task             | taskyield       | *                                  |
1214   // | task             | barrier         | +                                  |
1215   // | task             | taskwait        | *                                  |
1216   // +------------------+-----------------+------------------------------------+
1217   if (Stack->getCurScope()) {
1218     auto ParentRegion = Stack->getParentDirective();
1219     bool NestingProhibited = false;
1220     bool CloseNesting = true;
1221     bool ShouldBeInParallelRegion = false;
1222     if (isOpenMPSimdDirective(ParentRegion)) {
1223       // OpenMP [2.16, Nesting of Regions]
1224       // OpenMP constructs may not be nested inside a simd region.
1225       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
1226       return true;
1227     }
1228     if (CurrentRegion == OMPD_section) {
1229       // OpenMP [2.7.2, sections Construct, Restrictions]
1230       // Orphaned section directives are prohibited. That is, the section
1231       // directives must appear within the sections construct and must not be
1232       // encountered elsewhere in the sections region.
1233       if (ParentRegion != OMPD_sections &&
1234           ParentRegion != OMPD_parallel_sections) {
1235         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
1236             << (ParentRegion != OMPD_unknown)
1237             << getOpenMPDirectiveName(ParentRegion);
1238         return true;
1239       }
1240       return false;
1241     }
1242     if (CurrentRegion == OMPD_master) {
1243       // OpenMP [2.16, Nesting of Regions]
1244       // A master region may not be closely nested inside a worksharing,
1245       // atomic (TODO), or explicit task region.
1246       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1247                           ParentRegion == OMPD_task;
1248     } else if (CurrentRegion == OMPD_barrier) {
1249       // OpenMP [2.16, Nesting of Regions]
1250       // A barrier region may not be closely nested inside a worksharing,
1251       // explicit task, critical(TODO), ordered(TODO), atomic(TODO), or master
1252       // region.
1253       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
1254                           ParentRegion == OMPD_task ||
1255                           ParentRegion == OMPD_master;
1256     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
1257                !isOpenMPParallelDirective(CurrentRegion) &&
1258                !isOpenMPSimdDirective(CurrentRegion)) {
1259       // OpenMP [2.16, Nesting of Regions]
1260       // A worksharing region may not be closely nested inside a worksharing,
1261       // explicit task, critical, ordered, atomic, or master region.
1262       // TODO
1263       NestingProhibited = (isOpenMPWorksharingDirective(ParentRegion) &&
1264                            !isOpenMPSimdDirective(ParentRegion)) ||
1265                           ParentRegion == OMPD_task ||
1266                           ParentRegion == OMPD_master;
1267       ShouldBeInParallelRegion = true;
1268     }
1269     if (NestingProhibited) {
1270       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
1271           << CloseNesting << getOpenMPDirectiveName(ParentRegion)
1272           << ShouldBeInParallelRegion << getOpenMPDirectiveName(CurrentRegion);
1273       return true;
1274     }
1275   }
1276   return false;
1277 }
1278 
1279 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
1280                                                 ArrayRef<OMPClause *> Clauses,
1281                                                 Stmt *AStmt,
1282                                                 SourceLocation StartLoc,
1283                                                 SourceLocation EndLoc) {
1284   StmtResult Res = StmtError();
1285   if (CheckNestingOfRegions(*this, DSAStack, Kind, StartLoc))
1286     return StmtError();
1287 
1288   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
1289   llvm::DenseMap<VarDecl *, Expr *> VarsWithInheritedDSA;
1290   bool ErrorFound = false;
1291   if (AStmt) {
1292     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
1293 
1294     // Check default data sharing attributes for referenced variables.
1295     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
1296     DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
1297     if (DSAChecker.isErrorFound())
1298       return StmtError();
1299     // Generate list of implicitly defined firstprivate variables.
1300     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
1301     ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
1302 
1303     if (!DSAChecker.getImplicitFirstprivate().empty()) {
1304       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
1305               DSAChecker.getImplicitFirstprivate(), SourceLocation(),
1306               SourceLocation(), SourceLocation())) {
1307         ClausesWithImplicit.push_back(Implicit);
1308         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
1309                      DSAChecker.getImplicitFirstprivate().size();
1310       } else
1311         ErrorFound = true;
1312     }
1313   }
1314 
1315   switch (Kind) {
1316   case OMPD_parallel:
1317     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
1318                                        EndLoc);
1319     break;
1320   case OMPD_simd:
1321     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1322                                    VarsWithInheritedDSA);
1323     break;
1324   case OMPD_for:
1325     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
1326                                   VarsWithInheritedDSA);
1327     break;
1328   case OMPD_sections:
1329     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
1330                                        EndLoc);
1331     break;
1332   case OMPD_section:
1333     assert(ClausesWithImplicit.empty() &&
1334            "No clauses are allowed for 'omp section' directive");
1335     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
1336     break;
1337   case OMPD_single:
1338     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
1339                                      EndLoc);
1340     break;
1341   case OMPD_master:
1342     assert(ClausesWithImplicit.empty() &&
1343            "No clauses are allowed for 'omp master' directive");
1344     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
1345     break;
1346   case OMPD_parallel_for:
1347     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
1348                                           EndLoc, VarsWithInheritedDSA);
1349     break;
1350   case OMPD_parallel_sections:
1351     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
1352                                                StartLoc, EndLoc);
1353     break;
1354   case OMPD_task:
1355     Res =
1356         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
1357     break;
1358   case OMPD_taskyield:
1359     assert(ClausesWithImplicit.empty() &&
1360            "No clauses are allowed for 'omp taskyield' directive");
1361     assert(AStmt == nullptr &&
1362            "No associated statement allowed for 'omp taskyield' directive");
1363     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
1364     break;
1365   case OMPD_barrier:
1366     assert(ClausesWithImplicit.empty() &&
1367            "No clauses are allowed for 'omp barrier' directive");
1368     assert(AStmt == nullptr &&
1369            "No associated statement allowed for 'omp barrier' directive");
1370     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
1371     break;
1372   case OMPD_taskwait:
1373     assert(ClausesWithImplicit.empty() &&
1374            "No clauses are allowed for 'omp taskwait' directive");
1375     assert(AStmt == nullptr &&
1376            "No associated statement allowed for 'omp taskwait' directive");
1377     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
1378     break;
1379   case OMPD_threadprivate:
1380     llvm_unreachable("OpenMP Directive is not allowed");
1381   case OMPD_unknown:
1382     llvm_unreachable("Unknown OpenMP directive");
1383   }
1384 
1385   for (auto P : VarsWithInheritedDSA) {
1386     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
1387         << P.first << P.second->getSourceRange();
1388   }
1389   if (!VarsWithInheritedDSA.empty())
1390     return StmtError();
1391 
1392   if (ErrorFound)
1393     return StmtError();
1394   return Res;
1395 }
1396 
1397 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
1398                                               Stmt *AStmt,
1399                                               SourceLocation StartLoc,
1400                                               SourceLocation EndLoc) {
1401   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1402   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
1403   // 1.2.2 OpenMP Language Terminology
1404   // Structured block - An executable statement with a single entry at the
1405   // top and a single exit at the bottom.
1406   // The point of exit cannot be a branch out of the structured block.
1407   // longjmp() and throw() must not violate the entry/exit criteria.
1408   CS->getCapturedDecl()->setNothrow();
1409 
1410   getCurFunction()->setHasBranchProtectedScope();
1411 
1412   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
1413                                       AStmt);
1414 }
1415 
1416 namespace {
1417 /// \brief Helper class for checking canonical form of the OpenMP loops and
1418 /// extracting iteration space of each loop in the loop nest, that will be used
1419 /// for IR generation.
1420 class OpenMPIterationSpaceChecker {
1421   /// \brief Reference to Sema.
1422   Sema &SemaRef;
1423   /// \brief A location for diagnostics (when there is no some better location).
1424   SourceLocation DefaultLoc;
1425   /// \brief A location for diagnostics (when increment is not compatible).
1426   SourceLocation ConditionLoc;
1427   /// \brief A source location for referring to condition later.
1428   SourceRange ConditionSrcRange;
1429   /// \brief Loop variable.
1430   VarDecl *Var;
1431   /// \brief Lower bound (initializer for the var).
1432   Expr *LB;
1433   /// \brief Upper bound.
1434   Expr *UB;
1435   /// \brief Loop step (increment).
1436   Expr *Step;
1437   /// \brief This flag is true when condition is one of:
1438   ///   Var <  UB
1439   ///   Var <= UB
1440   ///   UB  >  Var
1441   ///   UB  >= Var
1442   bool TestIsLessOp;
1443   /// \brief This flag is true when condition is strict ( < or > ).
1444   bool TestIsStrictOp;
1445   /// \brief This flag is true when step is subtracted on each iteration.
1446   bool SubtractStep;
1447 
1448 public:
1449   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
1450       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
1451         ConditionSrcRange(SourceRange()), Var(nullptr), LB(nullptr),
1452         UB(nullptr), Step(nullptr), TestIsLessOp(false), TestIsStrictOp(false),
1453         SubtractStep(false) {}
1454   /// \brief Check init-expr for canonical loop form and save loop counter
1455   /// variable - #Var and its initialization value - #LB.
1456   bool CheckInit(Stmt *S);
1457   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
1458   /// for less/greater and for strict/non-strict comparison.
1459   bool CheckCond(Expr *S);
1460   /// \brief Check incr-expr for canonical loop form and return true if it
1461   /// does not conform, otherwise save loop step (#Step).
1462   bool CheckInc(Expr *S);
1463   /// \brief Return the loop counter variable.
1464   VarDecl *GetLoopVar() const { return Var; }
1465   /// \brief Return true if any expression is dependent.
1466   bool Dependent() const;
1467 
1468 private:
1469   /// \brief Check the right-hand side of an assignment in the increment
1470   /// expression.
1471   bool CheckIncRHS(Expr *RHS);
1472   /// \brief Helper to set loop counter variable and its initializer.
1473   bool SetVarAndLB(VarDecl *NewVar, Expr *NewLB);
1474   /// \brief Helper to set upper bound.
1475   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
1476              const SourceLocation &SL);
1477   /// \brief Helper to set loop increment.
1478   bool SetStep(Expr *NewStep, bool Subtract);
1479 };
1480 
1481 bool OpenMPIterationSpaceChecker::Dependent() const {
1482   if (!Var) {
1483     assert(!LB && !UB && !Step);
1484     return false;
1485   }
1486   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
1487          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
1488 }
1489 
1490 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar, Expr *NewLB) {
1491   // State consistency checking to ensure correct usage.
1492   assert(Var == nullptr && LB == nullptr && UB == nullptr && Step == nullptr &&
1493          !TestIsLessOp && !TestIsStrictOp);
1494   if (!NewVar || !NewLB)
1495     return true;
1496   Var = NewVar;
1497   LB = NewLB;
1498   return false;
1499 }
1500 
1501 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
1502                                         const SourceRange &SR,
1503                                         const SourceLocation &SL) {
1504   // State consistency checking to ensure correct usage.
1505   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
1506          !TestIsLessOp && !TestIsStrictOp);
1507   if (!NewUB)
1508     return true;
1509   UB = NewUB;
1510   TestIsLessOp = LessOp;
1511   TestIsStrictOp = StrictOp;
1512   ConditionSrcRange = SR;
1513   ConditionLoc = SL;
1514   return false;
1515 }
1516 
1517 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
1518   // State consistency checking to ensure correct usage.
1519   assert(Var != nullptr && LB != nullptr && Step == nullptr);
1520   if (!NewStep)
1521     return true;
1522   if (!NewStep->isValueDependent()) {
1523     // Check that the step is integer expression.
1524     SourceLocation StepLoc = NewStep->getLocStart();
1525     ExprResult Val =
1526         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
1527     if (Val.isInvalid())
1528       return true;
1529     NewStep = Val.get();
1530 
1531     // OpenMP [2.6, Canonical Loop Form, Restrictions]
1532     //  If test-expr is of form var relational-op b and relational-op is < or
1533     //  <= then incr-expr must cause var to increase on each iteration of the
1534     //  loop. If test-expr is of form var relational-op b and relational-op is
1535     //  > or >= then incr-expr must cause var to decrease on each iteration of
1536     //  the loop.
1537     //  If test-expr is of form b relational-op var and relational-op is < or
1538     //  <= then incr-expr must cause var to decrease on each iteration of the
1539     //  loop. If test-expr is of form b relational-op var and relational-op is
1540     //  > or >= then incr-expr must cause var to increase on each iteration of
1541     //  the loop.
1542     llvm::APSInt Result;
1543     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
1544     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
1545     bool IsConstNeg =
1546         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
1547     bool IsConstZero = IsConstant && !Result.getBoolValue();
1548     if (UB && (IsConstZero ||
1549                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
1550                              : (!IsConstNeg || (IsUnsigned && !Subtract))))) {
1551       SemaRef.Diag(NewStep->getExprLoc(),
1552                    diag::err_omp_loop_incr_not_compatible)
1553           << Var << TestIsLessOp << NewStep->getSourceRange();
1554       SemaRef.Diag(ConditionLoc,
1555                    diag::note_omp_loop_cond_requres_compatible_incr)
1556           << TestIsLessOp << ConditionSrcRange;
1557       return true;
1558     }
1559   }
1560 
1561   Step = NewStep;
1562   SubtractStep = Subtract;
1563   return false;
1564 }
1565 
1566 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
1567   // Check init-expr for canonical loop form and save loop counter
1568   // variable - #Var and its initialization value - #LB.
1569   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
1570   //   var = lb
1571   //   integer-type var = lb
1572   //   random-access-iterator-type var = lb
1573   //   pointer-type var = lb
1574   //
1575   if (!S) {
1576     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
1577     return true;
1578   }
1579   if (Expr *E = dyn_cast<Expr>(S))
1580     S = E->IgnoreParens();
1581   if (auto BO = dyn_cast<BinaryOperator>(S)) {
1582     if (BO->getOpcode() == BO_Assign)
1583       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
1584         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), BO->getLHS());
1585   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
1586     if (DS->isSingleDecl()) {
1587       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
1588         if (Var->hasInit()) {
1589           // Accept non-canonical init form here but emit ext. warning.
1590           if (Var->getInitStyle() != VarDecl::CInit)
1591             SemaRef.Diag(S->getLocStart(),
1592                          diag::ext_omp_loop_not_canonical_init)
1593                 << S->getSourceRange();
1594           return SetVarAndLB(Var, Var->getInit());
1595         }
1596       }
1597     }
1598   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
1599     if (CE->getOperator() == OO_Equal)
1600       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
1601         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), CE->getArg(1));
1602 
1603   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
1604       << S->getSourceRange();
1605   return true;
1606 }
1607 
1608 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
1609 /// variable (which may be the loop variable) if possible.
1610 static const VarDecl *GetInitVarDecl(const Expr *E) {
1611   if (!E)
1612     return nullptr;
1613   E = E->IgnoreParenImpCasts();
1614   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
1615     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
1616       if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
1617           CE->getArg(0) != nullptr)
1618         E = CE->getArg(0)->IgnoreParenImpCasts();
1619   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
1620   if (!DRE)
1621     return nullptr;
1622   return dyn_cast<VarDecl>(DRE->getDecl());
1623 }
1624 
1625 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
1626   // Check test-expr for canonical form, save upper-bound UB, flags for
1627   // less/greater and for strict/non-strict comparison.
1628   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1629   //   var relational-op b
1630   //   b relational-op var
1631   //
1632   if (!S) {
1633     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
1634     return true;
1635   }
1636   S = S->IgnoreParenImpCasts();
1637   SourceLocation CondLoc = S->getLocStart();
1638   if (auto BO = dyn_cast<BinaryOperator>(S)) {
1639     if (BO->isRelationalOp()) {
1640       if (GetInitVarDecl(BO->getLHS()) == Var)
1641         return SetUB(BO->getRHS(),
1642                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
1643                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1644                      BO->getSourceRange(), BO->getOperatorLoc());
1645       if (GetInitVarDecl(BO->getRHS()) == Var)
1646         return SetUB(BO->getLHS(),
1647                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
1648                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1649                      BO->getSourceRange(), BO->getOperatorLoc());
1650     }
1651   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1652     if (CE->getNumArgs() == 2) {
1653       auto Op = CE->getOperator();
1654       switch (Op) {
1655       case OO_Greater:
1656       case OO_GreaterEqual:
1657       case OO_Less:
1658       case OO_LessEqual:
1659         if (GetInitVarDecl(CE->getArg(0)) == Var)
1660           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
1661                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1662                        CE->getOperatorLoc());
1663         if (GetInitVarDecl(CE->getArg(1)) == Var)
1664           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
1665                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1666                        CE->getOperatorLoc());
1667         break;
1668       default:
1669         break;
1670       }
1671     }
1672   }
1673   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
1674       << S->getSourceRange() << Var;
1675   return true;
1676 }
1677 
1678 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
1679   // RHS of canonical loop form increment can be:
1680   //   var + incr
1681   //   incr + var
1682   //   var - incr
1683   //
1684   RHS = RHS->IgnoreParenImpCasts();
1685   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
1686     if (BO->isAdditiveOp()) {
1687       bool IsAdd = BO->getOpcode() == BO_Add;
1688       if (GetInitVarDecl(BO->getLHS()) == Var)
1689         return SetStep(BO->getRHS(), !IsAdd);
1690       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
1691         return SetStep(BO->getLHS(), false);
1692     }
1693   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
1694     bool IsAdd = CE->getOperator() == OO_Plus;
1695     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
1696       if (GetInitVarDecl(CE->getArg(0)) == Var)
1697         return SetStep(CE->getArg(1), !IsAdd);
1698       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
1699         return SetStep(CE->getArg(0), false);
1700     }
1701   }
1702   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1703       << RHS->getSourceRange() << Var;
1704   return true;
1705 }
1706 
1707 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
1708   // Check incr-expr for canonical loop form and return true if it
1709   // does not conform.
1710   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1711   //   ++var
1712   //   var++
1713   //   --var
1714   //   var--
1715   //   var += incr
1716   //   var -= incr
1717   //   var = var + incr
1718   //   var = incr + var
1719   //   var = var - incr
1720   //
1721   if (!S) {
1722     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
1723     return true;
1724   }
1725   S = S->IgnoreParens();
1726   if (auto UO = dyn_cast<UnaryOperator>(S)) {
1727     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
1728       return SetStep(
1729           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
1730                                        (UO->isDecrementOp() ? -1 : 1)).get(),
1731           false);
1732   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
1733     switch (BO->getOpcode()) {
1734     case BO_AddAssign:
1735     case BO_SubAssign:
1736       if (GetInitVarDecl(BO->getLHS()) == Var)
1737         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
1738       break;
1739     case BO_Assign:
1740       if (GetInitVarDecl(BO->getLHS()) == Var)
1741         return CheckIncRHS(BO->getRHS());
1742       break;
1743     default:
1744       break;
1745     }
1746   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1747     switch (CE->getOperator()) {
1748     case OO_PlusPlus:
1749     case OO_MinusMinus:
1750       if (GetInitVarDecl(CE->getArg(0)) == Var)
1751         return SetStep(
1752             SemaRef.ActOnIntegerConstant(
1753                         CE->getLocStart(),
1754                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
1755             false);
1756       break;
1757     case OO_PlusEqual:
1758     case OO_MinusEqual:
1759       if (GetInitVarDecl(CE->getArg(0)) == Var)
1760         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
1761       break;
1762     case OO_Equal:
1763       if (GetInitVarDecl(CE->getArg(0)) == Var)
1764         return CheckIncRHS(CE->getArg(1));
1765       break;
1766     default:
1767       break;
1768     }
1769   }
1770   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1771       << S->getSourceRange() << Var;
1772   return true;
1773 }
1774 } // namespace
1775 
1776 /// \brief Called on a for stmt to check and extract its iteration space
1777 /// for further processing (such as collapsing).
1778 static bool CheckOpenMPIterationSpace(
1779     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
1780     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
1781     Expr *NestedLoopCountExpr,
1782     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
1783   // OpenMP [2.6, Canonical Loop Form]
1784   //   for (init-expr; test-expr; incr-expr) structured-block
1785   auto For = dyn_cast_or_null<ForStmt>(S);
1786   if (!For) {
1787     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
1788         << (NestedLoopCountExpr != nullptr) << getOpenMPDirectiveName(DKind)
1789         << NestedLoopCount << (CurrentNestedLoopCount > 0)
1790         << CurrentNestedLoopCount;
1791     if (NestedLoopCount > 1)
1792       SemaRef.Diag(NestedLoopCountExpr->getExprLoc(),
1793                    diag::note_omp_collapse_expr)
1794           << NestedLoopCountExpr->getSourceRange();
1795     return true;
1796   }
1797   assert(For->getBody());
1798 
1799   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
1800 
1801   // Check init.
1802   auto Init = For->getInit();
1803   if (ISC.CheckInit(Init)) {
1804     return true;
1805   }
1806 
1807   bool HasErrors = false;
1808 
1809   // Check loop variable's type.
1810   auto Var = ISC.GetLoopVar();
1811 
1812   // OpenMP [2.6, Canonical Loop Form]
1813   // Var is one of the following:
1814   //   A variable of signed or unsigned integer type.
1815   //   For C++, a variable of a random access iterator type.
1816   //   For C, a variable of a pointer type.
1817   auto VarType = Var->getType();
1818   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
1819       !VarType->isPointerType() &&
1820       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
1821     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
1822         << SemaRef.getLangOpts().CPlusPlus;
1823     HasErrors = true;
1824   }
1825 
1826   // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
1827   // Construct
1828   // The loop iteration variable(s) in the associated for-loop(s) of a for or
1829   // parallel for construct is (are) private.
1830   // The loop iteration variable in the associated for-loop of a simd construct
1831   // with just one associated for-loop is linear with a constant-linear-step
1832   // that is the increment of the associated for-loop.
1833   // Exclude loop var from the list of variables with implicitly defined data
1834   // sharing attributes.
1835   while (VarsWithImplicitDSA.count(Var) > 0)
1836     VarsWithImplicitDSA.erase(Var);
1837 
1838   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
1839   // a Construct, C/C++].
1840   // The loop iteration variable in the associated for-loop of a simd construct
1841   // with just one associated for-loop may be listed in a linear clause with a
1842   // constant-linear-step that is the increment of the associated for-loop.
1843   // The loop iteration variable(s) in the associated for-loop(s) of a for or
1844   // parallel for construct may be listed in a private or lastprivate clause.
1845   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
1846   auto PredeterminedCKind =
1847       isOpenMPSimdDirective(DKind)
1848           ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
1849           : OMPC_private;
1850   if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
1851         DVar.CKind != PredeterminedCKind) ||
1852        (isOpenMPWorksharingDirective(DKind) && DVar.CKind != OMPC_unknown &&
1853         DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
1854       (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
1855     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
1856         << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
1857         << getOpenMPClauseName(PredeterminedCKind);
1858     ReportOriginalDSA(SemaRef, &DSA, Var, DVar, true);
1859     HasErrors = true;
1860   } else {
1861     // Make the loop iteration variable private (for worksharing constructs),
1862     // linear (for simd directives with the only one associated loop) or
1863     // lastprivate (for simd directives with several collapsed loops).
1864     DSA.addDSA(Var, nullptr, PredeterminedCKind);
1865   }
1866 
1867   assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
1868 
1869   // Check test-expr.
1870   HasErrors |= ISC.CheckCond(For->getCond());
1871 
1872   // Check incr-expr.
1873   HasErrors |= ISC.CheckInc(For->getInc());
1874 
1875   if (ISC.Dependent())
1876     return HasErrors;
1877 
1878   // FIXME: Build loop's iteration space representation.
1879   return HasErrors;
1880 }
1881 
1882 /// \brief A helper routine to skip no-op (attributed, compound) stmts get the
1883 /// next nested for loop. If \a IgnoreCaptured is true, it skips captured stmt
1884 /// to get the first for loop.
1885 static Stmt *IgnoreContainerStmts(Stmt *S, bool IgnoreCaptured) {
1886   if (IgnoreCaptured)
1887     if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
1888       S = CapS->getCapturedStmt();
1889   // OpenMP [2.8.1, simd construct, Restrictions]
1890   // All loops associated with the construct must be perfectly nested; that is,
1891   // there must be no intervening code nor any OpenMP directive between any two
1892   // loops.
1893   while (true) {
1894     if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
1895       S = AS->getSubStmt();
1896     else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
1897       if (CS->size() != 1)
1898         break;
1899       S = CS->body_back();
1900     } else
1901       break;
1902   }
1903   return S;
1904 }
1905 
1906 /// \brief Called on a for stmt to check itself and nested loops (if any).
1907 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
1908 /// number of collapsed loops otherwise.
1909 static unsigned
1910 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *NestedLoopCountExpr,
1911                 Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA,
1912                 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
1913   unsigned NestedLoopCount = 1;
1914   if (NestedLoopCountExpr) {
1915     // Found 'collapse' clause - calculate collapse number.
1916     llvm::APSInt Result;
1917     if (NestedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
1918       NestedLoopCount = Result.getLimitedValue();
1919   }
1920   // This is helper routine for loop directives (e.g., 'for', 'simd',
1921   // 'for simd', etc.).
1922   Stmt *CurStmt = IgnoreContainerStmts(AStmt, true);
1923   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
1924     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
1925                                   NestedLoopCount, NestedLoopCountExpr,
1926                                   VarsWithImplicitDSA))
1927       return 0;
1928     // Move on to the next nested for loop, or to the loop body.
1929     CurStmt = IgnoreContainerStmts(cast<ForStmt>(CurStmt)->getBody(), false);
1930   }
1931 
1932   // FIXME: Build resulting iteration space for IR generation (collapsing
1933   // iteration spaces when loop count > 1 ('collapse' clause)).
1934   return NestedLoopCount;
1935 }
1936 
1937 static Expr *GetCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
1938   auto CollapseFilter = [](const OMPClause *C) -> bool {
1939     return C->getClauseKind() == OMPC_collapse;
1940   };
1941   OMPExecutableDirective::filtered_clause_iterator<decltype(CollapseFilter)> I(
1942       Clauses, CollapseFilter);
1943   if (I)
1944     return cast<OMPCollapseClause>(*I)->getNumForLoops();
1945   return nullptr;
1946 }
1947 
1948 StmtResult Sema::ActOnOpenMPSimdDirective(
1949     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
1950     SourceLocation EndLoc,
1951     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
1952   // In presence of clause 'collapse', it will define the nested loops number.
1953   unsigned NestedLoopCount =
1954       CheckOpenMPLoop(OMPD_simd, GetCollapseNumberExpr(Clauses), AStmt, *this,
1955                       *DSAStack, VarsWithImplicitDSA);
1956   if (NestedLoopCount == 0)
1957     return StmtError();
1958 
1959   getCurFunction()->setHasBranchProtectedScope();
1960   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
1961                                   Clauses, AStmt);
1962 }
1963 
1964 StmtResult Sema::ActOnOpenMPForDirective(
1965     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
1966     SourceLocation EndLoc,
1967     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
1968   // In presence of clause 'collapse', it will define the nested loops number.
1969   unsigned NestedLoopCount =
1970       CheckOpenMPLoop(OMPD_for, GetCollapseNumberExpr(Clauses), AStmt, *this,
1971                       *DSAStack, VarsWithImplicitDSA);
1972   if (NestedLoopCount == 0)
1973     return StmtError();
1974 
1975   getCurFunction()->setHasBranchProtectedScope();
1976   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
1977                                  Clauses, AStmt);
1978 }
1979 
1980 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
1981                                               Stmt *AStmt,
1982                                               SourceLocation StartLoc,
1983                                               SourceLocation EndLoc) {
1984   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
1985   auto BaseStmt = AStmt;
1986   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
1987     BaseStmt = CS->getCapturedStmt();
1988   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
1989     auto S = C->children();
1990     if (!S)
1991       return StmtError();
1992     // All associated statements must be '#pragma omp section' except for
1993     // the first one.
1994     for (++S; S; ++S) {
1995       auto SectionStmt = *S;
1996       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
1997         if (SectionStmt)
1998           Diag(SectionStmt->getLocStart(),
1999                diag::err_omp_sections_substmt_not_section);
2000         return StmtError();
2001       }
2002     }
2003   } else {
2004     Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
2005     return StmtError();
2006   }
2007 
2008   getCurFunction()->setHasBranchProtectedScope();
2009 
2010   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses,
2011                                       AStmt);
2012 }
2013 
2014 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
2015                                              SourceLocation StartLoc,
2016                                              SourceLocation EndLoc) {
2017   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2018 
2019   getCurFunction()->setHasBranchProtectedScope();
2020 
2021   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt);
2022 }
2023 
2024 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
2025                                             Stmt *AStmt,
2026                                             SourceLocation StartLoc,
2027                                             SourceLocation EndLoc) {
2028   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2029 
2030   getCurFunction()->setHasBranchProtectedScope();
2031 
2032   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2033 }
2034 
2035 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
2036                                             SourceLocation StartLoc,
2037                                             SourceLocation EndLoc) {
2038   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2039 
2040   getCurFunction()->setHasBranchProtectedScope();
2041 
2042   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
2043 }
2044 
2045 StmtResult Sema::ActOnOpenMPParallelForDirective(
2046     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
2047     SourceLocation EndLoc,
2048     llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA) {
2049   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2050   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2051   // 1.2.2 OpenMP Language Terminology
2052   // Structured block - An executable statement with a single entry at the
2053   // top and a single exit at the bottom.
2054   // The point of exit cannot be a branch out of the structured block.
2055   // longjmp() and throw() must not violate the entry/exit criteria.
2056   CS->getCapturedDecl()->setNothrow();
2057 
2058   // In presence of clause 'collapse', it will define the nested loops number.
2059   unsigned NestedLoopCount =
2060       CheckOpenMPLoop(OMPD_parallel_for, GetCollapseNumberExpr(Clauses), AStmt,
2061                       *this, *DSAStack, VarsWithImplicitDSA);
2062   if (NestedLoopCount == 0)
2063     return StmtError();
2064 
2065   getCurFunction()->setHasBranchProtectedScope();
2066   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
2067                                          NestedLoopCount, Clauses, AStmt);
2068 }
2069 
2070 StmtResult
2071 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
2072                                            Stmt *AStmt, SourceLocation StartLoc,
2073                                            SourceLocation EndLoc) {
2074   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2075   auto BaseStmt = AStmt;
2076   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
2077     BaseStmt = CS->getCapturedStmt();
2078   if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
2079     auto S = C->children();
2080     if (!S)
2081       return StmtError();
2082     // All associated statements must be '#pragma omp section' except for
2083     // the first one.
2084     for (++S; S; ++S) {
2085       auto SectionStmt = *S;
2086       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
2087         if (SectionStmt)
2088           Diag(SectionStmt->getLocStart(),
2089                diag::err_omp_parallel_sections_substmt_not_section);
2090         return StmtError();
2091       }
2092     }
2093   } else {
2094     Diag(AStmt->getLocStart(),
2095          diag::err_omp_parallel_sections_not_compound_stmt);
2096     return StmtError();
2097   }
2098 
2099   getCurFunction()->setHasBranchProtectedScope();
2100 
2101   return OMPParallelSectionsDirective::Create(Context, StartLoc, EndLoc,
2102                                               Clauses, AStmt);
2103 }
2104 
2105 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
2106                                           Stmt *AStmt, SourceLocation StartLoc,
2107                                           SourceLocation EndLoc) {
2108   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
2109   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2110   // 1.2.2 OpenMP Language Terminology
2111   // Structured block - An executable statement with a single entry at the
2112   // top and a single exit at the bottom.
2113   // The point of exit cannot be a branch out of the structured block.
2114   // longjmp() and throw() must not violate the entry/exit criteria.
2115   CS->getCapturedDecl()->setNothrow();
2116 
2117   getCurFunction()->setHasBranchProtectedScope();
2118 
2119   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
2120 }
2121 
2122 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
2123                                                SourceLocation EndLoc) {
2124   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
2125 }
2126 
2127 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
2128                                              SourceLocation EndLoc) {
2129   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
2130 }
2131 
2132 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
2133                                               SourceLocation EndLoc) {
2134   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
2135 }
2136 
2137 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
2138                                              SourceLocation StartLoc,
2139                                              SourceLocation LParenLoc,
2140                                              SourceLocation EndLoc) {
2141   OMPClause *Res = nullptr;
2142   switch (Kind) {
2143   case OMPC_if:
2144     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
2145     break;
2146   case OMPC_final:
2147     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
2148     break;
2149   case OMPC_num_threads:
2150     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
2151     break;
2152   case OMPC_safelen:
2153     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
2154     break;
2155   case OMPC_collapse:
2156     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
2157     break;
2158   case OMPC_default:
2159   case OMPC_proc_bind:
2160   case OMPC_schedule:
2161   case OMPC_private:
2162   case OMPC_firstprivate:
2163   case OMPC_lastprivate:
2164   case OMPC_shared:
2165   case OMPC_reduction:
2166   case OMPC_linear:
2167   case OMPC_aligned:
2168   case OMPC_copyin:
2169   case OMPC_copyprivate:
2170   case OMPC_ordered:
2171   case OMPC_nowait:
2172   case OMPC_untied:
2173   case OMPC_mergeable:
2174   case OMPC_threadprivate:
2175   case OMPC_unknown:
2176     llvm_unreachable("Clause is not allowed.");
2177   }
2178   return Res;
2179 }
2180 
2181 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
2182                                      SourceLocation LParenLoc,
2183                                      SourceLocation EndLoc) {
2184   Expr *ValExpr = Condition;
2185   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
2186       !Condition->isInstantiationDependent() &&
2187       !Condition->containsUnexpandedParameterPack()) {
2188     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
2189                                            Condition->getExprLoc(), Condition);
2190     if (Val.isInvalid())
2191       return nullptr;
2192 
2193     ValExpr = Val.get();
2194   }
2195 
2196   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2197 }
2198 
2199 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
2200                                         SourceLocation StartLoc,
2201                                         SourceLocation LParenLoc,
2202                                         SourceLocation EndLoc) {
2203   Expr *ValExpr = Condition;
2204   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
2205       !Condition->isInstantiationDependent() &&
2206       !Condition->containsUnexpandedParameterPack()) {
2207     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
2208                                            Condition->getExprLoc(), Condition);
2209     if (Val.isInvalid())
2210       return nullptr;
2211 
2212     ValExpr = Val.get();
2213   }
2214 
2215   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2216 }
2217 
2218 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
2219                                                         Expr *Op) {
2220   if (!Op)
2221     return ExprError();
2222 
2223   class IntConvertDiagnoser : public ICEConvertDiagnoser {
2224   public:
2225     IntConvertDiagnoser()
2226         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
2227     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2228                                          QualType T) override {
2229       return S.Diag(Loc, diag::err_omp_not_integral) << T;
2230     }
2231     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2232                                              QualType T) override {
2233       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
2234     }
2235     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2236                                                QualType T,
2237                                                QualType ConvTy) override {
2238       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
2239     }
2240     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2241                                            QualType ConvTy) override {
2242       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
2243              << ConvTy->isEnumeralType() << ConvTy;
2244     }
2245     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2246                                             QualType T) override {
2247       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
2248     }
2249     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2250                                         QualType ConvTy) override {
2251       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
2252              << ConvTy->isEnumeralType() << ConvTy;
2253     }
2254     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
2255                                              QualType) override {
2256       llvm_unreachable("conversion functions are permitted");
2257     }
2258   } ConvertDiagnoser;
2259   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
2260 }
2261 
2262 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
2263                                              SourceLocation StartLoc,
2264                                              SourceLocation LParenLoc,
2265                                              SourceLocation EndLoc) {
2266   Expr *ValExpr = NumThreads;
2267   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
2268       !NumThreads->isInstantiationDependent() &&
2269       !NumThreads->containsUnexpandedParameterPack()) {
2270     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
2271     ExprResult Val =
2272         PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
2273     if (Val.isInvalid())
2274       return nullptr;
2275 
2276     ValExpr = Val.get();
2277 
2278     // OpenMP [2.5, Restrictions]
2279     //  The num_threads expression must evaluate to a positive integer value.
2280     llvm::APSInt Result;
2281     if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
2282         !Result.isStrictlyPositive()) {
2283       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
2284           << "num_threads" << NumThreads->getSourceRange();
2285       return nullptr;
2286     }
2287   }
2288 
2289   return new (Context)
2290       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
2291 }
2292 
2293 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
2294                                                        OpenMPClauseKind CKind) {
2295   if (!E)
2296     return ExprError();
2297   if (E->isValueDependent() || E->isTypeDependent() ||
2298       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2299     return E;
2300   llvm::APSInt Result;
2301   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
2302   if (ICE.isInvalid())
2303     return ExprError();
2304   if (!Result.isStrictlyPositive()) {
2305     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
2306         << getOpenMPClauseName(CKind) << E->getSourceRange();
2307     return ExprError();
2308   }
2309   return ICE;
2310 }
2311 
2312 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
2313                                           SourceLocation LParenLoc,
2314                                           SourceLocation EndLoc) {
2315   // OpenMP [2.8.1, simd construct, Description]
2316   // The parameter of the safelen clause must be a constant
2317   // positive integer expression.
2318   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
2319   if (Safelen.isInvalid())
2320     return nullptr;
2321   return new (Context)
2322       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
2323 }
2324 
2325 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
2326                                            SourceLocation StartLoc,
2327                                            SourceLocation LParenLoc,
2328                                            SourceLocation EndLoc) {
2329   // OpenMP [2.7.1, loop construct, Description]
2330   // OpenMP [2.8.1, simd construct, Description]
2331   // OpenMP [2.9.6, distribute construct, Description]
2332   // The parameter of the collapse clause must be a constant
2333   // positive integer expression.
2334   ExprResult NumForLoopsResult =
2335       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
2336   if (NumForLoopsResult.isInvalid())
2337     return nullptr;
2338   return new (Context)
2339       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
2340 }
2341 
2342 OMPClause *Sema::ActOnOpenMPSimpleClause(
2343     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
2344     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
2345   OMPClause *Res = nullptr;
2346   switch (Kind) {
2347   case OMPC_default:
2348     Res =
2349         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
2350                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
2351     break;
2352   case OMPC_proc_bind:
2353     Res = ActOnOpenMPProcBindClause(
2354         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
2355         LParenLoc, EndLoc);
2356     break;
2357   case OMPC_if:
2358   case OMPC_final:
2359   case OMPC_num_threads:
2360   case OMPC_safelen:
2361   case OMPC_collapse:
2362   case OMPC_schedule:
2363   case OMPC_private:
2364   case OMPC_firstprivate:
2365   case OMPC_lastprivate:
2366   case OMPC_shared:
2367   case OMPC_reduction:
2368   case OMPC_linear:
2369   case OMPC_aligned:
2370   case OMPC_copyin:
2371   case OMPC_copyprivate:
2372   case OMPC_ordered:
2373   case OMPC_nowait:
2374   case OMPC_untied:
2375   case OMPC_mergeable:
2376   case OMPC_threadprivate:
2377   case OMPC_unknown:
2378     llvm_unreachable("Clause is not allowed.");
2379   }
2380   return Res;
2381 }
2382 
2383 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
2384                                           SourceLocation KindKwLoc,
2385                                           SourceLocation StartLoc,
2386                                           SourceLocation LParenLoc,
2387                                           SourceLocation EndLoc) {
2388   if (Kind == OMPC_DEFAULT_unknown) {
2389     std::string Values;
2390     static_assert(OMPC_DEFAULT_unknown > 0,
2391                   "OMPC_DEFAULT_unknown not greater than 0");
2392     std::string Sep(", ");
2393     for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
2394       Values += "'";
2395       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
2396       Values += "'";
2397       switch (i) {
2398       case OMPC_DEFAULT_unknown - 2:
2399         Values += " or ";
2400         break;
2401       case OMPC_DEFAULT_unknown - 1:
2402         break;
2403       default:
2404         Values += Sep;
2405         break;
2406       }
2407     }
2408     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
2409         << Values << getOpenMPClauseName(OMPC_default);
2410     return nullptr;
2411   }
2412   switch (Kind) {
2413   case OMPC_DEFAULT_none:
2414     DSAStack->setDefaultDSANone(KindKwLoc);
2415     break;
2416   case OMPC_DEFAULT_shared:
2417     DSAStack->setDefaultDSAShared(KindKwLoc);
2418     break;
2419   case OMPC_DEFAULT_unknown:
2420     llvm_unreachable("Clause kind is not allowed.");
2421     break;
2422   }
2423   return new (Context)
2424       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
2425 }
2426 
2427 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
2428                                            SourceLocation KindKwLoc,
2429                                            SourceLocation StartLoc,
2430                                            SourceLocation LParenLoc,
2431                                            SourceLocation EndLoc) {
2432   if (Kind == OMPC_PROC_BIND_unknown) {
2433     std::string Values;
2434     std::string Sep(", ");
2435     for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
2436       Values += "'";
2437       Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
2438       Values += "'";
2439       switch (i) {
2440       case OMPC_PROC_BIND_unknown - 2:
2441         Values += " or ";
2442         break;
2443       case OMPC_PROC_BIND_unknown - 1:
2444         break;
2445       default:
2446         Values += Sep;
2447         break;
2448       }
2449     }
2450     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
2451         << Values << getOpenMPClauseName(OMPC_proc_bind);
2452     return nullptr;
2453   }
2454   return new (Context)
2455       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
2456 }
2457 
2458 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
2459     OpenMPClauseKind Kind, unsigned Argument, Expr *Expr,
2460     SourceLocation StartLoc, SourceLocation LParenLoc,
2461     SourceLocation ArgumentLoc, SourceLocation CommaLoc,
2462     SourceLocation EndLoc) {
2463   OMPClause *Res = nullptr;
2464   switch (Kind) {
2465   case OMPC_schedule:
2466     Res = ActOnOpenMPScheduleClause(
2467         static_cast<OpenMPScheduleClauseKind>(Argument), Expr, StartLoc,
2468         LParenLoc, ArgumentLoc, CommaLoc, EndLoc);
2469     break;
2470   case OMPC_if:
2471   case OMPC_final:
2472   case OMPC_num_threads:
2473   case OMPC_safelen:
2474   case OMPC_collapse:
2475   case OMPC_default:
2476   case OMPC_proc_bind:
2477   case OMPC_private:
2478   case OMPC_firstprivate:
2479   case OMPC_lastprivate:
2480   case OMPC_shared:
2481   case OMPC_reduction:
2482   case OMPC_linear:
2483   case OMPC_aligned:
2484   case OMPC_copyin:
2485   case OMPC_copyprivate:
2486   case OMPC_ordered:
2487   case OMPC_nowait:
2488   case OMPC_untied:
2489   case OMPC_mergeable:
2490   case OMPC_threadprivate:
2491   case OMPC_unknown:
2492     llvm_unreachable("Clause is not allowed.");
2493   }
2494   return Res;
2495 }
2496 
2497 OMPClause *Sema::ActOnOpenMPScheduleClause(
2498     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
2499     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
2500     SourceLocation EndLoc) {
2501   if (Kind == OMPC_SCHEDULE_unknown) {
2502     std::string Values;
2503     std::string Sep(", ");
2504     for (unsigned i = 0; i < OMPC_SCHEDULE_unknown; ++i) {
2505       Values += "'";
2506       Values += getOpenMPSimpleClauseTypeName(OMPC_schedule, i);
2507       Values += "'";
2508       switch (i) {
2509       case OMPC_SCHEDULE_unknown - 2:
2510         Values += " or ";
2511         break;
2512       case OMPC_SCHEDULE_unknown - 1:
2513         break;
2514       default:
2515         Values += Sep;
2516         break;
2517       }
2518     }
2519     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
2520         << Values << getOpenMPClauseName(OMPC_schedule);
2521     return nullptr;
2522   }
2523   Expr *ValExpr = ChunkSize;
2524   if (ChunkSize) {
2525     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
2526         !ChunkSize->isInstantiationDependent() &&
2527         !ChunkSize->containsUnexpandedParameterPack()) {
2528       SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
2529       ExprResult Val =
2530           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
2531       if (Val.isInvalid())
2532         return nullptr;
2533 
2534       ValExpr = Val.get();
2535 
2536       // OpenMP [2.7.1, Restrictions]
2537       //  chunk_size must be a loop invariant integer expression with a positive
2538       //  value.
2539       llvm::APSInt Result;
2540       if (ValExpr->isIntegerConstantExpr(Result, Context) &&
2541           Result.isSigned() && !Result.isStrictlyPositive()) {
2542         Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
2543             << "schedule" << ChunkSize->getSourceRange();
2544         return nullptr;
2545       }
2546     }
2547   }
2548 
2549   return new (Context) OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc,
2550                                          EndLoc, Kind, ValExpr);
2551 }
2552 
2553 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
2554                                    SourceLocation StartLoc,
2555                                    SourceLocation EndLoc) {
2556   OMPClause *Res = nullptr;
2557   switch (Kind) {
2558   case OMPC_ordered:
2559     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
2560     break;
2561   case OMPC_nowait:
2562     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
2563     break;
2564   case OMPC_untied:
2565     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
2566     break;
2567   case OMPC_mergeable:
2568     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
2569     break;
2570   case OMPC_if:
2571   case OMPC_final:
2572   case OMPC_num_threads:
2573   case OMPC_safelen:
2574   case OMPC_collapse:
2575   case OMPC_schedule:
2576   case OMPC_private:
2577   case OMPC_firstprivate:
2578   case OMPC_lastprivate:
2579   case OMPC_shared:
2580   case OMPC_reduction:
2581   case OMPC_linear:
2582   case OMPC_aligned:
2583   case OMPC_copyin:
2584   case OMPC_copyprivate:
2585   case OMPC_default:
2586   case OMPC_proc_bind:
2587   case OMPC_threadprivate:
2588   case OMPC_unknown:
2589     llvm_unreachable("Clause is not allowed.");
2590   }
2591   return Res;
2592 }
2593 
2594 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
2595                                           SourceLocation EndLoc) {
2596   return new (Context) OMPOrderedClause(StartLoc, EndLoc);
2597 }
2598 
2599 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
2600                                          SourceLocation EndLoc) {
2601   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
2602 }
2603 
2604 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
2605                                          SourceLocation EndLoc) {
2606   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
2607 }
2608 
2609 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
2610                                             SourceLocation EndLoc) {
2611   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
2612 }
2613 
2614 OMPClause *Sema::ActOnOpenMPVarListClause(
2615     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
2616     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
2617     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
2618     const DeclarationNameInfo &ReductionId) {
2619   OMPClause *Res = nullptr;
2620   switch (Kind) {
2621   case OMPC_private:
2622     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2623     break;
2624   case OMPC_firstprivate:
2625     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2626     break;
2627   case OMPC_lastprivate:
2628     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2629     break;
2630   case OMPC_shared:
2631     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
2632     break;
2633   case OMPC_reduction:
2634     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
2635                                      EndLoc, ReductionIdScopeSpec, ReductionId);
2636     break;
2637   case OMPC_linear:
2638     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
2639                                   ColonLoc, EndLoc);
2640     break;
2641   case OMPC_aligned:
2642     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
2643                                    ColonLoc, EndLoc);
2644     break;
2645   case OMPC_copyin:
2646     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
2647     break;
2648   case OMPC_copyprivate:
2649     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
2650     break;
2651   case OMPC_if:
2652   case OMPC_final:
2653   case OMPC_num_threads:
2654   case OMPC_safelen:
2655   case OMPC_collapse:
2656   case OMPC_default:
2657   case OMPC_proc_bind:
2658   case OMPC_schedule:
2659   case OMPC_ordered:
2660   case OMPC_nowait:
2661   case OMPC_untied:
2662   case OMPC_mergeable:
2663   case OMPC_threadprivate:
2664   case OMPC_unknown:
2665     llvm_unreachable("Clause is not allowed.");
2666   }
2667   return Res;
2668 }
2669 
2670 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
2671                                           SourceLocation StartLoc,
2672                                           SourceLocation LParenLoc,
2673                                           SourceLocation EndLoc) {
2674   SmallVector<Expr *, 8> Vars;
2675   for (auto &RefExpr : VarList) {
2676     assert(RefExpr && "NULL expr in OpenMP private clause.");
2677     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2678       // It will be analyzed later.
2679       Vars.push_back(RefExpr);
2680       continue;
2681     }
2682 
2683     SourceLocation ELoc = RefExpr->getExprLoc();
2684     // OpenMP [2.1, C/C++]
2685     //  A list item is a variable name.
2686     // OpenMP  [2.9.3.3, Restrictions, p.1]
2687     //  A variable that is part of another variable (as an array or
2688     //  structure element) cannot appear in a private clause.
2689     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
2690     if (!DE || !isa<VarDecl>(DE->getDecl())) {
2691       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2692       continue;
2693     }
2694     Decl *D = DE->getDecl();
2695     VarDecl *VD = cast<VarDecl>(D);
2696 
2697     QualType Type = VD->getType();
2698     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
2699       // It will be analyzed later.
2700       Vars.push_back(DE);
2701       continue;
2702     }
2703 
2704     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
2705     //  A variable that appears in a private clause must not have an incomplete
2706     //  type or a reference type.
2707     if (RequireCompleteType(ELoc, Type,
2708                             diag::err_omp_private_incomplete_type)) {
2709       continue;
2710     }
2711     if (Type->isReferenceType()) {
2712       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
2713           << getOpenMPClauseName(OMPC_private) << Type;
2714       bool IsDecl =
2715           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2716       Diag(VD->getLocation(),
2717            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2718           << VD;
2719       continue;
2720     }
2721 
2722     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
2723     //  A variable of class type (or array thereof) that appears in a private
2724     //  clause requires an accessible, unambiguous default constructor for the
2725     //  class type.
2726     while (Type.getNonReferenceType()->isArrayType()) {
2727       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
2728                  ->getElementType();
2729     }
2730     CXXRecordDecl *RD = getLangOpts().CPlusPlus
2731                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
2732                             : nullptr;
2733     // FIXME This code must be replaced by actual constructing/destructing of
2734     // the private variable.
2735     if (RD) {
2736       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
2737       PartialDiagnostic PD =
2738           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
2739       if (!CD ||
2740           CheckConstructorAccess(ELoc, CD,
2741                                  InitializedEntity::InitializeTemporary(Type),
2742                                  CD->getAccess(), PD) == AR_inaccessible ||
2743           CD->isDeleted()) {
2744         Diag(ELoc, diag::err_omp_required_method)
2745             << getOpenMPClauseName(OMPC_private) << 0;
2746         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2747                       VarDecl::DeclarationOnly;
2748         Diag(VD->getLocation(),
2749              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2750             << VD;
2751         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2752         continue;
2753       }
2754       MarkFunctionReferenced(ELoc, CD);
2755       DiagnoseUseOfDecl(CD, ELoc);
2756 
2757       CXXDestructorDecl *DD = RD->getDestructor();
2758       if (DD) {
2759         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
2760             DD->isDeleted()) {
2761           Diag(ELoc, diag::err_omp_required_method)
2762               << getOpenMPClauseName(OMPC_private) << 4;
2763           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2764                         VarDecl::DeclarationOnly;
2765           Diag(VD->getLocation(),
2766                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2767               << VD;
2768           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2769           continue;
2770         }
2771         MarkFunctionReferenced(ELoc, DD);
2772         DiagnoseUseOfDecl(DD, ELoc);
2773       }
2774     }
2775 
2776     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
2777     // in a Construct]
2778     //  Variables with the predetermined data-sharing attributes may not be
2779     //  listed in data-sharing attributes clauses, except for the cases
2780     //  listed below. For these exceptions only, listing a predetermined
2781     //  variable in a data-sharing attribute clause is allowed and overrides
2782     //  the variable's predetermined data-sharing attributes.
2783     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
2784     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
2785       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
2786                                           << getOpenMPClauseName(OMPC_private);
2787       ReportOriginalDSA(*this, DSAStack, VD, DVar);
2788       continue;
2789     }
2790 
2791     DSAStack->addDSA(VD, DE, OMPC_private);
2792     Vars.push_back(DE);
2793   }
2794 
2795   if (Vars.empty())
2796     return nullptr;
2797 
2798   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
2799 }
2800 
2801 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
2802                                                SourceLocation StartLoc,
2803                                                SourceLocation LParenLoc,
2804                                                SourceLocation EndLoc) {
2805   SmallVector<Expr *, 8> Vars;
2806   bool IsImplicitClause =
2807       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
2808   auto ImplicitClauseLoc = DSAStack->getConstructLoc();
2809 
2810   for (auto &RefExpr : VarList) {
2811     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
2812     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2813       // It will be analyzed later.
2814       Vars.push_back(RefExpr);
2815       continue;
2816     }
2817 
2818     SourceLocation ELoc = IsImplicitClause ? ImplicitClauseLoc
2819                                            : RefExpr->getExprLoc();
2820     // OpenMP [2.1, C/C++]
2821     //  A list item is a variable name.
2822     // OpenMP  [2.9.3.3, Restrictions, p.1]
2823     //  A variable that is part of another variable (as an array or
2824     //  structure element) cannot appear in a private clause.
2825     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
2826     if (!DE || !isa<VarDecl>(DE->getDecl())) {
2827       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2828       continue;
2829     }
2830     Decl *D = DE->getDecl();
2831     VarDecl *VD = cast<VarDecl>(D);
2832 
2833     QualType Type = VD->getType();
2834     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
2835       // It will be analyzed later.
2836       Vars.push_back(DE);
2837       continue;
2838     }
2839 
2840     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
2841     //  A variable that appears in a private clause must not have an incomplete
2842     //  type or a reference type.
2843     if (RequireCompleteType(ELoc, Type,
2844                             diag::err_omp_firstprivate_incomplete_type)) {
2845       continue;
2846     }
2847     if (Type->isReferenceType()) {
2848       if (IsImplicitClause) {
2849         Diag(ImplicitClauseLoc,
2850              diag::err_omp_task_predetermined_firstprivate_ref_type_arg)
2851             << Type;
2852         Diag(RefExpr->getExprLoc(), diag::note_used_here);
2853       } else {
2854         Diag(ELoc, diag::err_omp_clause_ref_type_arg)
2855             << getOpenMPClauseName(OMPC_firstprivate) << Type;
2856       }
2857       bool IsDecl =
2858           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2859       Diag(VD->getLocation(),
2860            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2861           << VD;
2862       continue;
2863     }
2864 
2865     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
2866     //  A variable of class type (or array thereof) that appears in a private
2867     //  clause requires an accessible, unambiguous copy constructor for the
2868     //  class type.
2869     Type = Context.getBaseElementType(Type);
2870     CXXRecordDecl *RD = getLangOpts().CPlusPlus
2871                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
2872                             : nullptr;
2873     // FIXME This code must be replaced by actual constructing/destructing of
2874     // the firstprivate variable.
2875     if (RD) {
2876       CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
2877       PartialDiagnostic PD =
2878           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
2879       if (!CD ||
2880           CheckConstructorAccess(ELoc, CD,
2881                                  InitializedEntity::InitializeTemporary(Type),
2882                                  CD->getAccess(), PD) == AR_inaccessible ||
2883           CD->isDeleted()) {
2884         if (IsImplicitClause) {
2885           Diag(ImplicitClauseLoc,
2886                diag::err_omp_task_predetermined_firstprivate_required_method)
2887               << 0;
2888           Diag(RefExpr->getExprLoc(), diag::note_used_here);
2889         } else {
2890           Diag(ELoc, diag::err_omp_required_method)
2891               << getOpenMPClauseName(OMPC_firstprivate) << 1;
2892         }
2893         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2894                       VarDecl::DeclarationOnly;
2895         Diag(VD->getLocation(),
2896              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2897             << VD;
2898         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2899         continue;
2900       }
2901       MarkFunctionReferenced(ELoc, CD);
2902       DiagnoseUseOfDecl(CD, ELoc);
2903 
2904       CXXDestructorDecl *DD = RD->getDestructor();
2905       if (DD) {
2906         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
2907             DD->isDeleted()) {
2908           if (IsImplicitClause) {
2909             Diag(ImplicitClauseLoc,
2910                  diag::err_omp_task_predetermined_firstprivate_required_method)
2911                 << 1;
2912             Diag(RefExpr->getExprLoc(), diag::note_used_here);
2913           } else {
2914             Diag(ELoc, diag::err_omp_required_method)
2915                 << getOpenMPClauseName(OMPC_firstprivate) << 4;
2916           }
2917           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2918                         VarDecl::DeclarationOnly;
2919           Diag(VD->getLocation(),
2920                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2921               << VD;
2922           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2923           continue;
2924         }
2925         MarkFunctionReferenced(ELoc, DD);
2926         DiagnoseUseOfDecl(DD, ELoc);
2927       }
2928     }
2929 
2930     // If an implicit firstprivate variable found it was checked already.
2931     if (!IsImplicitClause) {
2932       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
2933       Type = Type.getNonReferenceType().getCanonicalType();
2934       bool IsConstant = Type.isConstant(Context);
2935       Type = Context.getBaseElementType(Type);
2936       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
2937       //  A list item that specifies a given variable may not appear in more
2938       // than one clause on the same directive, except that a variable may be
2939       //  specified in both firstprivate and lastprivate clauses.
2940       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
2941           DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
2942         Diag(ELoc, diag::err_omp_wrong_dsa)
2943             << getOpenMPClauseName(DVar.CKind)
2944             << getOpenMPClauseName(OMPC_firstprivate);
2945         ReportOriginalDSA(*this, DSAStack, VD, DVar);
2946         continue;
2947       }
2948 
2949       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
2950       // in a Construct]
2951       //  Variables with the predetermined data-sharing attributes may not be
2952       //  listed in data-sharing attributes clauses, except for the cases
2953       //  listed below. For these exceptions only, listing a predetermined
2954       //  variable in a data-sharing attribute clause is allowed and overrides
2955       //  the variable's predetermined data-sharing attributes.
2956       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
2957       // in a Construct, C/C++, p.2]
2958       //  Variables with const-qualified type having no mutable member may be
2959       //  listed in a firstprivate clause, even if they are static data members.
2960       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
2961           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
2962         Diag(ELoc, diag::err_omp_wrong_dsa)
2963             << getOpenMPClauseName(DVar.CKind)
2964             << getOpenMPClauseName(OMPC_firstprivate);
2965         ReportOriginalDSA(*this, DSAStack, VD, DVar);
2966         continue;
2967       }
2968 
2969       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
2970       // OpenMP [2.9.3.4, Restrictions, p.2]
2971       //  A list item that is private within a parallel region must not appear
2972       //  in a firstprivate clause on a worksharing construct if any of the
2973       //  worksharing regions arising from the worksharing construct ever bind
2974       //  to any of the parallel regions arising from the parallel construct.
2975       if (isOpenMPWorksharingDirective(CurrDir) &&
2976           !isOpenMPParallelDirective(CurrDir)) {
2977         DVar = DSAStack->getImplicitDSA(VD, true);
2978         if (DVar.CKind != OMPC_shared &&
2979             (isOpenMPParallelDirective(DVar.DKind) ||
2980              DVar.DKind == OMPD_unknown)) {
2981           Diag(ELoc, diag::err_omp_required_access)
2982               << getOpenMPClauseName(OMPC_firstprivate)
2983               << getOpenMPClauseName(OMPC_shared);
2984           ReportOriginalDSA(*this, DSAStack, VD, DVar);
2985           continue;
2986         }
2987       }
2988       // OpenMP [2.9.3.4, Restrictions, p.3]
2989       //  A list item that appears in a reduction clause of a parallel construct
2990       //  must not appear in a firstprivate clause on a worksharing or task
2991       //  construct if any of the worksharing or task regions arising from the
2992       //  worksharing or task construct ever bind to any of the parallel regions
2993       //  arising from the parallel construct.
2994       // OpenMP [2.9.3.4, Restrictions, p.4]
2995       //  A list item that appears in a reduction clause in worksharing
2996       //  construct must not appear in a firstprivate clause in a task construct
2997       //  encountered during execution of any of the worksharing regions arising
2998       //  from the worksharing construct.
2999       if (CurrDir == OMPD_task) {
3000         DVar =
3001             DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
3002                                       [](OpenMPDirectiveKind K) -> bool {
3003                                         return isOpenMPParallelDirective(K) ||
3004                                                isOpenMPWorksharingDirective(K);
3005                                       },
3006                                       false);
3007         if (DVar.CKind == OMPC_reduction &&
3008             (isOpenMPParallelDirective(DVar.DKind) ||
3009              isOpenMPWorksharingDirective(DVar.DKind))) {
3010           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
3011               << getOpenMPDirectiveName(DVar.DKind);
3012           ReportOriginalDSA(*this, DSAStack, VD, DVar);
3013           continue;
3014         }
3015       }
3016     }
3017 
3018     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
3019     Vars.push_back(DE);
3020   }
3021 
3022   if (Vars.empty())
3023     return nullptr;
3024 
3025   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
3026                                        Vars);
3027 }
3028 
3029 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
3030                                               SourceLocation StartLoc,
3031                                               SourceLocation LParenLoc,
3032                                               SourceLocation EndLoc) {
3033   SmallVector<Expr *, 8> Vars;
3034   for (auto &RefExpr : VarList) {
3035     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
3036     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3037       // It will be analyzed later.
3038       Vars.push_back(RefExpr);
3039       continue;
3040     }
3041 
3042     SourceLocation ELoc = RefExpr->getExprLoc();
3043     // OpenMP [2.1, C/C++]
3044     //  A list item is a variable name.
3045     // OpenMP  [2.14.3.5, Restrictions, p.1]
3046     //  A variable that is part of another variable (as an array or structure
3047     //  element) cannot appear in a lastprivate clause.
3048     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3049     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3050       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3051       continue;
3052     }
3053     Decl *D = DE->getDecl();
3054     VarDecl *VD = cast<VarDecl>(D);
3055 
3056     QualType Type = VD->getType();
3057     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3058       // It will be analyzed later.
3059       Vars.push_back(DE);
3060       continue;
3061     }
3062 
3063     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
3064     //  A variable that appears in a lastprivate clause must not have an
3065     //  incomplete type or a reference type.
3066     if (RequireCompleteType(ELoc, Type,
3067                             diag::err_omp_lastprivate_incomplete_type)) {
3068       continue;
3069     }
3070     if (Type->isReferenceType()) {
3071       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3072           << getOpenMPClauseName(OMPC_lastprivate) << Type;
3073       bool IsDecl =
3074           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3075       Diag(VD->getLocation(),
3076            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3077           << VD;
3078       continue;
3079     }
3080 
3081     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3082     // in a Construct]
3083     //  Variables with the predetermined data-sharing attributes may not be
3084     //  listed in data-sharing attributes clauses, except for the cases
3085     //  listed below.
3086     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3087     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
3088         DVar.CKind != OMPC_firstprivate &&
3089         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3090       Diag(ELoc, diag::err_omp_wrong_dsa)
3091           << getOpenMPClauseName(DVar.CKind)
3092           << getOpenMPClauseName(OMPC_lastprivate);
3093       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3094       continue;
3095     }
3096 
3097     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3098     // OpenMP [2.14.3.5, Restrictions, p.2]
3099     // A list item that is private within a parallel region, or that appears in
3100     // the reduction clause of a parallel construct, must not appear in a
3101     // lastprivate clause on a worksharing construct if any of the corresponding
3102     // worksharing regions ever binds to any of the corresponding parallel
3103     // regions.
3104     if (isOpenMPWorksharingDirective(CurrDir) &&
3105         !isOpenMPParallelDirective(CurrDir)) {
3106       DVar = DSAStack->getImplicitDSA(VD, true);
3107       if (DVar.CKind != OMPC_shared) {
3108         Diag(ELoc, diag::err_omp_required_access)
3109             << getOpenMPClauseName(OMPC_lastprivate)
3110             << getOpenMPClauseName(OMPC_shared);
3111         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3112         continue;
3113       }
3114     }
3115     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
3116     //  A variable of class type (or array thereof) that appears in a
3117     //  lastprivate clause requires an accessible, unambiguous default
3118     //  constructor for the class type, unless the list item is also specified
3119     //  in a firstprivate clause.
3120     //  A variable of class type (or array thereof) that appears in a
3121     //  lastprivate clause requires an accessible, unambiguous copy assignment
3122     //  operator for the class type.
3123     while (Type.getNonReferenceType()->isArrayType())
3124       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
3125                  ->getElementType();
3126     CXXRecordDecl *RD = getLangOpts().CPlusPlus
3127                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3128                             : nullptr;
3129     // FIXME This code must be replaced by actual copying and destructing of the
3130     // lastprivate variable.
3131     if (RD) {
3132       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
3133       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
3134       if (MD) {
3135         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
3136             MD->isDeleted()) {
3137           Diag(ELoc, diag::err_omp_required_method)
3138               << getOpenMPClauseName(OMPC_lastprivate) << 2;
3139           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3140                         VarDecl::DeclarationOnly;
3141           Diag(VD->getLocation(),
3142                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3143               << VD;
3144           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3145           continue;
3146         }
3147         MarkFunctionReferenced(ELoc, MD);
3148         DiagnoseUseOfDecl(MD, ELoc);
3149       }
3150 
3151       CXXDestructorDecl *DD = RD->getDestructor();
3152       if (DD) {
3153         PartialDiagnostic PD =
3154             PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3155         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3156             DD->isDeleted()) {
3157           Diag(ELoc, diag::err_omp_required_method)
3158               << getOpenMPClauseName(OMPC_lastprivate) << 4;
3159           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3160                         VarDecl::DeclarationOnly;
3161           Diag(VD->getLocation(),
3162                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3163               << VD;
3164           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3165           continue;
3166         }
3167         MarkFunctionReferenced(ELoc, DD);
3168         DiagnoseUseOfDecl(DD, ELoc);
3169       }
3170     }
3171 
3172     if (DVar.CKind != OMPC_firstprivate)
3173       DSAStack->addDSA(VD, DE, OMPC_lastprivate);
3174     Vars.push_back(DE);
3175   }
3176 
3177   if (Vars.empty())
3178     return nullptr;
3179 
3180   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
3181                                       Vars);
3182 }
3183 
3184 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
3185                                          SourceLocation StartLoc,
3186                                          SourceLocation LParenLoc,
3187                                          SourceLocation EndLoc) {
3188   SmallVector<Expr *, 8> Vars;
3189   for (auto &RefExpr : VarList) {
3190     assert(RefExpr && "NULL expr in OpenMP shared clause.");
3191     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3192       // It will be analyzed later.
3193       Vars.push_back(RefExpr);
3194       continue;
3195     }
3196 
3197     SourceLocation ELoc = RefExpr->getExprLoc();
3198     // OpenMP [2.1, C/C++]
3199     //  A list item is a variable name.
3200     // OpenMP  [2.14.3.2, Restrictions, p.1]
3201     //  A variable that is part of another variable (as an array or structure
3202     //  element) cannot appear in a shared unless it is a static data member
3203     //  of a C++ class.
3204     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3205     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3206       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3207       continue;
3208     }
3209     Decl *D = DE->getDecl();
3210     VarDecl *VD = cast<VarDecl>(D);
3211 
3212     QualType Type = VD->getType();
3213     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3214       // It will be analyzed later.
3215       Vars.push_back(DE);
3216       continue;
3217     }
3218 
3219     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
3220     // in a Construct]
3221     //  Variables with the predetermined data-sharing attributes may not be
3222     //  listed in data-sharing attributes clauses, except for the cases
3223     //  listed below. For these exceptions only, listing a predetermined
3224     //  variable in a data-sharing attribute clause is allowed and overrides
3225     //  the variable's predetermined data-sharing attributes.
3226     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3227     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
3228         DVar.RefExpr) {
3229       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3230                                           << getOpenMPClauseName(OMPC_shared);
3231       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3232       continue;
3233     }
3234 
3235     DSAStack->addDSA(VD, DE, OMPC_shared);
3236     Vars.push_back(DE);
3237   }
3238 
3239   if (Vars.empty())
3240     return nullptr;
3241 
3242   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3243 }
3244 
3245 namespace {
3246 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
3247   DSAStackTy *Stack;
3248 
3249 public:
3250   bool VisitDeclRefExpr(DeclRefExpr *E) {
3251     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
3252       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
3253       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
3254         return false;
3255       if (DVar.CKind != OMPC_unknown)
3256         return true;
3257       DSAStackTy::DSAVarData DVarPrivate =
3258           Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
3259       if (DVarPrivate.CKind != OMPC_unknown)
3260         return true;
3261       return false;
3262     }
3263     return false;
3264   }
3265   bool VisitStmt(Stmt *S) {
3266     for (auto Child : S->children()) {
3267       if (Child && Visit(Child))
3268         return true;
3269     }
3270     return false;
3271   }
3272   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
3273 };
3274 } // namespace
3275 
3276 OMPClause *Sema::ActOnOpenMPReductionClause(
3277     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
3278     SourceLocation ColonLoc, SourceLocation EndLoc,
3279     CXXScopeSpec &ReductionIdScopeSpec,
3280     const DeclarationNameInfo &ReductionId) {
3281   // TODO: Allow scope specification search when 'declare reduction' is
3282   // supported.
3283   assert(ReductionIdScopeSpec.isEmpty() &&
3284          "No support for scoped reduction identifiers yet.");
3285 
3286   auto DN = ReductionId.getName();
3287   auto OOK = DN.getCXXOverloadedOperator();
3288   BinaryOperatorKind BOK = BO_Comma;
3289 
3290   // OpenMP [2.14.3.6, reduction clause]
3291   // C
3292   // reduction-identifier is either an identifier or one of the following
3293   // operators: +, -, *,  &, |, ^, && and ||
3294   // C++
3295   // reduction-identifier is either an id-expression or one of the following
3296   // operators: +, -, *, &, |, ^, && and ||
3297   // FIXME: Only 'min' and 'max' identifiers are supported for now.
3298   switch (OOK) {
3299   case OO_Plus:
3300   case OO_Minus:
3301     BOK = BO_AddAssign;
3302     break;
3303   case OO_Star:
3304     BOK = BO_MulAssign;
3305     break;
3306   case OO_Amp:
3307     BOK = BO_AndAssign;
3308     break;
3309   case OO_Pipe:
3310     BOK = BO_OrAssign;
3311     break;
3312   case OO_Caret:
3313     BOK = BO_XorAssign;
3314     break;
3315   case OO_AmpAmp:
3316     BOK = BO_LAnd;
3317     break;
3318   case OO_PipePipe:
3319     BOK = BO_LOr;
3320     break;
3321   default:
3322     if (auto II = DN.getAsIdentifierInfo()) {
3323       if (II->isStr("max"))
3324         BOK = BO_GT;
3325       else if (II->isStr("min"))
3326         BOK = BO_LT;
3327     }
3328     break;
3329   }
3330   SourceRange ReductionIdRange;
3331   if (ReductionIdScopeSpec.isValid()) {
3332     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
3333   }
3334   ReductionIdRange.setEnd(ReductionId.getEndLoc());
3335   if (BOK == BO_Comma) {
3336     // Not allowed reduction identifier is found.
3337     Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
3338         << ReductionIdRange;
3339     return nullptr;
3340   }
3341 
3342   SmallVector<Expr *, 8> Vars;
3343   for (auto RefExpr : VarList) {
3344     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
3345     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3346       // It will be analyzed later.
3347       Vars.push_back(RefExpr);
3348       continue;
3349     }
3350 
3351     if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3352         RefExpr->isInstantiationDependent() ||
3353         RefExpr->containsUnexpandedParameterPack()) {
3354       // It will be analyzed later.
3355       Vars.push_back(RefExpr);
3356       continue;
3357     }
3358 
3359     auto ELoc = RefExpr->getExprLoc();
3360     auto ERange = RefExpr->getSourceRange();
3361     // OpenMP [2.1, C/C++]
3362     //  A list item is a variable or array section, subject to the restrictions
3363     //  specified in Section 2.4 on page 42 and in each of the sections
3364     // describing clauses and directives for which a list appears.
3365     // OpenMP  [2.14.3.3, Restrictions, p.1]
3366     //  A variable that is part of another variable (as an array or
3367     //  structure element) cannot appear in a private clause.
3368     auto DE = dyn_cast<DeclRefExpr>(RefExpr);
3369     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3370       Diag(ELoc, diag::err_omp_expected_var_name) << ERange;
3371       continue;
3372     }
3373     auto D = DE->getDecl();
3374     auto VD = cast<VarDecl>(D);
3375     auto Type = VD->getType();
3376     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
3377     //  A variable that appears in a private clause must not have an incomplete
3378     //  type or a reference type.
3379     if (RequireCompleteType(ELoc, Type,
3380                             diag::err_omp_reduction_incomplete_type))
3381       continue;
3382     // OpenMP [2.14.3.6, reduction clause, Restrictions]
3383     // Arrays may not appear in a reduction clause.
3384     if (Type.getNonReferenceType()->isArrayType()) {
3385       Diag(ELoc, diag::err_omp_reduction_type_array) << Type << ERange;
3386       bool IsDecl =
3387           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3388       Diag(VD->getLocation(),
3389            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3390           << VD;
3391       continue;
3392     }
3393     // OpenMP [2.14.3.6, reduction clause, Restrictions]
3394     // A list item that appears in a reduction clause must not be
3395     // const-qualified.
3396     if (Type.getNonReferenceType().isConstant(Context)) {
3397       Diag(ELoc, diag::err_omp_const_variable)
3398           << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
3399       bool IsDecl =
3400           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3401       Diag(VD->getLocation(),
3402            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3403           << VD;
3404       continue;
3405     }
3406     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
3407     //  If a list-item is a reference type then it must bind to the same object
3408     //  for all threads of the team.
3409     VarDecl *VDDef = VD->getDefinition();
3410     if (Type->isReferenceType() && VDDef) {
3411       DSARefChecker Check(DSAStack);
3412       if (Check.Visit(VDDef->getInit())) {
3413         Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
3414         Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
3415         continue;
3416       }
3417     }
3418     // OpenMP [2.14.3.6, reduction clause, Restrictions]
3419     // The type of a list item that appears in a reduction clause must be valid
3420     // for the reduction-identifier. For a max or min reduction in C, the type
3421     // of the list item must be an allowed arithmetic data type: char, int,
3422     // float, double, or _Bool, possibly modified with long, short, signed, or
3423     // unsigned. For a max or min reduction in C++, the type of the list item
3424     // must be an allowed arithmetic data type: char, wchar_t, int, float,
3425     // double, or bool, possibly modified with long, short, signed, or unsigned.
3426     if ((BOK == BO_GT || BOK == BO_LT) &&
3427         !(Type->isScalarType() ||
3428           (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
3429       Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
3430           << getLangOpts().CPlusPlus;
3431       bool IsDecl =
3432           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3433       Diag(VD->getLocation(),
3434            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3435           << VD;
3436       continue;
3437     }
3438     if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
3439         !getLangOpts().CPlusPlus && Type->isFloatingType()) {
3440       Diag(ELoc, diag::err_omp_clause_floating_type_arg);
3441       bool IsDecl =
3442           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3443       Diag(VD->getLocation(),
3444            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3445           << VD;
3446       continue;
3447     }
3448     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
3449     getDiagnostics().setSuppressAllDiagnostics(true);
3450     ExprResult ReductionOp =
3451         BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
3452                    RefExpr, RefExpr);
3453     getDiagnostics().setSuppressAllDiagnostics(Suppress);
3454     if (ReductionOp.isInvalid()) {
3455       Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
3456                                                             << ReductionIdRange;
3457       bool IsDecl =
3458           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3459       Diag(VD->getLocation(),
3460            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3461           << VD;
3462       continue;
3463     }
3464 
3465     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3466     // in a Construct]
3467     //  Variables with the predetermined data-sharing attributes may not be
3468     //  listed in data-sharing attributes clauses, except for the cases
3469     //  listed below. For these exceptions only, listing a predetermined
3470     //  variable in a data-sharing attribute clause is allowed and overrides
3471     //  the variable's predetermined data-sharing attributes.
3472     // OpenMP [2.14.3.6, Restrictions, p.3]
3473     //  Any number of reduction clauses can be specified on the directive,
3474     //  but a list item can appear only once in the reduction clauses for that
3475     //  directive.
3476     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3477     if (DVar.CKind == OMPC_reduction) {
3478       Diag(ELoc, diag::err_omp_once_referenced)
3479           << getOpenMPClauseName(OMPC_reduction);
3480       if (DVar.RefExpr) {
3481         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
3482       }
3483     } else if (DVar.CKind != OMPC_unknown) {
3484       Diag(ELoc, diag::err_omp_wrong_dsa)
3485           << getOpenMPClauseName(DVar.CKind)
3486           << getOpenMPClauseName(OMPC_reduction);
3487       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3488       continue;
3489     }
3490 
3491     // OpenMP [2.14.3.6, Restrictions, p.1]
3492     //  A list item that appears in a reduction clause of a worksharing
3493     //  construct must be shared in the parallel regions to which any of the
3494     //  worksharing regions arising from the worksharing construct bind.
3495     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
3496     if (isOpenMPWorksharingDirective(CurrDir) &&
3497         !isOpenMPParallelDirective(CurrDir)) {
3498       DVar = DSAStack->getImplicitDSA(VD, true);
3499       if (DVar.CKind != OMPC_shared) {
3500         Diag(ELoc, diag::err_omp_required_access)
3501             << getOpenMPClauseName(OMPC_reduction)
3502             << getOpenMPClauseName(OMPC_shared);
3503         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3504         continue;
3505       }
3506     }
3507 
3508     CXXRecordDecl *RD = getLangOpts().CPlusPlus
3509                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
3510                             : nullptr;
3511     // FIXME This code must be replaced by actual constructing/destructing of
3512     // the reduction variable.
3513     if (RD) {
3514       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
3515       PartialDiagnostic PD =
3516           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
3517       if (!CD ||
3518           CheckConstructorAccess(ELoc, CD,
3519                                  InitializedEntity::InitializeTemporary(Type),
3520                                  CD->getAccess(), PD) == AR_inaccessible ||
3521           CD->isDeleted()) {
3522         Diag(ELoc, diag::err_omp_required_method)
3523             << getOpenMPClauseName(OMPC_reduction) << 0;
3524         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3525                       VarDecl::DeclarationOnly;
3526         Diag(VD->getLocation(),
3527              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3528             << VD;
3529         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3530         continue;
3531       }
3532       MarkFunctionReferenced(ELoc, CD);
3533       DiagnoseUseOfDecl(CD, ELoc);
3534 
3535       CXXDestructorDecl *DD = RD->getDestructor();
3536       if (DD) {
3537         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
3538             DD->isDeleted()) {
3539           Diag(ELoc, diag::err_omp_required_method)
3540               << getOpenMPClauseName(OMPC_reduction) << 4;
3541           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3542                         VarDecl::DeclarationOnly;
3543           Diag(VD->getLocation(),
3544                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3545               << VD;
3546           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3547           continue;
3548         }
3549         MarkFunctionReferenced(ELoc, DD);
3550         DiagnoseUseOfDecl(DD, ELoc);
3551       }
3552     }
3553 
3554     DSAStack->addDSA(VD, DE, OMPC_reduction);
3555     Vars.push_back(DE);
3556   }
3557 
3558   if (Vars.empty())
3559     return nullptr;
3560 
3561   return OMPReductionClause::Create(
3562       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
3563       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId);
3564 }
3565 
3566 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
3567                                          SourceLocation StartLoc,
3568                                          SourceLocation LParenLoc,
3569                                          SourceLocation ColonLoc,
3570                                          SourceLocation EndLoc) {
3571   SmallVector<Expr *, 8> Vars;
3572   for (auto &RefExpr : VarList) {
3573     assert(RefExpr && "NULL expr in OpenMP linear clause.");
3574     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3575       // It will be analyzed later.
3576       Vars.push_back(RefExpr);
3577       continue;
3578     }
3579 
3580     // OpenMP [2.14.3.7, linear clause]
3581     // A list item that appears in a linear clause is subject to the private
3582     // clause semantics described in Section 2.14.3.3 on page 159 except as
3583     // noted. In addition, the value of the new list item on each iteration
3584     // of the associated loop(s) corresponds to the value of the original
3585     // list item before entering the construct plus the logical number of
3586     // the iteration times linear-step.
3587 
3588     SourceLocation ELoc = RefExpr->getExprLoc();
3589     // OpenMP [2.1, C/C++]
3590     //  A list item is a variable name.
3591     // OpenMP  [2.14.3.3, Restrictions, p.1]
3592     //  A variable that is part of another variable (as an array or
3593     //  structure element) cannot appear in a private clause.
3594     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3595     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3596       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3597       continue;
3598     }
3599 
3600     VarDecl *VD = cast<VarDecl>(DE->getDecl());
3601 
3602     // OpenMP [2.14.3.7, linear clause]
3603     //  A list-item cannot appear in more than one linear clause.
3604     //  A list-item that appears in a linear clause cannot appear in any
3605     //  other data-sharing attribute clause.
3606     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
3607     if (DVar.RefExpr) {
3608       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
3609                                           << getOpenMPClauseName(OMPC_linear);
3610       ReportOriginalDSA(*this, DSAStack, VD, DVar);
3611       continue;
3612     }
3613 
3614     QualType QType = VD->getType();
3615     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
3616       // It will be analyzed later.
3617       Vars.push_back(DE);
3618       continue;
3619     }
3620 
3621     // A variable must not have an incomplete type or a reference type.
3622     if (RequireCompleteType(ELoc, QType,
3623                             diag::err_omp_linear_incomplete_type)) {
3624       continue;
3625     }
3626     if (QType->isReferenceType()) {
3627       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
3628           << getOpenMPClauseName(OMPC_linear) << QType;
3629       bool IsDecl =
3630           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3631       Diag(VD->getLocation(),
3632            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3633           << VD;
3634       continue;
3635     }
3636 
3637     // A list item must not be const-qualified.
3638     if (QType.isConstant(Context)) {
3639       Diag(ELoc, diag::err_omp_const_variable)
3640           << getOpenMPClauseName(OMPC_linear);
3641       bool IsDecl =
3642           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3643       Diag(VD->getLocation(),
3644            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3645           << VD;
3646       continue;
3647     }
3648 
3649     // A list item must be of integral or pointer type.
3650     QType = QType.getUnqualifiedType().getCanonicalType();
3651     const Type *Ty = QType.getTypePtrOrNull();
3652     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
3653                 !Ty->isPointerType())) {
3654       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
3655       bool IsDecl =
3656           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3657       Diag(VD->getLocation(),
3658            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3659           << VD;
3660       continue;
3661     }
3662 
3663     DSAStack->addDSA(VD, DE, OMPC_linear);
3664     Vars.push_back(DE);
3665   }
3666 
3667   if (Vars.empty())
3668     return nullptr;
3669 
3670   Expr *StepExpr = Step;
3671   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3672       !Step->isInstantiationDependent() &&
3673       !Step->containsUnexpandedParameterPack()) {
3674     SourceLocation StepLoc = Step->getLocStart();
3675     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
3676     if (Val.isInvalid())
3677       return nullptr;
3678     StepExpr = Val.get();
3679 
3680     // Warn about zero linear step (it would be probably better specified as
3681     // making corresponding variables 'const').
3682     llvm::APSInt Result;
3683     if (StepExpr->isIntegerConstantExpr(Result, Context) &&
3684         !Result.isNegative() && !Result.isStrictlyPositive())
3685       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
3686                                                      << (Vars.size() > 1);
3687   }
3688 
3689   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
3690                                  Vars, StepExpr);
3691 }
3692 
3693 OMPClause *Sema::ActOnOpenMPAlignedClause(
3694     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
3695     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
3696 
3697   SmallVector<Expr *, 8> Vars;
3698   for (auto &RefExpr : VarList) {
3699     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
3700     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3701       // It will be analyzed later.
3702       Vars.push_back(RefExpr);
3703       continue;
3704     }
3705 
3706     SourceLocation ELoc = RefExpr->getExprLoc();
3707     // OpenMP [2.1, C/C++]
3708     //  A list item is a variable name.
3709     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3710     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3711       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3712       continue;
3713     }
3714 
3715     VarDecl *VD = cast<VarDecl>(DE->getDecl());
3716 
3717     // OpenMP  [2.8.1, simd construct, Restrictions]
3718     // The type of list items appearing in the aligned clause must be
3719     // array, pointer, reference to array, or reference to pointer.
3720     QualType QType = DE->getType()
3721                          .getNonReferenceType()
3722                          .getUnqualifiedType()
3723                          .getCanonicalType();
3724     const Type *Ty = QType.getTypePtrOrNull();
3725     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
3726                 !Ty->isPointerType())) {
3727       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
3728           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
3729       bool IsDecl =
3730           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3731       Diag(VD->getLocation(),
3732            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3733           << VD;
3734       continue;
3735     }
3736 
3737     // OpenMP  [2.8.1, simd construct, Restrictions]
3738     // A list-item cannot appear in more than one aligned clause.
3739     if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
3740       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
3741       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
3742           << getOpenMPClauseName(OMPC_aligned);
3743       continue;
3744     }
3745 
3746     Vars.push_back(DE);
3747   }
3748 
3749   // OpenMP [2.8.1, simd construct, Description]
3750   // The parameter of the aligned clause, alignment, must be a constant
3751   // positive integer expression.
3752   // If no optional parameter is specified, implementation-defined default
3753   // alignments for SIMD instructions on the target platforms are assumed.
3754   if (Alignment != nullptr) {
3755     ExprResult AlignResult =
3756         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
3757     if (AlignResult.isInvalid())
3758       return nullptr;
3759     Alignment = AlignResult.get();
3760   }
3761   if (Vars.empty())
3762     return nullptr;
3763 
3764   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
3765                                   EndLoc, Vars, Alignment);
3766 }
3767 
3768 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
3769                                          SourceLocation StartLoc,
3770                                          SourceLocation LParenLoc,
3771                                          SourceLocation EndLoc) {
3772   SmallVector<Expr *, 8> Vars;
3773   for (auto &RefExpr : VarList) {
3774     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
3775     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3776       // It will be analyzed later.
3777       Vars.push_back(RefExpr);
3778       continue;
3779     }
3780 
3781     SourceLocation ELoc = RefExpr->getExprLoc();
3782     // OpenMP [2.1, C/C++]
3783     //  A list item is a variable name.
3784     // OpenMP  [2.14.4.1, Restrictions, p.1]
3785     //  A list item that appears in a copyin clause must be threadprivate.
3786     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3787     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3788       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3789       continue;
3790     }
3791 
3792     Decl *D = DE->getDecl();
3793     VarDecl *VD = cast<VarDecl>(D);
3794 
3795     QualType Type = VD->getType();
3796     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3797       // It will be analyzed later.
3798       Vars.push_back(DE);
3799       continue;
3800     }
3801 
3802     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
3803     //  A list item that appears in a copyin clause must be threadprivate.
3804     if (!DSAStack->isThreadPrivate(VD)) {
3805       Diag(ELoc, diag::err_omp_required_access)
3806           << getOpenMPClauseName(OMPC_copyin)
3807           << getOpenMPDirectiveName(OMPD_threadprivate);
3808       continue;
3809     }
3810 
3811     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
3812     //  A variable of class type (or array thereof) that appears in a
3813     //  copyin clause requires an accessible, unambiguous copy assignment
3814     //  operator for the class type.
3815     Type = Context.getBaseElementType(Type);
3816     CXXRecordDecl *RD =
3817         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
3818     // FIXME This code must be replaced by actual assignment of the
3819     // threadprivate variable.
3820     if (RD) {
3821       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
3822       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
3823       if (MD) {
3824         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
3825             MD->isDeleted()) {
3826           Diag(ELoc, diag::err_omp_required_method)
3827               << getOpenMPClauseName(OMPC_copyin) << 2;
3828           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3829                         VarDecl::DeclarationOnly;
3830           Diag(VD->getLocation(),
3831                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3832               << VD;
3833           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3834           continue;
3835         }
3836         MarkFunctionReferenced(ELoc, MD);
3837         DiagnoseUseOfDecl(MD, ELoc);
3838       }
3839     }
3840 
3841     DSAStack->addDSA(VD, DE, OMPC_copyin);
3842     Vars.push_back(DE);
3843   }
3844 
3845   if (Vars.empty())
3846     return nullptr;
3847 
3848   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3849 }
3850 
3851 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
3852                                               SourceLocation StartLoc,
3853                                               SourceLocation LParenLoc,
3854                                               SourceLocation EndLoc) {
3855   SmallVector<Expr *, 8> Vars;
3856   for (auto &RefExpr : VarList) {
3857     assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
3858     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
3859       // It will be analyzed later.
3860       Vars.push_back(RefExpr);
3861       continue;
3862     }
3863 
3864     SourceLocation ELoc = RefExpr->getExprLoc();
3865     // OpenMP [2.1, C/C++]
3866     //  A list item is a variable name.
3867     // OpenMP  [2.14.4.1, Restrictions, p.1]
3868     //  A list item that appears in a copyin clause must be threadprivate.
3869     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
3870     if (!DE || !isa<VarDecl>(DE->getDecl())) {
3871       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
3872       continue;
3873     }
3874 
3875     Decl *D = DE->getDecl();
3876     VarDecl *VD = cast<VarDecl>(D);
3877 
3878     QualType Type = VD->getType();
3879     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
3880       // It will be analyzed later.
3881       Vars.push_back(DE);
3882       continue;
3883     }
3884 
3885     // OpenMP [2.14.4.2, Restrictions, p.2]
3886     //  A list item that appears in a copyprivate clause may not appear in a
3887     //  private or firstprivate clause on the single construct.
3888     if (!DSAStack->isThreadPrivate(VD)) {
3889       auto DVar = DSAStack->getTopDSA(VD, false);
3890       if (DVar.CKind != OMPC_copyprivate && DVar.CKind != OMPC_unknown &&
3891           !(DVar.CKind == OMPC_private && !DVar.RefExpr)) {
3892         Diag(ELoc, diag::err_omp_wrong_dsa)
3893             << getOpenMPClauseName(DVar.CKind)
3894             << getOpenMPClauseName(OMPC_copyprivate);
3895         ReportOriginalDSA(*this, DSAStack, VD, DVar);
3896         continue;
3897       }
3898 
3899       // OpenMP [2.11.4.2, Restrictions, p.1]
3900       //  All list items that appear in a copyprivate clause must be either
3901       //  threadprivate or private in the enclosing context.
3902       if (DVar.CKind == OMPC_unknown) {
3903         DVar = DSAStack->getImplicitDSA(VD, false);
3904         if (DVar.CKind == OMPC_shared) {
3905           Diag(ELoc, diag::err_omp_required_access)
3906               << getOpenMPClauseName(OMPC_copyprivate)
3907               << "threadprivate or private in the enclosing context";
3908           ReportOriginalDSA(*this, DSAStack, VD, DVar);
3909           continue;
3910         }
3911       }
3912     }
3913 
3914     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
3915     //  A variable of class type (or array thereof) that appears in a
3916     //  copyin clause requires an accessible, unambiguous copy assignment
3917     //  operator for the class type.
3918     Type = Context.getBaseElementType(Type);
3919     CXXRecordDecl *RD =
3920         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
3921     // FIXME This code must be replaced by actual assignment of the
3922     // threadprivate variable.
3923     if (RD) {
3924       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
3925       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
3926       if (MD) {
3927         if (CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
3928             MD->isDeleted()) {
3929           Diag(ELoc, diag::err_omp_required_method)
3930               << getOpenMPClauseName(OMPC_copyprivate) << 2;
3931           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3932                         VarDecl::DeclarationOnly;
3933           Diag(VD->getLocation(),
3934                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3935               << VD;
3936           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
3937           continue;
3938         }
3939         MarkFunctionReferenced(ELoc, MD);
3940         DiagnoseUseOfDecl(MD, ELoc);
3941       }
3942     }
3943 
3944     // No need to mark vars as copyprivate, they are already threadprivate or
3945     // implicitly private.
3946     Vars.push_back(DE);
3947   }
3948 
3949   if (Vars.empty())
3950     return nullptr;
3951 
3952   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
3953 }
3954 
3955 #undef DSAStack
3956