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