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