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/SemaInternal.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.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 public:
86   explicit DSAStackTy(Sema &S) : Stack(1), Actions(S) { }
87 
88   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
89             Scope *CurScope) {
90     Stack.push_back(SharingMapTy(DKind, DirName, CurScope));
91   }
92 
93   void pop() {
94     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
95     Stack.pop_back();
96   }
97 
98   /// \brief Adds explicit data sharing attribute to the specified declaration.
99   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
100 
101   /// \brief Checks if the variable is a local for OpenMP region.
102   bool isOpenMPLocal(VarDecl *D);
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 
110   /// \brief Returns currently analyzed directive.
111   OpenMPDirectiveKind getCurrentDirective() const {
112     return Stack.back().Directive;
113   }
114 
115   /// \brief Set default data sharing attribute to none.
116   void setDefaultDSANone() { Stack.back().DefaultAttr = DSA_none; }
117   /// \brief Set default data sharing attribute to shared.
118   void setDefaultDSAShared() { Stack.back().DefaultAttr = DSA_shared; }
119 
120   DefaultDataSharingAttributes getDefaultDSA() const {
121     return Stack.back().DefaultAttr;
122   }
123 
124   Scope *getCurScope() { return Stack.back().CurScope; }
125 };
126 } // end anonymous namespace.
127 
128 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
129                                           VarDecl *D) {
130   DSAVarData DVar;
131   if (Iter == Stack.rend() - 1) {
132     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
133     // in a region but not in construct]
134     //  File-scope or namespace-scope variables referenced in called routines
135     //  in the region are shared unless they appear in a threadprivate
136     //  directive.
137     // TODO
138     if (!D->isFunctionOrMethodVarDecl())
139       DVar.CKind = OMPC_shared;
140 
141     return DVar;
142   }
143   DVar.DKind = Iter->Directive;
144   // Explicitly specified attributes and local variables with predetermined
145   // attributes.
146   if (Iter->SharingMap.count(D)) {
147     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
148     DVar.CKind = Iter->SharingMap[D].Attributes;
149     return DVar;
150   }
151 
152   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
153   // in a Construct, C/C++, implicitly determined, p.1]
154   //  In a parallel or task construct, the data-sharing attributes of these
155   //  variables are determined by the default clause, if present.
156   switch (Iter->DefaultAttr) {
157   case DSA_shared:
158     DVar.CKind = OMPC_shared;
159     return DVar;
160   case DSA_none:
161     return DVar;
162   case DSA_unspecified:
163     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
164     // in a Construct, implicitly determined, p.2]
165     //  In a parallel construct, if no default clause is present, these
166     //  variables are shared.
167     if (DVar.DKind == OMPD_parallel) {
168       DVar.CKind = OMPC_shared;
169       return DVar;
170     }
171 
172     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
173     // in a Construct, implicitly determined, p.4]
174     //  In a task construct, if no default clause is present, a variable that in
175     //  the enclosing context is determined to be shared by all implicit tasks
176     //  bound to the current team is shared.
177     // TODO
178     if (DVar.DKind == OMPD_task) {
179       DSAVarData DVarTemp;
180       for (StackTy::reverse_iterator I = Iter + 1,
181                                      EE = Stack.rend() - 1;
182            I != EE; ++I) {
183         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
184         // in a Construct, implicitly determined, p.6]
185         //  In a task construct, if no default clause is present, a variable
186         //  whose data-sharing attribute is not determined by the rules above is
187         //  firstprivate.
188         DVarTemp = getDSA(I, D);
189         if (DVarTemp.CKind != OMPC_shared) {
190           DVar.RefExpr = 0;
191           DVar.DKind = OMPD_task;
192           DVar.CKind = OMPC_unknown;
193           // TODO: should return OMPC_firstprivate
194           return DVar;
195         }
196         if (I->Directive == OMPD_parallel) break;
197       }
198       DVar.DKind = OMPD_task;
199       // TODO: Should return OMPC_firstprivate instead of OMPC_unknown.
200       DVar.CKind =
201         (DVarTemp.CKind == OMPC_unknown) ? OMPC_unknown : OMPC_shared;
202       return DVar;
203     }
204   }
205   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
206   // in a Construct, implicitly determined, p.3]
207   //  For constructs other than task, if no default clause is present, these
208   //  variables inherit their data-sharing attributes from the enclosing
209   //  context.
210   return getDSA(Iter + 1, D);
211 }
212 
213 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
214   if (A == OMPC_threadprivate) {
215     Stack[0].SharingMap[D].Attributes = A;
216     Stack[0].SharingMap[D].RefExpr = E;
217   } else {
218     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
219     Stack.back().SharingMap[D].Attributes = A;
220     Stack.back().SharingMap[D].RefExpr = E;
221   }
222 }
223 
224 bool DSAStackTy::isOpenMPLocal(VarDecl *D) {
225   Scope *CurScope = getCurScope();
226   while (CurScope && !CurScope->isDeclScope(D))
227     CurScope = CurScope->getParent();
228   while (CurScope && !CurScope->isOpenMPDirectiveScope())
229     CurScope = CurScope->getParent();
230   bool isOpenMPLocal = !!CurScope;
231   if (!isOpenMPLocal) {
232     CurScope = getCurScope();
233     while (CurScope && !CurScope->isOpenMPDirectiveScope())
234       CurScope = CurScope->getParent();
235     isOpenMPLocal =
236       CurScope &&
237       isa<CapturedDecl>(D->getDeclContext()) &&
238       static_cast<DeclContext *>(
239         CurScope->getFnParent()->getEntity())->Encloses(D->getDeclContext());
240   }
241   return isOpenMPLocal;
242 }
243 
244 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D) {
245   DSAVarData DVar;
246 
247   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
248   // in a Construct, C/C++, predetermined, p.1]
249   //  Variables appearing in threadprivate directives are threadprivate.
250   if (D->getTLSKind() != VarDecl::TLS_None) {
251     DVar.CKind = OMPC_threadprivate;
252     return DVar;
253   }
254   if (Stack[0].SharingMap.count(D)) {
255     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
256     DVar.CKind = OMPC_threadprivate;
257     return DVar;
258   }
259 
260   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
261   // in a Construct, C/C++, predetermined, p.1]
262   // Variables with automatic storage duration that are declared in a scope
263   // inside the construct are private.
264   if (isOpenMPLocal(D) && D->isLocalVarDecl() &&
265       (D->getStorageClass() == SC_Auto ||
266        D->getStorageClass() == SC_None)) {
267     DVar.CKind = OMPC_private;
268     return DVar;
269   }
270 
271   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
272   // in a Construct, C/C++, predetermined, p.4]
273   //  Static data memebers are shared.
274   if (D->isStaticDataMember()) {
275     // Variables with const-qualified type having no mutable member may be
276     // listed in a firstprivate clause, even if they are static data members.
277     // TODO:
278     DVar.CKind = OMPC_shared;
279     return DVar;
280   }
281 
282   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
283   bool IsConstant = Type.isConstant(Actions.getASTContext());
284   while (Type->isArrayType()) {
285     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
286     Type = ElemType.getNonReferenceType().getCanonicalType();
287   }
288   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
289   // in a Construct, C/C++, predetermined, p.6]
290   //  Variables with const qualified type having no mutable member are
291   //  shared.
292   CXXRecordDecl *RD = Actions.getLangOpts().CPlusPlus ?
293                                 Type->getAsCXXRecordDecl() : 0;
294   if (IsConstant &&
295       !(Actions.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
296     // Variables with const-qualified type having no mutable member may be
297     // listed in a firstprivate clause, even if they are static data members.
298     // TODO
299     DVar.CKind = OMPC_shared;
300     return DVar;
301   }
302 
303   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
304   // in a Construct, C/C++, predetermined, p.7]
305   //  Variables with static storage duration that are declared in a scope
306   //  inside the construct are shared.
307   if (isOpenMPLocal(D) && D->isStaticLocal()) {
308     DVar.CKind = OMPC_shared;
309     return DVar;
310   }
311 
312   // Explicitly specified attributes and local variables with predetermined
313   // attributes.
314   if (Stack.back().SharingMap.count(D)) {
315     DVar.RefExpr = Stack.back().SharingMap[D].RefExpr;
316     DVar.CKind = Stack.back().SharingMap[D].Attributes;
317   }
318 
319   return DVar;
320 }
321 
322 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D) {
323   return getDSA(Stack.rbegin() + 1, D);
324 }
325 
326 void Sema::InitDataSharingAttributesStack() {
327   VarDataSharingAttributesStack = new DSAStackTy(*this);
328 }
329 
330 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
331 
332 void Sema::DestroyDataSharingAttributesStack() {
333   delete DSAStack;
334 }
335 
336 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
337                                const DeclarationNameInfo &DirName,
338                                Scope *CurScope) {
339   DSAStack->push(DKind, DirName, CurScope);
340   PushExpressionEvaluationContext(PotentiallyEvaluated);
341 }
342 
343 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
344   DSAStack->pop();
345   DiscardCleanupsInEvaluationContext();
346   PopExpressionEvaluationContext();
347 }
348 
349 namespace {
350 
351 class VarDeclFilterCCC : public CorrectionCandidateCallback {
352 private:
353   Sema &Actions;
354 public:
355   VarDeclFilterCCC(Sema &S) : Actions(S) { }
356   virtual bool ValidateCandidate(const TypoCorrection &Candidate) {
357     NamedDecl *ND = Candidate.getCorrectionDecl();
358     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
359       return VD->hasGlobalStorage() &&
360              Actions.isDeclInScope(ND, Actions.getCurLexicalContext(),
361                                    Actions.getCurScope());
362     }
363     return false;
364   }
365 };
366 }
367 
368 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
369                                          CXXScopeSpec &ScopeSpec,
370                                          const DeclarationNameInfo &Id) {
371   LookupResult Lookup(*this, Id, LookupOrdinaryName);
372   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
373 
374   if (Lookup.isAmbiguous())
375     return ExprError();
376 
377   VarDecl *VD;
378   if (!Lookup.isSingleResult()) {
379     VarDeclFilterCCC Validator(*this);
380     if (TypoCorrection Corrected = CorrectTypo(Id, LookupOrdinaryName, CurScope,
381                                                0, Validator)) {
382       diagnoseTypo(Corrected,
383                    PDiag(Lookup.empty()? diag::err_undeclared_var_use_suggest
384                                        : diag::err_omp_expected_var_arg_suggest)
385                      << Id.getName());
386       VD = Corrected.getCorrectionDeclAs<VarDecl>();
387     } else {
388       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
389                                        : diag::err_omp_expected_var_arg)
390           << Id.getName();
391       return ExprError();
392     }
393   } else {
394     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
395       Diag(Id.getLoc(), diag::err_omp_expected_var_arg)
396         << Id.getName();
397       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
398       return ExprError();
399     }
400   }
401   Lookup.suppressDiagnostics();
402 
403   // OpenMP [2.9.2, Syntax, C/C++]
404   //   Variables must be file-scope, namespace-scope, or static block-scope.
405   if (!VD->hasGlobalStorage()) {
406     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
407       << getOpenMPDirectiveName(OMPD_threadprivate)
408       << !VD->isStaticLocal();
409     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
410                   VarDecl::DeclarationOnly;
411     Diag(VD->getLocation(),
412          IsDecl ? diag::note_previous_decl : diag::note_defined_here) << VD;
413     return ExprError();
414   }
415 
416   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
417   //   A threadprivate directive for file-scope variables must appear outside
418   //   any definition or declaration.
419   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
420   //   A threadprivate directive for static class member variables must appear
421   //   in the class definition, in the same scope in which the member
422   //   variables are declared.
423   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
424   //   A threadprivate directive for namespace-scope variables must appear
425   //   outside any definition or declaration other than the namespace
426   //   definition itself.
427   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
428   //   A threadprivate directive for static block-scope variables must appear
429   //   in the scope of the variable and not in a nested scope.
430   NamedDecl *ND = cast<NamedDecl>(VD);
431   if (!isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
432     Diag(Id.getLoc(), diag::err_omp_var_scope)
433       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
434     bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
435                   VarDecl::DeclarationOnly;
436     Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
437                                      diag::note_defined_here) << VD;
438     return ExprError();
439   }
440 
441   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
442   //   A threadprivate directive must lexically precede all references to any
443   //   of the variables in its list.
444   if (VD->isUsed()) {
445     Diag(Id.getLoc(), diag::err_omp_var_used)
446       << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
447     return ExprError();
448   }
449 
450   QualType ExprType = VD->getType().getNonReferenceType();
451   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_RValue, Id.getLoc());
452   DSAStack->addDSA(VD, cast<DeclRefExpr>(DE.get()), OMPC_threadprivate);
453   return DE;
454 }
455 
456 Sema::DeclGroupPtrTy Sema::ActOnOpenMPThreadprivateDirective(
457                                 SourceLocation Loc,
458                                 ArrayRef<Expr *> VarList) {
459   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
460     CurContext->addDecl(D);
461     return DeclGroupPtrTy::make(DeclGroupRef(D));
462   }
463   return DeclGroupPtrTy();
464 }
465 
466 OMPThreadPrivateDecl *Sema::CheckOMPThreadPrivateDecl(
467                                  SourceLocation Loc,
468                                  ArrayRef<Expr *> VarList) {
469   SmallVector<Expr *, 8> Vars;
470   for (ArrayRef<Expr *>::iterator I = VarList.begin(),
471                                          E = VarList.end();
472        I != E; ++I) {
473     DeclRefExpr *DE = cast<DeclRefExpr>(*I);
474     VarDecl *VD = cast<VarDecl>(DE->getDecl());
475     SourceLocation ILoc = DE->getExprLoc();
476 
477     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
478     //   A threadprivate variable must not have an incomplete type.
479     if (RequireCompleteType(ILoc, VD->getType(),
480                             diag::err_omp_threadprivate_incomplete_type)) {
481       continue;
482     }
483 
484     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
485     //   A threadprivate variable must not have a reference type.
486     if (VD->getType()->isReferenceType()) {
487       Diag(ILoc, diag::err_omp_ref_type_arg)
488         << getOpenMPDirectiveName(OMPD_threadprivate)
489         << VD->getType();
490       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
491                     VarDecl::DeclarationOnly;
492       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
493                                        diag::note_defined_here) << VD;
494       continue;
495     }
496 
497     // Check if this is a TLS variable.
498     if (VD->getTLSKind()) {
499       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
500       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
501                     VarDecl::DeclarationOnly;
502       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
503                                        diag::note_defined_here) << VD;
504       continue;
505     }
506 
507     Vars.push_back(*I);
508   }
509   return Vars.empty() ?
510               0 : OMPThreadPrivateDecl::Create(Context,
511                                                getCurLexicalContext(),
512                                                Loc, Vars);
513 }
514 
515 namespace {
516 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
517   DSAStackTy *Stack;
518   Sema &Actions;
519   bool ErrorFound;
520   CapturedStmt *CS;
521 public:
522   void VisitDeclRefExpr(DeclRefExpr *E) {
523     if(VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
524       if (VD->isImplicit() && VD->hasAttr<UnusedAttr>()) return;
525       // Skip internally declared variables.
526       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) return;
527 
528       SourceLocation ELoc = E->getExprLoc();
529 
530       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
531       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD);
532       if (DVar.CKind != OMPC_unknown) {
533         if (DKind == OMPD_task && DVar.CKind != OMPC_shared &&
534             DVar.CKind != OMPC_threadprivate && !DVar.RefExpr) {
535           // TODO: should be marked as firstprivate.
536         }
537         return;
538       }
539       // The default(none) clause requires that each variable that is referenced
540       // in the construct, and does not have a predetermined data-sharing
541       // attribute, must have its data-sharing attribute explicitly determined
542       // by being listed in a data-sharing attribute clause.
543       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
544           (DKind == OMPD_parallel || DKind == OMPD_task)) {
545         ErrorFound = true;
546         Actions.Diag(ELoc, diag::err_omp_no_dsa_for_variable) << VD;
547         return;
548       }
549 
550       // OpenMP [2.9.3.6, Restrictions, p.2]
551       //  A list item that appears in a reduction clause of the innermost
552       //  enclosing worksharing or parallel construct may not be accessed in an
553       //  explicit task.
554       // TODO:
555 
556       // Define implicit data-sharing attributes for task.
557       DVar = Stack->getImplicitDSA(VD);
558       if (DKind == OMPD_task && DVar.CKind != OMPC_shared) {
559         // TODO: should be marked as firstprivate.
560       }
561     }
562   }
563   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
564     for (ArrayRef<OMPClause *>::iterator I = S->clauses().begin(),
565                                          E = S->clauses().end();
566          I != E; ++I)
567       if (OMPClause *C = *I)
568         for (StmtRange R = C->children(); R; ++R)
569           if (Stmt *Child = *R)
570             Visit(Child);
571   }
572   void VisitStmt(Stmt *S) {
573     for (Stmt::child_iterator I = S->child_begin(), E = S->child_end();
574          I != E; ++I)
575       if (Stmt *Child = *I)
576         if (!isa<OMPExecutableDirective>(Child))
577           Visit(Child);
578     }
579 
580   bool isErrorFound() { return ErrorFound; }
581 
582   DSAAttrChecker(DSAStackTy *S, Sema &Actions, CapturedStmt *CS)
583     : Stack(S), Actions(Actions), ErrorFound(false), CS(CS) { }
584 };
585 }
586 
587 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
588                                                 ArrayRef<OMPClause *> Clauses,
589                                                 Stmt *AStmt,
590                                                 SourceLocation StartLoc,
591                                                 SourceLocation EndLoc) {
592   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
593 
594   StmtResult Res = StmtError();
595 
596   // Check default data sharing attributes for referenced variables.
597   DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
598   DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
599   if (DSAChecker.isErrorFound())
600     return StmtError();
601 
602   switch (Kind) {
603   case OMPD_parallel:
604     Res = ActOnOpenMPParallelDirective(Clauses, AStmt, StartLoc, EndLoc);
605     break;
606   case OMPD_threadprivate:
607   case OMPD_task:
608     llvm_unreachable("OpenMP Directive is not allowed");
609   case OMPD_unknown:
610   case NUM_OPENMP_DIRECTIVES:
611     llvm_unreachable("Unknown OpenMP directive");
612   }
613   return Res;
614 }
615 
616 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
617                                               Stmt *AStmt,
618                                               SourceLocation StartLoc,
619                                               SourceLocation EndLoc) {
620   getCurFunction()->setHasBranchProtectedScope();
621 
622   return Owned(OMPParallelDirective::Create(Context, StartLoc, EndLoc,
623                                             Clauses, AStmt));
624 }
625 
626 OMPClause *Sema::ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
627                                          unsigned Argument,
628                                          SourceLocation ArgumentLoc,
629                                          SourceLocation StartLoc,
630                                          SourceLocation LParenLoc,
631                                          SourceLocation EndLoc) {
632   OMPClause *Res = 0;
633   switch (Kind) {
634   case OMPC_default:
635     Res =
636       ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
637                                ArgumentLoc, StartLoc, LParenLoc, EndLoc);
638     break;
639   case OMPC_private:
640   case OMPC_shared:
641   case OMPC_threadprivate:
642   case OMPC_unknown:
643   case NUM_OPENMP_CLAUSES:
644     llvm_unreachable("Clause is not allowed.");
645   }
646   return Res;
647 }
648 
649 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
650                                           SourceLocation KindKwLoc,
651                                           SourceLocation StartLoc,
652                                           SourceLocation LParenLoc,
653                                           SourceLocation EndLoc) {
654   if (Kind == OMPC_DEFAULT_unknown) {
655     std::string Values;
656     std::string Sep(NUM_OPENMP_DEFAULT_KINDS > 1 ? ", " : "");
657     for (unsigned i = OMPC_DEFAULT_unknown + 1;
658          i < NUM_OPENMP_DEFAULT_KINDS; ++i) {
659       Values += "'";
660       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
661       Values += "'";
662       switch (i) {
663       case NUM_OPENMP_DEFAULT_KINDS - 2:
664         Values += " or ";
665         break;
666       case NUM_OPENMP_DEFAULT_KINDS - 1:
667         break;
668       default:
669         Values += Sep;
670         break;
671       }
672     }
673     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
674       << Values << getOpenMPClauseName(OMPC_default);
675     return 0;
676   }
677   switch (Kind) {
678   case OMPC_DEFAULT_none:
679     DSAStack->setDefaultDSANone();
680     break;
681   case OMPC_DEFAULT_shared:
682     DSAStack->setDefaultDSAShared();
683     break;
684   default:
685     break;
686   }
687   return new (Context) OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc,
688                                         EndLoc);
689 }
690 
691 OMPClause *Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
692                                           ArrayRef<Expr *> VarList,
693                                           SourceLocation StartLoc,
694                                           SourceLocation LParenLoc,
695                                           SourceLocation EndLoc) {
696   OMPClause *Res = 0;
697   switch (Kind) {
698   case OMPC_private:
699     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
700     break;
701   case OMPC_shared:
702     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
703     break;
704   case OMPC_default:
705   case OMPC_threadprivate:
706   case OMPC_unknown:
707   case NUM_OPENMP_CLAUSES:
708     llvm_unreachable("Clause is not allowed.");
709   }
710   return Res;
711 }
712 
713 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
714                                           SourceLocation StartLoc,
715                                           SourceLocation LParenLoc,
716                                           SourceLocation EndLoc) {
717   SmallVector<Expr *, 8> Vars;
718   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
719        I != E; ++I) {
720     if (*I && isa<DependentScopeDeclRefExpr>(*I)) {
721       // It will be analyzed later.
722       Vars.push_back(*I);
723       continue;
724     }
725 
726     SourceLocation ELoc = (*I)->getExprLoc();
727     // OpenMP [2.1, C/C++]
728     //  A list item is a variable name.
729     // OpenMP  [2.9.3.3, Restrictions, p.1]
730     //  A variable that is part of another variable (as an array or
731     //  structure element) cannot appear in a private clause.
732     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(*I);
733     if (!DE || !isa<VarDecl>(DE->getDecl())) {
734       Diag(ELoc, diag::err_omp_expected_var_name)
735         << (*I)->getSourceRange();
736       continue;
737     }
738     Decl *D = DE->getDecl();
739     VarDecl *VD = cast<VarDecl>(D);
740 
741     QualType Type = VD->getType();
742     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
743       // It will be analyzed later.
744       Vars.push_back(DE);
745       continue;
746     }
747 
748     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
749     //  A variable that appears in a private clause must not have an incomplete
750     //  type or a reference type.
751     if (RequireCompleteType(ELoc, Type,
752                             diag::err_omp_private_incomplete_type)) {
753       continue;
754     }
755     if (Type->isReferenceType()) {
756       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
757         << getOpenMPClauseName(OMPC_private) << Type;
758       bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
759                     VarDecl::DeclarationOnly;
760       Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
761                                        diag::note_defined_here) << VD;
762       continue;
763     }
764 
765     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
766     //  A variable of class type (or array thereof) that appears in a private
767     //  clause requires an accesible, unambiguous default constructor for the
768     //  class type.
769     while (Type.getNonReferenceType()->isArrayType()) {
770       Type = cast<ArrayType>(
771                  Type.getNonReferenceType().getTypePtr())->getElementType();
772     }
773     CXXRecordDecl *RD = getLangOpts().CPlusPlus ?
774                           Type.getNonReferenceType()->getAsCXXRecordDecl() : 0;
775     if (RD) {
776       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
777       PartialDiagnostic PD =
778         PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
779       if (!CD ||
780           CheckConstructorAccess(ELoc, CD,
781                                  InitializedEntity::InitializeTemporary(Type),
782                                  CD->getAccess(), PD) == AR_inaccessible ||
783           CD->isDeleted()) {
784         Diag(ELoc, diag::err_omp_required_method)
785              << getOpenMPClauseName(OMPC_private) << 0;
786         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
787                       VarDecl::DeclarationOnly;
788         Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
789                                          diag::note_defined_here) << VD;
790         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
791         continue;
792       }
793       MarkFunctionReferenced(ELoc, CD);
794       DiagnoseUseOfDecl(CD, ELoc);
795 
796       CXXDestructorDecl *DD = RD->getDestructor();
797       if (DD) {
798         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
799             DD->isDeleted()) {
800           Diag(ELoc, diag::err_omp_required_method)
801                << getOpenMPClauseName(OMPC_private) << 4;
802           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
803                         VarDecl::DeclarationOnly;
804           Diag(VD->getLocation(), IsDecl ? diag::note_previous_decl :
805                                            diag::note_defined_here) << VD;
806           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
807           continue;
808         }
809         MarkFunctionReferenced(ELoc, DD);
810         DiagnoseUseOfDecl(DD, ELoc);
811       }
812     }
813 
814     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
815     // in a Construct]
816     //  Variables with the predetermined data-sharing attributes may not be
817     //  listed in data-sharing attributes clauses, except for the cases
818     //  listed below. For these exceptions only, listing a predetermined
819     //  variable in a data-sharing attribute clause is allowed and overrides
820     //  the variable's predetermined data-sharing attributes.
821     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
822     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
823       Diag(ELoc, diag::err_omp_wrong_dsa)
824          << getOpenMPClauseName(DVar.CKind)
825          << getOpenMPClauseName(OMPC_private);
826       if (DVar.RefExpr) {
827         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
828              << getOpenMPClauseName(DVar.CKind);
829       } else {
830         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
831              << getOpenMPClauseName(DVar.CKind);
832       }
833       continue;
834     }
835 
836     DSAStack->addDSA(VD, DE, OMPC_private);
837     Vars.push_back(DE);
838   }
839 
840   if (Vars.empty()) return 0;
841 
842   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
843 }
844 
845 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
846                                          SourceLocation StartLoc,
847                                          SourceLocation LParenLoc,
848                                          SourceLocation EndLoc) {
849   SmallVector<Expr *, 8> Vars;
850   for (ArrayRef<Expr *>::iterator I = VarList.begin(), E = VarList.end();
851        I != E; ++I) {
852     if (*I && isa<DependentScopeDeclRefExpr>(*I)) {
853       // It will be analyzed later.
854       Vars.push_back(*I);
855       continue;
856     }
857 
858     SourceLocation ELoc = (*I)->getExprLoc();
859     // OpenMP [2.1, C/C++]
860     //  A list item is a variable name.
861     // OpenMP  [2.9.3.4, Restrictions, p.1]
862     //  A variable that is part of another variable (as an array or
863     //  structure element) cannot appear in a private clause.
864     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(*I);
865     if (!DE || !isa<VarDecl>(DE->getDecl())) {
866       Diag(ELoc, diag::err_omp_expected_var_name)
867         << (*I)->getSourceRange();
868       continue;
869     }
870     Decl *D = DE->getDecl();
871     VarDecl *VD = cast<VarDecl>(D);
872 
873     QualType Type = VD->getType();
874     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
875       // It will be analyzed later.
876       Vars.push_back(DE);
877       continue;
878     }
879 
880     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
881     // in a Construct]
882     //  Variables with the predetermined data-sharing attributes may not be
883     //  listed in data-sharing attributes clauses, except for the cases
884     //  listed below. For these exceptions only, listing a predetermined
885     //  variable in a data-sharing attribute clause is allowed and overrides
886     //  the variable's predetermined data-sharing attributes.
887     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
888     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && DVar.RefExpr) {
889       Diag(ELoc, diag::err_omp_wrong_dsa)
890          << getOpenMPClauseName(DVar.CKind)
891          << getOpenMPClauseName(OMPC_shared);
892       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
893            << getOpenMPClauseName(DVar.CKind);
894       continue;
895     }
896 
897     DSAStack->addDSA(VD, DE, OMPC_shared);
898     Vars.push_back(DE);
899   }
900 
901   if (Vars.empty()) return 0;
902 
903   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
904 }
905 
906 #undef DSAStack
907