1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// \brief This file implements semantic analysis for OpenMP directives and
11 /// clauses.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclOpenMP.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/AST/StmtOpenMP.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/OpenMPKinds.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaInternal.h"
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Stack of data-sharing attributes for variables
33 //===----------------------------------------------------------------------===//
34 
35 namespace {
36 /// \brief Default data sharing attributes, which can be applied to directive.
37 enum DefaultDataSharingAttributes {
38   DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
39   DSA_none = 1 << 0,   /// \brief Default data sharing attribute 'none'.
40   DSA_shared = 1 << 1  /// \brief Default data sharing attribute 'shared'.
41 };
42 
43 /// \brief Stack for tracking declarations used in OpenMP directives and
44 /// clauses and their data-sharing attributes.
45 class DSAStackTy {
46 public:
47   struct DSAVarData {
48     OpenMPDirectiveKind DKind;
49     OpenMPClauseKind CKind;
50     DeclRefExpr *RefExpr;
51     DSAVarData() : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr) {}
52   };
53 
54 private:
55   struct DSAInfo {
56     OpenMPClauseKind Attributes;
57     DeclRefExpr *RefExpr;
58   };
59   typedef llvm::SmallDenseMap<VarDecl *, DSAInfo, 64> DeclSAMapTy;
60   typedef llvm::SmallDenseMap<VarDecl *, DeclRefExpr *, 64> AlignedMapTy;
61 
62   struct SharingMapTy {
63     DeclSAMapTy SharingMap;
64     AlignedMapTy AlignedMap;
65     DefaultDataSharingAttributes DefaultAttr;
66     OpenMPDirectiveKind Directive;
67     DeclarationNameInfo DirectiveName;
68     Scope *CurScope;
69     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
70                  Scope *CurScope)
71         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
72           Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope) {
73     }
74     SharingMapTy()
75         : SharingMap(), AlignedMap(), DefaultAttr(DSA_unspecified),
76           Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr) {}
77   };
78 
79   typedef SmallVector<SharingMapTy, 64> StackTy;
80 
81   /// \brief Stack of used declaration and their data-sharing attributes.
82   StackTy Stack;
83   Sema &Actions;
84 
85   typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
86 
87   DSAVarData getDSA(StackTy::reverse_iterator Iter, VarDecl *D);
88 
89   /// \brief Checks if the variable is a local for OpenMP region.
90   bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
91 
92 public:
93   explicit DSAStackTy(Sema &S) : Stack(1), Actions(S) {}
94 
95   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
96             Scope *CurScope) {
97     Stack.push_back(SharingMapTy(DKind, DirName, CurScope));
98   }
99 
100   void pop() {
101     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
102     Stack.pop_back();
103   }
104 
105   /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
106   /// add it and return NULL; otherwise return previous occurrence's expression
107   /// for diagnostics.
108   DeclRefExpr *addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE);
109 
110   /// \brief Adds explicit data sharing attribute to the specified declaration.
111   void addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A);
112 
113   /// \brief Returns data sharing attributes from top of the stack for the
114   /// specified declaration.
115   DSAVarData getTopDSA(VarDecl *D);
116   /// \brief Returns data-sharing attributes for the specified declaration.
117   DSAVarData getImplicitDSA(VarDecl *D);
118   /// \brief Checks if the specified variables has \a CKind data-sharing
119   /// attribute in \a DKind directive.
120   DSAVarData hasDSA(VarDecl *D, OpenMPClauseKind CKind,
121                     OpenMPDirectiveKind DKind = OMPD_unknown);
122 
123   /// \brief Returns currently analyzed directive.
124   OpenMPDirectiveKind getCurrentDirective() const {
125     return Stack.back().Directive;
126   }
127 
128   /// \brief Set default data sharing attribute to none.
129   void setDefaultDSANone() { Stack.back().DefaultAttr = DSA_none; }
130   /// \brief Set default data sharing attribute to shared.
131   void setDefaultDSAShared() { Stack.back().DefaultAttr = DSA_shared; }
132 
133   DefaultDataSharingAttributes getDefaultDSA() const {
134     return Stack.back().DefaultAttr;
135   }
136 
137   /// \brief Checks if the spewcified variable is threadprivate.
138   bool isThreadPrivate(VarDecl *D) {
139     DSAVarData DVar = getTopDSA(D);
140     return (DVar.CKind == OMPC_threadprivate || DVar.CKind == OMPC_copyin);
141   }
142 
143   Scope *getCurScope() const { return Stack.back().CurScope; }
144   Scope *getCurScope() { return Stack.back().CurScope; }
145 };
146 } // namespace
147 
148 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
149                                           VarDecl *D) {
150   DSAVarData DVar;
151   if (Iter == Stack.rend() - 1) {
152     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
153     // in a region but not in construct]
154     //  File-scope or namespace-scope variables referenced in called routines
155     //  in the region are shared unless they appear in a threadprivate
156     //  directive.
157     // TODO
158     if (!D->isFunctionOrMethodVarDecl())
159       DVar.CKind = OMPC_shared;
160 
161     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
162     // in a region but not in construct]
163     //  Variables with static storage duration that are declared in called
164     //  routines in the region are shared.
165     if (D->hasGlobalStorage())
166       DVar.CKind = OMPC_shared;
167 
168     return DVar;
169   }
170 
171   DVar.DKind = Iter->Directive;
172   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
173   // in a Construct, C/C++, predetermined, p.1]
174   // Variables with automatic storage duration that are declared in a scope
175   // inside the construct are private.
176   if (DVar.DKind != OMPD_parallel) {
177     if (isOpenMPLocal(D, Iter) && D->isLocalVarDecl() &&
178         (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
179       DVar.CKind = OMPC_private;
180       return DVar;
181     }
182   }
183 
184   // Explicitly specified attributes and local variables with predetermined
185   // attributes.
186   if (Iter->SharingMap.count(D)) {
187     DVar.RefExpr = Iter->SharingMap[D].RefExpr;
188     DVar.CKind = Iter->SharingMap[D].Attributes;
189     return DVar;
190   }
191 
192   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
193   // in a Construct, C/C++, implicitly determined, p.1]
194   //  In a parallel or task construct, the data-sharing attributes of these
195   //  variables are determined by the default clause, if present.
196   switch (Iter->DefaultAttr) {
197   case DSA_shared:
198     DVar.CKind = OMPC_shared;
199     return DVar;
200   case DSA_none:
201     return DVar;
202   case DSA_unspecified:
203     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
204     // in a Construct, implicitly determined, p.2]
205     //  In a parallel construct, if no default clause is present, these
206     //  variables are shared.
207     if (DVar.DKind == OMPD_parallel) {
208       DVar.CKind = OMPC_shared;
209       return DVar;
210     }
211 
212     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
213     // in a Construct, implicitly determined, p.4]
214     //  In a task construct, if no default clause is present, a variable that in
215     //  the enclosing context is determined to be shared by all implicit tasks
216     //  bound to the current team is shared.
217     // TODO
218     if (DVar.DKind == OMPD_task) {
219       DSAVarData DVarTemp;
220       for (StackTy::reverse_iterator I = std::next(Iter),
221                                      EE = std::prev(Stack.rend());
222            I != EE; ++I) {
223         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
224         // Referenced
225         // in a Construct, implicitly determined, p.6]
226         //  In a task construct, if no default clause is present, a variable
227         //  whose data-sharing attribute is not determined by the rules above is
228         //  firstprivate.
229         DVarTemp = getDSA(I, D);
230         if (DVarTemp.CKind != OMPC_shared) {
231           DVar.RefExpr = nullptr;
232           DVar.DKind = OMPD_task;
233           DVar.CKind = OMPC_firstprivate;
234           return DVar;
235         }
236         if (I->Directive == OMPD_parallel)
237           break;
238       }
239       DVar.DKind = OMPD_task;
240       DVar.CKind =
241           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
242       return DVar;
243     }
244   }
245   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
246   // in a Construct, implicitly determined, p.3]
247   //  For constructs other than task, if no default clause is present, these
248   //  variables inherit their data-sharing attributes from the enclosing
249   //  context.
250   return getDSA(std::next(Iter), D);
251 }
252 
253 DeclRefExpr *DSAStackTy::addUniqueAligned(VarDecl *D, DeclRefExpr *NewDE) {
254   assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
255   auto It = Stack.back().AlignedMap.find(D);
256   if (It == Stack.back().AlignedMap.end()) {
257     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
258     Stack.back().AlignedMap[D] = NewDE;
259     return nullptr;
260   } else {
261     assert(It->second && "Unexpected nullptr expr in the aligned map");
262     return It->second;
263   }
264   return nullptr;
265 }
266 
267 void DSAStackTy::addDSA(VarDecl *D, DeclRefExpr *E, OpenMPClauseKind A) {
268   if (A == OMPC_threadprivate) {
269     Stack[0].SharingMap[D].Attributes = A;
270     Stack[0].SharingMap[D].RefExpr = E;
271   } else {
272     assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
273     Stack.back().SharingMap[D].Attributes = A;
274     Stack.back().SharingMap[D].RefExpr = E;
275   }
276 }
277 
278 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
279   if (Stack.size() > 2) {
280     reverse_iterator I = Iter, E = Stack.rend() - 1;
281     Scope *TopScope = nullptr;
282     while (I != E && I->Directive != OMPD_parallel) {
283       ++I;
284     }
285     if (I == E)
286       return false;
287     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
288     Scope *CurScope = getCurScope();
289     while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
290       CurScope = CurScope->getParent();
291     }
292     return CurScope != TopScope;
293   }
294   return false;
295 }
296 
297 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(VarDecl *D) {
298   DSAVarData DVar;
299 
300   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
301   // in a Construct, C/C++, predetermined, p.1]
302   //  Variables appearing in threadprivate directives are threadprivate.
303   if (D->getTLSKind() != VarDecl::TLS_None) {
304     DVar.CKind = OMPC_threadprivate;
305     return DVar;
306   }
307   if (Stack[0].SharingMap.count(D)) {
308     DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
309     DVar.CKind = OMPC_threadprivate;
310     return DVar;
311   }
312 
313   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
314   // in a Construct, C/C++, predetermined, p.1]
315   // Variables with automatic storage duration that are declared in a scope
316   // inside the construct are private.
317   OpenMPDirectiveKind Kind = getCurrentDirective();
318   if (Kind != OMPD_parallel) {
319     if (isOpenMPLocal(D, std::next(Stack.rbegin())) && D->isLocalVarDecl() &&
320         (D->getStorageClass() == SC_Auto || D->getStorageClass() == SC_None)) {
321       DVar.CKind = OMPC_private;
322       return DVar;
323     }
324   }
325 
326   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
327   // in a Construct, C/C++, predetermined, p.4]
328   //  Static data memebers are shared.
329   if (D->isStaticDataMember()) {
330     // Variables with const-qualified type having no mutable member may be
331     // listed
332     // in a firstprivate clause, even if they are static data members.
333     DSAVarData DVarTemp = hasDSA(D, OMPC_firstprivate);
334     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
335       return DVar;
336 
337     DVar.CKind = OMPC_shared;
338     return DVar;
339   }
340 
341   QualType Type = D->getType().getNonReferenceType().getCanonicalType();
342   bool IsConstant = Type.isConstant(Actions.getASTContext());
343   while (Type->isArrayType()) {
344     QualType ElemType = cast<ArrayType>(Type.getTypePtr())->getElementType();
345     Type = ElemType.getNonReferenceType().getCanonicalType();
346   }
347   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
348   // in a Construct, C/C++, predetermined, p.6]
349   //  Variables with const qualified type having no mutable member are
350   //  shared.
351   CXXRecordDecl *RD =
352       Actions.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
353   if (IsConstant &&
354       !(Actions.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
355     // Variables with const-qualified type having no mutable member may be
356     // listed in a firstprivate clause, even if they are static data members.
357     DSAVarData DVarTemp = hasDSA(D, OMPC_firstprivate);
358     if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
359       return DVar;
360 
361     DVar.CKind = OMPC_shared;
362     return DVar;
363   }
364 
365   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
366   // in a Construct, C/C++, predetermined, p.7]
367   //  Variables with static storage duration that are declared in a scope
368   //  inside the construct are shared.
369   if (D->isStaticLocal()) {
370     DVar.CKind = OMPC_shared;
371     return DVar;
372   }
373 
374   // Explicitly specified attributes and local variables with predetermined
375   // attributes.
376   if (Stack.back().SharingMap.count(D)) {
377     DVar.RefExpr = Stack.back().SharingMap[D].RefExpr;
378     DVar.CKind = Stack.back().SharingMap[D].Attributes;
379   }
380 
381   return DVar;
382 }
383 
384 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(VarDecl *D) {
385   return getDSA(std::next(Stack.rbegin()), D);
386 }
387 
388 DSAStackTy::DSAVarData DSAStackTy::hasDSA(VarDecl *D, OpenMPClauseKind CKind,
389                                           OpenMPDirectiveKind DKind) {
390   for (StackTy::reverse_iterator I = std::next(Stack.rbegin()),
391                                  E = std::prev(Stack.rend());
392        I != E; ++I) {
393     if (DKind != OMPD_unknown && DKind != I->Directive)
394       continue;
395     DSAVarData DVar = getDSA(I, D);
396     if (DVar.CKind == CKind)
397       return DVar;
398   }
399   return DSAVarData();
400 }
401 
402 void Sema::InitDataSharingAttributesStack() {
403   VarDataSharingAttributesStack = new DSAStackTy(*this);
404 }
405 
406 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
407 
408 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
409 
410 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
411                                const DeclarationNameInfo &DirName,
412                                Scope *CurScope) {
413   DSAStack->push(DKind, DirName, CurScope);
414   PushExpressionEvaluationContext(PotentiallyEvaluated);
415 }
416 
417 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
418   DSAStack->pop();
419   DiscardCleanupsInEvaluationContext();
420   PopExpressionEvaluationContext();
421 }
422 
423 namespace {
424 
425 class VarDeclFilterCCC : public CorrectionCandidateCallback {
426 private:
427   Sema &Actions;
428 
429 public:
430   VarDeclFilterCCC(Sema &S) : Actions(S) {}
431   bool ValidateCandidate(const TypoCorrection &Candidate) override {
432     NamedDecl *ND = Candidate.getCorrectionDecl();
433     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
434       return VD->hasGlobalStorage() &&
435              Actions.isDeclInScope(ND, Actions.getCurLexicalContext(),
436                                    Actions.getCurScope());
437     }
438     return false;
439   }
440 };
441 } // namespace
442 
443 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
444                                          CXXScopeSpec &ScopeSpec,
445                                          const DeclarationNameInfo &Id) {
446   LookupResult Lookup(*this, Id, LookupOrdinaryName);
447   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
448 
449   if (Lookup.isAmbiguous())
450     return ExprError();
451 
452   VarDecl *VD;
453   if (!Lookup.isSingleResult()) {
454     VarDeclFilterCCC Validator(*this);
455     if (TypoCorrection Corrected =
456             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, Validator,
457                         CTK_ErrorRecovery)) {
458       diagnoseTypo(Corrected,
459                    PDiag(Lookup.empty()
460                              ? diag::err_undeclared_var_use_suggest
461                              : diag::err_omp_expected_var_arg_suggest)
462                        << Id.getName());
463       VD = Corrected.getCorrectionDeclAs<VarDecl>();
464     } else {
465       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
466                                        : diag::err_omp_expected_var_arg)
467           << Id.getName();
468       return ExprError();
469     }
470   } else {
471     if (!(VD = Lookup.getAsSingle<VarDecl>())) {
472       Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
473       Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
474       return ExprError();
475     }
476   }
477   Lookup.suppressDiagnostics();
478 
479   // OpenMP [2.9.2, Syntax, C/C++]
480   //   Variables must be file-scope, namespace-scope, or static block-scope.
481   if (!VD->hasGlobalStorage()) {
482     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
483         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
484     bool IsDecl =
485         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
486     Diag(VD->getLocation(),
487          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
488         << VD;
489     return ExprError();
490   }
491 
492   VarDecl *CanonicalVD = VD->getCanonicalDecl();
493   NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
494   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
495   //   A threadprivate directive for file-scope variables must appear outside
496   //   any definition or declaration.
497   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
498       !getCurLexicalContext()->isTranslationUnit()) {
499     Diag(Id.getLoc(), diag::err_omp_var_scope)
500         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
501     bool IsDecl =
502         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
503     Diag(VD->getLocation(),
504          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
505         << VD;
506     return ExprError();
507   }
508   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
509   //   A threadprivate directive for static class member variables must appear
510   //   in the class definition, in the same scope in which the member
511   //   variables are declared.
512   if (CanonicalVD->isStaticDataMember() &&
513       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
514     Diag(Id.getLoc(), diag::err_omp_var_scope)
515         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
516     bool IsDecl =
517         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
518     Diag(VD->getLocation(),
519          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
520         << VD;
521     return ExprError();
522   }
523   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
524   //   A threadprivate directive for namespace-scope variables must appear
525   //   outside any definition or declaration other than the namespace
526   //   definition itself.
527   if (CanonicalVD->getDeclContext()->isNamespace() &&
528       (!getCurLexicalContext()->isFileContext() ||
529        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
530     Diag(Id.getLoc(), diag::err_omp_var_scope)
531         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
532     bool IsDecl =
533         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
534     Diag(VD->getLocation(),
535          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
536         << VD;
537     return ExprError();
538   }
539   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
540   //   A threadprivate directive for static block-scope variables must appear
541   //   in the scope of the variable and not in a nested scope.
542   if (CanonicalVD->isStaticLocal() && CurScope &&
543       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
544     Diag(Id.getLoc(), diag::err_omp_var_scope)
545         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
546     bool IsDecl =
547         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
548     Diag(VD->getLocation(),
549          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
550         << VD;
551     return ExprError();
552   }
553 
554   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
555   //   A threadprivate directive must lexically precede all references to any
556   //   of the variables in its list.
557   if (VD->isUsed()) {
558     Diag(Id.getLoc(), diag::err_omp_var_used)
559         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
560     return ExprError();
561   }
562 
563   QualType ExprType = VD->getType().getNonReferenceType();
564   ExprResult DE = BuildDeclRefExpr(VD, ExprType, VK_LValue, Id.getLoc());
565   return DE;
566 }
567 
568 Sema::DeclGroupPtrTy
569 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
570                                         ArrayRef<Expr *> VarList) {
571   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
572     CurContext->addDecl(D);
573     return DeclGroupPtrTy::make(DeclGroupRef(D));
574   }
575   return DeclGroupPtrTy();
576 }
577 
578 namespace {
579 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
580   Sema &SemaRef;
581 
582 public:
583   bool VisitDeclRefExpr(const DeclRefExpr *E) {
584     if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
585       if (VD->hasLocalStorage()) {
586         SemaRef.Diag(E->getLocStart(),
587                      diag::err_omp_local_var_in_threadprivate_init)
588             << E->getSourceRange();
589         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
590             << VD << VD->getSourceRange();
591         return true;
592       }
593     }
594     return false;
595   }
596   bool VisitStmt(const Stmt *S) {
597     for (auto Child : S->children()) {
598       if (Child && Visit(Child))
599         return true;
600     }
601     return false;
602   }
603   LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
604 };
605 } // namespace
606 
607 OMPThreadPrivateDecl *
608 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
609   SmallVector<Expr *, 8> Vars;
610   for (auto &RefExpr : VarList) {
611     DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
612     VarDecl *VD = cast<VarDecl>(DE->getDecl());
613     SourceLocation ILoc = DE->getExprLoc();
614 
615     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
616     //   A threadprivate variable must not have an incomplete type.
617     if (RequireCompleteType(ILoc, VD->getType(),
618                             diag::err_omp_threadprivate_incomplete_type)) {
619       continue;
620     }
621 
622     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
623     //   A threadprivate variable must not have a reference type.
624     if (VD->getType()->isReferenceType()) {
625       Diag(ILoc, diag::err_omp_ref_type_arg)
626           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
627       bool IsDecl =
628           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
629       Diag(VD->getLocation(),
630            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
631           << VD;
632       continue;
633     }
634 
635     // Check if this is a TLS variable.
636     if (VD->getTLSKind()) {
637       Diag(ILoc, diag::err_omp_var_thread_local) << VD;
638       bool IsDecl =
639           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
640       Diag(VD->getLocation(),
641            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
642           << VD;
643       continue;
644     }
645 
646     // Check if initial value of threadprivate variable reference variable with
647     // local storage (it is not supported by runtime).
648     if (auto Init = VD->getAnyInitializer()) {
649       LocalVarRefChecker Checker(*this);
650       if (Checker.Visit(Init)) continue;
651     }
652 
653     Vars.push_back(RefExpr);
654     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
655   }
656   OMPThreadPrivateDecl *D = nullptr;
657   if (!Vars.empty()) {
658     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
659                                      Vars);
660     D->setAccess(AS_public);
661   }
662   return D;
663 }
664 
665 namespace {
666 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
667   DSAStackTy *Stack;
668   Sema &Actions;
669   bool ErrorFound;
670   CapturedStmt *CS;
671   llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
672 
673 public:
674   void VisitDeclRefExpr(DeclRefExpr *E) {
675     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
676       // Skip internally declared variables.
677       if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
678         return;
679 
680       SourceLocation ELoc = E->getExprLoc();
681 
682       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
683       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD);
684       if (DVar.CKind != OMPC_unknown) {
685         if (DKind == OMPD_task && DVar.CKind != OMPC_shared &&
686             !Stack->isThreadPrivate(VD) && !DVar.RefExpr)
687           ImplicitFirstprivate.push_back(DVar.RefExpr);
688         return;
689       }
690       // The default(none) clause requires that each variable that is referenced
691       // in the construct, and does not have a predetermined data-sharing
692       // attribute, must have its data-sharing attribute explicitly determined
693       // by being listed in a data-sharing attribute clause.
694       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
695           (DKind == OMPD_parallel || DKind == OMPD_task)) {
696         ErrorFound = true;
697         Actions.Diag(ELoc, diag::err_omp_no_dsa_for_variable) << VD;
698         return;
699       }
700 
701       // OpenMP [2.9.3.6, Restrictions, p.2]
702       //  A list item that appears in a reduction clause of the innermost
703       //  enclosing worksharing or parallel construct may not be accessed in an
704       //  explicit task.
705       // TODO:
706 
707       // Define implicit data-sharing attributes for task.
708       DVar = Stack->getImplicitDSA(VD);
709       if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
710         ImplicitFirstprivate.push_back(DVar.RefExpr);
711     }
712   }
713   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
714     for (auto C : S->clauses())
715       if (C)
716         for (StmtRange R = C->children(); R; ++R)
717           if (Stmt *Child = *R)
718             Visit(Child);
719   }
720   void VisitStmt(Stmt *S) {
721     for (Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E;
722          ++I)
723       if (Stmt *Child = *I)
724         if (!isa<OMPExecutableDirective>(Child))
725           Visit(Child);
726   }
727 
728   bool isErrorFound() { return ErrorFound; }
729   ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
730 
731   DSAAttrChecker(DSAStackTy *S, Sema &Actions, CapturedStmt *CS)
732       : Stack(S), Actions(Actions), ErrorFound(false), CS(CS) {}
733 };
734 } // namespace
735 
736 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, SourceLocation Loc,
737                                   Scope *CurScope) {
738   switch (DKind) {
739   case OMPD_parallel: {
740     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
741     QualType KmpInt32PtrTy = Context.getPointerType(KmpInt32Ty);
742     Sema::CapturedParamNameType Params[3] = {
743       std::make_pair(".global_tid.", KmpInt32PtrTy),
744       std::make_pair(".bound_tid.", KmpInt32PtrTy),
745       std::make_pair(StringRef(), QualType()) // __context with shared vars
746     };
747     ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP, Params);
748     break;
749   }
750   case OMPD_simd: {
751     Sema::CapturedParamNameType Params[1] = {
752       std::make_pair(StringRef(), QualType()) // __context with shared vars
753     };
754     ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP, Params);
755     break;
756   }
757   case OMPD_threadprivate:
758   case OMPD_task:
759     llvm_unreachable("OpenMP Directive is not allowed");
760   case OMPD_unknown:
761     llvm_unreachable("Unknown OpenMP directive");
762   }
763 }
764 
765 StmtResult Sema::ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind,
766                                                 ArrayRef<OMPClause *> Clauses,
767                                                 Stmt *AStmt,
768                                                 SourceLocation StartLoc,
769                                                 SourceLocation EndLoc) {
770   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
771 
772   StmtResult Res = StmtError();
773 
774   // Check default data sharing attributes for referenced variables.
775   DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
776   DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
777   if (DSAChecker.isErrorFound())
778     return StmtError();
779   // Generate list of implicitly defined firstprivate variables.
780   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
781   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
782 
783   bool ErrorFound = false;
784   if (!DSAChecker.getImplicitFirstprivate().empty()) {
785     if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
786             DSAChecker.getImplicitFirstprivate(), SourceLocation(),
787             SourceLocation(), SourceLocation())) {
788       ClausesWithImplicit.push_back(Implicit);
789       ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
790                    DSAChecker.getImplicitFirstprivate().size();
791     } else
792       ErrorFound = true;
793   }
794 
795   switch (Kind) {
796   case OMPD_parallel:
797     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
798                                        EndLoc);
799     break;
800   case OMPD_simd:
801     Res =
802         ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
803     break;
804   case OMPD_threadprivate:
805   case OMPD_task:
806     llvm_unreachable("OpenMP Directive is not allowed");
807   case OMPD_unknown:
808     llvm_unreachable("Unknown OpenMP directive");
809   }
810 
811   if (ErrorFound)
812     return StmtError();
813   return Res;
814 }
815 
816 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
817                                               Stmt *AStmt,
818                                               SourceLocation StartLoc,
819                                               SourceLocation EndLoc) {
820   assert(AStmt && isa<CapturedStmt>(AStmt) && "Captured statement expected");
821   CapturedStmt *CS = cast<CapturedStmt>(AStmt);
822   // 1.2.2 OpenMP Language Terminology
823   // Structured block - An executable statement with a single entry at the
824   // top and a single exit at the bottom.
825   // The point of exit cannot be a branch out of the structured block.
826   // longjmp() and throw() must not violate the entry/exit criteria.
827   CS->getCapturedDecl()->setNothrow();
828 
829   getCurFunction()->setHasBranchProtectedScope();
830 
831   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
832                                       AStmt);
833 }
834 
835 static bool isSimdDirective(OpenMPDirectiveKind DKind) {
836   return DKind == OMPD_simd; // FIXME: || DKind == OMPD_for_simd || ...
837 }
838 
839 namespace {
840 /// \brief Helper class for checking canonical form of the OpenMP loops and
841 /// extracting iteration space of each loop in the loop nest, that will be used
842 /// for IR generation.
843 class OpenMPIterationSpaceChecker {
844   /// \brief Reference to Sema.
845   Sema &SemaRef;
846   /// \brief A location for diagnostics (when there is no some better location).
847   SourceLocation DefaultLoc;
848   /// \brief A location for diagnostics (when increment is not compatible).
849   SourceLocation ConditionLoc;
850   /// \brief A source location for referring to condition later.
851   SourceRange ConditionSrcRange;
852   /// \brief Loop variable.
853   VarDecl *Var;
854   /// \brief Lower bound (initializer for the var).
855   Expr *LB;
856   /// \brief Upper bound.
857   Expr *UB;
858   /// \brief Loop step (increment).
859   Expr *Step;
860   /// \brief This flag is true when condition is one of:
861   ///   Var <  UB
862   ///   Var <= UB
863   ///   UB  >  Var
864   ///   UB  >= Var
865   bool TestIsLessOp;
866   /// \brief This flag is true when condition is strict ( < or > ).
867   bool TestIsStrictOp;
868   /// \brief This flag is true when step is subtracted on each iteration.
869   bool SubtractStep;
870 
871 public:
872   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
873       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
874         ConditionSrcRange(SourceRange()), Var(nullptr), LB(nullptr),
875         UB(nullptr), Step(nullptr), TestIsLessOp(false), TestIsStrictOp(false),
876         SubtractStep(false) {}
877   /// \brief Check init-expr for canonical loop form and save loop counter
878   /// variable - #Var and its initialization value - #LB.
879   bool CheckInit(Stmt *S);
880   /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
881   /// for less/greater and for strict/non-strict comparison.
882   bool CheckCond(Expr *S);
883   /// \brief Check incr-expr for canonical loop form and return true if it
884   /// does not conform, otherwise save loop step (#Step).
885   bool CheckInc(Expr *S);
886   /// \brief Return the loop counter variable.
887   VarDecl *GetLoopVar() const { return Var; }
888   /// \brief Return true if any expression is dependent.
889   bool Dependent() const;
890 
891 private:
892   /// \brief Check the right-hand side of an assignment in the increment
893   /// expression.
894   bool CheckIncRHS(Expr *RHS);
895   /// \brief Helper to set loop counter variable and its initializer.
896   bool SetVarAndLB(VarDecl *NewVar, Expr *NewLB);
897   /// \brief Helper to set upper bound.
898   bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, const SourceRange &SR,
899              const SourceLocation &SL);
900   /// \brief Helper to set loop increment.
901   bool SetStep(Expr *NewStep, bool Subtract);
902 };
903 
904 bool OpenMPIterationSpaceChecker::Dependent() const {
905   if (!Var) {
906     assert(!LB && !UB && !Step);
907     return false;
908   }
909   return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
910          (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
911 }
912 
913 bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar, Expr *NewLB) {
914   // State consistency checking to ensure correct usage.
915   assert(Var == nullptr && LB == nullptr && UB == nullptr && Step == nullptr &&
916          !TestIsLessOp && !TestIsStrictOp);
917   if (!NewVar || !NewLB)
918     return true;
919   Var = NewVar;
920   LB = NewLB;
921   return false;
922 }
923 
924 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
925                                         const SourceRange &SR,
926                                         const SourceLocation &SL) {
927   // State consistency checking to ensure correct usage.
928   assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
929          !TestIsLessOp && !TestIsStrictOp);
930   if (!NewUB)
931     return true;
932   UB = NewUB;
933   TestIsLessOp = LessOp;
934   TestIsStrictOp = StrictOp;
935   ConditionSrcRange = SR;
936   ConditionLoc = SL;
937   return false;
938 }
939 
940 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
941   // State consistency checking to ensure correct usage.
942   assert(Var != nullptr && LB != nullptr && Step == nullptr);
943   if (!NewStep)
944     return true;
945   if (!NewStep->isValueDependent()) {
946     // Check that the step is integer expression.
947     SourceLocation StepLoc = NewStep->getLocStart();
948     ExprResult Val =
949         SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
950     if (Val.isInvalid())
951       return true;
952     NewStep = Val.get();
953 
954     // OpenMP [2.6, Canonical Loop Form, Restrictions]
955     //  If test-expr is of form var relational-op b and relational-op is < or
956     //  <= then incr-expr must cause var to increase on each iteration of the
957     //  loop. If test-expr is of form var relational-op b and relational-op is
958     //  > or >= then incr-expr must cause var to decrease on each iteration of
959     //  the loop.
960     //  If test-expr is of form b relational-op var and relational-op is < or
961     //  <= then incr-expr must cause var to decrease on each iteration of the
962     //  loop. If test-expr is of form b relational-op var and relational-op is
963     //  > or >= then incr-expr must cause var to increase on each iteration of
964     //  the loop.
965     llvm::APSInt Result;
966     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
967     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
968     bool IsConstNeg =
969         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
970     bool IsConstZero = IsConstant && !Result.getBoolValue();
971     if (UB && (IsConstZero ||
972                (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
973                              : (!IsConstNeg || (IsUnsigned && !Subtract))))) {
974       SemaRef.Diag(NewStep->getExprLoc(),
975                    diag::err_omp_loop_incr_not_compatible)
976           << Var << TestIsLessOp << NewStep->getSourceRange();
977       SemaRef.Diag(ConditionLoc,
978                    diag::note_omp_loop_cond_requres_compatible_incr)
979           << TestIsLessOp << ConditionSrcRange;
980       return true;
981     }
982   }
983 
984   Step = NewStep;
985   SubtractStep = Subtract;
986   return false;
987 }
988 
989 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S) {
990   // Check init-expr for canonical loop form and save loop counter
991   // variable - #Var and its initialization value - #LB.
992   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
993   //   var = lb
994   //   integer-type var = lb
995   //   random-access-iterator-type var = lb
996   //   pointer-type var = lb
997   //
998   if (!S) {
999     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
1000     return true;
1001   }
1002   if (Expr *E = dyn_cast<Expr>(S))
1003     S = E->IgnoreParens();
1004   if (auto BO = dyn_cast<BinaryOperator>(S)) {
1005     if (BO->getOpcode() == BO_Assign)
1006       if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
1007         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), BO->getLHS());
1008   } else if (auto DS = dyn_cast<DeclStmt>(S)) {
1009     if (DS->isSingleDecl()) {
1010       if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
1011         if (Var->hasInit()) {
1012           // Accept non-canonical init form here but emit ext. warning.
1013           if (Var->getInitStyle() != VarDecl::CInit)
1014             SemaRef.Diag(S->getLocStart(),
1015                          diag::ext_omp_loop_not_canonical_init)
1016                 << S->getSourceRange();
1017           return SetVarAndLB(Var, Var->getInit());
1018         }
1019       }
1020     }
1021   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
1022     if (CE->getOperator() == OO_Equal)
1023       if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
1024         return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), CE->getArg(1));
1025 
1026   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
1027       << S->getSourceRange();
1028   return true;
1029 }
1030 
1031 /// \brief Ignore parenthesises, implicit casts, copy constructor and return the
1032 /// variable (which may be the loop variable) if possible.
1033 static const VarDecl *GetInitVarDecl(const Expr *E) {
1034   if (!E)
1035     return nullptr;
1036   E = E->IgnoreParenImpCasts();
1037   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
1038     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
1039       if (Ctor->isCopyConstructor() && CE->getNumArgs() == 1 &&
1040           CE->getArg(0) != nullptr)
1041         E = CE->getArg(0)->IgnoreParenImpCasts();
1042   auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
1043   if (!DRE)
1044     return nullptr;
1045   return dyn_cast<VarDecl>(DRE->getDecl());
1046 }
1047 
1048 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
1049   // Check test-expr for canonical form, save upper-bound UB, flags for
1050   // less/greater and for strict/non-strict comparison.
1051   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1052   //   var relational-op b
1053   //   b relational-op var
1054   //
1055   if (!S) {
1056     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
1057     return true;
1058   }
1059   S = S->IgnoreParenImpCasts();
1060   SourceLocation CondLoc = S->getLocStart();
1061   if (auto BO = dyn_cast<BinaryOperator>(S)) {
1062     if (BO->isRelationalOp()) {
1063       if (GetInitVarDecl(BO->getLHS()) == Var)
1064         return SetUB(BO->getRHS(),
1065                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
1066                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1067                      BO->getSourceRange(), BO->getOperatorLoc());
1068       if (GetInitVarDecl(BO->getRHS()) == Var)
1069         return SetUB(BO->getLHS(),
1070                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
1071                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
1072                      BO->getSourceRange(), BO->getOperatorLoc());
1073     }
1074   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1075     if (CE->getNumArgs() == 2) {
1076       auto Op = CE->getOperator();
1077       switch (Op) {
1078       case OO_Greater:
1079       case OO_GreaterEqual:
1080       case OO_Less:
1081       case OO_LessEqual:
1082         if (GetInitVarDecl(CE->getArg(0)) == Var)
1083           return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
1084                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1085                        CE->getOperatorLoc());
1086         if (GetInitVarDecl(CE->getArg(1)) == Var)
1087           return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
1088                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
1089                        CE->getOperatorLoc());
1090         break;
1091       default:
1092         break;
1093       }
1094     }
1095   }
1096   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
1097       << S->getSourceRange() << Var;
1098   return true;
1099 }
1100 
1101 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
1102   // RHS of canonical loop form increment can be:
1103   //   var + incr
1104   //   incr + var
1105   //   var - incr
1106   //
1107   RHS = RHS->IgnoreParenImpCasts();
1108   if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
1109     if (BO->isAdditiveOp()) {
1110       bool IsAdd = BO->getOpcode() == BO_Add;
1111       if (GetInitVarDecl(BO->getLHS()) == Var)
1112         return SetStep(BO->getRHS(), !IsAdd);
1113       if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
1114         return SetStep(BO->getLHS(), false);
1115     }
1116   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
1117     bool IsAdd = CE->getOperator() == OO_Plus;
1118     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
1119       if (GetInitVarDecl(CE->getArg(0)) == Var)
1120         return SetStep(CE->getArg(1), !IsAdd);
1121       if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
1122         return SetStep(CE->getArg(0), false);
1123     }
1124   }
1125   SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1126       << RHS->getSourceRange() << Var;
1127   return true;
1128 }
1129 
1130 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
1131   // Check incr-expr for canonical loop form and return true if it
1132   // does not conform.
1133   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
1134   //   ++var
1135   //   var++
1136   //   --var
1137   //   var--
1138   //   var += incr
1139   //   var -= incr
1140   //   var = var + incr
1141   //   var = incr + var
1142   //   var = var - incr
1143   //
1144   if (!S) {
1145     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
1146     return true;
1147   }
1148   S = S->IgnoreParens();
1149   if (auto UO = dyn_cast<UnaryOperator>(S)) {
1150     if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
1151       return SetStep(
1152           SemaRef.ActOnIntegerConstant(UO->getLocStart(),
1153                                        (UO->isDecrementOp() ? -1 : 1)).get(),
1154           false);
1155   } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
1156     switch (BO->getOpcode()) {
1157     case BO_AddAssign:
1158     case BO_SubAssign:
1159       if (GetInitVarDecl(BO->getLHS()) == Var)
1160         return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
1161       break;
1162     case BO_Assign:
1163       if (GetInitVarDecl(BO->getLHS()) == Var)
1164         return CheckIncRHS(BO->getRHS());
1165       break;
1166     default:
1167       break;
1168     }
1169   } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
1170     switch (CE->getOperator()) {
1171     case OO_PlusPlus:
1172     case OO_MinusMinus:
1173       if (GetInitVarDecl(CE->getArg(0)) == Var)
1174         return SetStep(
1175             SemaRef.ActOnIntegerConstant(
1176                         CE->getLocStart(),
1177                         ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
1178             false);
1179       break;
1180     case OO_PlusEqual:
1181     case OO_MinusEqual:
1182       if (GetInitVarDecl(CE->getArg(0)) == Var)
1183         return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
1184       break;
1185     case OO_Equal:
1186       if (GetInitVarDecl(CE->getArg(0)) == Var)
1187         return CheckIncRHS(CE->getArg(1));
1188       break;
1189     default:
1190       break;
1191     }
1192   }
1193   SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
1194       << S->getSourceRange() << Var;
1195   return true;
1196 }
1197 }
1198 
1199 /// \brief Called on a for stmt to check and extract its iteration space
1200 /// for further processing (such as collapsing).
1201 static bool CheckOpenMPIterationSpace(OpenMPDirectiveKind DKind, Stmt *S,
1202                                       Sema &SemaRef, DSAStackTy &DSA) {
1203   // OpenMP [2.6, Canonical Loop Form]
1204   //   for (init-expr; test-expr; incr-expr) structured-block
1205   auto For = dyn_cast_or_null<ForStmt>(S);
1206   if (!For) {
1207     SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
1208         << getOpenMPDirectiveName(DKind);
1209     return true;
1210   }
1211   assert(For->getBody());
1212 
1213   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
1214 
1215   // Check init.
1216   Stmt *Init = For->getInit();
1217   if (ISC.CheckInit(Init)) {
1218     return true;
1219   }
1220 
1221   bool HasErrors = false;
1222 
1223   // Check loop variable's type.
1224   VarDecl *Var = ISC.GetLoopVar();
1225 
1226   // OpenMP [2.6, Canonical Loop Form]
1227   // Var is one of the following:
1228   //   A variable of signed or unsigned integer type.
1229   //   For C++, a variable of a random access iterator type.
1230   //   For C, a variable of a pointer type.
1231   QualType VarType = Var->getType();
1232   if (!VarType->isDependentType() && !VarType->isIntegerType() &&
1233       !VarType->isPointerType() &&
1234       !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
1235     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
1236         << SemaRef.getLangOpts().CPlusPlus;
1237     HasErrors = true;
1238   }
1239 
1240   // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
1241   // a Construct, C/C++].
1242   // The loop iteration variable(s) in the associated for-loop(s) of a for or
1243   // parallel for construct may be listed in a private or lastprivate clause.
1244   DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var);
1245   if (isSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
1246       DVar.CKind != OMPC_linear && DVar.CKind != OMPC_lastprivate &&
1247       (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
1248     // The loop iteration variable in the associated for-loop of a simd
1249     // construct with just one associated for-loop may be listed in a linear
1250     // clause with a constant-linear-step that is the increment of the
1251     // associated for-loop.
1252     SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
1253         << getOpenMPClauseName(DVar.CKind);
1254     if (DVar.RefExpr)
1255       SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1256           << getOpenMPClauseName(DVar.CKind);
1257     else
1258       SemaRef.Diag(Var->getLocation(), diag::note_omp_predetermined_dsa)
1259           << getOpenMPClauseName(DVar.CKind);
1260     HasErrors = true;
1261   } else {
1262     // Make the loop iteration variable private by default.
1263     DSA.addDSA(Var, nullptr, OMPC_private);
1264   }
1265 
1266   assert(isSimdDirective(DKind) && "DSA for non-simd loop vars");
1267 
1268   // Check test-expr.
1269   HasErrors |= ISC.CheckCond(For->getCond());
1270 
1271   // Check incr-expr.
1272   HasErrors |= ISC.CheckInc(For->getInc());
1273 
1274   if (ISC.Dependent())
1275     return HasErrors;
1276 
1277   // FIXME: Build loop's iteration space representation.
1278   return HasErrors;
1279 }
1280 
1281 /// \brief A helper routine to skip no-op (attributed, compound) stmts get the
1282 /// next nested for loop. If \a IgnoreCaptured is true, it skips captured stmt
1283 /// to get the first for loop.
1284 static Stmt *IgnoreContainerStmts(Stmt *S, bool IgnoreCaptured) {
1285   if (IgnoreCaptured)
1286     if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
1287       S = CapS->getCapturedStmt();
1288   // OpenMP [2.8.1, simd construct, Restrictions]
1289   // All loops associated with the construct must be perfectly nested; that is,
1290   // there must be no intervening code nor any OpenMP directive between any two
1291   // loops.
1292   while (true) {
1293     if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
1294       S = AS->getSubStmt();
1295     else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
1296       if (CS->size() != 1)
1297         break;
1298       S = CS->body_back();
1299     } else
1300       break;
1301   }
1302   return S;
1303 }
1304 
1305 /// \brief Called on a for stmt to check itself and nested loops (if any).
1306 static bool CheckOpenMPLoop(OpenMPDirectiveKind DKind, unsigned NestedLoopCount,
1307                             Stmt *AStmt, Sema &SemaRef, DSAStackTy &DSA) {
1308   // This is helper routine for loop directives (e.g., 'for', 'simd',
1309   // 'for simd', etc.).
1310   assert(NestedLoopCount == 1);
1311   Stmt *CurStmt = IgnoreContainerStmts(AStmt, true);
1312   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
1313     if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA))
1314       return true;
1315     // Move on to the next nested for loop, or to the loop body.
1316     CurStmt = IgnoreContainerStmts(cast<ForStmt>(CurStmt)->getBody(), false);
1317   }
1318 
1319   // FIXME: Build resulting iteration space for IR generation (collapsing
1320   // iteration spaces when loop count > 1 ('collapse' clause)).
1321   return false;
1322 }
1323 
1324 StmtResult Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses,
1325                                           Stmt *AStmt, SourceLocation StartLoc,
1326                                           SourceLocation EndLoc) {
1327   // In presence of clause 'collapse', it will define the nested loops number.
1328   // For now, pass default value of 1.
1329   if (CheckOpenMPLoop(OMPD_simd, 1, AStmt, *this, *DSAStack))
1330     return StmtError();
1331 
1332   getCurFunction()->setHasBranchProtectedScope();
1333   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
1334 }
1335 
1336 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
1337                                              SourceLocation StartLoc,
1338                                              SourceLocation LParenLoc,
1339                                              SourceLocation EndLoc) {
1340   OMPClause *Res = nullptr;
1341   switch (Kind) {
1342   case OMPC_if:
1343     Res = ActOnOpenMPIfClause(Expr, StartLoc, LParenLoc, EndLoc);
1344     break;
1345   case OMPC_num_threads:
1346     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
1347     break;
1348   case OMPC_safelen:
1349     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
1350     break;
1351   case OMPC_collapse:
1352     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
1353     break;
1354   case OMPC_default:
1355   case OMPC_proc_bind:
1356   case OMPC_private:
1357   case OMPC_firstprivate:
1358   case OMPC_lastprivate:
1359   case OMPC_shared:
1360   case OMPC_linear:
1361   case OMPC_aligned:
1362   case OMPC_copyin:
1363   case OMPC_threadprivate:
1364   case OMPC_unknown:
1365     llvm_unreachable("Clause is not allowed.");
1366   }
1367   return Res;
1368 }
1369 
1370 OMPClause *Sema::ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
1371                                      SourceLocation LParenLoc,
1372                                      SourceLocation EndLoc) {
1373   Expr *ValExpr = Condition;
1374   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
1375       !Condition->isInstantiationDependent() &&
1376       !Condition->containsUnexpandedParameterPack()) {
1377     ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
1378                                            Condition->getExprLoc(), Condition);
1379     if (Val.isInvalid())
1380       return nullptr;
1381 
1382     ValExpr = Val.get();
1383   }
1384 
1385   return new (Context) OMPIfClause(ValExpr, StartLoc, LParenLoc, EndLoc);
1386 }
1387 
1388 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
1389                                                         Expr *Op) {
1390   if (!Op)
1391     return ExprError();
1392 
1393   class IntConvertDiagnoser : public ICEConvertDiagnoser {
1394   public:
1395     IntConvertDiagnoser()
1396         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
1397     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1398                                          QualType T) override {
1399       return S.Diag(Loc, diag::err_omp_not_integral) << T;
1400     }
1401     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1402                                              QualType T) override {
1403       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
1404     }
1405     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
1406                                                QualType T,
1407                                                QualType ConvTy) override {
1408       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
1409     }
1410     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
1411                                            QualType ConvTy) override {
1412       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
1413              << ConvTy->isEnumeralType() << ConvTy;
1414     }
1415     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1416                                             QualType T) override {
1417       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
1418     }
1419     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1420                                         QualType ConvTy) override {
1421       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
1422              << ConvTy->isEnumeralType() << ConvTy;
1423     }
1424     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
1425                                              QualType) override {
1426       llvm_unreachable("conversion functions are permitted");
1427     }
1428   } ConvertDiagnoser;
1429   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
1430 }
1431 
1432 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
1433                                              SourceLocation StartLoc,
1434                                              SourceLocation LParenLoc,
1435                                              SourceLocation EndLoc) {
1436   Expr *ValExpr = NumThreads;
1437   if (!NumThreads->isValueDependent() && !NumThreads->isTypeDependent() &&
1438       !NumThreads->isInstantiationDependent() &&
1439       !NumThreads->containsUnexpandedParameterPack()) {
1440     SourceLocation NumThreadsLoc = NumThreads->getLocStart();
1441     ExprResult Val =
1442         PerformOpenMPImplicitIntegerConversion(NumThreadsLoc, NumThreads);
1443     if (Val.isInvalid())
1444       return nullptr;
1445 
1446     ValExpr = Val.get();
1447 
1448     // OpenMP [2.5, Restrictions]
1449     //  The num_threads expression must evaluate to a positive integer value.
1450     llvm::APSInt Result;
1451     if (ValExpr->isIntegerConstantExpr(Result, Context) && Result.isSigned() &&
1452         !Result.isStrictlyPositive()) {
1453       Diag(NumThreadsLoc, diag::err_omp_negative_expression_in_clause)
1454           << "num_threads" << NumThreads->getSourceRange();
1455       return nullptr;
1456     }
1457   }
1458 
1459   return new (Context)
1460       OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
1461 }
1462 
1463 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
1464                                                        OpenMPClauseKind CKind) {
1465   if (!E)
1466     return ExprError();
1467   if (E->isValueDependent() || E->isTypeDependent() ||
1468       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
1469     return E;
1470   llvm::APSInt Result;
1471   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
1472   if (ICE.isInvalid())
1473     return ExprError();
1474   if (!Result.isStrictlyPositive()) {
1475     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
1476         << getOpenMPClauseName(CKind) << E->getSourceRange();
1477     return ExprError();
1478   }
1479   return ICE;
1480 }
1481 
1482 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1483                                           SourceLocation LParenLoc,
1484                                           SourceLocation EndLoc) {
1485   // OpenMP [2.8.1, simd construct, Description]
1486   // The parameter of the safelen clause must be a constant
1487   // positive integer expression.
1488   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
1489   if (Safelen.isInvalid())
1490     return nullptr;
1491   return new (Context)
1492       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
1493 }
1494 
1495 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
1496                                            SourceLocation StartLoc,
1497                                            SourceLocation LParenLoc,
1498                                            SourceLocation EndLoc) {
1499   // OpenMP [2.7.1, loop construct, Description]
1500   // OpenMP [2.8.1, simd construct, Description]
1501   // OpenMP [2.9.6, distribute construct, Description]
1502   // The parameter of the collapse clause must be a constant
1503   // positive integer expression.
1504   ExprResult NumForLoopsResult =
1505       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
1506   if (NumForLoopsResult.isInvalid())
1507     return nullptr;
1508   return new (Context)
1509       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
1510 }
1511 
1512 OMPClause *Sema::ActOnOpenMPSimpleClause(
1513     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
1514     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
1515   OMPClause *Res = nullptr;
1516   switch (Kind) {
1517   case OMPC_default:
1518     Res =
1519         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
1520                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
1521     break;
1522   case OMPC_proc_bind:
1523     Res = ActOnOpenMPProcBindClause(
1524         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
1525         LParenLoc, EndLoc);
1526     break;
1527   case OMPC_if:
1528   case OMPC_num_threads:
1529   case OMPC_safelen:
1530   case OMPC_collapse:
1531   case OMPC_private:
1532   case OMPC_firstprivate:
1533   case OMPC_lastprivate:
1534   case OMPC_shared:
1535   case OMPC_linear:
1536   case OMPC_aligned:
1537   case OMPC_copyin:
1538   case OMPC_threadprivate:
1539   case OMPC_unknown:
1540     llvm_unreachable("Clause is not allowed.");
1541   }
1542   return Res;
1543 }
1544 
1545 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
1546                                           SourceLocation KindKwLoc,
1547                                           SourceLocation StartLoc,
1548                                           SourceLocation LParenLoc,
1549                                           SourceLocation EndLoc) {
1550   if (Kind == OMPC_DEFAULT_unknown) {
1551     std::string Values;
1552     static_assert(OMPC_DEFAULT_unknown > 0,
1553                   "OMPC_DEFAULT_unknown not greater than 0");
1554     std::string Sep(", ");
1555     for (unsigned i = 0; i < OMPC_DEFAULT_unknown; ++i) {
1556       Values += "'";
1557       Values += getOpenMPSimpleClauseTypeName(OMPC_default, i);
1558       Values += "'";
1559       switch (i) {
1560       case OMPC_DEFAULT_unknown - 2:
1561         Values += " or ";
1562         break;
1563       case OMPC_DEFAULT_unknown - 1:
1564         break;
1565       default:
1566         Values += Sep;
1567         break;
1568       }
1569     }
1570     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
1571         << Values << getOpenMPClauseName(OMPC_default);
1572     return nullptr;
1573   }
1574   switch (Kind) {
1575   case OMPC_DEFAULT_none:
1576     DSAStack->setDefaultDSANone();
1577     break;
1578   case OMPC_DEFAULT_shared:
1579     DSAStack->setDefaultDSAShared();
1580     break;
1581   case OMPC_DEFAULT_unknown:
1582     llvm_unreachable("Clause kind is not allowed.");
1583     break;
1584   }
1585   return new (Context)
1586       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
1587 }
1588 
1589 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
1590                                            SourceLocation KindKwLoc,
1591                                            SourceLocation StartLoc,
1592                                            SourceLocation LParenLoc,
1593                                            SourceLocation EndLoc) {
1594   if (Kind == OMPC_PROC_BIND_unknown) {
1595     std::string Values;
1596     std::string Sep(", ");
1597     for (unsigned i = 0; i < OMPC_PROC_BIND_unknown; ++i) {
1598       Values += "'";
1599       Values += getOpenMPSimpleClauseTypeName(OMPC_proc_bind, i);
1600       Values += "'";
1601       switch (i) {
1602       case OMPC_PROC_BIND_unknown - 2:
1603         Values += " or ";
1604         break;
1605       case OMPC_PROC_BIND_unknown - 1:
1606         break;
1607       default:
1608         Values += Sep;
1609         break;
1610       }
1611     }
1612     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
1613         << Values << getOpenMPClauseName(OMPC_proc_bind);
1614     return nullptr;
1615   }
1616   return new (Context)
1617       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
1618 }
1619 
1620 OMPClause *
1621 Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> VarList,
1622                                Expr *TailExpr, SourceLocation StartLoc,
1623                                SourceLocation LParenLoc,
1624                                SourceLocation ColonLoc, SourceLocation EndLoc) {
1625   OMPClause *Res = nullptr;
1626   switch (Kind) {
1627   case OMPC_private:
1628     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
1629     break;
1630   case OMPC_firstprivate:
1631     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
1632     break;
1633   case OMPC_lastprivate:
1634     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
1635     break;
1636   case OMPC_shared:
1637     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
1638     break;
1639   case OMPC_linear:
1640     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
1641                                   ColonLoc, EndLoc);
1642     break;
1643   case OMPC_aligned:
1644     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
1645                                    ColonLoc, EndLoc);
1646     break;
1647   case OMPC_copyin:
1648     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
1649     break;
1650   case OMPC_if:
1651   case OMPC_num_threads:
1652   case OMPC_safelen:
1653   case OMPC_collapse:
1654   case OMPC_default:
1655   case OMPC_proc_bind:
1656   case OMPC_threadprivate:
1657   case OMPC_unknown:
1658     llvm_unreachable("Clause is not allowed.");
1659   }
1660   return Res;
1661 }
1662 
1663 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
1664                                           SourceLocation StartLoc,
1665                                           SourceLocation LParenLoc,
1666                                           SourceLocation EndLoc) {
1667   SmallVector<Expr *, 8> Vars;
1668   for (auto &RefExpr : VarList) {
1669     assert(RefExpr && "NULL expr in OpenMP private clause.");
1670     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
1671       // It will be analyzed later.
1672       Vars.push_back(RefExpr);
1673       continue;
1674     }
1675 
1676     SourceLocation ELoc = RefExpr->getExprLoc();
1677     // OpenMP [2.1, C/C++]
1678     //  A list item is a variable name.
1679     // OpenMP  [2.9.3.3, Restrictions, p.1]
1680     //  A variable that is part of another variable (as an array or
1681     //  structure element) cannot appear in a private clause.
1682     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
1683     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1684       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
1685       continue;
1686     }
1687     Decl *D = DE->getDecl();
1688     VarDecl *VD = cast<VarDecl>(D);
1689 
1690     QualType Type = VD->getType();
1691     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1692       // It will be analyzed later.
1693       Vars.push_back(DE);
1694       continue;
1695     }
1696 
1697     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1698     //  A variable that appears in a private clause must not have an incomplete
1699     //  type or a reference type.
1700     if (RequireCompleteType(ELoc, Type,
1701                             diag::err_omp_private_incomplete_type)) {
1702       continue;
1703     }
1704     if (Type->isReferenceType()) {
1705       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1706           << getOpenMPClauseName(OMPC_private) << Type;
1707       bool IsDecl =
1708           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1709       Diag(VD->getLocation(),
1710            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1711           << VD;
1712       continue;
1713     }
1714 
1715     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
1716     //  A variable of class type (or array thereof) that appears in a private
1717     //  clause requires an accesible, unambiguous default constructor for the
1718     //  class type.
1719     while (Type.getNonReferenceType()->isArrayType()) {
1720       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
1721                  ->getElementType();
1722     }
1723     CXXRecordDecl *RD = getLangOpts().CPlusPlus
1724                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
1725                             : nullptr;
1726     if (RD) {
1727       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
1728       PartialDiagnostic PD =
1729           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1730       if (!CD || CheckConstructorAccess(
1731                      ELoc, CD, InitializedEntity::InitializeTemporary(Type),
1732                      CD->getAccess(), PD) == AR_inaccessible ||
1733           CD->isDeleted()) {
1734         Diag(ELoc, diag::err_omp_required_method)
1735             << getOpenMPClauseName(OMPC_private) << 0;
1736         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1737                       VarDecl::DeclarationOnly;
1738         Diag(VD->getLocation(),
1739              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1740             << VD;
1741         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1742         continue;
1743       }
1744       MarkFunctionReferenced(ELoc, CD);
1745       DiagnoseUseOfDecl(CD, ELoc);
1746 
1747       CXXDestructorDecl *DD = RD->getDestructor();
1748       if (DD) {
1749         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1750             DD->isDeleted()) {
1751           Diag(ELoc, diag::err_omp_required_method)
1752               << getOpenMPClauseName(OMPC_private) << 4;
1753           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1754                         VarDecl::DeclarationOnly;
1755           Diag(VD->getLocation(),
1756                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1757               << VD;
1758           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1759           continue;
1760         }
1761         MarkFunctionReferenced(ELoc, DD);
1762         DiagnoseUseOfDecl(DD, ELoc);
1763       }
1764     }
1765 
1766     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1767     // in a Construct]
1768     //  Variables with the predetermined data-sharing attributes may not be
1769     //  listed in data-sharing attributes clauses, except for the cases
1770     //  listed below. For these exceptions only, listing a predetermined
1771     //  variable in a data-sharing attribute clause is allowed and overrides
1772     //  the variable's predetermined data-sharing attributes.
1773     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1774     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
1775       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
1776                                           << getOpenMPClauseName(OMPC_private);
1777       if (DVar.RefExpr) {
1778         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1779             << getOpenMPClauseName(DVar.CKind);
1780       } else {
1781         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1782             << getOpenMPClauseName(DVar.CKind);
1783       }
1784       continue;
1785     }
1786 
1787     DSAStack->addDSA(VD, DE, OMPC_private);
1788     Vars.push_back(DE);
1789   }
1790 
1791   if (Vars.empty())
1792     return nullptr;
1793 
1794   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
1795 }
1796 
1797 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
1798                                                SourceLocation StartLoc,
1799                                                SourceLocation LParenLoc,
1800                                                SourceLocation EndLoc) {
1801   SmallVector<Expr *, 8> Vars;
1802   for (auto &RefExpr : VarList) {
1803     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
1804     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
1805       // It will be analyzed later.
1806       Vars.push_back(RefExpr);
1807       continue;
1808     }
1809 
1810     SourceLocation ELoc = RefExpr->getExprLoc();
1811     // OpenMP [2.1, C/C++]
1812     //  A list item is a variable name.
1813     // OpenMP  [2.9.3.3, Restrictions, p.1]
1814     //  A variable that is part of another variable (as an array or
1815     //  structure element) cannot appear in a private clause.
1816     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
1817     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1818       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
1819       continue;
1820     }
1821     Decl *D = DE->getDecl();
1822     VarDecl *VD = cast<VarDecl>(D);
1823 
1824     QualType Type = VD->getType();
1825     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1826       // It will be analyzed later.
1827       Vars.push_back(DE);
1828       continue;
1829     }
1830 
1831     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
1832     //  A variable that appears in a private clause must not have an incomplete
1833     //  type or a reference type.
1834     if (RequireCompleteType(ELoc, Type,
1835                             diag::err_omp_firstprivate_incomplete_type)) {
1836       continue;
1837     }
1838     if (Type->isReferenceType()) {
1839       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
1840           << getOpenMPClauseName(OMPC_firstprivate) << Type;
1841       bool IsDecl =
1842           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1843       Diag(VD->getLocation(),
1844            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1845           << VD;
1846       continue;
1847     }
1848 
1849     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
1850     //  A variable of class type (or array thereof) that appears in a private
1851     //  clause requires an accesible, unambiguous copy constructor for the
1852     //  class type.
1853     Type = Context.getBaseElementType(Type);
1854     CXXRecordDecl *RD = getLangOpts().CPlusPlus
1855                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
1856                             : nullptr;
1857     if (RD) {
1858       CXXConstructorDecl *CD = LookupCopyingConstructor(RD, 0);
1859       PartialDiagnostic PD =
1860           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
1861       if (!CD || CheckConstructorAccess(
1862                      ELoc, CD, InitializedEntity::InitializeTemporary(Type),
1863                      CD->getAccess(), PD) == AR_inaccessible ||
1864           CD->isDeleted()) {
1865         Diag(ELoc, diag::err_omp_required_method)
1866             << getOpenMPClauseName(OMPC_firstprivate) << 1;
1867         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1868                       VarDecl::DeclarationOnly;
1869         Diag(VD->getLocation(),
1870              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1871             << VD;
1872         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1873         continue;
1874       }
1875       MarkFunctionReferenced(ELoc, CD);
1876       DiagnoseUseOfDecl(CD, ELoc);
1877 
1878       CXXDestructorDecl *DD = RD->getDestructor();
1879       if (DD) {
1880         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
1881             DD->isDeleted()) {
1882           Diag(ELoc, diag::err_omp_required_method)
1883               << getOpenMPClauseName(OMPC_firstprivate) << 4;
1884           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
1885                         VarDecl::DeclarationOnly;
1886           Diag(VD->getLocation(),
1887                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1888               << VD;
1889           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
1890           continue;
1891         }
1892         MarkFunctionReferenced(ELoc, DD);
1893         DiagnoseUseOfDecl(DD, ELoc);
1894       }
1895     }
1896 
1897     // If StartLoc and EndLoc are invalid - this is an implicit firstprivate
1898     // variable and it was checked already.
1899     if (StartLoc.isValid() && EndLoc.isValid()) {
1900       DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
1901       Type = Type.getNonReferenceType().getCanonicalType();
1902       bool IsConstant = Type.isConstant(Context);
1903       Type = Context.getBaseElementType(Type);
1904       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
1905       //  A list item that specifies a given variable may not appear in more
1906       // than one clause on the same directive, except that a variable may be
1907       //  specified in both firstprivate and lastprivate clauses.
1908       //  TODO: add processing for lastprivate.
1909       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
1910           DVar.RefExpr) {
1911         Diag(ELoc, diag::err_omp_wrong_dsa)
1912             << getOpenMPClauseName(DVar.CKind)
1913             << getOpenMPClauseName(OMPC_firstprivate);
1914         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1915             << getOpenMPClauseName(DVar.CKind);
1916         continue;
1917       }
1918 
1919       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1920       // in a Construct]
1921       //  Variables with the predetermined data-sharing attributes may not be
1922       //  listed in data-sharing attributes clauses, except for the cases
1923       //  listed below. For these exceptions only, listing a predetermined
1924       //  variable in a data-sharing attribute clause is allowed and overrides
1925       //  the variable's predetermined data-sharing attributes.
1926       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1927       // in a Construct, C/C++, p.2]
1928       //  Variables with const-qualified type having no mutable member may be
1929       //  listed in a firstprivate clause, even if they are static data members.
1930       if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
1931           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
1932         Diag(ELoc, diag::err_omp_wrong_dsa)
1933             << getOpenMPClauseName(DVar.CKind)
1934             << getOpenMPClauseName(OMPC_firstprivate);
1935         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
1936             << getOpenMPClauseName(DVar.CKind);
1937         continue;
1938       }
1939 
1940       // OpenMP [2.9.3.4, Restrictions, p.2]
1941       //  A list item that is private within a parallel region must not appear
1942       //  in a firstprivate clause on a worksharing construct if any of the
1943       //  worksharing regions arising from the worksharing construct ever bind
1944       //  to any of the parallel regions arising from the parallel construct.
1945       // OpenMP [2.9.3.4, Restrictions, p.3]
1946       //  A list item that appears in a reduction clause of a parallel construct
1947       //  must not appear in a firstprivate clause on a worksharing or task
1948       //  construct if any of the worksharing or task regions arising from the
1949       //  worksharing or task construct ever bind to any of the parallel regions
1950       //  arising from the parallel construct.
1951       // OpenMP [2.9.3.4, Restrictions, p.4]
1952       //  A list item that appears in a reduction clause in worksharing
1953       //  construct must not appear in a firstprivate clause in a task construct
1954       //  encountered during execution of any of the worksharing regions arising
1955       //  from the worksharing construct.
1956       // TODO:
1957     }
1958 
1959     DSAStack->addDSA(VD, DE, OMPC_firstprivate);
1960     Vars.push_back(DE);
1961   }
1962 
1963   if (Vars.empty())
1964     return nullptr;
1965 
1966   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
1967                                        Vars);
1968 }
1969 
1970 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
1971                                               SourceLocation StartLoc,
1972                                               SourceLocation LParenLoc,
1973                                               SourceLocation EndLoc) {
1974   SmallVector<Expr *, 8> Vars;
1975   for (auto &RefExpr : VarList) {
1976     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
1977     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
1978       // It will be analyzed later.
1979       Vars.push_back(RefExpr);
1980       continue;
1981     }
1982 
1983     SourceLocation ELoc = RefExpr->getExprLoc();
1984     // OpenMP [2.1, C/C++]
1985     //  A list item is a variable name.
1986     // OpenMP  [2.14.3.5, Restrictions, p.1]
1987     //  A variable that is part of another variable (as an array or structure
1988     //  element) cannot appear in a lastprivate clause.
1989     DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
1990     if (!DE || !isa<VarDecl>(DE->getDecl())) {
1991       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
1992       continue;
1993     }
1994     Decl *D = DE->getDecl();
1995     VarDecl *VD = cast<VarDecl>(D);
1996 
1997     QualType Type = VD->getType();
1998     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
1999       // It will be analyzed later.
2000       Vars.push_back(DE);
2001       continue;
2002     }
2003 
2004     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
2005     //  A variable that appears in a lastprivate clause must not have an
2006     //  incomplete type or a reference type.
2007     if (RequireCompleteType(ELoc, Type,
2008                             diag::err_omp_lastprivate_incomplete_type)) {
2009       continue;
2010     }
2011     if (Type->isReferenceType()) {
2012       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
2013           << getOpenMPClauseName(OMPC_lastprivate) << Type;
2014       bool IsDecl =
2015           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2016       Diag(VD->getLocation(),
2017            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2018           << VD;
2019       continue;
2020     }
2021 
2022     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
2023     // in a Construct]
2024     //  Variables with the predetermined data-sharing attributes may not be
2025     //  listed in data-sharing attributes clauses, except for the cases
2026     //  listed below.
2027     //  A list item that is private within a parallel region, or that appears in
2028     //  the reduction clause of a parallel construct, must not appear in a
2029     //  lastprivate clause on a worksharing construct if any of the
2030     //  corresponding worksharing regions ever binds to any of the corresponding
2031     //  parallel regions.
2032     //  TODO: Check implicit DSA for worksharing directives.
2033     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
2034     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
2035         DVar.CKind != OMPC_firstprivate &&
2036         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
2037       Diag(ELoc, diag::err_omp_wrong_dsa)
2038           << getOpenMPClauseName(DVar.CKind)
2039           << getOpenMPClauseName(OMPC_lastprivate);
2040       if (DVar.RefExpr)
2041         Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2042             << getOpenMPClauseName(DVar.CKind);
2043       else
2044         Diag(VD->getLocation(), diag::note_omp_predetermined_dsa)
2045             << getOpenMPClauseName(DVar.CKind);
2046       continue;
2047     }
2048 
2049     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
2050     //  A variable of class type (or array thereof) that appears in a lastprivate
2051     //  clause requires an accessible, unambiguous default constructor for the
2052     //  class type, unless the list item is also specified in a firstprivate
2053     //  clause.
2054     //  A variable of class type (or array thereof) that appears in a
2055     //  lastprivate clause requires an accessible, unambiguous copy assignment
2056     //  operator for the class type.
2057     while (Type.getNonReferenceType()->isArrayType())
2058       Type = cast<ArrayType>(Type.getNonReferenceType().getTypePtr())
2059                  ->getElementType();
2060     CXXRecordDecl *RD = getLangOpts().CPlusPlus
2061                             ? Type.getNonReferenceType()->getAsCXXRecordDecl()
2062                             : nullptr;
2063     if (RD) {
2064       // FIXME: If a variable is also specified in a firstprivate clause, we may
2065       // not require default constructor. This can be fixed after adding some
2066       // directive allowing both firstprivate and lastprivate clauses (and this
2067       // should be probably checked after all clauses are processed).
2068       CXXConstructorDecl *CD = LookupDefaultConstructor(RD);
2069       PartialDiagnostic PD =
2070           PartialDiagnostic(PartialDiagnostic::NullDiagnostic());
2071       if (!CD || CheckConstructorAccess(
2072                      ELoc, CD, InitializedEntity::InitializeTemporary(Type),
2073                      CD->getAccess(), PD) == AR_inaccessible ||
2074           CD->isDeleted()) {
2075         Diag(ELoc, diag::err_omp_required_method)
2076             << getOpenMPClauseName(OMPC_lastprivate) << 0;
2077         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2078                       VarDecl::DeclarationOnly;
2079         Diag(VD->getLocation(),
2080              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2081             << VD;
2082         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2083         continue;
2084       }
2085       MarkFunctionReferenced(ELoc, CD);
2086       DiagnoseUseOfDecl(CD, ELoc);
2087 
2088       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
2089       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
2090       if (!MD || CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
2091           MD->isDeleted()) {
2092         Diag(ELoc, diag::err_omp_required_method)
2093             << getOpenMPClauseName(OMPC_lastprivate) << 2;
2094         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2095                       VarDecl::DeclarationOnly;
2096         Diag(VD->getLocation(),
2097              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2098             << VD;
2099         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2100         continue;
2101       }
2102       MarkFunctionReferenced(ELoc, MD);
2103       DiagnoseUseOfDecl(MD, ELoc);
2104 
2105       CXXDestructorDecl *DD = RD->getDestructor();
2106       if (DD) {
2107         if (CheckDestructorAccess(ELoc, DD, PD) == AR_inaccessible ||
2108             DD->isDeleted()) {
2109           Diag(ELoc, diag::err_omp_required_method)
2110               << getOpenMPClauseName(OMPC_lastprivate) << 4;
2111           bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2112                         VarDecl::DeclarationOnly;
2113           Diag(VD->getLocation(),
2114                IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2115               << VD;
2116           Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2117           continue;
2118         }
2119         MarkFunctionReferenced(ELoc, DD);
2120         DiagnoseUseOfDecl(DD, ELoc);
2121       }
2122     }
2123 
2124     DSAStack->addDSA(VD, DE, OMPC_lastprivate);
2125     Vars.push_back(DE);
2126   }
2127 
2128   if (Vars.empty())
2129     return nullptr;
2130 
2131   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
2132                                       Vars);
2133 }
2134 
2135 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
2136                                          SourceLocation StartLoc,
2137                                          SourceLocation LParenLoc,
2138                                          SourceLocation EndLoc) {
2139   SmallVector<Expr *, 8> Vars;
2140   for (auto &RefExpr : VarList) {
2141     assert(RefExpr && "NULL expr in OpenMP shared clause.");
2142     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2143       // It will be analyzed later.
2144       Vars.push_back(RefExpr);
2145       continue;
2146     }
2147 
2148     SourceLocation ELoc = RefExpr->getExprLoc();
2149     // OpenMP [2.1, C/C++]
2150     //  A list item is a variable name.
2151     // OpenMP  [2.14.3.2, Restrictions, p.1]
2152     //  A variable that is part of another variable (as an array or structure
2153     //  element) cannot appear in a shared unless it is a static data member
2154     //  of a C++ class.
2155     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
2156     if (!DE || !isa<VarDecl>(DE->getDecl())) {
2157       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2158       continue;
2159     }
2160     Decl *D = DE->getDecl();
2161     VarDecl *VD = cast<VarDecl>(D);
2162 
2163     QualType Type = VD->getType();
2164     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
2165       // It will be analyzed later.
2166       Vars.push_back(DE);
2167       continue;
2168     }
2169 
2170     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
2171     // in a Construct]
2172     //  Variables with the predetermined data-sharing attributes may not be
2173     //  listed in data-sharing attributes clauses, except for the cases
2174     //  listed below. For these exceptions only, listing a predetermined
2175     //  variable in a data-sharing attribute clause is allowed and overrides
2176     //  the variable's predetermined data-sharing attributes.
2177     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
2178     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
2179         DVar.RefExpr) {
2180       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
2181                                           << getOpenMPClauseName(OMPC_shared);
2182       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2183           << getOpenMPClauseName(DVar.CKind);
2184       continue;
2185     }
2186 
2187     DSAStack->addDSA(VD, DE, OMPC_shared);
2188     Vars.push_back(DE);
2189   }
2190 
2191   if (Vars.empty())
2192     return nullptr;
2193 
2194   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
2195 }
2196 
2197 OMPClause *Sema::ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
2198                                          SourceLocation StartLoc,
2199                                          SourceLocation LParenLoc,
2200                                          SourceLocation ColonLoc,
2201                                          SourceLocation EndLoc) {
2202   SmallVector<Expr *, 8> Vars;
2203   for (auto &RefExpr : VarList) {
2204     assert(RefExpr && "NULL expr in OpenMP linear clause.");
2205     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2206       // It will be analyzed later.
2207       Vars.push_back(RefExpr);
2208       continue;
2209     }
2210 
2211     // OpenMP [2.14.3.7, linear clause]
2212     // A list item that appears in a linear clause is subject to the private
2213     // clause semantics described in Section 2.14.3.3 on page 159 except as
2214     // noted. In addition, the value of the new list item on each iteration
2215     // of the associated loop(s) corresponds to the value of the original
2216     // list item before entering the construct plus the logical number of
2217     // the iteration times linear-step.
2218 
2219     SourceLocation ELoc = RefExpr->getExprLoc();
2220     // OpenMP [2.1, C/C++]
2221     //  A list item is a variable name.
2222     // OpenMP  [2.14.3.3, Restrictions, p.1]
2223     //  A variable that is part of another variable (as an array or
2224     //  structure element) cannot appear in a private clause.
2225     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
2226     if (!DE || !isa<VarDecl>(DE->getDecl())) {
2227       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2228       continue;
2229     }
2230 
2231     VarDecl *VD = cast<VarDecl>(DE->getDecl());
2232 
2233     // OpenMP [2.14.3.7, linear clause]
2234     //  A list-item cannot appear in more than one linear clause.
2235     //  A list-item that appears in a linear clause cannot appear in any
2236     //  other data-sharing attribute clause.
2237     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD);
2238     if (DVar.RefExpr) {
2239       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
2240                                           << getOpenMPClauseName(OMPC_linear);
2241       Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2242           << getOpenMPClauseName(DVar.CKind);
2243       continue;
2244     }
2245 
2246     QualType QType = VD->getType();
2247     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2248       // It will be analyzed later.
2249       Vars.push_back(DE);
2250       continue;
2251     }
2252 
2253     // A variable must not have an incomplete type or a reference type.
2254     if (RequireCompleteType(ELoc, QType,
2255                             diag::err_omp_linear_incomplete_type)) {
2256       continue;
2257     }
2258     if (QType->isReferenceType()) {
2259       Diag(ELoc, diag::err_omp_clause_ref_type_arg)
2260           << getOpenMPClauseName(OMPC_linear) << QType;
2261       bool IsDecl =
2262           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2263       Diag(VD->getLocation(),
2264            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2265           << VD;
2266       continue;
2267     }
2268 
2269     // A list item must not be const-qualified.
2270     if (QType.isConstant(Context)) {
2271       Diag(ELoc, diag::err_omp_const_variable)
2272           << getOpenMPClauseName(OMPC_linear);
2273       bool IsDecl =
2274           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2275       Diag(VD->getLocation(),
2276            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2277           << VD;
2278       continue;
2279     }
2280 
2281     // A list item must be of integral or pointer type.
2282     QType = QType.getUnqualifiedType().getCanonicalType();
2283     const Type *Ty = QType.getTypePtrOrNull();
2284     if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
2285                 !Ty->isPointerType())) {
2286       Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
2287       bool IsDecl =
2288           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2289       Diag(VD->getLocation(),
2290            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2291           << VD;
2292       continue;
2293     }
2294 
2295     DSAStack->addDSA(VD, DE, OMPC_linear);
2296     Vars.push_back(DE);
2297   }
2298 
2299   if (Vars.empty())
2300     return nullptr;
2301 
2302   Expr *StepExpr = Step;
2303   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2304       !Step->isInstantiationDependent() &&
2305       !Step->containsUnexpandedParameterPack()) {
2306     SourceLocation StepLoc = Step->getLocStart();
2307     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
2308     if (Val.isInvalid())
2309       return nullptr;
2310     StepExpr = Val.get();
2311 
2312     // Warn about zero linear step (it would be probably better specified as
2313     // making corresponding variables 'const').
2314     llvm::APSInt Result;
2315     if (StepExpr->isIntegerConstantExpr(Result, Context) &&
2316         !Result.isNegative() && !Result.isStrictlyPositive())
2317       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
2318                                                      << (Vars.size() > 1);
2319   }
2320 
2321   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, ColonLoc, EndLoc,
2322                                  Vars, StepExpr);
2323 }
2324 
2325 OMPClause *Sema::ActOnOpenMPAlignedClause(
2326     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
2327     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
2328 
2329   SmallVector<Expr *, 8> Vars;
2330   for (auto &RefExpr : VarList) {
2331     assert(RefExpr && "NULL expr in OpenMP aligned clause.");
2332     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2333       // It will be analyzed later.
2334       Vars.push_back(RefExpr);
2335       continue;
2336     }
2337 
2338     SourceLocation ELoc = RefExpr->getExprLoc();
2339     // OpenMP [2.1, C/C++]
2340     //  A list item is a variable name.
2341     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
2342     if (!DE || !isa<VarDecl>(DE->getDecl())) {
2343       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2344       continue;
2345     }
2346 
2347     VarDecl *VD = cast<VarDecl>(DE->getDecl());
2348 
2349     // OpenMP  [2.8.1, simd construct, Restrictions]
2350     // The type of list items appearing in the aligned clause must be
2351     // array, pointer, reference to array, or reference to pointer.
2352     QualType QType = DE->getType()
2353                          .getNonReferenceType()
2354                          .getUnqualifiedType()
2355                          .getCanonicalType();
2356     const Type *Ty = QType.getTypePtrOrNull();
2357     if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
2358                 !Ty->isPointerType())) {
2359       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
2360           << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
2361       bool IsDecl =
2362           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2363       Diag(VD->getLocation(),
2364            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2365           << VD;
2366       continue;
2367     }
2368 
2369     // OpenMP  [2.8.1, simd construct, Restrictions]
2370     // A list-item cannot appear in more than one aligned clause.
2371     if (DeclRefExpr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
2372       Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
2373       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
2374           << getOpenMPClauseName(OMPC_aligned);
2375       continue;
2376     }
2377 
2378     Vars.push_back(DE);
2379   }
2380 
2381   // OpenMP [2.8.1, simd construct, Description]
2382   // The parameter of the aligned clause, alignment, must be a constant
2383   // positive integer expression.
2384   // If no optional parameter is specified, implementation-defined default
2385   // alignments for SIMD instructions on the target platforms are assumed.
2386   if (Alignment != nullptr) {
2387     ExprResult AlignResult =
2388         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
2389     if (AlignResult.isInvalid())
2390       return nullptr;
2391     Alignment = AlignResult.get();
2392   }
2393   if (Vars.empty())
2394     return nullptr;
2395 
2396   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
2397                                   EndLoc, Vars, Alignment);
2398 }
2399 
2400 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
2401                                          SourceLocation StartLoc,
2402                                          SourceLocation LParenLoc,
2403                                          SourceLocation EndLoc) {
2404   SmallVector<Expr *, 8> Vars;
2405   for (auto &RefExpr : VarList) {
2406     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
2407     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
2408       // It will be analyzed later.
2409       Vars.push_back(RefExpr);
2410       continue;
2411     }
2412 
2413     SourceLocation ELoc = RefExpr->getExprLoc();
2414     // OpenMP [2.1, C/C++]
2415     //  A list item is a variable name.
2416     // OpenMP  [2.14.4.1, Restrictions, p.1]
2417     //  A list item that appears in a copyin clause must be threadprivate.
2418     DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
2419     if (!DE || !isa<VarDecl>(DE->getDecl())) {
2420       Diag(ELoc, diag::err_omp_expected_var_name) << RefExpr->getSourceRange();
2421       continue;
2422     }
2423 
2424     Decl *D = DE->getDecl();
2425     VarDecl *VD = cast<VarDecl>(D);
2426 
2427     QualType Type = VD->getType();
2428     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
2429       // It will be analyzed later.
2430       Vars.push_back(DE);
2431       continue;
2432     }
2433 
2434     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
2435     //  A list item that appears in a copyin clause must be threadprivate.
2436     if (!DSAStack->isThreadPrivate(VD)) {
2437       Diag(ELoc, diag::err_omp_required_access)
2438           << getOpenMPClauseName(OMPC_copyin)
2439           << getOpenMPDirectiveName(OMPD_threadprivate);
2440       continue;
2441     }
2442 
2443     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
2444     //  A variable of class type (or array thereof) that appears in a
2445     //  copyin clause requires an accesible, unambiguous copy assignment
2446     //  operator for the class type.
2447     Type = Context.getBaseElementType(Type);
2448     CXXRecordDecl *RD =
2449         getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
2450     if (RD) {
2451       CXXMethodDecl *MD = LookupCopyingAssignment(RD, 0, false, 0);
2452       DeclAccessPair FoundDecl = DeclAccessPair::make(MD, MD->getAccess());
2453       if (!MD || CheckMemberAccess(ELoc, RD, FoundDecl) == AR_inaccessible ||
2454           MD->isDeleted()) {
2455         Diag(ELoc, diag::err_omp_required_method)
2456             << getOpenMPClauseName(OMPC_copyin) << 2;
2457         bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2458                       VarDecl::DeclarationOnly;
2459         Diag(VD->getLocation(),
2460              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2461             << VD;
2462         Diag(RD->getLocation(), diag::note_previous_decl) << RD;
2463         continue;
2464       }
2465       MarkFunctionReferenced(ELoc, MD);
2466       DiagnoseUseOfDecl(MD, ELoc);
2467     }
2468 
2469     DSAStack->addDSA(VD, DE, OMPC_copyin);
2470     Vars.push_back(DE);
2471   }
2472 
2473   if (Vars.empty())
2474     return nullptr;
2475 
2476   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
2477 }
2478 
2479 #undef DSAStack
2480