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/Basic/OpenMPKinds.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/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 using namespace clang;
29 
30 //===----------------------------------------------------------------------===//
31 // Stack of data-sharing attributes for variables
32 //===----------------------------------------------------------------------===//
33 
34 namespace {
35 /// \brief Default data sharing attributes, which can be applied to directive.
36 enum DefaultDataSharingAttributes {
37   DSA_unspecified = 0,   /// \brief Data sharing attribute not specified.
38   DSA_none = 1 << 0,     /// \brief Default data sharing attribute 'none'.
39   DSA_shared = 1 << 1    /// \brief Default data sharing attribute 'shared'.
40 };
41 
42 /// \brief Stack for tracking declarations used in OpenMP directives and
43 /// clauses and their data-sharing attributes.
44 class DSAStackTy {
45 public:
46   struct DSAVarData {
47     OpenMPDirectiveKind DKind;
48     OpenMPClauseKind CKind;
49     DeclRefExpr *RefExpr;
50     DSAVarData() : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(0) { }
51   };
52 private:
53   struct DSAInfo {
54     OpenMPClauseKind Attributes;
55     DeclRefExpr *RefExpr;
56   };
57   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
58 
59   struct SharingMapTy {
60     DeclSAMapTy SharingMap;
61     DefaultDataSharingAttributes DefaultAttr;
62     OpenMPDirectiveKind Directive;
63     DeclarationNameInfo DirectiveName;
64     Scope *CurScope;
65     SharingMapTy(OpenMPDirectiveKind DKind,
66                  const DeclarationNameInfo &Name,
67                  Scope *CurScope)
68       : SharingMap(), DefaultAttr(DSA_unspecified), Directive(DKind),
69         DirectiveName(Name), CurScope(CurScope) { }
70     SharingMapTy()
71       : SharingMap(), DefaultAttr(DSA_unspecified),
72         Directive(OMPD_unknown), DirectiveName(),
73         CurScope(0) { }
74   };
75 
76   typedef SmallVector<SharingMapTy, 64> StackTy;
77 
78   /// \brief Stack of used declaration and their data-sharing attributes.
79   StackTy Stack;
80   Sema &Actions;
81 
82   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
83 
84   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
85 
86   /// \brief Checks if the variable is a local for OpenMP region.
87   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
88 public:
89   explicit DSAStackTy(Sema &S) : Stack(1), Actions(S) { }
90 
91   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
92             Scope *CurScope) {
93     Stack.push_back(SharingMapTy(DKind, DirName, CurScope));
94   }
95 
96   void pop() {
97     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
98     Stack.pop_back();
99   }
100 
101   /// \brief Adds explicit data sharing attribute to the specified declaration.
102   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
103 
104   /// \brief Returns data sharing attributes from top of the stack for the
105   /// specified declaration.
106   DSAVarData getTopDSA(VarDecl *D);
107   /// \brief Returns data-sharing attributes for the specified declaration.
108   DSAVarData getImplicitDSA(VarDecl *D);
109   /// \brief Checks if the specified variables has \a CKind data-sharing
110   /// attribute in \a DKind directive.
111   DSAVarData hasDSA(VarDecl *D, OpenMPClauseKind CKind,
112                     OpenMPDirectiveKind DKind = OMPD_unknown);
113 
114   /// \brief Returns currently analyzed directive.
115   OpenMPDirectiveKind getCurrentDirective() const {
116     return Stack.back().Directive;
117   }
118 
119   /// \brief Set default data sharing attribute to none.
120   void setDefaultDSANone() { Stack.back().DefaultAttr = DSA_none; }
121   /// \brief Set default data sharing attribute to shared.
122   void setDefaultDSAShared() { Stack.back().DefaultAttr = DSA_shared; }
123 
124   DefaultDataSharingAttributes getDefaultDSA() const {
125     return Stack.back().DefaultAttr;
126   }
127 
128   /// \brief Checks if the spewcified variable is threadprivate.
129   bool isThreadPrivate(VarDecl *D) {
130     DSAVarData DVar = getTopDSA(D);
131     return (DVar.CKind == OMPC_threadprivate || DVar.CKind == OMPC_copyin);
132   }
133 
134   Scope *getCurScope() const { return Stack.back().CurScope; }
135   Scope *getCurScope() { return Stack.back().CurScope; }
136 };
137 } // end anonymous namespace.
138 
139 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
140                                           VarDecl *D) {
141   DSAVarData DVar;
142   if (Iter == Stack.rend() - 1) {
143     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
144     // in a region but not in construct]
145     //  File-scope or namespace-scope variables referenced in called routines
146     //  in the region are shared unless they appear in a threadprivate
147     //  directive.
148     // TODO
149     if (!D->isFunctionOrMethodVarDecl())
150       DVar.CKind = OMPC_shared;
151 
152     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
153     // in a region but not in construct]
154     //  Variables with static storage duration that are declared in called
155     //  routines in the region are shared.
156     if (D->hasGlobalStorage())
157       DVar.CKind = OMPC_shared;
158 
159     return DVar;
160   }
161 
162   DVar.DKind = Iter->Directive;
163   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
164   // in a Construct, C/C++, predetermined, p.1]
165   // Variables with automatic storage duration that are declared in a scope
166   // inside the construct are private.
167   if (DVar.DKind != OMPD_parallel) {
168     if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
169         (D->getStorageClass() == SC_Auto ||
170          D->getStorageClass() == SC_None)) {
171       DVar.CKind = OMPC_private;
172       return DVar;
173     }
174   }
175 
176   // Explicitly specified attributes and local variables with predetermined
177   // attributes.
178   if (Iter->SharingMap.count(D)) {
179     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
180     DVar.CKind = Iter->SharingMap[D].Attributes;
181     return DVar;
182   }
183 
184   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
185   // in a Construct, C/C++, implicitly determined, p.1]
186   //  In a parallel or task construct, the data-sharing attributes of these
187   //  variables are determined by the default clause, if present.
188   switch (Iter->DefaultAttr) {
189   case DSA_shared:
190     DVar.CKind = OMPC_shared;
191     return DVar;
192   case DSA_none:
193     return DVar;
194   case DSA_unspecified:
195     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
196     // in a Construct, implicitly determined, p.2]
197     //  In a parallel construct, if no default clause is present, these
198     //  variables are shared.
199     if (DVar.DKind == OMPD_parallel) {
200       DVar.CKind = OMPC_shared;
201       return DVar;
202     }
203 
204     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
205     // in a Construct, implicitly determined, p.4]
206     //  In a task construct, if no default clause is present, a variable that in
207     //  the enclosing context is determined to be shared by all implicit tasks
208     //  bound to the current team is shared.
209     // TODO
210     if (DVar.DKind == OMPD_task) {
211       DSAVarData DVarTemp;
212       for (StackTy::reverse_iterator I = std::next(Iter),
213                                      EE = std::prev(Stack.rend());
214            I != EE; ++I) {
215         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
216         // in a Construct, implicitly determined, p.6]
217         //  In a task construct, if no default clause is present, a variable
218         //  whose data-sharing attribute is not determined by the rules above is
219         //  firstprivate.
220         DVarTemp = getDSA(I, D);
221         if (DVarTemp.CKind != OMPC_shared) {
222           DVar.RefExpr = 0;
223           DVar.DKind = OMPD_task;
224           DVar.CKind = OMPC_firstprivate;
225           return DVar;
226         }
227         if (I->Directive == OMPD_parallel) break;
228       }
229       DVar.DKind = OMPD_task;
230       DVar.CKind =
231         (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
232       return DVar;
233     }
234   }
235   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
236   // in a Construct, implicitly determined, p.3]
237   //  For constructs other than task, if no default clause is present, these
238   //  variables inherit their data-sharing attributes from the enclosing
239   //  context.
240   return getDSA(std::next(Iter), D);
241 }
242 
243 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
244   if (A == OMPC_threadprivate) {
245     Stack[0].SharingMap[D].Attributes = A;
246     Stack[0].SharingMap[D].RefExpr = E;
247   } else {
248     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
249     Stack.back().SharingMap[D].Attributes = A;
250     Stack.back().SharingMap[D].RefExpr = E;
251   }
252 }
253 
254 bool
255 DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
256   if (Stack.size() > 2) {
257     reverse_iterator I = Iter, E = Stack.rend() - 1;
258     Scope *TopScope = 0;
259     while (I != E && I->Directive != OMPD_parallel) {
260       ++I;
261     }
262     if (I == E) return false;
263     TopScope = I->CurScope ? I->CurScope->getParent() : 0;
264     Scope *CurScope = getCurScope();
265     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
266       CurScope = CurScope->getParent();
267     }
268     return CurScope != TopScope;
269   }
270   return false;
271 }
272 
273 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D) {
274   DSAVarData DVar;
275 
276   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
277   // in a Construct, C/C++, predetermined, p.1]
278   //  Variables appearing in threadprivate directives are threadprivate.
279   if (D->getTLSKind() != VarDecl::TLS_None) {
280     DVar.CKind = OMPC_threadprivate;
281     return DVar;
282   }
283   if (Stack[0].SharingMap.count(D)) {
284     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
285     DVar.CKind = OMPC_threadprivate;
286     return DVar;
287   }
288 
289   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
290   // in a Construct, C/C++, predetermined, p.1]
291   // Variables with automatic storage duration that are declared in a scope
292   // inside the construct are private.
293   OpenMPDirectiveKind Kind = getCurrentDirective();
294   if (Kind != OMPD_parallel) {
295     if (isOpenMPLocal(D, std::next(Stack.rbegin())) && D->isLocalVarDecl() &&
296         (D->getStorageClass() == SC_Auto ||
297          D->getStorageClass() == SC_None))
298       DVar.CKind = OMPC_private;
299       return DVar;
300   }
301 
302   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
303   // in a Construct, C/C++, predetermined, p.4]
304   //  Static data memebers are shared.
305   if (D->isStaticDataMember()) {
306     // Variables with const-qualified type having no mutable member may be listed
307     // in a firstprivate clause, even if they are static data members.
308     DSAVarData DVarTemp = hasDSA(D, OMPC_firstprivate);
309     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
310       return DVar;
311 
312     DVar.CKind = OMPC_shared;
313     return DVar;
314   }
315 
316   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
317   bool IsConstant = Type.isConstant(Actions.getASTContext());
318   while (Type->isArrayType()) {
319     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
320     Type = ElemType.getNonReferenceType().getCanonicalType();
321   }
322   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
323   // in a Construct, C/C++, predetermined, p.6]
324   //  Variables with const qualified type having no mutable member are
325   //  shared.
326   CXXRecordDecl *RD = Actions.getLangOpts().CPlusPlus ?
327                                 Type->getAsCXXRecordDecl() : 0;
328   if (IsConstant &&
329       !(Actions.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
330     // Variables with const-qualified type having no mutable member may be
331     // listed in a firstprivate clause, even if they are static data members.
332     DSAVarData DVarTemp = hasDSA(D, OMPC_firstprivate);
333     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
334       return DVar;
335 
336     DVar.CKind = OMPC_shared;
337     return DVar;
338   }
339 
340   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
341   // in a Construct, C/C++, predetermined, p.7]
342   //  Variables with static storage duration that are declared in a scope
343   //  inside the construct are shared.
344   if (D->isStaticLocal()) {
345     DVar.CKind = OMPC_shared;
346     return DVar;
347   }
348 
349   // Explicitly specified attributes and local variables with predetermined
350   // attributes.
351   if (Stack.back().SharingMap.count(D)) {
352     DVar.RefExpr = Stack.back().SharingMap[D].RefExpr;
353     DVar.CKind = Stack.back().SharingMap[D].Attributes;
354   }
355 
356   return DVar;
357 }
358 
359 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D) {
360   return getDSA(std::next(Stack.rbegin()), D);
361 }
362 
363 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, OpenMPClauseKind CKind,
364                                           OpenMPDirectiveKind DKind) {
365   for (StackTy::reverse_iterator I = std::next(Stack.rbegin()),
366                                  E = std::prev(Stack.rend());
367        I != E; ++I) {
368     if (DKind != OMPD_unknown && DKind != I->Directive) continue;
369     DSAVarData DVar = getDSA(I, D);
370     if (DVar.CKind == CKind)
371       return DVar;
372   }
373   return DSAVarData();
374 }
375 
376 void Sema::InitDataSharingAttributesStack() {
377   VarDataSharingAttributesStack = new DSAStackTy(*this);
378 }
379 
380 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
381 
382 void Sema::DestroyDataSharingAttributesStack() {
383   delete DSAStack;
384 }
385 
386 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
387                                const DeclarationNameInfo &DirName,
388                                Scope *CurScope) {
389   DSAStack->push(DKind, DirName, CurScope);
390   PushExpressionEvaluationContext(PotentiallyEvaluated);
391 }
392 
393 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
394   DSAStack->pop();
395   DiscardCleanupsInEvaluationContext();
396   PopExpressionEvaluationContext();
397 }
398 
399 namespace {
400 
401 class VarDeclFilterCCC : public CorrectionCandidateCallback {
402 private:
403   Sema &Actions;
404 public:
405   VarDeclFilterCCC(Sema &S) : Actions(S) { }
406   bool ValidateCandidate(const TypoCorrection &Candidate) override {
407     NamedDecl *ND = Candidate.getCorrectionDecl();
408     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
409       return VD->hasGlobalStorage() &&
410              Actions.isDeclInScope(ND, Actions.getCurLexicalContext(),
411                                    Actions.getCurScope());
412     }
413     return false;
414   }
415 };
416 }
417 
418 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
419                                          CXXScopeSpec &ScopeSpec,
420                                          const DeclarationNameInfo &Id) {
421   LookupResult Lookup(*this, Id, LookupOrdinaryName);
422   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
423 
424   if (Lookup.isAmbiguous())
425     return ExprError();
426 
427   VarDecl *VD;
428   if (!Lookup.isSingleResult()) {
429     VarDeclFilterCCC Validator(*this);
430     if (TypoCorrection Corrected = CorrectTypo(Id, LookupOrdinaryName, CurScope,
431                                                0, Validator)) {
432       diagnoseTypo(Corrected,
433                    PDiag(Lookup.empty()? diag::err_undeclared_var_use_suggest
434                                        : diag::err_omp_expected_var_arg_suggest)
435                      << Id.getName());
436       VD = Corrected.getCorrectionDeclAs<VarDecl>();
437     } else {
438       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
439                                        : diag::err_omp_expected_var_arg)
440           << Id.getName();
441       return ExprError();
442     }
443   } else {
444     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
445       Diag(Id.getLoc(), diag::err_omp_expected_var_arg)
446         << Id.getName();
447       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
448       return ExprError();
449     }
450   }
451   Lookup.suppressDiagnostics();
452 
453   // OpenMP [2.9.2, Syntax, C/C++]
454   //   Variables must be file-scope, namespace-scope, or static block-scope.
455   if (!VD->hasGlobalStorage()) {
456     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
457       << getOpenMPDirectiveName(OMPD_threadprivate)
458       << !VD->isStaticLocal();
459     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
460                   VarDecl::DeclarationOnly;
461     Diag(VD->getLocation(),
462          IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD;
463     return ExprError();
464   }
465 
466   VarDecl *CanonicalVD = VD->getCanonicalDecl();
467   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
468   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
469   //   A threadprivate directive for file-scope variables must appear outside
470   //   any definition or declaration.
471   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
472       !getCurLexicalContext()->isTranslationUnit()) {
473     Diag(Id.getLoc(), diag::err_omp_var_scope)
474       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
475     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
476                   VarDecl::DeclarationOnly;
477     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
478                                      diag::note_defined_here) << VD;
479     return ExprError();
480   }
481   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
482   //   A threadprivate directive for static class member variables must appear
483   //   in the class definition, in the same scope in which the member
484   //   variables are declared.
485   if (CanonicalVD->isStaticDataMember() &&
486       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
487     Diag(Id.getLoc(), diag::err_omp_var_scope)
488       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
489     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
490                   VarDecl::DeclarationOnly;
491     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
492                                      diag::note_defined_here) << VD;
493     return ExprError();
494   }
495   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
496   //   A threadprivate directive for namespace-scope variables must appear
497   //   outside any definition or declaration other than the namespace
498   //   definition itself.
499   if (CanonicalVD->getDeclContext()->isNamespace() &&
500       (!getCurLexicalContext()->isFileContext() ||
501        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
502     Diag(Id.getLoc(), diag::err_omp_var_scope)
503       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
504     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
505                   VarDecl::DeclarationOnly;
506     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
507                                      diag::note_defined_here) << VD;
508     return ExprError();
509   }
510   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
511   //   A threadprivate directive for static block-scope variables must appear
512   //   in the scope of the variable and not in a nested scope.
513   if (CanonicalVD->isStaticLocal() && CurScope &&
514       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
515     Diag(Id.getLoc(), diag::err_omp_var_scope)
516       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
517     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
518                   VarDecl::DeclarationOnly;
519     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
520                                      diag::note_defined_here) << VD;
521     return ExprError();
522   }
523 
524   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
525   //   A threadprivate directive must lexically precede all references to any
526   //   of the variables in its list.
527   if (VD->isUsed()) {
528     Diag(Id.getLoc(), diag::err_omp_var_used)
529       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
530     return ExprError();
531   }
532 
533   QualType ExprType = VD->getType().getNonReferenceType();
534   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
535   return DE;
536 }
537 
538 Sema::DeclGroupPtrTy Sema::ActOnOpenMPThreadprivateDirective(
539                                 SourceLocation Loc,
540                                 ArrayRef<Expr *> VarList) {
541   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
542     CurContext->addDecl(D);
543     return DeclGroupPtrTy::make(DeclGroupRef(D));
544   }
545   return DeclGroupPtrTy();
546 }
547 
548 OMPThreadPrivateDecl *Sema::CheckOMPThreadPrivateDecl(
549                                  SourceLocation Loc,
550                                  ArrayRef<Expr *> VarList) {
551   SmallVector<Expr *, 8> Vars;
552   for (ArrayRef<Expr *>::iterator I = VarList.begin(),
553                                          E = VarList.end();
554        I != E; ++I) {
555     DeclRefExpr *DE = cast<DeclRefExpr>(*I);
556     VarDecl *VD = cast<VarDecl>(DE->getDecl());
557     SourceLocation ILoc = DE->getExprLoc();
558 
559     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
560     //   A threadprivate variable must not have an incomplete type.
561     if (RequireCompleteType(ILoc, VD->getType(),
562                             diag::err_omp_threadprivate_incomplete_type)) {
563       continue;
564     }
565 
566     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
567     //   A threadprivate variable must not have a reference type.
568     if (VD->getType()->isReferenceType()) {
569       Diag(ILoc, diag::err_omp_ref_type_arg)
570         << getOpenMPDirectiveName(OMPD_threadprivate)
571         << VD->getType();
572       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
573                     VarDecl::DeclarationOnly;
574       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
575                                        diag::note_defined_here) << VD;
576       continue;
577     }
578 
579     // Check if this is a TLS variable.
580     if (VD->getTLSKind()) {
581       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
582       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
583                     VarDecl::DeclarationOnly;
584       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
585                                        diag::note_defined_here) << VD;
586       continue;
587     }
588 
589     Vars.push_back(*I);
590     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
591   }
592   OMPThreadPrivateDecl *D = 0;
593   if (!Vars.empty()) {
594     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
595                                      Vars);
596     D->setAccess(AS_public);
597   }
598   return D;
599 }
600 
601 namespace {
602 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
603   DSAStackTy *Stack;
604   Sema &Actions;
605   bool ErrorFound;
606   CapturedStmt *CS;
607   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
608 public:
609   void VisitDeclRefExpr(DeclRefExpr *E) {
610     if(VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
611       // Skip internally declared variables.
612       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) return;
613 
614       SourceLocation ELoc = E->getExprLoc();
615 
616       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
617       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD);
618       if (DVar.CKind != OMPC_unknown) {
619         if (DKind == OMPD_task && DVar.CKind != OMPC_shared &&
620             !Stack->isThreadPrivate(VD) && !DVar.RefExpr)
621           ImplicitFirstprivate.push_back(DVar.RefExpr);
622         return;
623       }
624       // The default(none) clause requires that each variable that is referenced
625       // in the construct, and does not have a predetermined data-sharing
626       // attribute, must have its data-sharing attribute explicitly determined
627       // by being listed in a data-sharing attribute clause.
628       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
629           (DKind == OMPD_parallel || DKind == OMPD_task)) {
630         ErrorFound = true;
631         Actions.Diag(ELoc, diag::err_omp_no_dsa_for_variable) << VD;
632         return;
633       }
634 
635       // OpenMP [2.9.3.6, Restrictions, p.2]
636       //  A list item that appears in a reduction clause of the innermost
637       //  enclosing worksharing or parallel construct may not be accessed in an
638       //  explicit task.
639       // TODO:
640 
641       // Define implicit data-sharing attributes for task.
642       DVar = Stack->getImplicitDSA(VD);
643       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
644         ImplicitFirstprivate.push_back(DVar.RefExpr);
645     }
646   }
647   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
648     for (ArrayRef<OMPClause *>::iterator I = S->clauses().begin(),
649                                          E = S->clauses().end();
650          I != E; ++I)
651       if (OMPClause *C = *I)
652         for (StmtRange R = C->children(); R; ++R)
653           if (Stmt *Child = *R)
654             Visit(Child);
655   }
656   void VisitStmt(Stmt *S) {
657     for (Stmt::child_iterator I = S->child_begin(), E = S->child_end();
658          I != E; ++I)
659       if (Stmt *Child = *I)
660         if (!isa<OMPExecutableDirective>(Child))
661           Visit(Child);
662     }
663 
664   bool isErrorFound() { return ErrorFound; }
665   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
666 
667   DSAAttrChecker(DSAStackTy *S, Sema &Actions, CapturedStmt *CS)
668     : Stack(S), Actions(Actions), ErrorFound(false), CS(CS) { }
669 };
670 }
671 
672 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
673                                                 ArrayRef<OMPClause *> Clauses,
674                                                 Stmt *AStmt,
675                                                 SourceLocation StartLoc,
676                                                 SourceLocation EndLoc) {
677   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
678 
679   StmtResult Res = StmtError();
680 
681   // Check default data sharing attributes for referenced variables.
682   DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
683   DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
684   if (DSAChecker.isErrorFound())
685     return StmtError();
686   // Generate list of implicitly defined firstprivate variables.
687   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
688   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
689 
690   bool ErrorFound = false;
691   if (!DSAChecker.getImplicitFirstprivate().empty()) {
692     if (OMPClause *Implicit =
693          ActOnOpenMPFirstprivateClause(DSAChecker.getImplicitFirstprivate(),
694                                        SourceLocation(), SourceLocation(),
695                                        SourceLocation())) {
696       ClausesWithImplicit.push_back(Implicit);
697       ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
698                                     DSAChecker.getImplicitFirstprivate().size();
699     } else
700       ErrorFound = true;
701   }
702 
703   switch (Kind) {
704   case OMPD_parallel:
705     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt,
706                                        StartLoc, EndLoc);
707     break;
708   case OMPD_simd:
709     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt,
710                                    StartLoc, EndLoc);
711     break;
712   case OMPD_threadprivate:
713   case OMPD_task:
714     llvm_unreachable("OpenMP Directive is not allowed");
715   case OMPD_unknown:
716   case NUM_OPENMP_DIRECTIVES:
717     llvm_unreachable("Unknown OpenMP directive");
718   }
719 
720   if (ErrorFound) return StmtError();
721   return Res;
722 }
723 
724 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
725                                               Stmt *AStmt,
726                                               SourceLocation StartLoc,
727                                               SourceLocation EndLoc) {
728   getCurFunction()->setHasBranchProtectedScope();
729 
730   return Owned(OMPParallelDirective::Create(Context, StartLoc, EndLoc,
731                                             Clauses, AStmt));
732 }
733 
734 StmtResult Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses,
735                                           Stmt *AStmt,
736                                           SourceLocation StartLoc,
737                                           SourceLocation EndLoc) {
738   Stmt *CStmt = AStmt;
739   while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(CStmt))
740     CStmt = CS->getCapturedStmt();
741   while (AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(CStmt))
742     CStmt = AS->getSubStmt();
743   ForStmt *For = dyn_cast<ForStmt>(CStmt);
744   if (!For) {
745     Diag(CStmt->getLocStart(), diag::err_omp_not_for)
746       << getOpenMPDirectiveName(OMPD_simd);
747     return StmtError();
748   }
749 
750   // FIXME: Checking loop canonical form, collapsing etc.
751 
752   getCurFunction()->setHasBranchProtectedScope();
753   return Owned(OMPSimdDirective::Create(Context, StartLoc, EndLoc,
754                                         Clauses, AStmt));
755 }
756 
757 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
758                                              Expr *Expr,
759                                              SourceLocation StartLoc,
760                                              SourceLocation LParenLoc,
761                                              SourceLocation EndLoc) {
762   OMPClause *Res = 0;
763   switch (Kind) {
764   case OMPC_if:
765     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
766     break;
767   case OMPC_num_threads:
768     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
769     break;
770   case OMPC_safelen:
771     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
772     break;
773   case OMPC_default:
774   case OMPC_private:
775   case OMPC_firstprivate:
776   case OMPC_shared:
777   case OMPC_copyin:
778   case OMPC_threadprivate:
779   case OMPC_unknown:
780   case NUM_OPENMP_CLAUSES:
781     llvm_unreachable("Clause is not allowed.");
782   }
783   return Res;
784 }
785 
786 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition,
787                                      SourceLocation StartLoc,
788                                      SourceLocation LParenLoc,
789                                      SourceLocation EndLoc) {
790   Expr *ValExpr = Condition;
791   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
792       !Condition->isInstantiationDependent() &&
793       !Condition->containsUnexpandedParameterPack()) {
794     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
795                                            Condition->getExprLoc(),
796                                            Condition);
797     if (Val.isInvalid())
798       return 0;
799 
800     ValExpr = Val.take();
801   }
802 
803   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
804 }
805 
806 ExprResult Sema::PerformImplicitIntegerConversion(SourceLocation Loc,
807                                                   Expr *Op) {
808   if (!Op)
809     return ExprError();
810 
811   class IntConvertDiagnoser : public ICEConvertDiagnoser {
812   public:
813     IntConvertDiagnoser()
814         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
815                               false, true) {}
816     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
817                                          QualType T) override {
818       return S.Diag(Loc, diag::err_omp_not_integral) << T;
819     }
820     SemaDiagnosticBuilder diagnoseIncomplete(
821         Sema &S, SourceLocation Loc, QualType T) override {
822       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
823     }
824     SemaDiagnosticBuilder diagnoseExplicitConv(
825         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
826       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
827     }
828     SemaDiagnosticBuilder noteExplicitConv(
829         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
830       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
831                << ConvTy->isEnumeralType() << ConvTy;
832     }
833     SemaDiagnosticBuilder diagnoseAmbiguous(
834         Sema &S, SourceLocation Loc, QualType T) override {
835       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
836     }
837     SemaDiagnosticBuilder noteAmbiguous(
838         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
839       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
840                << ConvTy->isEnumeralType() << ConvTy;
841     }
842     SemaDiagnosticBuilder diagnoseConversion(
843         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
844       llvm_unreachable("conversion functions are permitted");
845     }
846   } ConvertDiagnoser;
847   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
848 }
849 
850 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
851                                              SourceLocation StartLoc,
852                                              SourceLocation LParenLoc,
853                                              SourceLocation EndLoc) {
854   Expr *ValExpr = NumThreads;
855   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
856       !NumThreads->isInstantiationDependent() &&
857       !NumThreads->containsUnexpandedParameterPack()) {
858     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
859     ExprResult Val =
860         PerformImplicitIntegerConversion(NumThreadsLoc, NumThreads);
861     if (Val.isInvalid())
862       return 0;
863 
864     ValExpr = Val.take();
865 
866     // OpenMP [2.5, Restrictions]
867     //  The num_threads expression must evaluate to a positive integer value.
868     llvm::APSInt Result;
869     if (ValExpr->isIntegerConstantExpr(Result, Context) &&
870         Result.isSigned() && !Result.isStrictlyPositive()) {
871       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
872           << "num_threads" << NumThreads->getSourceRange();
873       return 0;
874     }
875   }
876 
877   return new (Context) OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc,
878                                            EndLoc);
879 }
880 
881 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
882                                                        OpenMPClauseKind CKind) {
883   if (!E)
884     return ExprError();
885   if (E->isValueDependent() || E->isTypeDependent() ||
886       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
887     return Owned(E);
888   llvm::APSInt Result;
889   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
890   if (ICE.isInvalid())
891     return ExprError();
892   if (!Result.isStrictlyPositive()) {
893     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
894         << getOpenMPClauseName(CKind) << E->getSourceRange();
895     return ExprError();
896   }
897   return ICE;
898 }
899 
900 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
901                                           SourceLocation LParenLoc,
902                                           SourceLocation EndLoc) {
903   // OpenMP [2.8.1, simd construct, Description]
904   // The parameter of the safelen clause must be a constant
905   // positive integer expression.
906   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
907   if (Safelen.isInvalid())
908     return 0;
909   return new (Context)
910       OMPSafelenClause(Safelen.take(), StartLoc, LParenLoc, EndLoc);
911 }
912 
913 OMPClause *Sema::ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
914                                          unsigned Argument,
915                                          SourceLocation ArgumentLoc,
916                                          SourceLocation StartLoc,
917                                          SourceLocation LParenLoc,
918                                          SourceLocation EndLoc) {
919   OMPClause *Res = 0;
920   switch (Kind) {
921   case OMPC_default:
922     Res =
923       ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
924                                ArgumentLoc, StartLoc, LParenLoc, EndLoc);
925     break;
926   case OMPC_if:
927   case OMPC_num_threads:
928   case OMPC_safelen:
929   case OMPC_private:
930   case OMPC_firstprivate:
931   case OMPC_shared:
932   case OMPC_copyin:
933   case OMPC_threadprivate:
934   case OMPC_unknown:
935   case NUM_OPENMP_CLAUSES:
936     llvm_unreachable("Clause is not allowed.");
937   }
938   return Res;
939 }
940 
941 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
942                                           SourceLocation KindKwLoc,
943                                           SourceLocation StartLoc,
944                                           SourceLocation LParenLoc,
945                                           SourceLocation EndLoc) {
946   if (Kind == OMPC_DEFAULT_unknown) {
947     std::string Values;
948     static_assert(NUM_OPENMP_DEFAULT_KINDS > 1,
949                   "NUM_OPENMP_DEFAULT_KINDS not greater than 1");
950     std::string Sep(", ");
951     for (unsigned i = OMPC_DEFAULT_unknown + 1;
952          i < NUM_OPENMP_DEFAULT_KINDS; ++i) {
953       Values += "'";
954       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
955       Values += "'";
956       switch (i) {
957       case NUM_OPENMP_DEFAULT_KINDS - 2:
958         Values += " or ";
959         break;
960       case NUM_OPENMP_DEFAULT_KINDS - 1:
961         break;
962       default:
963         Values += Sep;
964         break;
965       }
966     }
967     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
968       << Values << getOpenMPClauseName(OMPC_default);
969     return 0;
970   }
971   switch (Kind) {
972   case OMPC_DEFAULT_none:
973     DSAStack->setDefaultDSANone();
974     break;
975   case OMPC_DEFAULT_shared:
976     DSAStack->setDefaultDSAShared();
977     break;
978   case OMPC_DEFAULT_unknown:
979   case NUM_OPENMP_DEFAULT_KINDS:
980     llvm_unreachable("Clause kind is not allowed.");
981     break;
982   }
983   return new (Context) OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc,
984                                         EndLoc);
985 }
986 
987 OMPClause *Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
988                                           ArrayRef<Expr *> VarList,
989                                           SourceLocation StartLoc,
990                                           SourceLocation LParenLoc,
991                                           SourceLocation EndLoc) {
992   OMPClause *Res = 0;
993   switch (Kind) {
994   case OMPC_private:
995     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
996     break;
997   case OMPC_firstprivate:
998     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
999     break;
1000   case OMPC_shared:
1001     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
1002     break;
1003   case OMPC_copyin:
1004     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
1005     break;
1006   case OMPC_if:
1007   case OMPC_num_threads:
1008   case OMPC_safelen:
1009   case OMPC_default:
1010   case OMPC_threadprivate:
1011   case OMPC_unknown:
1012   case NUM_OPENMP_CLAUSES:
1013     llvm_unreachable("Clause is not allowed.");
1014   }
1015   return Res;
1016 }
1017 
1018 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
1019                                           SourceLocation StartLoc,
1020                                           SourceLocation LParenLoc,
1021                                           SourceLocation EndLoc) {
1022   SmallVector<Expr *, 8> Vars;
1023   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1024        I != E; ++I) {
1025     assert(*I && "NULL expr in OpenMP private clause.");
1026     if (isa<DependentScopeDeclRefExpr>(*I)) {
1027       // It will be analyzed later.
1028       Vars.push_back(*I);
1029       continue;
1030     }
1031 
1032     SourceLocation ELoc = (*I)->getExprLoc();
1033     // OpenMP [2.1, C/C++]
1034     //  A list item is a variable name.
1035     // OpenMP  [2.9.3.3, Restrictions, p.1]
1036     //  A variable that is part of another variable (as an array or
1037     //  structure element) cannot appear in a private clause.
1038     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
1039     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1040       Diag(ELoc, diag::err_omp_expected_var_name)
1041         << (*I)->getSourceRange();
1042       continue;
1043     }
1044     Decl *D = DE->getDecl();
1045     VarDecl *VD = cast<VarDecl>(D);
1046 
1047     QualType Type = VD->getType();
1048     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1049       // It will be analyzed later.
1050       Vars.push_back(DE);
1051       continue;
1052     }
1053 
1054     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1055     //  A variable that appears in a private clause must not have an incomplete
1056     //  type or a reference type.
1057     if (RequireCompleteType(ELoc, Type,
1058                             diag::err_omp_private_incomplete_type)) {
1059       continue;
1060     }
1061     if (Type->isReferenceType()) {
1062       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1063         << getOpenMPClauseName(OMPC_private) << Type;
1064       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1065                     VarDecl::DeclarationOnly;
1066       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1067                                        diag::note_defined_here) << VD;
1068       continue;
1069     }
1070 
1071     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
1072     //  A variable of class type (or array thereof) that appears in a private
1073     //  clause requires an accesible, unambiguous default constructor for the
1074     //  class type.
1075     while (Type.getNonReferenceType()->isArrayType()) {
1076       Type = cast<ArrayType>(
1077                  Type.getNonReferenceType().getTypePtr())->getElementType();
1078     }
1079     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1080                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
1081     if (RD) {
1082       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
1083       PartialDiagnostic PD =
1084         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1085       if (!CD ||
1086           CheckConstructorAccess(ELoc, CD,
1087                                  InitializedEntity::InitializeTemporary(Type),
1088                                  CD->getAccess(), PD) == AR_inaccessible ||
1089           CD->isDeleted()) {
1090         Diag(ELoc, diag::err_omp_required_method)
1091              << getOpenMPClauseName(OMPC_private) << 0;
1092         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1093                       VarDecl::DeclarationOnly;
1094         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1095                                          diag::note_defined_here) << VD;
1096         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1097         continue;
1098       }
1099       MarkFunctionReferenced(ELoc, CD);
1100       DiagnoseUseOfDecl(CD, ELoc);
1101 
1102       CXXDestructorDecl *DD = RD->getDestructor();
1103       if (DD) {
1104         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1105             DD->isDeleted()) {
1106           Diag(ELoc, diag::err_omp_required_method)
1107                << getOpenMPClauseName(OMPC_private) << 4;
1108           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1109                         VarDecl::DeclarationOnly;
1110           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1111                                            diag::note_defined_here) << VD;
1112           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1113           continue;
1114         }
1115         MarkFunctionReferenced(ELoc, DD);
1116         DiagnoseUseOfDecl(DD, ELoc);
1117       }
1118     }
1119 
1120     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1121     // in a Construct]
1122     //  Variables with the predetermined data-sharing attributes may not be
1123     //  listed in data-sharing attributes clauses, except for the cases
1124     //  listed below. For these exceptions only, listing a predetermined
1125     //  variable in a data-sharing attribute clause is allowed and overrides
1126     //  the variable's predetermined data-sharing attributes.
1127     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1128     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
1129       Diag(ELoc, diag::err_omp_wrong_dsa)
1130          << getOpenMPClauseName(DVar.CKind)
1131          << getOpenMPClauseName(OMPC_private);
1132       if (DVar.RefExpr) {
1133         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1134              << getOpenMPClauseName(DVar.CKind);
1135       } else {
1136         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1137              << getOpenMPClauseName(DVar.CKind);
1138       }
1139       continue;
1140     }
1141 
1142     DSAStack->addDSA(VD, DE, OMPC_private);
1143     Vars.push_back(DE);
1144   }
1145 
1146   if (Vars.empty()) return 0;
1147 
1148   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1149 }
1150 
1151 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
1152                                                SourceLocation StartLoc,
1153                                                SourceLocation LParenLoc,
1154                                                SourceLocation EndLoc) {
1155   SmallVector<Expr *, 8> Vars;
1156   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1157        I != E; ++I) {
1158     assert(*I && "NULL expr in OpenMP firstprivate clause.");
1159     if (isa<DependentScopeDeclRefExpr>(*I)) {
1160       // It will be analyzed later.
1161       Vars.push_back(*I);
1162       continue;
1163     }
1164 
1165     SourceLocation ELoc = (*I)->getExprLoc();
1166     // OpenMP [2.1, C/C++]
1167     //  A list item is a variable name.
1168     // OpenMP  [2.9.3.3, Restrictions, p.1]
1169     //  A variable that is part of another variable (as an array or
1170     //  structure element) cannot appear in a private clause.
1171     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
1172     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1173       Diag(ELoc, diag::err_omp_expected_var_name)
1174         << (*I)->getSourceRange();
1175       continue;
1176     }
1177     Decl *D = DE->getDecl();
1178     VarDecl *VD = cast<VarDecl>(D);
1179 
1180     QualType Type = VD->getType();
1181     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1182       // It will be analyzed later.
1183       Vars.push_back(DE);
1184       continue;
1185     }
1186 
1187     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1188     //  A variable that appears in a private clause must not have an incomplete
1189     //  type or a reference type.
1190     if (RequireCompleteType(ELoc, Type,
1191                             diag::err_omp_firstprivate_incomplete_type)) {
1192       continue;
1193     }
1194     if (Type->isReferenceType()) {
1195       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1196         << getOpenMPClauseName(OMPC_firstprivate) << Type;
1197       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1198                     VarDecl::DeclarationOnly;
1199       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1200                                        diag::note_defined_here) << VD;
1201       continue;
1202     }
1203 
1204     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
1205     //  A variable of class type (or array thereof) that appears in a private
1206     //  clause requires an accesible, unambiguous copy constructor for the
1207     //  class type.
1208     Type = Context.getBaseElementType(Type);
1209     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1210                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
1211     if (RD) {
1212       CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
1213       PartialDiagnostic PD =
1214         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1215       if (!CD ||
1216           CheckConstructorAccess(ELoc, CD,
1217                                  InitializedEntity::InitializeTemporary(Type),
1218                                  CD->getAccess(), PD) == AR_inaccessible ||
1219           CD->isDeleted()) {
1220         Diag(ELoc, diag::err_omp_required_method)
1221              << getOpenMPClauseName(OMPC_firstprivate) << 1;
1222         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1223                       VarDecl::DeclarationOnly;
1224         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1225                                          diag::note_defined_here) << VD;
1226         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1227         continue;
1228       }
1229       MarkFunctionReferenced(ELoc, CD);
1230       DiagnoseUseOfDecl(CD, ELoc);
1231 
1232       CXXDestructorDecl *DD = RD->getDestructor();
1233       if (DD) {
1234         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1235             DD->isDeleted()) {
1236           Diag(ELoc, diag::err_omp_required_method)
1237                << getOpenMPClauseName(OMPC_firstprivate) << 4;
1238           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1239                         VarDecl::DeclarationOnly;
1240           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1241                                            diag::note_defined_here) << VD;
1242           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1243           continue;
1244         }
1245         MarkFunctionReferenced(ELoc, DD);
1246         DiagnoseUseOfDecl(DD, ELoc);
1247       }
1248     }
1249 
1250     // If StartLoc and EndLoc are invalid - this is an implicit firstprivate
1251     // variable and it was checked already.
1252     if (StartLoc.isValid() && EndLoc.isValid()) {
1253       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1254       Type = Type.getNonReferenceType().getCanonicalType();
1255       bool IsConstant = Type.isConstant(Context);
1256       Type = Context.getBaseElementType(Type);
1257       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
1258       //  A list item that specifies a given variable may not appear in more
1259       // than one clause on the same directive, except that a variable may be
1260       //  specified in both firstprivate and lastprivate clauses.
1261       //  TODO: add processing for lastprivate.
1262       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
1263           DVar.RefExpr) {
1264         Diag(ELoc, diag::err_omp_wrong_dsa)
1265            << getOpenMPClauseName(DVar.CKind)
1266            << getOpenMPClauseName(OMPC_firstprivate);
1267         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1268            << getOpenMPClauseName(DVar.CKind);
1269         continue;
1270       }
1271 
1272       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1273       // in a Construct]
1274       //  Variables with the predetermined data-sharing attributes may not be
1275       //  listed in data-sharing attributes clauses, except for the cases
1276       //  listed below. For these exceptions only, listing a predetermined
1277       //  variable in a data-sharing attribute clause is allowed and overrides
1278       //  the variable's predetermined data-sharing attributes.
1279       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1280       // in a Construct, C/C++, p.2]
1281       //  Variables with const-qualified type having no mutable member may be
1282       //  listed in a firstprivate clause, even if they are static data members.
1283       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
1284           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
1285         Diag(ELoc, diag::err_omp_wrong_dsa)
1286            << getOpenMPClauseName(DVar.CKind)
1287            << getOpenMPClauseName(OMPC_firstprivate);
1288         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1289            << getOpenMPClauseName(DVar.CKind);
1290         continue;
1291       }
1292 
1293       // OpenMP [2.9.3.4, Restrictions, p.2]
1294       //  A list item that is private within a parallel region must not appear
1295       //  in a firstprivate clause on a worksharing construct if any of the
1296       //  worksharing regions arising from the worksharing construct ever bind
1297       //  to any of the parallel regions arising from the parallel construct.
1298       // OpenMP [2.9.3.4, Restrictions, p.3]
1299       //  A list item that appears in a reduction clause of a parallel construct
1300       //  must not appear in a firstprivate clause on a worksharing or task
1301       //  construct if any of the worksharing or task regions arising from the
1302       //  worksharing or task construct ever bind to any of the parallel regions
1303       //  arising from the parallel construct.
1304       // OpenMP [2.9.3.4, Restrictions, p.4]
1305       //  A list item that appears in a reduction clause in worksharing
1306       //  construct must not appear in a firstprivate clause in a task construct
1307       //  encountered during execution of any of the worksharing regions arising
1308       //  from the worksharing construct.
1309       // TODO:
1310     }
1311 
1312     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
1313     Vars.push_back(DE);
1314   }
1315 
1316   if (Vars.empty()) return 0;
1317 
1318   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
1319                                        Vars);
1320 }
1321 
1322 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
1323                                          SourceLocation StartLoc,
1324                                          SourceLocation LParenLoc,
1325                                          SourceLocation EndLoc) {
1326   SmallVector<Expr *, 8> Vars;
1327   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1328        I != E; ++I) {
1329     assert(*I && "NULL expr in OpenMP shared clause.");
1330     if (isa<DependentScopeDeclRefExpr>(*I)) {
1331       // It will be analyzed later.
1332       Vars.push_back(*I);
1333       continue;
1334     }
1335 
1336     SourceLocation ELoc = (*I)->getExprLoc();
1337     // OpenMP [2.1, C/C++]
1338     //  A list item is a variable name.
1339     // OpenMP  [2.14.3.2, Restrictions, p.1]
1340     //  A variable that is part of another variable (as an array or structure
1341     //  element) cannot appear in a shared unless it is a static data member
1342     //  of a C++ class.
1343     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1344     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1345       Diag(ELoc, diag::err_omp_expected_var_name)
1346         << (*I)->getSourceRange();
1347       continue;
1348     }
1349     Decl *D = DE->getDecl();
1350     VarDecl *VD = cast<VarDecl>(D);
1351 
1352     QualType Type = VD->getType();
1353     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1354       // It will be analyzed later.
1355       Vars.push_back(DE);
1356       continue;
1357     }
1358 
1359     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1360     // in a Construct]
1361     //  Variables with the predetermined data-sharing attributes may not be
1362     //  listed in data-sharing attributes clauses, except for the cases
1363     //  listed below. For these exceptions only, listing a predetermined
1364     //  variable in a data-sharing attribute clause is allowed and overrides
1365     //  the variable's predetermined data-sharing attributes.
1366     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1367     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && DVar.RefExpr) {
1368       Diag(ELoc, diag::err_omp_wrong_dsa)
1369          << getOpenMPClauseName(DVar.CKind)
1370          << getOpenMPClauseName(OMPC_shared);
1371       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1372            << getOpenMPClauseName(DVar.CKind);
1373       continue;
1374     }
1375 
1376     DSAStack->addDSA(VD, DE, OMPC_shared);
1377     Vars.push_back(DE);
1378   }
1379 
1380   if (Vars.empty()) return 0;
1381 
1382   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1383 }
1384 
1385 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
1386                                          SourceLocation StartLoc,
1387                                          SourceLocation LParenLoc,
1388                                          SourceLocation EndLoc) {
1389   SmallVector<Expr *, 8> Vars;
1390   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
1391        I != E; ++I) {
1392     assert(*I && "NULL expr in OpenMP copyin clause.");
1393     if (isa<DependentScopeDeclRefExpr>(*I)) {
1394       // It will be analyzed later.
1395       Vars.push_back(*I);
1396       continue;
1397     }
1398 
1399     SourceLocation ELoc = (*I)->getExprLoc();
1400     // OpenMP [2.1, C/C++]
1401     //  A list item is a variable name.
1402     // OpenMP  [2.14.4.1, Restrictions, p.1]
1403     //  A list item that appears in a copyin clause must be threadprivate.
1404     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
1405     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1406       Diag(ELoc, diag::err_omp_expected_var_name)
1407         << (*I)->getSourceRange();
1408       continue;
1409     }
1410 
1411     Decl *D = DE->getDecl();
1412     VarDecl *VD = cast<VarDecl>(D);
1413 
1414     QualType Type = VD->getType();
1415     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1416       // It will be analyzed later.
1417       Vars.push_back(DE);
1418       continue;
1419     }
1420 
1421     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
1422     //  A list item that appears in a copyin clause must be threadprivate.
1423     if (!DSAStack->isThreadPrivate(VD)) {
1424       Diag(ELoc, diag::err_omp_required_access)
1425            << getOpenMPClauseName(OMPC_copyin)
1426            << getOpenMPDirectiveName(OMPD_threadprivate);
1427       continue;
1428     }
1429 
1430     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
1431     //  A variable of class type (or array thereof) that appears in a
1432     //  copyin clause requires an accesible, unambiguous copy assignment
1433     //  operator for the class type.
1434     Type = Context.getBaseElementType(Type);
1435     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
1436                           Type->getAsCXXRecordDecl() : 0;
1437     if (RD) {
1438       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
1439       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
1440       if (!MD ||
1441           CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
1442           MD->isDeleted()) {
1443         Diag(ELoc, diag::err_omp_required_method)
1444              << getOpenMPClauseName(OMPC_copyin) << 2;
1445         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1446                       VarDecl::DeclarationOnly;
1447         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
1448                                          diag::note_defined_here) << VD;
1449         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1450         continue;
1451       }
1452       MarkFunctionReferenced(ELoc, MD);
1453       DiagnoseUseOfDecl(MD, ELoc);
1454     }
1455 
1456     DSAStack->addDSA(VD, DE, OMPC_copyin);
1457     Vars.push_back(DE);
1458   }
1459 
1460   if (Vars.empty()) return 0;
1461 
1462   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1463 }
1464 
1465 #undef DSAStack
1466