SemaDeclCXX.cpp revision 1c030e9a3f290a1eea5de82fe1e63dfde2bd8f1e
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
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//
10//  This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclVisitor.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallString.h"
40#include <map>
41#include <set>
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
49namespace {
50  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51  /// the default argument of a parameter to determine whether it
52  /// contains any ill-formed subexpressions. For example, this will
53  /// diagnose the use of local variables or parameters within the
54  /// default argument expression.
55  class CheckDefaultArgumentVisitor
56    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57    Expr *DefaultArg;
58    Sema *S;
59
60  public:
61    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62      : DefaultArg(defarg), S(s) {}
63
64    bool VisitExpr(Expr *Node);
65    bool VisitDeclRefExpr(DeclRefExpr *DRE);
66    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67    bool VisitLambdaExpr(LambdaExpr *Lambda);
68  };
69
70  /// VisitExpr - Visit all of the children of this expression.
71  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
72    bool IsInvalid = false;
73    for (Stmt::child_range I = Node->children(); I; ++I)
74      IsInvalid |= Visit(*I);
75    return IsInvalid;
76  }
77
78  /// VisitDeclRefExpr - Visit a reference to a declaration, to
79  /// determine whether this declaration can be used in the default
80  /// argument expression.
81  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
82    NamedDecl *Decl = DRE->getDecl();
83    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
84      // C++ [dcl.fct.default]p9
85      //   Default arguments are evaluated each time the function is
86      //   called. The order of evaluation of function arguments is
87      //   unspecified. Consequently, parameters of a function shall not
88      //   be used in default argument expressions, even if they are not
89      //   evaluated. Parameters of a function declared before a default
90      //   argument expression are in scope and can hide namespace and
91      //   class member names.
92      return S->Diag(DRE->getLocStart(),
93                     diag::err_param_default_argument_references_param)
94         << Param->getDeclName() << DefaultArg->getSourceRange();
95    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
96      // C++ [dcl.fct.default]p7
97      //   Local variables shall not be used in default argument
98      //   expressions.
99      if (VDecl->isLocalVarDecl())
100        return S->Diag(DRE->getLocStart(),
101                       diag::err_param_default_argument_references_local)
102          << VDecl->getDeclName() << DefaultArg->getSourceRange();
103    }
104
105    return false;
106  }
107
108  /// VisitCXXThisExpr - Visit a C++ "this" expression.
109  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
110    // C++ [dcl.fct.default]p8:
111    //   The keyword this shall not be used in a default argument of a
112    //   member function.
113    return S->Diag(ThisE->getLocStart(),
114                   diag::err_param_default_argument_references_this)
115               << ThisE->getSourceRange();
116  }
117
118  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
119    // C++11 [expr.lambda.prim]p13:
120    //   A lambda-expression appearing in a default argument shall not
121    //   implicitly or explicitly capture any entity.
122    if (Lambda->capture_begin() == Lambda->capture_end())
123      return false;
124
125    return S->Diag(Lambda->getLocStart(),
126                   diag::err_lambda_capture_default_arg);
127  }
128}
129
130void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
131                                                      CXXMethodDecl *Method) {
132  // If we have an MSAny spec already, don't bother.
133  if (!Method || ComputedEST == EST_MSAny)
134    return;
135
136  const FunctionProtoType *Proto
137    = Method->getType()->getAs<FunctionProtoType>();
138  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
139  if (!Proto)
140    return;
141
142  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
143
144  // If this function can throw any exceptions, make a note of that.
145  if (EST == EST_MSAny || EST == EST_None) {
146    ClearExceptions();
147    ComputedEST = EST;
148    return;
149  }
150
151  // FIXME: If the call to this decl is using any of its default arguments, we
152  // need to search them for potentially-throwing calls.
153
154  // If this function has a basic noexcept, it doesn't affect the outcome.
155  if (EST == EST_BasicNoexcept)
156    return;
157
158  // If we have a throw-all spec at this point, ignore the function.
159  if (ComputedEST == EST_None)
160    return;
161
162  // If we're still at noexcept(true) and there's a nothrow() callee,
163  // change to that specification.
164  if (EST == EST_DynamicNone) {
165    if (ComputedEST == EST_BasicNoexcept)
166      ComputedEST = EST_DynamicNone;
167    return;
168  }
169
170  // Check out noexcept specs.
171  if (EST == EST_ComputedNoexcept) {
172    FunctionProtoType::NoexceptResult NR =
173        Proto->getNoexceptSpec(Self->Context);
174    assert(NR != FunctionProtoType::NR_NoNoexcept &&
175           "Must have noexcept result for EST_ComputedNoexcept.");
176    assert(NR != FunctionProtoType::NR_Dependent &&
177           "Should not generate implicit declarations for dependent cases, "
178           "and don't know how to handle them anyway.");
179
180    // noexcept(false) -> no spec on the new function
181    if (NR == FunctionProtoType::NR_Throw) {
182      ClearExceptions();
183      ComputedEST = EST_None;
184    }
185    // noexcept(true) won't change anything either.
186    return;
187  }
188
189  assert(EST == EST_Dynamic && "EST case not considered earlier.");
190  assert(ComputedEST != EST_None &&
191         "Shouldn't collect exceptions when throw-all is guaranteed.");
192  ComputedEST = EST_Dynamic;
193  // Record the exceptions in this function's exception specification.
194  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
195                                          EEnd = Proto->exception_end();
196       E != EEnd; ++E)
197    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
198      Exceptions.push_back(*E);
199}
200
201void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
202  if (!E || ComputedEST == EST_MSAny)
203    return;
204
205  // FIXME:
206  //
207  // C++0x [except.spec]p14:
208  //   [An] implicit exception-specification specifies the type-id T if and
209  // only if T is allowed by the exception-specification of a function directly
210  // invoked by f's implicit definition; f shall allow all exceptions if any
211  // function it directly invokes allows all exceptions, and f shall allow no
212  // exceptions if every function it directly invokes allows no exceptions.
213  //
214  // Note in particular that if an implicit exception-specification is generated
215  // for a function containing a throw-expression, that specification can still
216  // be noexcept(true).
217  //
218  // Note also that 'directly invoked' is not defined in the standard, and there
219  // is no indication that we should only consider potentially-evaluated calls.
220  //
221  // Ultimately we should implement the intent of the standard: the exception
222  // specification should be the set of exceptions which can be thrown by the
223  // implicit definition. For now, we assume that any non-nothrow expression can
224  // throw any exception.
225
226  if (Self->canThrow(E))
227    ComputedEST = EST_None;
228}
229
230bool
231Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
232                              SourceLocation EqualLoc) {
233  if (RequireCompleteType(Param->getLocation(), Param->getType(),
234                          diag::err_typecheck_decl_incomplete_type)) {
235    Param->setInvalidDecl();
236    return true;
237  }
238
239  // C++ [dcl.fct.default]p5
240  //   A default argument expression is implicitly converted (clause
241  //   4) to the parameter type. The default argument expression has
242  //   the same semantic constraints as the initializer expression in
243  //   a declaration of a variable of the parameter type, using the
244  //   copy-initialization semantics (8.5).
245  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
246                                                                    Param);
247  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
248                                                           EqualLoc);
249  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
250  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
251  if (Result.isInvalid())
252    return true;
253  Arg = Result.takeAs<Expr>();
254
255  CheckImplicitConversions(Arg, EqualLoc);
256  Arg = MaybeCreateExprWithCleanups(Arg);
257
258  // Okay: add the default argument to the parameter
259  Param->setDefaultArg(Arg);
260
261  // We have already instantiated this parameter; provide each of the
262  // instantiations with the uninstantiated default argument.
263  UnparsedDefaultArgInstantiationsMap::iterator InstPos
264    = UnparsedDefaultArgInstantiations.find(Param);
265  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269    // We're done tracking this parameter's instantiations.
270    UnparsedDefaultArgInstantiations.erase(InstPos);
271  }
272
273  return false;
274}
275
276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
279void
280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
281                                Expr *DefaultArg) {
282  if (!param || !DefaultArg)
283    return;
284
285  ParmVarDecl *Param = cast<ParmVarDecl>(param);
286  UnparsedDefaultArgLocs.erase(Param);
287
288  // Default arguments are only permitted in C++
289  if (!getLangOpts().CPlusPlus) {
290    Diag(EqualLoc, diag::err_param_default_argument)
291      << DefaultArg->getSourceRange();
292    Param->setInvalidDecl();
293    return;
294  }
295
296  // Check for unexpanded parameter packs.
297  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298    Param->setInvalidDecl();
299    return;
300  }
301
302  // Check that the default argument is well-formed
303  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304  if (DefaultArgChecker.Visit(DefaultArg)) {
305    Param->setInvalidDecl();
306    return;
307  }
308
309  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
310}
311
312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
317                                             SourceLocation EqualLoc,
318                                             SourceLocation ArgLoc) {
319  if (!param)
320    return;
321
322  ParmVarDecl *Param = cast<ParmVarDecl>(param);
323  if (Param)
324    Param->setUnparsedDefaultArg();
325
326  UnparsedDefaultArgLocs[Param] = ArgLoc;
327}
328
329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
332  if (!param)
333    return;
334
335  ParmVarDecl *Param = cast<ParmVarDecl>(param);
336
337  Param->setInvalidDecl();
338
339  UnparsedDefaultArgLocs.erase(Param);
340}
341
342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348  // C++ [dcl.fct.default]p3
349  //   A default argument expression shall be specified only in the
350  //   parameter-declaration-clause of a function declaration or in a
351  //   template-parameter (14.1). It shall not be specified for a
352  //   parameter pack. If it is specified in a
353  //   parameter-declaration-clause, it shall not occur within a
354  //   declarator or abstract-declarator of a parameter-declaration.
355  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
356    DeclaratorChunk &chunk = D.getTypeObject(i);
357    if (chunk.Kind == DeclaratorChunk::Function) {
358      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359        ParmVarDecl *Param =
360          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
361        if (Param->hasUnparsedDefaultArg()) {
362          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
363          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365          delete Toks;
366          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
367        } else if (Param->getDefaultArg()) {
368          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369            << Param->getDefaultArg()->getSourceRange();
370          Param->setDefaultArg(0);
371        }
372      }
373    }
374  }
375}
376
377/// MergeCXXFunctionDecl - Merge two declarations of the same C++
378/// function, once we already know that they have the same
379/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380/// error, false otherwise.
381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382                                Scope *S) {
383  bool Invalid = false;
384
385  // C++ [dcl.fct.default]p4:
386  //   For non-template functions, default arguments can be added in
387  //   later declarations of a function in the same
388  //   scope. Declarations in different scopes have completely
389  //   distinct sets of default arguments. That is, declarations in
390  //   inner scopes do not acquire default arguments from
391  //   declarations in outer scopes, and vice versa. In a given
392  //   function declaration, all parameters subsequent to a
393  //   parameter with a default argument shall have default
394  //   arguments supplied in this or previous declarations. A
395  //   default argument shall not be redefined by a later
396  //   declaration (not even to the same value).
397  //
398  // C++ [dcl.fct.default]p6:
399  //   Except for member functions of class templates, the default arguments
400  //   in a member function definition that appears outside of the class
401  //   definition are added to the set of default arguments provided by the
402  //   member function declaration in the class definition.
403  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404    ParmVarDecl *OldParam = Old->getParamDecl(p);
405    ParmVarDecl *NewParam = New->getParamDecl(p);
406
407    bool OldParamHasDfl = OldParam->hasDefaultArg();
408    bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410    NamedDecl *ND = Old;
411    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412      // Ignore default parameters of old decl if they are not in
413      // the same scope.
414      OldParamHasDfl = false;
415
416    if (OldParamHasDfl && NewParamHasDfl) {
417
418      unsigned DiagDefaultParamID =
419        diag::err_param_default_argument_redefinition;
420
421      // MSVC accepts that default parameters be redefined for member functions
422      // of template class. The new default parameter's value is ignored.
423      Invalid = true;
424      if (getLangOpts().MicrosoftExt) {
425        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426        if (MD && MD->getParent()->getDescribedClassTemplate()) {
427          // Merge the old default argument into the new parameter.
428          NewParam->setHasInheritedDefaultArg();
429          if (OldParam->hasUninstantiatedDefaultArg())
430            NewParam->setUninstantiatedDefaultArg(
431                                      OldParam->getUninstantiatedDefaultArg());
432          else
433            NewParam->setDefaultArg(OldParam->getInit());
434          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
435          Invalid = false;
436        }
437      }
438
439      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440      // hint here. Alternatively, we could walk the type-source information
441      // for NewParam to find the last source location in the type... but it
442      // isn't worth the effort right now. This is the kind of test case that
443      // is hard to get right:
444      //   int f(int);
445      //   void g(int (*fp)(int) = f);
446      //   void g(int (*fp)(int) = &f);
447      Diag(NewParam->getLocation(), DiagDefaultParamID)
448        << NewParam->getDefaultArgRange();
449
450      // Look for the function declaration where the default argument was
451      // actually written, which may be a declaration prior to Old.
452      for (FunctionDecl *Older = Old->getPreviousDecl();
453           Older; Older = Older->getPreviousDecl()) {
454        if (!Older->getParamDecl(p)->hasDefaultArg())
455          break;
456
457        OldParam = Older->getParamDecl(p);
458      }
459
460      Diag(OldParam->getLocation(), diag::note_previous_definition)
461        << OldParam->getDefaultArgRange();
462    } else if (OldParamHasDfl) {
463      // Merge the old default argument into the new parameter.
464      // It's important to use getInit() here;  getDefaultArg()
465      // strips off any top-level ExprWithCleanups.
466      NewParam->setHasInheritedDefaultArg();
467      if (OldParam->hasUninstantiatedDefaultArg())
468        NewParam->setUninstantiatedDefaultArg(
469                                      OldParam->getUninstantiatedDefaultArg());
470      else
471        NewParam->setDefaultArg(OldParam->getInit());
472    } else if (NewParamHasDfl) {
473      if (New->getDescribedFunctionTemplate()) {
474        // Paragraph 4, quoted above, only applies to non-template functions.
475        Diag(NewParam->getLocation(),
476             diag::err_param_default_argument_template_redecl)
477          << NewParam->getDefaultArgRange();
478        Diag(Old->getLocation(), diag::note_template_prev_declaration)
479          << false;
480      } else if (New->getTemplateSpecializationKind()
481                   != TSK_ImplicitInstantiation &&
482                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483        // C++ [temp.expr.spec]p21:
484        //   Default function arguments shall not be specified in a declaration
485        //   or a definition for one of the following explicit specializations:
486        //     - the explicit specialization of a function template;
487        //     - the explicit specialization of a member function template;
488        //     - the explicit specialization of a member function of a class
489        //       template where the class template specialization to which the
490        //       member function specialization belongs is implicitly
491        //       instantiated.
492        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494          << New->getDeclName()
495          << NewParam->getDefaultArgRange();
496      } else if (New->getDeclContext()->isDependentContext()) {
497        // C++ [dcl.fct.default]p6 (DR217):
498        //   Default arguments for a member function of a class template shall
499        //   be specified on the initial declaration of the member function
500        //   within the class template.
501        //
502        // Reading the tea leaves a bit in DR217 and its reference to DR205
503        // leads me to the conclusion that one cannot add default function
504        // arguments for an out-of-line definition of a member function of a
505        // dependent type.
506        int WhichKind = 2;
507        if (CXXRecordDecl *Record
508              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509          if (Record->getDescribedClassTemplate())
510            WhichKind = 0;
511          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512            WhichKind = 1;
513          else
514            WhichKind = 2;
515        }
516
517        Diag(NewParam->getLocation(),
518             diag::err_param_default_argument_member_template_redecl)
519          << WhichKind
520          << NewParam->getDefaultArgRange();
521      }
522    }
523  }
524
525  // DR1344: If a default argument is added outside a class definition and that
526  // default argument makes the function a special member function, the program
527  // is ill-formed. This can only happen for constructors.
528  if (isa<CXXConstructorDecl>(New) &&
529      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
530    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
531                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
532    if (NewSM != OldSM) {
533      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
534      assert(NewParam->hasDefaultArg());
535      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
536        << NewParam->getDefaultArgRange() << NewSM;
537      Diag(Old->getLocation(), diag::note_previous_declaration);
538    }
539  }
540
541  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
542  // template has a constexpr specifier then all its declarations shall
543  // contain the constexpr specifier.
544  if (New->isConstexpr() != Old->isConstexpr()) {
545    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
546      << New << New->isConstexpr();
547    Diag(Old->getLocation(), diag::note_previous_declaration);
548    Invalid = true;
549  }
550
551  if (CheckEquivalentExceptionSpec(Old, New))
552    Invalid = true;
553
554  return Invalid;
555}
556
557/// \brief Merge the exception specifications of two variable declarations.
558///
559/// This is called when there's a redeclaration of a VarDecl. The function
560/// checks if the redeclaration might have an exception specification and
561/// validates compatibility and merges the specs if necessary.
562void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
563  // Shortcut if exceptions are disabled.
564  if (!getLangOpts().CXXExceptions)
565    return;
566
567  assert(Context.hasSameType(New->getType(), Old->getType()) &&
568         "Should only be called if types are otherwise the same.");
569
570  QualType NewType = New->getType();
571  QualType OldType = Old->getType();
572
573  // We're only interested in pointers and references to functions, as well
574  // as pointers to member functions.
575  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
576    NewType = R->getPointeeType();
577    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
578  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
579    NewType = P->getPointeeType();
580    OldType = OldType->getAs<PointerType>()->getPointeeType();
581  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
582    NewType = M->getPointeeType();
583    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
584  }
585
586  if (!NewType->isFunctionProtoType())
587    return;
588
589  // There's lots of special cases for functions. For function pointers, system
590  // libraries are hopefully not as broken so that we don't need these
591  // workarounds.
592  if (CheckEquivalentExceptionSpec(
593        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
594        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
595    New->setInvalidDecl();
596  }
597}
598
599/// CheckCXXDefaultArguments - Verify that the default arguments for a
600/// function declaration are well-formed according to C++
601/// [dcl.fct.default].
602void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
603  unsigned NumParams = FD->getNumParams();
604  unsigned p;
605
606  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
607                  isa<CXXMethodDecl>(FD) &&
608                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
609
610  // Find first parameter with a default argument
611  for (p = 0; p < NumParams; ++p) {
612    ParmVarDecl *Param = FD->getParamDecl(p);
613    if (Param->hasDefaultArg()) {
614      // C++11 [expr.prim.lambda]p5:
615      //   [...] Default arguments (8.3.6) shall not be specified in the
616      //   parameter-declaration-clause of a lambda-declarator.
617      //
618      // FIXME: Core issue 974 strikes this sentence, we only provide an
619      // extension warning.
620      if (IsLambda)
621        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
622          << Param->getDefaultArgRange();
623      break;
624    }
625  }
626
627  // C++ [dcl.fct.default]p4:
628  //   In a given function declaration, all parameters
629  //   subsequent to a parameter with a default argument shall
630  //   have default arguments supplied in this or previous
631  //   declarations. A default argument shall not be redefined
632  //   by a later declaration (not even to the same value).
633  unsigned LastMissingDefaultArg = 0;
634  for (; p < NumParams; ++p) {
635    ParmVarDecl *Param = FD->getParamDecl(p);
636    if (!Param->hasDefaultArg()) {
637      if (Param->isInvalidDecl())
638        /* We already complained about this parameter. */;
639      else if (Param->getIdentifier())
640        Diag(Param->getLocation(),
641             diag::err_param_default_argument_missing_name)
642          << Param->getIdentifier();
643      else
644        Diag(Param->getLocation(),
645             diag::err_param_default_argument_missing);
646
647      LastMissingDefaultArg = p;
648    }
649  }
650
651  if (LastMissingDefaultArg > 0) {
652    // Some default arguments were missing. Clear out all of the
653    // default arguments up to (and including) the last missing
654    // default argument, so that we leave the function parameters
655    // in a semantically valid state.
656    for (p = 0; p <= LastMissingDefaultArg; ++p) {
657      ParmVarDecl *Param = FD->getParamDecl(p);
658      if (Param->hasDefaultArg()) {
659        Param->setDefaultArg(0);
660      }
661    }
662  }
663}
664
665// CheckConstexprParameterTypes - Check whether a function's parameter types
666// are all literal types. If so, return true. If not, produce a suitable
667// diagnostic and return false.
668static bool CheckConstexprParameterTypes(Sema &SemaRef,
669                                         const FunctionDecl *FD) {
670  unsigned ArgIndex = 0;
671  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
672  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
673       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
674    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
675    SourceLocation ParamLoc = PD->getLocation();
676    if (!(*i)->isDependentType() &&
677        SemaRef.RequireLiteralType(ParamLoc, *i,
678                                   diag::err_constexpr_non_literal_param,
679                                   ArgIndex+1, PD->getSourceRange(),
680                                   isa<CXXConstructorDecl>(FD)))
681      return false;
682  }
683  return true;
684}
685
686/// \brief Get diagnostic %select index for tag kind for
687/// record diagnostic message.
688/// WARNING: Indexes apply to particular diagnostics only!
689///
690/// \returns diagnostic %select index.
691static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
692  switch (Tag) {
693  case TTK_Struct: return 0;
694  case TTK_Interface: return 1;
695  case TTK_Class:  return 2;
696  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
697  }
698}
699
700// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
701// the requirements of a constexpr function definition or a constexpr
702// constructor definition. If so, return true. If not, produce appropriate
703// diagnostics and return false.
704//
705// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
706bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
707  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
708  if (MD && MD->isInstance()) {
709    // C++11 [dcl.constexpr]p4:
710    //  The definition of a constexpr constructor shall satisfy the following
711    //  constraints:
712    //  - the class shall not have any virtual base classes;
713    const CXXRecordDecl *RD = MD->getParent();
714    if (RD->getNumVBases()) {
715      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
716        << isa<CXXConstructorDecl>(NewFD)
717        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
718      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
719             E = RD->vbases_end(); I != E; ++I)
720        Diag(I->getLocStart(),
721             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
722      return false;
723    }
724  }
725
726  if (!isa<CXXConstructorDecl>(NewFD)) {
727    // C++11 [dcl.constexpr]p3:
728    //  The definition of a constexpr function shall satisfy the following
729    //  constraints:
730    // - it shall not be virtual;
731    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
732    if (Method && Method->isVirtual()) {
733      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
734
735      // If it's not obvious why this function is virtual, find an overridden
736      // function which uses the 'virtual' keyword.
737      const CXXMethodDecl *WrittenVirtual = Method;
738      while (!WrittenVirtual->isVirtualAsWritten())
739        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
740      if (WrittenVirtual != Method)
741        Diag(WrittenVirtual->getLocation(),
742             diag::note_overridden_virtual_function);
743      return false;
744    }
745
746    // - its return type shall be a literal type;
747    QualType RT = NewFD->getResultType();
748    if (!RT->isDependentType() &&
749        RequireLiteralType(NewFD->getLocation(), RT,
750                           diag::err_constexpr_non_literal_return))
751      return false;
752  }
753
754  // - each of its parameter types shall be a literal type;
755  if (!CheckConstexprParameterTypes(*this, NewFD))
756    return false;
757
758  return true;
759}
760
761/// Check the given declaration statement is legal within a constexpr function
762/// body. C++0x [dcl.constexpr]p3,p4.
763///
764/// \return true if the body is OK, false if we have diagnosed a problem.
765static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
766                                   DeclStmt *DS) {
767  // C++0x [dcl.constexpr]p3 and p4:
768  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
769  //  contain only
770  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
771         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
772    switch ((*DclIt)->getKind()) {
773    case Decl::StaticAssert:
774    case Decl::Using:
775    case Decl::UsingShadow:
776    case Decl::UsingDirective:
777    case Decl::UnresolvedUsingTypename:
778      //   - static_assert-declarations
779      //   - using-declarations,
780      //   - using-directives,
781      continue;
782
783    case Decl::Typedef:
784    case Decl::TypeAlias: {
785      //   - typedef declarations and alias-declarations that do not define
786      //     classes or enumerations,
787      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
788      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
789        // Don't allow variably-modified types in constexpr functions.
790        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
791        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
792          << TL.getSourceRange() << TL.getType()
793          << isa<CXXConstructorDecl>(Dcl);
794        return false;
795      }
796      continue;
797    }
798
799    case Decl::Enum:
800    case Decl::CXXRecord:
801      // As an extension, we allow the declaration (but not the definition) of
802      // classes and enumerations in all declarations, not just in typedef and
803      // alias declarations.
804      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
805        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
806          << isa<CXXConstructorDecl>(Dcl);
807        return false;
808      }
809      continue;
810
811    case Decl::Var:
812      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
813        << isa<CXXConstructorDecl>(Dcl);
814      return false;
815
816    default:
817      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
818        << isa<CXXConstructorDecl>(Dcl);
819      return false;
820    }
821  }
822
823  return true;
824}
825
826/// Check that the given field is initialized within a constexpr constructor.
827///
828/// \param Dcl The constexpr constructor being checked.
829/// \param Field The field being checked. This may be a member of an anonymous
830///        struct or union nested within the class being checked.
831/// \param Inits All declarations, including anonymous struct/union members and
832///        indirect members, for which any initialization was provided.
833/// \param Diagnosed Set to true if an error is produced.
834static void CheckConstexprCtorInitializer(Sema &SemaRef,
835                                          const FunctionDecl *Dcl,
836                                          FieldDecl *Field,
837                                          llvm::SmallSet<Decl*, 16> &Inits,
838                                          bool &Diagnosed) {
839  if (Field->isUnnamedBitfield())
840    return;
841
842  if (Field->isAnonymousStructOrUnion() &&
843      Field->getType()->getAsCXXRecordDecl()->isEmpty())
844    return;
845
846  if (!Inits.count(Field)) {
847    if (!Diagnosed) {
848      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
849      Diagnosed = true;
850    }
851    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
852  } else if (Field->isAnonymousStructOrUnion()) {
853    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
854    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
855         I != E; ++I)
856      // If an anonymous union contains an anonymous struct of which any member
857      // is initialized, all members must be initialized.
858      if (!RD->isUnion() || Inits.count(*I))
859        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
860  }
861}
862
863/// Check the body for the given constexpr function declaration only contains
864/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
865///
866/// \return true if the body is OK, false if we have diagnosed a problem.
867bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
868  if (isa<CXXTryStmt>(Body)) {
869    // C++11 [dcl.constexpr]p3:
870    //  The definition of a constexpr function shall satisfy the following
871    //  constraints: [...]
872    // - its function-body shall be = delete, = default, or a
873    //   compound-statement
874    //
875    // C++11 [dcl.constexpr]p4:
876    //  In the definition of a constexpr constructor, [...]
877    // - its function-body shall not be a function-try-block;
878    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
879      << isa<CXXConstructorDecl>(Dcl);
880    return false;
881  }
882
883  // - its function-body shall be [...] a compound-statement that contains only
884  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
885
886  SmallVector<SourceLocation, 4> ReturnStmts;
887  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
888         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
889    switch ((*BodyIt)->getStmtClass()) {
890    case Stmt::NullStmtClass:
891      //   - null statements,
892      continue;
893
894    case Stmt::DeclStmtClass:
895      //   - static_assert-declarations
896      //   - using-declarations,
897      //   - using-directives,
898      //   - typedef declarations and alias-declarations that do not define
899      //     classes or enumerations,
900      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
901        return false;
902      continue;
903
904    case Stmt::ReturnStmtClass:
905      //   - and exactly one return statement;
906      if (isa<CXXConstructorDecl>(Dcl))
907        break;
908
909      ReturnStmts.push_back((*BodyIt)->getLocStart());
910      continue;
911
912    default:
913      break;
914    }
915
916    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
917      << isa<CXXConstructorDecl>(Dcl);
918    return false;
919  }
920
921  if (const CXXConstructorDecl *Constructor
922        = dyn_cast<CXXConstructorDecl>(Dcl)) {
923    const CXXRecordDecl *RD = Constructor->getParent();
924    // DR1359:
925    // - every non-variant non-static data member and base class sub-object
926    //   shall be initialized;
927    // - if the class is a non-empty union, or for each non-empty anonymous
928    //   union member of a non-union class, exactly one non-static data member
929    //   shall be initialized;
930    if (RD->isUnion()) {
931      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
932        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
933        return false;
934      }
935    } else if (!Constructor->isDependentContext() &&
936               !Constructor->isDelegatingConstructor()) {
937      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
938
939      // Skip detailed checking if we have enough initializers, and we would
940      // allow at most one initializer per member.
941      bool AnyAnonStructUnionMembers = false;
942      unsigned Fields = 0;
943      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944           E = RD->field_end(); I != E; ++I, ++Fields) {
945        if (I->isAnonymousStructOrUnion()) {
946          AnyAnonStructUnionMembers = true;
947          break;
948        }
949      }
950      if (AnyAnonStructUnionMembers ||
951          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
952        // Check initialization of non-static data members. Base classes are
953        // always initialized so do not need to be checked. Dependent bases
954        // might not have initializers in the member initializer list.
955        llvm::SmallSet<Decl*, 16> Inits;
956        for (CXXConstructorDecl::init_const_iterator
957               I = Constructor->init_begin(), E = Constructor->init_end();
958             I != E; ++I) {
959          if (FieldDecl *FD = (*I)->getMember())
960            Inits.insert(FD);
961          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
962            Inits.insert(ID->chain_begin(), ID->chain_end());
963        }
964
965        bool Diagnosed = false;
966        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
967             E = RD->field_end(); I != E; ++I)
968          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
969        if (Diagnosed)
970          return false;
971      }
972    }
973  } else {
974    if (ReturnStmts.empty()) {
975      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
976      return false;
977    }
978    if (ReturnStmts.size() > 1) {
979      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
980      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
981        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
982      return false;
983    }
984  }
985
986  // C++11 [dcl.constexpr]p5:
987  //   if no function argument values exist such that the function invocation
988  //   substitution would produce a constant expression, the program is
989  //   ill-formed; no diagnostic required.
990  // C++11 [dcl.constexpr]p3:
991  //   - every constructor call and implicit conversion used in initializing the
992  //     return value shall be one of those allowed in a constant expression.
993  // C++11 [dcl.constexpr]p4:
994  //   - every constructor involved in initializing non-static data members and
995  //     base class sub-objects shall be a constexpr constructor.
996  SmallVector<PartialDiagnosticAt, 8> Diags;
997  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
998    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
999      << isa<CXXConstructorDecl>(Dcl);
1000    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1001      Diag(Diags[I].first, Diags[I].second);
1002    // Don't return false here: we allow this for compatibility in
1003    // system headers.
1004  }
1005
1006  return true;
1007}
1008
1009/// isCurrentClassName - Determine whether the identifier II is the
1010/// name of the class type currently being defined. In the case of
1011/// nested classes, this will only return true if II is the name of
1012/// the innermost class.
1013bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1014                              const CXXScopeSpec *SS) {
1015  assert(getLangOpts().CPlusPlus && "No class names in C!");
1016
1017  CXXRecordDecl *CurDecl;
1018  if (SS && SS->isSet() && !SS->isInvalid()) {
1019    DeclContext *DC = computeDeclContext(*SS, true);
1020    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1021  } else
1022    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1023
1024  if (CurDecl && CurDecl->getIdentifier())
1025    return &II == CurDecl->getIdentifier();
1026  else
1027    return false;
1028}
1029
1030/// \brief Determine whether the given class is a base class of the given
1031/// class, including looking at dependent bases.
1032static bool findCircularInheritance(const CXXRecordDecl *Class,
1033                                    const CXXRecordDecl *Current) {
1034  SmallVector<const CXXRecordDecl*, 8> Queue;
1035
1036  Class = Class->getCanonicalDecl();
1037  while (true) {
1038    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1039                                                  E = Current->bases_end();
1040         I != E; ++I) {
1041      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1042      if (!Base)
1043        continue;
1044
1045      Base = Base->getDefinition();
1046      if (!Base)
1047        continue;
1048
1049      if (Base->getCanonicalDecl() == Class)
1050        return true;
1051
1052      Queue.push_back(Base);
1053    }
1054
1055    if (Queue.empty())
1056      return false;
1057
1058    Current = Queue.back();
1059    Queue.pop_back();
1060  }
1061
1062  return false;
1063}
1064
1065/// \brief Check the validity of a C++ base class specifier.
1066///
1067/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1068/// and returns NULL otherwise.
1069CXXBaseSpecifier *
1070Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1071                         SourceRange SpecifierRange,
1072                         bool Virtual, AccessSpecifier Access,
1073                         TypeSourceInfo *TInfo,
1074                         SourceLocation EllipsisLoc) {
1075  QualType BaseType = TInfo->getType();
1076
1077  // C++ [class.union]p1:
1078  //   A union shall not have base classes.
1079  if (Class->isUnion()) {
1080    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1081      << SpecifierRange;
1082    return 0;
1083  }
1084
1085  if (EllipsisLoc.isValid() &&
1086      !TInfo->getType()->containsUnexpandedParameterPack()) {
1087    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1088      << TInfo->getTypeLoc().getSourceRange();
1089    EllipsisLoc = SourceLocation();
1090  }
1091
1092  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1093
1094  if (BaseType->isDependentType()) {
1095    // Make sure that we don't have circular inheritance among our dependent
1096    // bases. For non-dependent bases, the check for completeness below handles
1097    // this.
1098    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1099      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1100          ((BaseDecl = BaseDecl->getDefinition()) &&
1101           findCircularInheritance(Class, BaseDecl))) {
1102        Diag(BaseLoc, diag::err_circular_inheritance)
1103          << BaseType << Context.getTypeDeclType(Class);
1104
1105        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1106          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1107            << BaseType;
1108
1109        return 0;
1110      }
1111    }
1112
1113    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1114                                          Class->getTagKind() == TTK_Class,
1115                                          Access, TInfo, EllipsisLoc);
1116  }
1117
1118  // Base specifiers must be record types.
1119  if (!BaseType->isRecordType()) {
1120    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1121    return 0;
1122  }
1123
1124  // C++ [class.union]p1:
1125  //   A union shall not be used as a base class.
1126  if (BaseType->isUnionType()) {
1127    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1128    return 0;
1129  }
1130
1131  // C++ [class.derived]p2:
1132  //   The class-name in a base-specifier shall not be an incompletely
1133  //   defined class.
1134  if (RequireCompleteType(BaseLoc, BaseType,
1135                          diag::err_incomplete_base_class, SpecifierRange)) {
1136    Class->setInvalidDecl();
1137    return 0;
1138  }
1139
1140  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1141  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1142  assert(BaseDecl && "Record type has no declaration");
1143  BaseDecl = BaseDecl->getDefinition();
1144  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1145  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1146  assert(CXXBaseDecl && "Base type is not a C++ type");
1147
1148  // C++ [class]p3:
1149  //   If a class is marked final and it appears as a base-type-specifier in
1150  //   base-clause, the program is ill-formed.
1151  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1152    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1153      << CXXBaseDecl->getDeclName();
1154    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1155      << CXXBaseDecl->getDeclName();
1156    return 0;
1157  }
1158
1159  if (BaseDecl->isInvalidDecl())
1160    Class->setInvalidDecl();
1161
1162  // Create the base specifier.
1163  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1164                                        Class->getTagKind() == TTK_Class,
1165                                        Access, TInfo, EllipsisLoc);
1166}
1167
1168/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1169/// one entry in the base class list of a class specifier, for
1170/// example:
1171///    class foo : public bar, virtual private baz {
1172/// 'public bar' and 'virtual private baz' are each base-specifiers.
1173BaseResult
1174Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1175                         bool Virtual, AccessSpecifier Access,
1176                         ParsedType basetype, SourceLocation BaseLoc,
1177                         SourceLocation EllipsisLoc) {
1178  if (!classdecl)
1179    return true;
1180
1181  AdjustDeclIfTemplate(classdecl);
1182  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1183  if (!Class)
1184    return true;
1185
1186  TypeSourceInfo *TInfo = 0;
1187  GetTypeFromParser(basetype, &TInfo);
1188
1189  if (EllipsisLoc.isInvalid() &&
1190      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1191                                      UPPC_BaseType))
1192    return true;
1193
1194  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1195                                                      Virtual, Access, TInfo,
1196                                                      EllipsisLoc))
1197    return BaseSpec;
1198  else
1199    Class->setInvalidDecl();
1200
1201  return true;
1202}
1203
1204/// \brief Performs the actual work of attaching the given base class
1205/// specifiers to a C++ class.
1206bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1207                                unsigned NumBases) {
1208 if (NumBases == 0)
1209    return false;
1210
1211  // Used to keep track of which base types we have already seen, so
1212  // that we can properly diagnose redundant direct base types. Note
1213  // that the key is always the unqualified canonical type of the base
1214  // class.
1215  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1216
1217  // Copy non-redundant base specifiers into permanent storage.
1218  unsigned NumGoodBases = 0;
1219  bool Invalid = false;
1220  for (unsigned idx = 0; idx < NumBases; ++idx) {
1221    QualType NewBaseType
1222      = Context.getCanonicalType(Bases[idx]->getType());
1223    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1224
1225    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1226    if (KnownBase) {
1227      // C++ [class.mi]p3:
1228      //   A class shall not be specified as a direct base class of a
1229      //   derived class more than once.
1230      Diag(Bases[idx]->getLocStart(),
1231           diag::err_duplicate_base_class)
1232        << KnownBase->getType()
1233        << Bases[idx]->getSourceRange();
1234
1235      // Delete the duplicate base class specifier; we're going to
1236      // overwrite its pointer later.
1237      Context.Deallocate(Bases[idx]);
1238
1239      Invalid = true;
1240    } else {
1241      // Okay, add this new base class.
1242      KnownBase = Bases[idx];
1243      Bases[NumGoodBases++] = Bases[idx];
1244      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1245        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1246        if (Class->isInterface() &&
1247              (!RD->isInterface() ||
1248               KnownBase->getAccessSpecifier() != AS_public)) {
1249          // The Microsoft extension __interface does not permit bases that
1250          // are not themselves public interfaces.
1251          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1252            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1253            << RD->getSourceRange();
1254          Invalid = true;
1255        }
1256        if (RD->hasAttr<WeakAttr>())
1257          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1258      }
1259    }
1260  }
1261
1262  // Attach the remaining base class specifiers to the derived class.
1263  Class->setBases(Bases, NumGoodBases);
1264
1265  // Delete the remaining (good) base class specifiers, since their
1266  // data has been copied into the CXXRecordDecl.
1267  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1268    Context.Deallocate(Bases[idx]);
1269
1270  return Invalid;
1271}
1272
1273/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1274/// class, after checking whether there are any duplicate base
1275/// classes.
1276void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1277                               unsigned NumBases) {
1278  if (!ClassDecl || !Bases || !NumBases)
1279    return;
1280
1281  AdjustDeclIfTemplate(ClassDecl);
1282  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1283                       (CXXBaseSpecifier**)(Bases), NumBases);
1284}
1285
1286static CXXRecordDecl *GetClassForType(QualType T) {
1287  if (const RecordType *RT = T->getAs<RecordType>())
1288    return cast<CXXRecordDecl>(RT->getDecl());
1289  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1290    return ICT->getDecl();
1291  else
1292    return 0;
1293}
1294
1295/// \brief Determine whether the type \p Derived is a C++ class that is
1296/// derived from the type \p Base.
1297bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1298  if (!getLangOpts().CPlusPlus)
1299    return false;
1300
1301  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1302  if (!DerivedRD)
1303    return false;
1304
1305  CXXRecordDecl *BaseRD = GetClassForType(Base);
1306  if (!BaseRD)
1307    return false;
1308
1309  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1310  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1311}
1312
1313/// \brief Determine whether the type \p Derived is a C++ class that is
1314/// derived from the type \p Base.
1315bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1316  if (!getLangOpts().CPlusPlus)
1317    return false;
1318
1319  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1320  if (!DerivedRD)
1321    return false;
1322
1323  CXXRecordDecl *BaseRD = GetClassForType(Base);
1324  if (!BaseRD)
1325    return false;
1326
1327  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1328}
1329
1330void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1331                              CXXCastPath &BasePathArray) {
1332  assert(BasePathArray.empty() && "Base path array must be empty!");
1333  assert(Paths.isRecordingPaths() && "Must record paths!");
1334
1335  const CXXBasePath &Path = Paths.front();
1336
1337  // We first go backward and check if we have a virtual base.
1338  // FIXME: It would be better if CXXBasePath had the base specifier for
1339  // the nearest virtual base.
1340  unsigned Start = 0;
1341  for (unsigned I = Path.size(); I != 0; --I) {
1342    if (Path[I - 1].Base->isVirtual()) {
1343      Start = I - 1;
1344      break;
1345    }
1346  }
1347
1348  // Now add all bases.
1349  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1350    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1351}
1352
1353/// \brief Determine whether the given base path includes a virtual
1354/// base class.
1355bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1356  for (CXXCastPath::const_iterator B = BasePath.begin(),
1357                                BEnd = BasePath.end();
1358       B != BEnd; ++B)
1359    if ((*B)->isVirtual())
1360      return true;
1361
1362  return false;
1363}
1364
1365/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1366/// conversion (where Derived and Base are class types) is
1367/// well-formed, meaning that the conversion is unambiguous (and
1368/// that all of the base classes are accessible). Returns true
1369/// and emits a diagnostic if the code is ill-formed, returns false
1370/// otherwise. Loc is the location where this routine should point to
1371/// if there is an error, and Range is the source range to highlight
1372/// if there is an error.
1373bool
1374Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1375                                   unsigned InaccessibleBaseID,
1376                                   unsigned AmbigiousBaseConvID,
1377                                   SourceLocation Loc, SourceRange Range,
1378                                   DeclarationName Name,
1379                                   CXXCastPath *BasePath) {
1380  // First, determine whether the path from Derived to Base is
1381  // ambiguous. This is slightly more expensive than checking whether
1382  // the Derived to Base conversion exists, because here we need to
1383  // explore multiple paths to determine if there is an ambiguity.
1384  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1385                     /*DetectVirtual=*/false);
1386  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1387  assert(DerivationOkay &&
1388         "Can only be used with a derived-to-base conversion");
1389  (void)DerivationOkay;
1390
1391  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1392    if (InaccessibleBaseID) {
1393      // Check that the base class can be accessed.
1394      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1395                                   InaccessibleBaseID)) {
1396        case AR_inaccessible:
1397          return true;
1398        case AR_accessible:
1399        case AR_dependent:
1400        case AR_delayed:
1401          break;
1402      }
1403    }
1404
1405    // Build a base path if necessary.
1406    if (BasePath)
1407      BuildBasePathArray(Paths, *BasePath);
1408    return false;
1409  }
1410
1411  // We know that the derived-to-base conversion is ambiguous, and
1412  // we're going to produce a diagnostic. Perform the derived-to-base
1413  // search just one more time to compute all of the possible paths so
1414  // that we can print them out. This is more expensive than any of
1415  // the previous derived-to-base checks we've done, but at this point
1416  // performance isn't as much of an issue.
1417  Paths.clear();
1418  Paths.setRecordingPaths(true);
1419  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1420  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1421  (void)StillOkay;
1422
1423  // Build up a textual representation of the ambiguous paths, e.g.,
1424  // D -> B -> A, that will be used to illustrate the ambiguous
1425  // conversions in the diagnostic. We only print one of the paths
1426  // to each base class subobject.
1427  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1428
1429  Diag(Loc, AmbigiousBaseConvID)
1430  << Derived << Base << PathDisplayStr << Range << Name;
1431  return true;
1432}
1433
1434bool
1435Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1436                                   SourceLocation Loc, SourceRange Range,
1437                                   CXXCastPath *BasePath,
1438                                   bool IgnoreAccess) {
1439  return CheckDerivedToBaseConversion(Derived, Base,
1440                                      IgnoreAccess ? 0
1441                                       : diag::err_upcast_to_inaccessible_base,
1442                                      diag::err_ambiguous_derived_to_base_conv,
1443                                      Loc, Range, DeclarationName(),
1444                                      BasePath);
1445}
1446
1447
1448/// @brief Builds a string representing ambiguous paths from a
1449/// specific derived class to different subobjects of the same base
1450/// class.
1451///
1452/// This function builds a string that can be used in error messages
1453/// to show the different paths that one can take through the
1454/// inheritance hierarchy to go from the derived class to different
1455/// subobjects of a base class. The result looks something like this:
1456/// @code
1457/// struct D -> struct B -> struct A
1458/// struct D -> struct C -> struct A
1459/// @endcode
1460std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1461  std::string PathDisplayStr;
1462  std::set<unsigned> DisplayedPaths;
1463  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1464       Path != Paths.end(); ++Path) {
1465    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1466      // We haven't displayed a path to this particular base
1467      // class subobject yet.
1468      PathDisplayStr += "\n    ";
1469      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1470      for (CXXBasePath::const_iterator Element = Path->begin();
1471           Element != Path->end(); ++Element)
1472        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1473    }
1474  }
1475
1476  return PathDisplayStr;
1477}
1478
1479//===----------------------------------------------------------------------===//
1480// C++ class member Handling
1481//===----------------------------------------------------------------------===//
1482
1483/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1484bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1485                                SourceLocation ASLoc,
1486                                SourceLocation ColonLoc,
1487                                AttributeList *Attrs) {
1488  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1489  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1490                                                  ASLoc, ColonLoc);
1491  CurContext->addHiddenDecl(ASDecl);
1492  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1493}
1494
1495/// CheckOverrideControl - Check C++11 override control semantics.
1496void Sema::CheckOverrideControl(Decl *D) {
1497  if (D->isInvalidDecl())
1498    return;
1499
1500  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1501
1502  // Do we know which functions this declaration might be overriding?
1503  bool OverridesAreKnown = !MD ||
1504      (!MD->getParent()->hasAnyDependentBases() &&
1505       !MD->getType()->isDependentType());
1506
1507  if (!MD || !MD->isVirtual()) {
1508    if (OverridesAreKnown) {
1509      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1510        Diag(OA->getLocation(),
1511             diag::override_keyword_only_allowed_on_virtual_member_functions)
1512          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1513        D->dropAttr<OverrideAttr>();
1514      }
1515      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1516        Diag(FA->getLocation(),
1517             diag::override_keyword_only_allowed_on_virtual_member_functions)
1518          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1519        D->dropAttr<FinalAttr>();
1520      }
1521    }
1522    return;
1523  }
1524
1525  if (!OverridesAreKnown)
1526    return;
1527
1528  // C++11 [class.virtual]p5:
1529  //   If a virtual function is marked with the virt-specifier override and
1530  //   does not override a member function of a base class, the program is
1531  //   ill-formed.
1532  bool HasOverriddenMethods =
1533    MD->begin_overridden_methods() != MD->end_overridden_methods();
1534  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1535    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1536      << MD->getDeclName();
1537}
1538
1539/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1540/// function overrides a virtual member function marked 'final', according to
1541/// C++11 [class.virtual]p4.
1542bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1543                                                  const CXXMethodDecl *Old) {
1544  if (!Old->hasAttr<FinalAttr>())
1545    return false;
1546
1547  Diag(New->getLocation(), diag::err_final_function_overridden)
1548    << New->getDeclName();
1549  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1550  return true;
1551}
1552
1553static bool InitializationHasSideEffects(const FieldDecl &FD) {
1554  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1555  // FIXME: Destruction of ObjC lifetime types has side-effects.
1556  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1557    return !RD->isCompleteDefinition() ||
1558           !RD->hasTrivialDefaultConstructor() ||
1559           !RD->hasTrivialDestructor();
1560  return false;
1561}
1562
1563/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1564/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1565/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1566/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1567/// present (but parsing it has been deferred).
1568NamedDecl *
1569Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1570                               MultiTemplateParamsArg TemplateParameterLists,
1571                               Expr *BW, const VirtSpecifiers &VS,
1572                               InClassInitStyle InitStyle) {
1573  const DeclSpec &DS = D.getDeclSpec();
1574  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1575  DeclarationName Name = NameInfo.getName();
1576  SourceLocation Loc = NameInfo.getLoc();
1577
1578  // For anonymous bitfields, the location should point to the type.
1579  if (Loc.isInvalid())
1580    Loc = D.getLocStart();
1581
1582  Expr *BitWidth = static_cast<Expr*>(BW);
1583
1584  assert(isa<CXXRecordDecl>(CurContext));
1585  assert(!DS.isFriendSpecified());
1586
1587  bool isFunc = D.isDeclarationOfFunction();
1588
1589  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1590    // The Microsoft extension __interface only permits public member functions
1591    // and prohibits constructors, destructors, operators, non-public member
1592    // functions, static methods and data members.
1593    unsigned InvalidDecl;
1594    bool ShowDeclName = true;
1595    if (!isFunc)
1596      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1597    else if (AS != AS_public)
1598      InvalidDecl = 2;
1599    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1600      InvalidDecl = 3;
1601    else switch (Name.getNameKind()) {
1602      case DeclarationName::CXXConstructorName:
1603        InvalidDecl = 4;
1604        ShowDeclName = false;
1605        break;
1606
1607      case DeclarationName::CXXDestructorName:
1608        InvalidDecl = 5;
1609        ShowDeclName = false;
1610        break;
1611
1612      case DeclarationName::CXXOperatorName:
1613      case DeclarationName::CXXConversionFunctionName:
1614        InvalidDecl = 6;
1615        break;
1616
1617      default:
1618        InvalidDecl = 0;
1619        break;
1620    }
1621
1622    if (InvalidDecl) {
1623      if (ShowDeclName)
1624        Diag(Loc, diag::err_invalid_member_in_interface)
1625          << (InvalidDecl-1) << Name;
1626      else
1627        Diag(Loc, diag::err_invalid_member_in_interface)
1628          << (InvalidDecl-1) << "";
1629      return 0;
1630    }
1631  }
1632
1633  // C++ 9.2p6: A member shall not be declared to have automatic storage
1634  // duration (auto, register) or with the extern storage-class-specifier.
1635  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1636  // data members and cannot be applied to names declared const or static,
1637  // and cannot be applied to reference members.
1638  switch (DS.getStorageClassSpec()) {
1639    case DeclSpec::SCS_unspecified:
1640    case DeclSpec::SCS_typedef:
1641    case DeclSpec::SCS_static:
1642      // FALL THROUGH.
1643      break;
1644    case DeclSpec::SCS_mutable:
1645      if (isFunc) {
1646        if (DS.getStorageClassSpecLoc().isValid())
1647          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1648        else
1649          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1650
1651        // FIXME: It would be nicer if the keyword was ignored only for this
1652        // declarator. Otherwise we could get follow-up errors.
1653        D.getMutableDeclSpec().ClearStorageClassSpecs();
1654      }
1655      break;
1656    default:
1657      if (DS.getStorageClassSpecLoc().isValid())
1658        Diag(DS.getStorageClassSpecLoc(),
1659             diag::err_storageclass_invalid_for_member);
1660      else
1661        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1662      D.getMutableDeclSpec().ClearStorageClassSpecs();
1663  }
1664
1665  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1666                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1667                      !isFunc);
1668
1669  NamedDecl *Member;
1670  if (isInstField) {
1671    CXXScopeSpec &SS = D.getCXXScopeSpec();
1672
1673    // Data members must have identifiers for names.
1674    if (!Name.isIdentifier()) {
1675      Diag(Loc, diag::err_bad_variable_name)
1676        << Name;
1677      return 0;
1678    }
1679
1680    IdentifierInfo *II = Name.getAsIdentifierInfo();
1681
1682    // Member field could not be with "template" keyword.
1683    // So TemplateParameterLists should be empty in this case.
1684    if (TemplateParameterLists.size()) {
1685      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1686      if (TemplateParams->size()) {
1687        // There is no such thing as a member field template.
1688        Diag(D.getIdentifierLoc(), diag::err_template_member)
1689            << II
1690            << SourceRange(TemplateParams->getTemplateLoc(),
1691                TemplateParams->getRAngleLoc());
1692      } else {
1693        // There is an extraneous 'template<>' for this member.
1694        Diag(TemplateParams->getTemplateLoc(),
1695            diag::err_template_member_noparams)
1696            << II
1697            << SourceRange(TemplateParams->getTemplateLoc(),
1698                TemplateParams->getRAngleLoc());
1699      }
1700      return 0;
1701    }
1702
1703    if (SS.isSet() && !SS.isInvalid()) {
1704      // The user provided a superfluous scope specifier inside a class
1705      // definition:
1706      //
1707      // class X {
1708      //   int X::member;
1709      // };
1710      if (DeclContext *DC = computeDeclContext(SS, false))
1711        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1712      else
1713        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1714          << Name << SS.getRange();
1715
1716      SS.clear();
1717    }
1718
1719    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1720                         InitStyle, AS);
1721    assert(Member && "HandleField never returns null");
1722  } else {
1723    assert(InitStyle == ICIS_NoInit);
1724
1725    Member = HandleDeclarator(S, D, TemplateParameterLists);
1726    if (!Member) {
1727      return 0;
1728    }
1729
1730    // Non-instance-fields can't have a bitfield.
1731    if (BitWidth) {
1732      if (Member->isInvalidDecl()) {
1733        // don't emit another diagnostic.
1734      } else if (isa<VarDecl>(Member)) {
1735        // C++ 9.6p3: A bit-field shall not be a static member.
1736        // "static member 'A' cannot be a bit-field"
1737        Diag(Loc, diag::err_static_not_bitfield)
1738          << Name << BitWidth->getSourceRange();
1739      } else if (isa<TypedefDecl>(Member)) {
1740        // "typedef member 'x' cannot be a bit-field"
1741        Diag(Loc, diag::err_typedef_not_bitfield)
1742          << Name << BitWidth->getSourceRange();
1743      } else {
1744        // A function typedef ("typedef int f(); f a;").
1745        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1746        Diag(Loc, diag::err_not_integral_type_bitfield)
1747          << Name << cast<ValueDecl>(Member)->getType()
1748          << BitWidth->getSourceRange();
1749      }
1750
1751      BitWidth = 0;
1752      Member->setInvalidDecl();
1753    }
1754
1755    Member->setAccess(AS);
1756
1757    // If we have declared a member function template, set the access of the
1758    // templated declaration as well.
1759    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1760      FunTmpl->getTemplatedDecl()->setAccess(AS);
1761  }
1762
1763  if (VS.isOverrideSpecified())
1764    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1765  if (VS.isFinalSpecified())
1766    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1767
1768  if (VS.getLastLocation().isValid()) {
1769    // Update the end location of a method that has a virt-specifiers.
1770    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1771      MD->setRangeEnd(VS.getLastLocation());
1772  }
1773
1774  CheckOverrideControl(Member);
1775
1776  assert((Name || isInstField) && "No identifier for non-field ?");
1777
1778  if (isInstField) {
1779    FieldDecl *FD = cast<FieldDecl>(Member);
1780    FieldCollector->Add(FD);
1781
1782    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1783                                 FD->getLocation())
1784          != DiagnosticsEngine::Ignored) {
1785      // Remember all explicit private FieldDecls that have a name, no side
1786      // effects and are not part of a dependent type declaration.
1787      if (!FD->isImplicit() && FD->getDeclName() &&
1788          FD->getAccess() == AS_private &&
1789          !FD->hasAttr<UnusedAttr>() &&
1790          !FD->getParent()->isDependentContext() &&
1791          !InitializationHasSideEffects(*FD))
1792        UnusedPrivateFields.insert(FD);
1793    }
1794  }
1795
1796  return Member;
1797}
1798
1799namespace {
1800  class UninitializedFieldVisitor
1801      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
1802    Sema &S;
1803    ValueDecl *VD;
1804  public:
1805    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
1806    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
1807                                                        S(S) {
1808      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
1809        this->VD = IFD->getAnonField();
1810      else
1811        this->VD = VD;
1812    }
1813
1814    void HandleExpr(Expr *E) {
1815      if (!E) return;
1816
1817      // Expressions like x(x) sometimes lack the surrounding expressions
1818      // but need to be checked anyways.
1819      HandleValue(E);
1820      Visit(E);
1821    }
1822
1823    void HandleValue(Expr *E) {
1824      E = E->IgnoreParens();
1825
1826      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1827        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
1828          return;
1829
1830        // FieldME is the inner-most MemberExpr that is not an anonymous struct
1831        // or union.
1832        MemberExpr *FieldME = ME;
1833
1834        Expr *Base = E;
1835        while (isa<MemberExpr>(Base)) {
1836          ME = cast<MemberExpr>(Base);
1837
1838          if (isa<VarDecl>(ME->getMemberDecl()))
1839            return;
1840
1841          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1842            if (!FD->isAnonymousStructOrUnion())
1843              FieldME = ME;
1844
1845          Base = ME->getBase();
1846        }
1847
1848        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
1849          unsigned diag = VD->getType()->isReferenceType()
1850              ? diag::warn_reference_field_is_uninit
1851              : diag::warn_field_is_uninit;
1852          S.Diag(FieldME->getExprLoc(), diag) << VD;
1853        }
1854        return;
1855      }
1856
1857      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1858        HandleValue(CO->getTrueExpr());
1859        HandleValue(CO->getFalseExpr());
1860        return;
1861      }
1862
1863      if (BinaryConditionalOperator *BCO =
1864              dyn_cast<BinaryConditionalOperator>(E)) {
1865        HandleValue(BCO->getCommon());
1866        HandleValue(BCO->getFalseExpr());
1867        return;
1868      }
1869
1870      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1871        switch (BO->getOpcode()) {
1872        default:
1873          return;
1874        case(BO_PtrMemD):
1875        case(BO_PtrMemI):
1876          HandleValue(BO->getLHS());
1877          return;
1878        case(BO_Comma):
1879          HandleValue(BO->getRHS());
1880          return;
1881        }
1882      }
1883    }
1884
1885    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
1886      if (E->getCastKind() == CK_LValueToRValue)
1887        HandleValue(E->getSubExpr());
1888
1889      Inherited::VisitImplicitCastExpr(E);
1890    }
1891
1892    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1893      Expr *Callee = E->getCallee();
1894      if (isa<MemberExpr>(Callee))
1895        HandleValue(Callee);
1896
1897      Inherited::VisitCXXMemberCallExpr(E);
1898    }
1899  };
1900  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
1901                                                       ValueDecl *VD) {
1902    UninitializedFieldVisitor(S, VD).HandleExpr(E);
1903  }
1904} // namespace
1905
1906/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1907/// in-class initializer for a non-static C++ class member, and after
1908/// instantiating an in-class initializer in a class template. Such actions
1909/// are deferred until the class is complete.
1910void
1911Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1912                                       Expr *InitExpr) {
1913  FieldDecl *FD = cast<FieldDecl>(D);
1914  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1915         "must set init style when field is created");
1916
1917  if (!InitExpr) {
1918    FD->setInvalidDecl();
1919    FD->removeInClassInitializer();
1920    return;
1921  }
1922
1923  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1924    FD->setInvalidDecl();
1925    FD->removeInClassInitializer();
1926    return;
1927  }
1928
1929  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
1930      != DiagnosticsEngine::Ignored) {
1931    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
1932  }
1933
1934  ExprResult Init = InitExpr;
1935  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1936    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1937      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1938        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1939    }
1940    Expr **Inits = &InitExpr;
1941    unsigned NumInits = 1;
1942    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1943    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1944        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1945        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1946    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1947    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1948    if (Init.isInvalid()) {
1949      FD->setInvalidDecl();
1950      return;
1951    }
1952
1953    CheckImplicitConversions(Init.get(), InitLoc);
1954  }
1955
1956  // C++0x [class.base.init]p7:
1957  //   The initialization of each base and member constitutes a
1958  //   full-expression.
1959  Init = MaybeCreateExprWithCleanups(Init);
1960  if (Init.isInvalid()) {
1961    FD->setInvalidDecl();
1962    return;
1963  }
1964
1965  InitExpr = Init.release();
1966
1967  FD->setInClassInitializer(InitExpr);
1968}
1969
1970/// \brief Find the direct and/or virtual base specifiers that
1971/// correspond to the given base type, for use in base initialization
1972/// within a constructor.
1973static bool FindBaseInitializer(Sema &SemaRef,
1974                                CXXRecordDecl *ClassDecl,
1975                                QualType BaseType,
1976                                const CXXBaseSpecifier *&DirectBaseSpec,
1977                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1978  // First, check for a direct base class.
1979  DirectBaseSpec = 0;
1980  for (CXXRecordDecl::base_class_const_iterator Base
1981         = ClassDecl->bases_begin();
1982       Base != ClassDecl->bases_end(); ++Base) {
1983    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1984      // We found a direct base of this type. That's what we're
1985      // initializing.
1986      DirectBaseSpec = &*Base;
1987      break;
1988    }
1989  }
1990
1991  // Check for a virtual base class.
1992  // FIXME: We might be able to short-circuit this if we know in advance that
1993  // there are no virtual bases.
1994  VirtualBaseSpec = 0;
1995  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1996    // We haven't found a base yet; search the class hierarchy for a
1997    // virtual base class.
1998    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1999                       /*DetectVirtual=*/false);
2000    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2001                              BaseType, Paths)) {
2002      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2003           Path != Paths.end(); ++Path) {
2004        if (Path->back().Base->isVirtual()) {
2005          VirtualBaseSpec = Path->back().Base;
2006          break;
2007        }
2008      }
2009    }
2010  }
2011
2012  return DirectBaseSpec || VirtualBaseSpec;
2013}
2014
2015/// \brief Handle a C++ member initializer using braced-init-list syntax.
2016MemInitResult
2017Sema::ActOnMemInitializer(Decl *ConstructorD,
2018                          Scope *S,
2019                          CXXScopeSpec &SS,
2020                          IdentifierInfo *MemberOrBase,
2021                          ParsedType TemplateTypeTy,
2022                          const DeclSpec &DS,
2023                          SourceLocation IdLoc,
2024                          Expr *InitList,
2025                          SourceLocation EllipsisLoc) {
2026  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2027                             DS, IdLoc, InitList,
2028                             EllipsisLoc);
2029}
2030
2031/// \brief Handle a C++ member initializer using parentheses syntax.
2032MemInitResult
2033Sema::ActOnMemInitializer(Decl *ConstructorD,
2034                          Scope *S,
2035                          CXXScopeSpec &SS,
2036                          IdentifierInfo *MemberOrBase,
2037                          ParsedType TemplateTypeTy,
2038                          const DeclSpec &DS,
2039                          SourceLocation IdLoc,
2040                          SourceLocation LParenLoc,
2041                          Expr **Args, unsigned NumArgs,
2042                          SourceLocation RParenLoc,
2043                          SourceLocation EllipsisLoc) {
2044  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2045                                           llvm::makeArrayRef(Args, NumArgs),
2046                                           RParenLoc);
2047  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2048                             DS, IdLoc, List, EllipsisLoc);
2049}
2050
2051namespace {
2052
2053// Callback to only accept typo corrections that can be a valid C++ member
2054// intializer: either a non-static field member or a base class.
2055class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2056 public:
2057  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2058      : ClassDecl(ClassDecl) {}
2059
2060  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2061    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2062      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2063        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2064      else
2065        return isa<TypeDecl>(ND);
2066    }
2067    return false;
2068  }
2069
2070 private:
2071  CXXRecordDecl *ClassDecl;
2072};
2073
2074}
2075
2076/// \brief Handle a C++ member initializer.
2077MemInitResult
2078Sema::BuildMemInitializer(Decl *ConstructorD,
2079                          Scope *S,
2080                          CXXScopeSpec &SS,
2081                          IdentifierInfo *MemberOrBase,
2082                          ParsedType TemplateTypeTy,
2083                          const DeclSpec &DS,
2084                          SourceLocation IdLoc,
2085                          Expr *Init,
2086                          SourceLocation EllipsisLoc) {
2087  if (!ConstructorD)
2088    return true;
2089
2090  AdjustDeclIfTemplate(ConstructorD);
2091
2092  CXXConstructorDecl *Constructor
2093    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2094  if (!Constructor) {
2095    // The user wrote a constructor initializer on a function that is
2096    // not a C++ constructor. Ignore the error for now, because we may
2097    // have more member initializers coming; we'll diagnose it just
2098    // once in ActOnMemInitializers.
2099    return true;
2100  }
2101
2102  CXXRecordDecl *ClassDecl = Constructor->getParent();
2103
2104  // C++ [class.base.init]p2:
2105  //   Names in a mem-initializer-id are looked up in the scope of the
2106  //   constructor's class and, if not found in that scope, are looked
2107  //   up in the scope containing the constructor's definition.
2108  //   [Note: if the constructor's class contains a member with the
2109  //   same name as a direct or virtual base class of the class, a
2110  //   mem-initializer-id naming the member or base class and composed
2111  //   of a single identifier refers to the class member. A
2112  //   mem-initializer-id for the hidden base class may be specified
2113  //   using a qualified name. ]
2114  if (!SS.getScopeRep() && !TemplateTypeTy) {
2115    // Look for a member, first.
2116    DeclContext::lookup_result Result
2117      = ClassDecl->lookup(MemberOrBase);
2118    if (!Result.empty()) {
2119      ValueDecl *Member;
2120      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2121          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2122        if (EllipsisLoc.isValid())
2123          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2124            << MemberOrBase
2125            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2126
2127        return BuildMemberInitializer(Member, Init, IdLoc);
2128      }
2129    }
2130  }
2131  // It didn't name a member, so see if it names a class.
2132  QualType BaseType;
2133  TypeSourceInfo *TInfo = 0;
2134
2135  if (TemplateTypeTy) {
2136    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2137  } else if (DS.getTypeSpecType() == TST_decltype) {
2138    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2139  } else {
2140    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2141    LookupParsedName(R, S, &SS);
2142
2143    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2144    if (!TyD) {
2145      if (R.isAmbiguous()) return true;
2146
2147      // We don't want access-control diagnostics here.
2148      R.suppressDiagnostics();
2149
2150      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2151        bool NotUnknownSpecialization = false;
2152        DeclContext *DC = computeDeclContext(SS, false);
2153        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2154          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2155
2156        if (!NotUnknownSpecialization) {
2157          // When the scope specifier can refer to a member of an unknown
2158          // specialization, we take it as a type name.
2159          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2160                                       SS.getWithLocInContext(Context),
2161                                       *MemberOrBase, IdLoc);
2162          if (BaseType.isNull())
2163            return true;
2164
2165          R.clear();
2166          R.setLookupName(MemberOrBase);
2167        }
2168      }
2169
2170      // If no results were found, try to correct typos.
2171      TypoCorrection Corr;
2172      MemInitializerValidatorCCC Validator(ClassDecl);
2173      if (R.empty() && BaseType.isNull() &&
2174          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2175                              Validator, ClassDecl))) {
2176        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2177        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2178        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2179          // We have found a non-static data member with a similar
2180          // name to what was typed; complain and initialize that
2181          // member.
2182          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2183            << MemberOrBase << true << CorrectedQuotedStr
2184            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2185          Diag(Member->getLocation(), diag::note_previous_decl)
2186            << CorrectedQuotedStr;
2187
2188          return BuildMemberInitializer(Member, Init, IdLoc);
2189        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2190          const CXXBaseSpecifier *DirectBaseSpec;
2191          const CXXBaseSpecifier *VirtualBaseSpec;
2192          if (FindBaseInitializer(*this, ClassDecl,
2193                                  Context.getTypeDeclType(Type),
2194                                  DirectBaseSpec, VirtualBaseSpec)) {
2195            // We have found a direct or virtual base class with a
2196            // similar name to what was typed; complain and initialize
2197            // that base class.
2198            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2199              << MemberOrBase << false << CorrectedQuotedStr
2200              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2201
2202            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2203                                                             : VirtualBaseSpec;
2204            Diag(BaseSpec->getLocStart(),
2205                 diag::note_base_class_specified_here)
2206              << BaseSpec->getType()
2207              << BaseSpec->getSourceRange();
2208
2209            TyD = Type;
2210          }
2211        }
2212      }
2213
2214      if (!TyD && BaseType.isNull()) {
2215        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2216          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2217        return true;
2218      }
2219    }
2220
2221    if (BaseType.isNull()) {
2222      BaseType = Context.getTypeDeclType(TyD);
2223      if (SS.isSet()) {
2224        NestedNameSpecifier *Qualifier =
2225          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2226
2227        // FIXME: preserve source range information
2228        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2229      }
2230    }
2231  }
2232
2233  if (!TInfo)
2234    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2235
2236  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2237}
2238
2239/// Checks a member initializer expression for cases where reference (or
2240/// pointer) members are bound to by-value parameters (or their addresses).
2241static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2242                                               Expr *Init,
2243                                               SourceLocation IdLoc) {
2244  QualType MemberTy = Member->getType();
2245
2246  // We only handle pointers and references currently.
2247  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2248  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2249    return;
2250
2251  const bool IsPointer = MemberTy->isPointerType();
2252  if (IsPointer) {
2253    if (const UnaryOperator *Op
2254          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2255      // The only case we're worried about with pointers requires taking the
2256      // address.
2257      if (Op->getOpcode() != UO_AddrOf)
2258        return;
2259
2260      Init = Op->getSubExpr();
2261    } else {
2262      // We only handle address-of expression initializers for pointers.
2263      return;
2264    }
2265  }
2266
2267  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2268    // Taking the address of a temporary will be diagnosed as a hard error.
2269    if (IsPointer)
2270      return;
2271
2272    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2273      << Member << Init->getSourceRange();
2274  } else if (const DeclRefExpr *DRE
2275               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2276    // We only warn when referring to a non-reference parameter declaration.
2277    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2278    if (!Parameter || Parameter->getType()->isReferenceType())
2279      return;
2280
2281    S.Diag(Init->getExprLoc(),
2282           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2283                     : diag::warn_bind_ref_member_to_parameter)
2284      << Member << Parameter << Init->getSourceRange();
2285  } else {
2286    // Other initializers are fine.
2287    return;
2288  }
2289
2290  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2291    << (unsigned)IsPointer;
2292}
2293
2294MemInitResult
2295Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2296                             SourceLocation IdLoc) {
2297  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2298  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2299  assert((DirectMember || IndirectMember) &&
2300         "Member must be a FieldDecl or IndirectFieldDecl");
2301
2302  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2303    return true;
2304
2305  if (Member->isInvalidDecl())
2306    return true;
2307
2308  // Diagnose value-uses of fields to initialize themselves, e.g.
2309  //   foo(foo)
2310  // where foo is not also a parameter to the constructor.
2311  // TODO: implement -Wuninitialized and fold this into that framework.
2312  Expr **Args;
2313  unsigned NumArgs;
2314  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2315    Args = ParenList->getExprs();
2316    NumArgs = ParenList->getNumExprs();
2317  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2318    Args = InitList->getInits();
2319    NumArgs = InitList->getNumInits();
2320  } else {
2321    // Template instantiation doesn't reconstruct ParenListExprs for us.
2322    Args = &Init;
2323    NumArgs = 1;
2324  }
2325
2326  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2327        != DiagnosticsEngine::Ignored)
2328    for (unsigned i = 0; i < NumArgs; ++i)
2329      // FIXME: Warn about the case when other fields are used before being
2330      // initialized. For example, let this field be the i'th field. When
2331      // initializing the i'th field, throw a warning if any of the >= i'th
2332      // fields are used, as they are not yet initialized.
2333      // Right now we are only handling the case where the i'th field uses
2334      // itself in its initializer.
2335      // Also need to take into account that some fields may be initialized by
2336      // in-class initializers, see C++11 [class.base.init]p9.
2337      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2338
2339  SourceRange InitRange = Init->getSourceRange();
2340
2341  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2342    // Can't check initialization for a member of dependent type or when
2343    // any of the arguments are type-dependent expressions.
2344    DiscardCleanupsInEvaluationContext();
2345  } else {
2346    bool InitList = false;
2347    if (isa<InitListExpr>(Init)) {
2348      InitList = true;
2349      Args = &Init;
2350      NumArgs = 1;
2351
2352      if (isStdInitializerList(Member->getType(), 0)) {
2353        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2354            << /*at end of ctor*/1 << InitRange;
2355      }
2356    }
2357
2358    // Initialize the member.
2359    InitializedEntity MemberEntity =
2360      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2361                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2362    InitializationKind Kind =
2363      InitList ? InitializationKind::CreateDirectList(IdLoc)
2364               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2365                                                  InitRange.getEnd());
2366
2367    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2368    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2369                                            MultiExprArg(Args, NumArgs),
2370                                            0);
2371    if (MemberInit.isInvalid())
2372      return true;
2373
2374    CheckImplicitConversions(MemberInit.get(),
2375                             InitRange.getBegin());
2376
2377    // C++0x [class.base.init]p7:
2378    //   The initialization of each base and member constitutes a
2379    //   full-expression.
2380    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2381    if (MemberInit.isInvalid())
2382      return true;
2383
2384    Init = MemberInit.get();
2385    CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2386  }
2387
2388  if (DirectMember) {
2389    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2390                                            InitRange.getBegin(), Init,
2391                                            InitRange.getEnd());
2392  } else {
2393    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2394                                            InitRange.getBegin(), Init,
2395                                            InitRange.getEnd());
2396  }
2397}
2398
2399MemInitResult
2400Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2401                                 CXXRecordDecl *ClassDecl) {
2402  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2403  if (!LangOpts.CPlusPlus11)
2404    return Diag(NameLoc, diag::err_delegating_ctor)
2405      << TInfo->getTypeLoc().getLocalSourceRange();
2406  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2407
2408  bool InitList = true;
2409  Expr **Args = &Init;
2410  unsigned NumArgs = 1;
2411  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2412    InitList = false;
2413    Args = ParenList->getExprs();
2414    NumArgs = ParenList->getNumExprs();
2415  }
2416
2417  SourceRange InitRange = Init->getSourceRange();
2418  // Initialize the object.
2419  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2420                                     QualType(ClassDecl->getTypeForDecl(), 0));
2421  InitializationKind Kind =
2422    InitList ? InitializationKind::CreateDirectList(NameLoc)
2423             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2424                                                InitRange.getEnd());
2425  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2426  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2427                                              MultiExprArg(Args, NumArgs),
2428                                              0);
2429  if (DelegationInit.isInvalid())
2430    return true;
2431
2432  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2433         "Delegating constructor with no target?");
2434
2435  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2436
2437  // C++0x [class.base.init]p7:
2438  //   The initialization of each base and member constitutes a
2439  //   full-expression.
2440  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2441  if (DelegationInit.isInvalid())
2442    return true;
2443
2444  // If we are in a dependent context, template instantiation will
2445  // perform this type-checking again. Just save the arguments that we
2446  // received in a ParenListExpr.
2447  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2448  // of the information that we have about the base
2449  // initializer. However, deconstructing the ASTs is a dicey process,
2450  // and this approach is far more likely to get the corner cases right.
2451  if (CurContext->isDependentContext())
2452    DelegationInit = Owned(Init);
2453
2454  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2455                                          DelegationInit.takeAs<Expr>(),
2456                                          InitRange.getEnd());
2457}
2458
2459MemInitResult
2460Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2461                           Expr *Init, CXXRecordDecl *ClassDecl,
2462                           SourceLocation EllipsisLoc) {
2463  SourceLocation BaseLoc
2464    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2465
2466  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2467    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2468             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2469
2470  // C++ [class.base.init]p2:
2471  //   [...] Unless the mem-initializer-id names a nonstatic data
2472  //   member of the constructor's class or a direct or virtual base
2473  //   of that class, the mem-initializer is ill-formed. A
2474  //   mem-initializer-list can initialize a base class using any
2475  //   name that denotes that base class type.
2476  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2477
2478  SourceRange InitRange = Init->getSourceRange();
2479  if (EllipsisLoc.isValid()) {
2480    // This is a pack expansion.
2481    if (!BaseType->containsUnexpandedParameterPack())  {
2482      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2483        << SourceRange(BaseLoc, InitRange.getEnd());
2484
2485      EllipsisLoc = SourceLocation();
2486    }
2487  } else {
2488    // Check for any unexpanded parameter packs.
2489    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2490      return true;
2491
2492    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2493      return true;
2494  }
2495
2496  // Check for direct and virtual base classes.
2497  const CXXBaseSpecifier *DirectBaseSpec = 0;
2498  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2499  if (!Dependent) {
2500    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2501                                       BaseType))
2502      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2503
2504    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2505                        VirtualBaseSpec);
2506
2507    // C++ [base.class.init]p2:
2508    // Unless the mem-initializer-id names a nonstatic data member of the
2509    // constructor's class or a direct or virtual base of that class, the
2510    // mem-initializer is ill-formed.
2511    if (!DirectBaseSpec && !VirtualBaseSpec) {
2512      // If the class has any dependent bases, then it's possible that
2513      // one of those types will resolve to the same type as
2514      // BaseType. Therefore, just treat this as a dependent base
2515      // class initialization.  FIXME: Should we try to check the
2516      // initialization anyway? It seems odd.
2517      if (ClassDecl->hasAnyDependentBases())
2518        Dependent = true;
2519      else
2520        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2521          << BaseType << Context.getTypeDeclType(ClassDecl)
2522          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2523    }
2524  }
2525
2526  if (Dependent) {
2527    DiscardCleanupsInEvaluationContext();
2528
2529    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2530                                            /*IsVirtual=*/false,
2531                                            InitRange.getBegin(), Init,
2532                                            InitRange.getEnd(), EllipsisLoc);
2533  }
2534
2535  // C++ [base.class.init]p2:
2536  //   If a mem-initializer-id is ambiguous because it designates both
2537  //   a direct non-virtual base class and an inherited virtual base
2538  //   class, the mem-initializer is ill-formed.
2539  if (DirectBaseSpec && VirtualBaseSpec)
2540    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2541      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2542
2543  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2544  if (!BaseSpec)
2545    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2546
2547  // Initialize the base.
2548  bool InitList = true;
2549  Expr **Args = &Init;
2550  unsigned NumArgs = 1;
2551  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2552    InitList = false;
2553    Args = ParenList->getExprs();
2554    NumArgs = ParenList->getNumExprs();
2555  }
2556
2557  InitializedEntity BaseEntity =
2558    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2559  InitializationKind Kind =
2560    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2561             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2562                                                InitRange.getEnd());
2563  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2564  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2565                                        MultiExprArg(Args, NumArgs), 0);
2566  if (BaseInit.isInvalid())
2567    return true;
2568
2569  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2570
2571  // C++0x [class.base.init]p7:
2572  //   The initialization of each base and member constitutes a
2573  //   full-expression.
2574  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2575  if (BaseInit.isInvalid())
2576    return true;
2577
2578  // If we are in a dependent context, template instantiation will
2579  // perform this type-checking again. Just save the arguments that we
2580  // received in a ParenListExpr.
2581  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2582  // of the information that we have about the base
2583  // initializer. However, deconstructing the ASTs is a dicey process,
2584  // and this approach is far more likely to get the corner cases right.
2585  if (CurContext->isDependentContext())
2586    BaseInit = Owned(Init);
2587
2588  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2589                                          BaseSpec->isVirtual(),
2590                                          InitRange.getBegin(),
2591                                          BaseInit.takeAs<Expr>(),
2592                                          InitRange.getEnd(), EllipsisLoc);
2593}
2594
2595// Create a static_cast\<T&&>(expr).
2596static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2597  QualType ExprType = E->getType();
2598  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2599  SourceLocation ExprLoc = E->getLocStart();
2600  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2601      TargetType, ExprLoc);
2602
2603  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2604                                   SourceRange(ExprLoc, ExprLoc),
2605                                   E->getSourceRange()).take();
2606}
2607
2608/// ImplicitInitializerKind - How an implicit base or member initializer should
2609/// initialize its base or member.
2610enum ImplicitInitializerKind {
2611  IIK_Default,
2612  IIK_Copy,
2613  IIK_Move
2614};
2615
2616static bool
2617BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2618                             ImplicitInitializerKind ImplicitInitKind,
2619                             CXXBaseSpecifier *BaseSpec,
2620                             bool IsInheritedVirtualBase,
2621                             CXXCtorInitializer *&CXXBaseInit) {
2622  InitializedEntity InitEntity
2623    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2624                                        IsInheritedVirtualBase);
2625
2626  ExprResult BaseInit;
2627
2628  switch (ImplicitInitKind) {
2629  case IIK_Default: {
2630    InitializationKind InitKind
2631      = InitializationKind::CreateDefault(Constructor->getLocation());
2632    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2633    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2634    break;
2635  }
2636
2637  case IIK_Move:
2638  case IIK_Copy: {
2639    bool Moving = ImplicitInitKind == IIK_Move;
2640    ParmVarDecl *Param = Constructor->getParamDecl(0);
2641    QualType ParamType = Param->getType().getNonReferenceType();
2642
2643    Expr *CopyCtorArg =
2644      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2645                          SourceLocation(), Param, false,
2646                          Constructor->getLocation(), ParamType,
2647                          VK_LValue, 0);
2648
2649    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2650
2651    // Cast to the base class to avoid ambiguities.
2652    QualType ArgTy =
2653      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2654                                       ParamType.getQualifiers());
2655
2656    if (Moving) {
2657      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2658    }
2659
2660    CXXCastPath BasePath;
2661    BasePath.push_back(BaseSpec);
2662    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2663                                            CK_UncheckedDerivedToBase,
2664                                            Moving ? VK_XValue : VK_LValue,
2665                                            &BasePath).take();
2666
2667    InitializationKind InitKind
2668      = InitializationKind::CreateDirect(Constructor->getLocation(),
2669                                         SourceLocation(), SourceLocation());
2670    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2671                                   &CopyCtorArg, 1);
2672    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2673                               MultiExprArg(&CopyCtorArg, 1));
2674    break;
2675  }
2676  }
2677
2678  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2679  if (BaseInit.isInvalid())
2680    return true;
2681
2682  CXXBaseInit =
2683    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2684               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2685                                                        SourceLocation()),
2686                                             BaseSpec->isVirtual(),
2687                                             SourceLocation(),
2688                                             BaseInit.takeAs<Expr>(),
2689                                             SourceLocation(),
2690                                             SourceLocation());
2691
2692  return false;
2693}
2694
2695static bool RefersToRValueRef(Expr *MemRef) {
2696  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2697  return Referenced->getType()->isRValueReferenceType();
2698}
2699
2700static bool
2701BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2702                               ImplicitInitializerKind ImplicitInitKind,
2703                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2704                               CXXCtorInitializer *&CXXMemberInit) {
2705  if (Field->isInvalidDecl())
2706    return true;
2707
2708  SourceLocation Loc = Constructor->getLocation();
2709
2710  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2711    bool Moving = ImplicitInitKind == IIK_Move;
2712    ParmVarDecl *Param = Constructor->getParamDecl(0);
2713    QualType ParamType = Param->getType().getNonReferenceType();
2714
2715    // Suppress copying zero-width bitfields.
2716    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2717      return false;
2718
2719    Expr *MemberExprBase =
2720      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2721                          SourceLocation(), Param, false,
2722                          Loc, ParamType, VK_LValue, 0);
2723
2724    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2725
2726    if (Moving) {
2727      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2728    }
2729
2730    // Build a reference to this field within the parameter.
2731    CXXScopeSpec SS;
2732    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2733                              Sema::LookupMemberName);
2734    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2735                                  : cast<ValueDecl>(Field), AS_public);
2736    MemberLookup.resolveKind();
2737    ExprResult CtorArg
2738      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2739                                         ParamType, Loc,
2740                                         /*IsArrow=*/false,
2741                                         SS,
2742                                         /*TemplateKWLoc=*/SourceLocation(),
2743                                         /*FirstQualifierInScope=*/0,
2744                                         MemberLookup,
2745                                         /*TemplateArgs=*/0);
2746    if (CtorArg.isInvalid())
2747      return true;
2748
2749    // C++11 [class.copy]p15:
2750    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2751    //     with static_cast<T&&>(x.m);
2752    if (RefersToRValueRef(CtorArg.get())) {
2753      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2754    }
2755
2756    // When the field we are copying is an array, create index variables for
2757    // each dimension of the array. We use these index variables to subscript
2758    // the source array, and other clients (e.g., CodeGen) will perform the
2759    // necessary iteration with these index variables.
2760    SmallVector<VarDecl *, 4> IndexVariables;
2761    QualType BaseType = Field->getType();
2762    QualType SizeType = SemaRef.Context.getSizeType();
2763    bool InitializingArray = false;
2764    while (const ConstantArrayType *Array
2765                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2766      InitializingArray = true;
2767      // Create the iteration variable for this array index.
2768      IdentifierInfo *IterationVarName = 0;
2769      {
2770        SmallString<8> Str;
2771        llvm::raw_svector_ostream OS(Str);
2772        OS << "__i" << IndexVariables.size();
2773        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2774      }
2775      VarDecl *IterationVar
2776        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2777                          IterationVarName, SizeType,
2778                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2779                          SC_None, SC_None);
2780      IndexVariables.push_back(IterationVar);
2781
2782      // Create a reference to the iteration variable.
2783      ExprResult IterationVarRef
2784        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2785      assert(!IterationVarRef.isInvalid() &&
2786             "Reference to invented variable cannot fail!");
2787      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2788      assert(!IterationVarRef.isInvalid() &&
2789             "Conversion of invented variable cannot fail!");
2790
2791      // Subscript the array with this iteration variable.
2792      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2793                                                        IterationVarRef.take(),
2794                                                        Loc);
2795      if (CtorArg.isInvalid())
2796        return true;
2797
2798      BaseType = Array->getElementType();
2799    }
2800
2801    // The array subscript expression is an lvalue, which is wrong for moving.
2802    if (Moving && InitializingArray)
2803      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2804
2805    // Construct the entity that we will be initializing. For an array, this
2806    // will be first element in the array, which may require several levels
2807    // of array-subscript entities.
2808    SmallVector<InitializedEntity, 4> Entities;
2809    Entities.reserve(1 + IndexVariables.size());
2810    if (Indirect)
2811      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2812    else
2813      Entities.push_back(InitializedEntity::InitializeMember(Field));
2814    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2815      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2816                                                              0,
2817                                                              Entities.back()));
2818
2819    // Direct-initialize to use the copy constructor.
2820    InitializationKind InitKind =
2821      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2822
2823    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2824    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2825                                   &CtorArgE, 1);
2826
2827    ExprResult MemberInit
2828      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2829                        MultiExprArg(&CtorArgE, 1));
2830    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2831    if (MemberInit.isInvalid())
2832      return true;
2833
2834    if (Indirect) {
2835      assert(IndexVariables.size() == 0 &&
2836             "Indirect field improperly initialized");
2837      CXXMemberInit
2838        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2839                                                   Loc, Loc,
2840                                                   MemberInit.takeAs<Expr>(),
2841                                                   Loc);
2842    } else
2843      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2844                                                 Loc, MemberInit.takeAs<Expr>(),
2845                                                 Loc,
2846                                                 IndexVariables.data(),
2847                                                 IndexVariables.size());
2848    return false;
2849  }
2850
2851  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2852
2853  QualType FieldBaseElementType =
2854    SemaRef.Context.getBaseElementType(Field->getType());
2855
2856  if (FieldBaseElementType->isRecordType()) {
2857    InitializedEntity InitEntity
2858      = Indirect? InitializedEntity::InitializeMember(Indirect)
2859                : InitializedEntity::InitializeMember(Field);
2860    InitializationKind InitKind =
2861      InitializationKind::CreateDefault(Loc);
2862
2863    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2864    ExprResult MemberInit =
2865      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2866
2867    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2868    if (MemberInit.isInvalid())
2869      return true;
2870
2871    if (Indirect)
2872      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2873                                                               Indirect, Loc,
2874                                                               Loc,
2875                                                               MemberInit.get(),
2876                                                               Loc);
2877    else
2878      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2879                                                               Field, Loc, Loc,
2880                                                               MemberInit.get(),
2881                                                               Loc);
2882    return false;
2883  }
2884
2885  if (!Field->getParent()->isUnion()) {
2886    if (FieldBaseElementType->isReferenceType()) {
2887      SemaRef.Diag(Constructor->getLocation(),
2888                   diag::err_uninitialized_member_in_ctor)
2889      << (int)Constructor->isImplicit()
2890      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2891      << 0 << Field->getDeclName();
2892      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2893      return true;
2894    }
2895
2896    if (FieldBaseElementType.isConstQualified()) {
2897      SemaRef.Diag(Constructor->getLocation(),
2898                   diag::err_uninitialized_member_in_ctor)
2899      << (int)Constructor->isImplicit()
2900      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2901      << 1 << Field->getDeclName();
2902      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2903      return true;
2904    }
2905  }
2906
2907  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2908      FieldBaseElementType->isObjCRetainableType() &&
2909      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2910      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2911    // ARC:
2912    //   Default-initialize Objective-C pointers to NULL.
2913    CXXMemberInit
2914      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2915                                                 Loc, Loc,
2916                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2917                                                 Loc);
2918    return false;
2919  }
2920
2921  // Nothing to initialize.
2922  CXXMemberInit = 0;
2923  return false;
2924}
2925
2926namespace {
2927struct BaseAndFieldInfo {
2928  Sema &S;
2929  CXXConstructorDecl *Ctor;
2930  bool AnyErrorsInInits;
2931  ImplicitInitializerKind IIK;
2932  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2933  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2934
2935  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2936    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2937    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2938    if (Generated && Ctor->isCopyConstructor())
2939      IIK = IIK_Copy;
2940    else if (Generated && Ctor->isMoveConstructor())
2941      IIK = IIK_Move;
2942    else
2943      IIK = IIK_Default;
2944  }
2945
2946  bool isImplicitCopyOrMove() const {
2947    switch (IIK) {
2948    case IIK_Copy:
2949    case IIK_Move:
2950      return true;
2951
2952    case IIK_Default:
2953      return false;
2954    }
2955
2956    llvm_unreachable("Invalid ImplicitInitializerKind!");
2957  }
2958
2959  bool addFieldInitializer(CXXCtorInitializer *Init) {
2960    AllToInit.push_back(Init);
2961
2962    // Check whether this initializer makes the field "used".
2963    if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2964      S.UnusedPrivateFields.remove(Init->getAnyMember());
2965
2966    return false;
2967  }
2968};
2969}
2970
2971/// \brief Determine whether the given indirect field declaration is somewhere
2972/// within an anonymous union.
2973static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2974  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2975                                      CEnd = F->chain_end();
2976       C != CEnd; ++C)
2977    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2978      if (Record->isUnion())
2979        return true;
2980
2981  return false;
2982}
2983
2984/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2985/// array type.
2986static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2987  if (T->isIncompleteArrayType())
2988    return true;
2989
2990  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2991    if (!ArrayT->getSize())
2992      return true;
2993
2994    T = ArrayT->getElementType();
2995  }
2996
2997  return false;
2998}
2999
3000static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3001                                    FieldDecl *Field,
3002                                    IndirectFieldDecl *Indirect = 0) {
3003
3004  // Overwhelmingly common case: we have a direct initializer for this field.
3005  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3006    return Info.addFieldInitializer(Init);
3007
3008  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3009  // has a brace-or-equal-initializer, the entity is initialized as specified
3010  // in [dcl.init].
3011  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3012    CXXCtorInitializer *Init;
3013    if (Indirect)
3014      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3015                                                      SourceLocation(),
3016                                                      SourceLocation(), 0,
3017                                                      SourceLocation());
3018    else
3019      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3020                                                      SourceLocation(),
3021                                                      SourceLocation(), 0,
3022                                                      SourceLocation());
3023    return Info.addFieldInitializer(Init);
3024  }
3025
3026  // Don't build an implicit initializer for union members if none was
3027  // explicitly specified.
3028  if (Field->getParent()->isUnion() ||
3029      (Indirect && isWithinAnonymousUnion(Indirect)))
3030    return false;
3031
3032  // Don't initialize incomplete or zero-length arrays.
3033  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3034    return false;
3035
3036  // Don't try to build an implicit initializer if there were semantic
3037  // errors in any of the initializers (and therefore we might be
3038  // missing some that the user actually wrote).
3039  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3040    return false;
3041
3042  CXXCtorInitializer *Init = 0;
3043  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3044                                     Indirect, Init))
3045    return true;
3046
3047  if (!Init)
3048    return false;
3049
3050  return Info.addFieldInitializer(Init);
3051}
3052
3053bool
3054Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3055                               CXXCtorInitializer *Initializer) {
3056  assert(Initializer->isDelegatingInitializer());
3057  Constructor->setNumCtorInitializers(1);
3058  CXXCtorInitializer **initializer =
3059    new (Context) CXXCtorInitializer*[1];
3060  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3061  Constructor->setCtorInitializers(initializer);
3062
3063  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3064    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3065    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3066  }
3067
3068  DelegatingCtorDecls.push_back(Constructor);
3069
3070  return false;
3071}
3072
3073bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
3074                               CXXCtorInitializer **Initializers,
3075                               unsigned NumInitializers,
3076                               bool AnyErrors) {
3077  if (Constructor->isDependentContext()) {
3078    // Just store the initializers as written, they will be checked during
3079    // instantiation.
3080    if (NumInitializers > 0) {
3081      Constructor->setNumCtorInitializers(NumInitializers);
3082      CXXCtorInitializer **baseOrMemberInitializers =
3083        new (Context) CXXCtorInitializer*[NumInitializers];
3084      memcpy(baseOrMemberInitializers, Initializers,
3085             NumInitializers * sizeof(CXXCtorInitializer*));
3086      Constructor->setCtorInitializers(baseOrMemberInitializers);
3087    }
3088
3089    // Let template instantiation know whether we had errors.
3090    if (AnyErrors)
3091      Constructor->setInvalidDecl();
3092
3093    return false;
3094  }
3095
3096  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3097
3098  // We need to build the initializer AST according to order of construction
3099  // and not what user specified in the Initializers list.
3100  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3101  if (!ClassDecl)
3102    return true;
3103
3104  bool HadError = false;
3105
3106  for (unsigned i = 0; i < NumInitializers; i++) {
3107    CXXCtorInitializer *Member = Initializers[i];
3108
3109    if (Member->isBaseInitializer())
3110      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3111    else
3112      Info.AllBaseFields[Member->getAnyMember()] = Member;
3113  }
3114
3115  // Keep track of the direct virtual bases.
3116  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3117  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3118       E = ClassDecl->bases_end(); I != E; ++I) {
3119    if (I->isVirtual())
3120      DirectVBases.insert(I);
3121  }
3122
3123  // Push virtual bases before others.
3124  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3125       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3126
3127    if (CXXCtorInitializer *Value
3128        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3129      Info.AllToInit.push_back(Value);
3130    } else if (!AnyErrors) {
3131      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3132      CXXCtorInitializer *CXXBaseInit;
3133      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3134                                       VBase, IsInheritedVirtualBase,
3135                                       CXXBaseInit)) {
3136        HadError = true;
3137        continue;
3138      }
3139
3140      Info.AllToInit.push_back(CXXBaseInit);
3141    }
3142  }
3143
3144  // Non-virtual bases.
3145  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3146       E = ClassDecl->bases_end(); Base != E; ++Base) {
3147    // Virtuals are in the virtual base list and already constructed.
3148    if (Base->isVirtual())
3149      continue;
3150
3151    if (CXXCtorInitializer *Value
3152          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3153      Info.AllToInit.push_back(Value);
3154    } else if (!AnyErrors) {
3155      CXXCtorInitializer *CXXBaseInit;
3156      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3157                                       Base, /*IsInheritedVirtualBase=*/false,
3158                                       CXXBaseInit)) {
3159        HadError = true;
3160        continue;
3161      }
3162
3163      Info.AllToInit.push_back(CXXBaseInit);
3164    }
3165  }
3166
3167  // Fields.
3168  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3169                               MemEnd = ClassDecl->decls_end();
3170       Mem != MemEnd; ++Mem) {
3171    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3172      // C++ [class.bit]p2:
3173      //   A declaration for a bit-field that omits the identifier declares an
3174      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3175      //   initialized.
3176      if (F->isUnnamedBitfield())
3177        continue;
3178
3179      // If we're not generating the implicit copy/move constructor, then we'll
3180      // handle anonymous struct/union fields based on their individual
3181      // indirect fields.
3182      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3183        continue;
3184
3185      if (CollectFieldInitializer(*this, Info, F))
3186        HadError = true;
3187      continue;
3188    }
3189
3190    // Beyond this point, we only consider default initialization.
3191    if (Info.IIK != IIK_Default)
3192      continue;
3193
3194    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3195      if (F->getType()->isIncompleteArrayType()) {
3196        assert(ClassDecl->hasFlexibleArrayMember() &&
3197               "Incomplete array type is not valid");
3198        continue;
3199      }
3200
3201      // Initialize each field of an anonymous struct individually.
3202      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3203        HadError = true;
3204
3205      continue;
3206    }
3207  }
3208
3209  NumInitializers = Info.AllToInit.size();
3210  if (NumInitializers > 0) {
3211    Constructor->setNumCtorInitializers(NumInitializers);
3212    CXXCtorInitializer **baseOrMemberInitializers =
3213      new (Context) CXXCtorInitializer*[NumInitializers];
3214    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3215           NumInitializers * sizeof(CXXCtorInitializer*));
3216    Constructor->setCtorInitializers(baseOrMemberInitializers);
3217
3218    // Constructors implicitly reference the base and member
3219    // destructors.
3220    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3221                                           Constructor->getParent());
3222  }
3223
3224  return HadError;
3225}
3226
3227static void *GetKeyForTopLevelField(FieldDecl *Field) {
3228  // For anonymous unions, use the class declaration as the key.
3229  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3230    if (RT->getDecl()->isAnonymousStructOrUnion())
3231      return static_cast<void *>(RT->getDecl());
3232  }
3233  return static_cast<void *>(Field);
3234}
3235
3236static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3237  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3238}
3239
3240static void *GetKeyForMember(ASTContext &Context,
3241                             CXXCtorInitializer *Member) {
3242  if (!Member->isAnyMemberInitializer())
3243    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3244
3245  // For fields injected into the class via declaration of an anonymous union,
3246  // use its anonymous union class declaration as the unique key.
3247  FieldDecl *Field = Member->getAnyMember();
3248
3249  // If the field is a member of an anonymous struct or union, our key
3250  // is the anonymous record decl that's a direct child of the class.
3251  RecordDecl *RD = Field->getParent();
3252  if (RD->isAnonymousStructOrUnion()) {
3253    while (true) {
3254      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3255      if (Parent->isAnonymousStructOrUnion())
3256        RD = Parent;
3257      else
3258        break;
3259    }
3260
3261    return static_cast<void *>(RD);
3262  }
3263
3264  return static_cast<void *>(Field);
3265}
3266
3267static void
3268DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3269                                  const CXXConstructorDecl *Constructor,
3270                                  CXXCtorInitializer **Inits,
3271                                  unsigned NumInits) {
3272  if (Constructor->getDeclContext()->isDependentContext())
3273    return;
3274
3275  // Don't check initializers order unless the warning is enabled at the
3276  // location of at least one initializer.
3277  bool ShouldCheckOrder = false;
3278  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3279    CXXCtorInitializer *Init = Inits[InitIndex];
3280    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3281                                         Init->getSourceLocation())
3282          != DiagnosticsEngine::Ignored) {
3283      ShouldCheckOrder = true;
3284      break;
3285    }
3286  }
3287  if (!ShouldCheckOrder)
3288    return;
3289
3290  // Build the list of bases and members in the order that they'll
3291  // actually be initialized.  The explicit initializers should be in
3292  // this same order but may be missing things.
3293  SmallVector<const void*, 32> IdealInitKeys;
3294
3295  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3296
3297  // 1. Virtual bases.
3298  for (CXXRecordDecl::base_class_const_iterator VBase =
3299       ClassDecl->vbases_begin(),
3300       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3301    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3302
3303  // 2. Non-virtual bases.
3304  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3305       E = ClassDecl->bases_end(); Base != E; ++Base) {
3306    if (Base->isVirtual())
3307      continue;
3308    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3309  }
3310
3311  // 3. Direct fields.
3312  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3313       E = ClassDecl->field_end(); Field != E; ++Field) {
3314    if (Field->isUnnamedBitfield())
3315      continue;
3316
3317    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3318  }
3319
3320  unsigned NumIdealInits = IdealInitKeys.size();
3321  unsigned IdealIndex = 0;
3322
3323  CXXCtorInitializer *PrevInit = 0;
3324  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3325    CXXCtorInitializer *Init = Inits[InitIndex];
3326    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3327
3328    // Scan forward to try to find this initializer in the idealized
3329    // initializers list.
3330    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3331      if (InitKey == IdealInitKeys[IdealIndex])
3332        break;
3333
3334    // If we didn't find this initializer, it must be because we
3335    // scanned past it on a previous iteration.  That can only
3336    // happen if we're out of order;  emit a warning.
3337    if (IdealIndex == NumIdealInits && PrevInit) {
3338      Sema::SemaDiagnosticBuilder D =
3339        SemaRef.Diag(PrevInit->getSourceLocation(),
3340                     diag::warn_initializer_out_of_order);
3341
3342      if (PrevInit->isAnyMemberInitializer())
3343        D << 0 << PrevInit->getAnyMember()->getDeclName();
3344      else
3345        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3346
3347      if (Init->isAnyMemberInitializer())
3348        D << 0 << Init->getAnyMember()->getDeclName();
3349      else
3350        D << 1 << Init->getTypeSourceInfo()->getType();
3351
3352      // Move back to the initializer's location in the ideal list.
3353      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3354        if (InitKey == IdealInitKeys[IdealIndex])
3355          break;
3356
3357      assert(IdealIndex != NumIdealInits &&
3358             "initializer not found in initializer list");
3359    }
3360
3361    PrevInit = Init;
3362  }
3363}
3364
3365namespace {
3366bool CheckRedundantInit(Sema &S,
3367                        CXXCtorInitializer *Init,
3368                        CXXCtorInitializer *&PrevInit) {
3369  if (!PrevInit) {
3370    PrevInit = Init;
3371    return false;
3372  }
3373
3374  if (FieldDecl *Field = Init->getMember())
3375    S.Diag(Init->getSourceLocation(),
3376           diag::err_multiple_mem_initialization)
3377      << Field->getDeclName()
3378      << Init->getSourceRange();
3379  else {
3380    const Type *BaseClass = Init->getBaseClass();
3381    assert(BaseClass && "neither field nor base");
3382    S.Diag(Init->getSourceLocation(),
3383           diag::err_multiple_base_initialization)
3384      << QualType(BaseClass, 0)
3385      << Init->getSourceRange();
3386  }
3387  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3388    << 0 << PrevInit->getSourceRange();
3389
3390  return true;
3391}
3392
3393typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3394typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3395
3396bool CheckRedundantUnionInit(Sema &S,
3397                             CXXCtorInitializer *Init,
3398                             RedundantUnionMap &Unions) {
3399  FieldDecl *Field = Init->getAnyMember();
3400  RecordDecl *Parent = Field->getParent();
3401  NamedDecl *Child = Field;
3402
3403  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3404    if (Parent->isUnion()) {
3405      UnionEntry &En = Unions[Parent];
3406      if (En.first && En.first != Child) {
3407        S.Diag(Init->getSourceLocation(),
3408               diag::err_multiple_mem_union_initialization)
3409          << Field->getDeclName()
3410          << Init->getSourceRange();
3411        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3412          << 0 << En.second->getSourceRange();
3413        return true;
3414      }
3415      if (!En.first) {
3416        En.first = Child;
3417        En.second = Init;
3418      }
3419      if (!Parent->isAnonymousStructOrUnion())
3420        return false;
3421    }
3422
3423    Child = Parent;
3424    Parent = cast<RecordDecl>(Parent->getDeclContext());
3425  }
3426
3427  return false;
3428}
3429}
3430
3431/// ActOnMemInitializers - Handle the member initializers for a constructor.
3432void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3433                                SourceLocation ColonLoc,
3434                                CXXCtorInitializer **meminits,
3435                                unsigned NumMemInits,
3436                                bool AnyErrors) {
3437  if (!ConstructorDecl)
3438    return;
3439
3440  AdjustDeclIfTemplate(ConstructorDecl);
3441
3442  CXXConstructorDecl *Constructor
3443    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3444
3445  if (!Constructor) {
3446    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3447    return;
3448  }
3449
3450  CXXCtorInitializer **MemInits =
3451    reinterpret_cast<CXXCtorInitializer **>(meminits);
3452
3453  // Mapping for the duplicate initializers check.
3454  // For member initializers, this is keyed with a FieldDecl*.
3455  // For base initializers, this is keyed with a Type*.
3456  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3457
3458  // Mapping for the inconsistent anonymous-union initializers check.
3459  RedundantUnionMap MemberUnions;
3460
3461  bool HadError = false;
3462  for (unsigned i = 0; i < NumMemInits; i++) {
3463    CXXCtorInitializer *Init = MemInits[i];
3464
3465    // Set the source order index.
3466    Init->setSourceOrder(i);
3467
3468    if (Init->isAnyMemberInitializer()) {
3469      FieldDecl *Field = Init->getAnyMember();
3470      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3471          CheckRedundantUnionInit(*this, Init, MemberUnions))
3472        HadError = true;
3473    } else if (Init->isBaseInitializer()) {
3474      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3475      if (CheckRedundantInit(*this, Init, Members[Key]))
3476        HadError = true;
3477    } else {
3478      assert(Init->isDelegatingInitializer());
3479      // This must be the only initializer
3480      if (NumMemInits != 1) {
3481        Diag(Init->getSourceLocation(),
3482             diag::err_delegating_initializer_alone)
3483          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3484        // We will treat this as being the only initializer.
3485      }
3486      SetDelegatingInitializer(Constructor, MemInits[i]);
3487      // Return immediately as the initializer is set.
3488      return;
3489    }
3490  }
3491
3492  if (HadError)
3493    return;
3494
3495  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3496
3497  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3498}
3499
3500void
3501Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3502                                             CXXRecordDecl *ClassDecl) {
3503  // Ignore dependent contexts. Also ignore unions, since their members never
3504  // have destructors implicitly called.
3505  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3506    return;
3507
3508  // FIXME: all the access-control diagnostics are positioned on the
3509  // field/base declaration.  That's probably good; that said, the
3510  // user might reasonably want to know why the destructor is being
3511  // emitted, and we currently don't say.
3512
3513  // Non-static data members.
3514  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3515       E = ClassDecl->field_end(); I != E; ++I) {
3516    FieldDecl *Field = *I;
3517    if (Field->isInvalidDecl())
3518      continue;
3519
3520    // Don't destroy incomplete or zero-length arrays.
3521    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3522      continue;
3523
3524    QualType FieldType = Context.getBaseElementType(Field->getType());
3525
3526    const RecordType* RT = FieldType->getAs<RecordType>();
3527    if (!RT)
3528      continue;
3529
3530    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3531    if (FieldClassDecl->isInvalidDecl())
3532      continue;
3533    if (FieldClassDecl->hasIrrelevantDestructor())
3534      continue;
3535    // The destructor for an implicit anonymous union member is never invoked.
3536    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3537      continue;
3538
3539    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3540    assert(Dtor && "No dtor found for FieldClassDecl!");
3541    CheckDestructorAccess(Field->getLocation(), Dtor,
3542                          PDiag(diag::err_access_dtor_field)
3543                            << Field->getDeclName()
3544                            << FieldType);
3545
3546    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3547    DiagnoseUseOfDecl(Dtor, Location);
3548  }
3549
3550  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3551
3552  // Bases.
3553  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3554       E = ClassDecl->bases_end(); Base != E; ++Base) {
3555    // Bases are always records in a well-formed non-dependent class.
3556    const RecordType *RT = Base->getType()->getAs<RecordType>();
3557
3558    // Remember direct virtual bases.
3559    if (Base->isVirtual())
3560      DirectVirtualBases.insert(RT);
3561
3562    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3563    // If our base class is invalid, we probably can't get its dtor anyway.
3564    if (BaseClassDecl->isInvalidDecl())
3565      continue;
3566    if (BaseClassDecl->hasIrrelevantDestructor())
3567      continue;
3568
3569    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3570    assert(Dtor && "No dtor found for BaseClassDecl!");
3571
3572    // FIXME: caret should be on the start of the class name
3573    CheckDestructorAccess(Base->getLocStart(), Dtor,
3574                          PDiag(diag::err_access_dtor_base)
3575                            << Base->getType()
3576                            << Base->getSourceRange(),
3577                          Context.getTypeDeclType(ClassDecl));
3578
3579    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3580    DiagnoseUseOfDecl(Dtor, Location);
3581  }
3582
3583  // Virtual bases.
3584  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3585       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3586
3587    // Bases are always records in a well-formed non-dependent class.
3588    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3589
3590    // Ignore direct virtual bases.
3591    if (DirectVirtualBases.count(RT))
3592      continue;
3593
3594    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3595    // If our base class is invalid, we probably can't get its dtor anyway.
3596    if (BaseClassDecl->isInvalidDecl())
3597      continue;
3598    if (BaseClassDecl->hasIrrelevantDestructor())
3599      continue;
3600
3601    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3602    assert(Dtor && "No dtor found for BaseClassDecl!");
3603    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3604                          PDiag(diag::err_access_dtor_vbase)
3605                            << VBase->getType(),
3606                          Context.getTypeDeclType(ClassDecl));
3607
3608    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3609    DiagnoseUseOfDecl(Dtor, Location);
3610  }
3611}
3612
3613void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3614  if (!CDtorDecl)
3615    return;
3616
3617  if (CXXConstructorDecl *Constructor
3618      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3619    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3620}
3621
3622bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3623                                  unsigned DiagID, AbstractDiagSelID SelID) {
3624  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3625    unsigned DiagID;
3626    AbstractDiagSelID SelID;
3627
3628  public:
3629    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3630      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3631
3632    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3633      if (Suppressed) return;
3634      if (SelID == -1)
3635        S.Diag(Loc, DiagID) << T;
3636      else
3637        S.Diag(Loc, DiagID) << SelID << T;
3638    }
3639  } Diagnoser(DiagID, SelID);
3640
3641  return RequireNonAbstractType(Loc, T, Diagnoser);
3642}
3643
3644bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3645                                  TypeDiagnoser &Diagnoser) {
3646  if (!getLangOpts().CPlusPlus)
3647    return false;
3648
3649  if (const ArrayType *AT = Context.getAsArrayType(T))
3650    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3651
3652  if (const PointerType *PT = T->getAs<PointerType>()) {
3653    // Find the innermost pointer type.
3654    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3655      PT = T;
3656
3657    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3658      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3659  }
3660
3661  const RecordType *RT = T->getAs<RecordType>();
3662  if (!RT)
3663    return false;
3664
3665  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3666
3667  // We can't answer whether something is abstract until it has a
3668  // definition.  If it's currently being defined, we'll walk back
3669  // over all the declarations when we have a full definition.
3670  const CXXRecordDecl *Def = RD->getDefinition();
3671  if (!Def || Def->isBeingDefined())
3672    return false;
3673
3674  if (!RD->isAbstract())
3675    return false;
3676
3677  Diagnoser.diagnose(*this, Loc, T);
3678  DiagnoseAbstractType(RD);
3679
3680  return true;
3681}
3682
3683void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3684  // Check if we've already emitted the list of pure virtual functions
3685  // for this class.
3686  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3687    return;
3688
3689  CXXFinalOverriderMap FinalOverriders;
3690  RD->getFinalOverriders(FinalOverriders);
3691
3692  // Keep a set of seen pure methods so we won't diagnose the same method
3693  // more than once.
3694  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3695
3696  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3697                                   MEnd = FinalOverriders.end();
3698       M != MEnd;
3699       ++M) {
3700    for (OverridingMethods::iterator SO = M->second.begin(),
3701                                  SOEnd = M->second.end();
3702         SO != SOEnd; ++SO) {
3703      // C++ [class.abstract]p4:
3704      //   A class is abstract if it contains or inherits at least one
3705      //   pure virtual function for which the final overrider is pure
3706      //   virtual.
3707
3708      //
3709      if (SO->second.size() != 1)
3710        continue;
3711
3712      if (!SO->second.front().Method->isPure())
3713        continue;
3714
3715      if (!SeenPureMethods.insert(SO->second.front().Method))
3716        continue;
3717
3718      Diag(SO->second.front().Method->getLocation(),
3719           diag::note_pure_virtual_function)
3720        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3721    }
3722  }
3723
3724  if (!PureVirtualClassDiagSet)
3725    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3726  PureVirtualClassDiagSet->insert(RD);
3727}
3728
3729namespace {
3730struct AbstractUsageInfo {
3731  Sema &S;
3732  CXXRecordDecl *Record;
3733  CanQualType AbstractType;
3734  bool Invalid;
3735
3736  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3737    : S(S), Record(Record),
3738      AbstractType(S.Context.getCanonicalType(
3739                   S.Context.getTypeDeclType(Record))),
3740      Invalid(false) {}
3741
3742  void DiagnoseAbstractType() {
3743    if (Invalid) return;
3744    S.DiagnoseAbstractType(Record);
3745    Invalid = true;
3746  }
3747
3748  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3749};
3750
3751struct CheckAbstractUsage {
3752  AbstractUsageInfo &Info;
3753  const NamedDecl *Ctx;
3754
3755  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3756    : Info(Info), Ctx(Ctx) {}
3757
3758  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3759    switch (TL.getTypeLocClass()) {
3760#define ABSTRACT_TYPELOC(CLASS, PARENT)
3761#define TYPELOC(CLASS, PARENT) \
3762    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3763#include "clang/AST/TypeLocNodes.def"
3764    }
3765  }
3766
3767  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3768    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3769    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3770      if (!TL.getArg(I))
3771        continue;
3772
3773      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3774      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3775    }
3776  }
3777
3778  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3779    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3780  }
3781
3782  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3783    // Visit the type parameters from a permissive context.
3784    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3785      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3786      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3787        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3788          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3789      // TODO: other template argument types?
3790    }
3791  }
3792
3793  // Visit pointee types from a permissive context.
3794#define CheckPolymorphic(Type) \
3795  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3796    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3797  }
3798  CheckPolymorphic(PointerTypeLoc)
3799  CheckPolymorphic(ReferenceTypeLoc)
3800  CheckPolymorphic(MemberPointerTypeLoc)
3801  CheckPolymorphic(BlockPointerTypeLoc)
3802  CheckPolymorphic(AtomicTypeLoc)
3803
3804  /// Handle all the types we haven't given a more specific
3805  /// implementation for above.
3806  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3807    // Every other kind of type that we haven't called out already
3808    // that has an inner type is either (1) sugar or (2) contains that
3809    // inner type in some way as a subobject.
3810    if (TypeLoc Next = TL.getNextTypeLoc())
3811      return Visit(Next, Sel);
3812
3813    // If there's no inner type and we're in a permissive context,
3814    // don't diagnose.
3815    if (Sel == Sema::AbstractNone) return;
3816
3817    // Check whether the type matches the abstract type.
3818    QualType T = TL.getType();
3819    if (T->isArrayType()) {
3820      Sel = Sema::AbstractArrayType;
3821      T = Info.S.Context.getBaseElementType(T);
3822    }
3823    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3824    if (CT != Info.AbstractType) return;
3825
3826    // It matched; do some magic.
3827    if (Sel == Sema::AbstractArrayType) {
3828      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3829        << T << TL.getSourceRange();
3830    } else {
3831      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3832        << Sel << T << TL.getSourceRange();
3833    }
3834    Info.DiagnoseAbstractType();
3835  }
3836};
3837
3838void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3839                                  Sema::AbstractDiagSelID Sel) {
3840  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3841}
3842
3843}
3844
3845/// Check for invalid uses of an abstract type in a method declaration.
3846static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3847                                    CXXMethodDecl *MD) {
3848  // No need to do the check on definitions, which require that
3849  // the return/param types be complete.
3850  if (MD->doesThisDeclarationHaveABody())
3851    return;
3852
3853  // For safety's sake, just ignore it if we don't have type source
3854  // information.  This should never happen for non-implicit methods,
3855  // but...
3856  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3857    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3858}
3859
3860/// Check for invalid uses of an abstract type within a class definition.
3861static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3862                                    CXXRecordDecl *RD) {
3863  for (CXXRecordDecl::decl_iterator
3864         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3865    Decl *D = *I;
3866    if (D->isImplicit()) continue;
3867
3868    // Methods and method templates.
3869    if (isa<CXXMethodDecl>(D)) {
3870      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3871    } else if (isa<FunctionTemplateDecl>(D)) {
3872      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3873      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3874
3875    // Fields and static variables.
3876    } else if (isa<FieldDecl>(D)) {
3877      FieldDecl *FD = cast<FieldDecl>(D);
3878      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3879        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3880    } else if (isa<VarDecl>(D)) {
3881      VarDecl *VD = cast<VarDecl>(D);
3882      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3883        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3884
3885    // Nested classes and class templates.
3886    } else if (isa<CXXRecordDecl>(D)) {
3887      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3888    } else if (isa<ClassTemplateDecl>(D)) {
3889      CheckAbstractClassUsage(Info,
3890                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3891    }
3892  }
3893}
3894
3895/// \brief Perform semantic checks on a class definition that has been
3896/// completing, introducing implicitly-declared members, checking for
3897/// abstract types, etc.
3898void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3899  if (!Record)
3900    return;
3901
3902  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3903    AbstractUsageInfo Info(*this, Record);
3904    CheckAbstractClassUsage(Info, Record);
3905  }
3906
3907  // If this is not an aggregate type and has no user-declared constructor,
3908  // complain about any non-static data members of reference or const scalar
3909  // type, since they will never get initializers.
3910  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3911      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3912      !Record->isLambda()) {
3913    bool Complained = false;
3914    for (RecordDecl::field_iterator F = Record->field_begin(),
3915                                 FEnd = Record->field_end();
3916         F != FEnd; ++F) {
3917      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3918        continue;
3919
3920      if (F->getType()->isReferenceType() ||
3921          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3922        if (!Complained) {
3923          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3924            << Record->getTagKind() << Record;
3925          Complained = true;
3926        }
3927
3928        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3929          << F->getType()->isReferenceType()
3930          << F->getDeclName();
3931      }
3932    }
3933  }
3934
3935  if (Record->isDynamicClass() && !Record->isDependentType())
3936    DynamicClasses.push_back(Record);
3937
3938  if (Record->getIdentifier()) {
3939    // C++ [class.mem]p13:
3940    //   If T is the name of a class, then each of the following shall have a
3941    //   name different from T:
3942    //     - every member of every anonymous union that is a member of class T.
3943    //
3944    // C++ [class.mem]p14:
3945    //   In addition, if class T has a user-declared constructor (12.1), every
3946    //   non-static data member of class T shall have a name different from T.
3947    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3948    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3949         ++I) {
3950      NamedDecl *D = *I;
3951      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3952          isa<IndirectFieldDecl>(D)) {
3953        Diag(D->getLocation(), diag::err_member_name_of_class)
3954          << D->getDeclName();
3955        break;
3956      }
3957    }
3958  }
3959
3960  // Warn if the class has virtual methods but non-virtual public destructor.
3961  if (Record->isPolymorphic() && !Record->isDependentType()) {
3962    CXXDestructorDecl *dtor = Record->getDestructor();
3963    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3964      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3965           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3966  }
3967
3968  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
3969    Diag(Record->getLocation(), diag::warn_abstract_final_class);
3970    DiagnoseAbstractType(Record);
3971  }
3972
3973  if (!Record->isDependentType()) {
3974    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3975                                     MEnd = Record->method_end();
3976         M != MEnd; ++M) {
3977      // See if a method overloads virtual methods in a base
3978      // class without overriding any.
3979      if (!M->isStatic())
3980        DiagnoseHiddenVirtualMethods(Record, *M);
3981
3982      // Check whether the explicitly-defaulted special members are valid.
3983      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
3984        CheckExplicitlyDefaultedSpecialMember(*M);
3985
3986      // For an explicitly defaulted or deleted special member, we defer
3987      // determining triviality until the class is complete. That time is now!
3988      if (!M->isImplicit() && !M->isUserProvided()) {
3989        CXXSpecialMember CSM = getSpecialMember(*M);
3990        if (CSM != CXXInvalid) {
3991          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
3992
3993          // Inform the class that we've finished declaring this member.
3994          Record->finishedDefaultedOrDeletedMember(*M);
3995        }
3996      }
3997    }
3998  }
3999
4000  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4001  // function that is not a constructor declares that member function to be
4002  // const. [...] The class of which that function is a member shall be
4003  // a literal type.
4004  //
4005  // If the class has virtual bases, any constexpr members will already have
4006  // been diagnosed by the checks performed on the member declaration, so
4007  // suppress this (less useful) diagnostic.
4008  //
4009  // We delay this until we know whether an explicitly-defaulted (or deleted)
4010  // destructor for the class is trivial.
4011  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4012      !Record->isLiteral() && !Record->getNumVBases()) {
4013    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4014                                     MEnd = Record->method_end();
4015         M != MEnd; ++M) {
4016      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4017        switch (Record->getTemplateSpecializationKind()) {
4018        case TSK_ImplicitInstantiation:
4019        case TSK_ExplicitInstantiationDeclaration:
4020        case TSK_ExplicitInstantiationDefinition:
4021          // If a template instantiates to a non-literal type, but its members
4022          // instantiate to constexpr functions, the template is technically
4023          // ill-formed, but we allow it for sanity.
4024          continue;
4025
4026        case TSK_Undeclared:
4027        case TSK_ExplicitSpecialization:
4028          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4029                             diag::err_constexpr_method_non_literal);
4030          break;
4031        }
4032
4033        // Only produce one error per class.
4034        break;
4035      }
4036    }
4037  }
4038
4039  // Declare inherited constructors. We do this eagerly here because:
4040  // - The standard requires an eager diagnostic for conflicting inherited
4041  //   constructors from different classes.
4042  // - The lazy declaration of the other implicit constructors is so as to not
4043  //   waste space and performance on classes that are not meant to be
4044  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4045  //   have inherited constructors.
4046  DeclareInheritedConstructors(Record);
4047}
4048
4049/// Is the special member function which would be selected to perform the
4050/// specified operation on the specified class type a constexpr constructor?
4051static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4052                                     Sema::CXXSpecialMember CSM,
4053                                     bool ConstArg) {
4054  Sema::SpecialMemberOverloadResult *SMOR =
4055      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4056                            false, false, false, false);
4057  if (!SMOR || !SMOR->getMethod())
4058    // A constructor we wouldn't select can't be "involved in initializing"
4059    // anything.
4060    return true;
4061  return SMOR->getMethod()->isConstexpr();
4062}
4063
4064/// Determine whether the specified special member function would be constexpr
4065/// if it were implicitly defined.
4066static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4067                                              Sema::CXXSpecialMember CSM,
4068                                              bool ConstArg) {
4069  if (!S.getLangOpts().CPlusPlus11)
4070    return false;
4071
4072  // C++11 [dcl.constexpr]p4:
4073  // In the definition of a constexpr constructor [...]
4074  switch (CSM) {
4075  case Sema::CXXDefaultConstructor:
4076    // Since default constructor lookup is essentially trivial (and cannot
4077    // involve, for instance, template instantiation), we compute whether a
4078    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4079    //
4080    // This is important for performance; we need to know whether the default
4081    // constructor is constexpr to determine whether the type is a literal type.
4082    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4083
4084  case Sema::CXXCopyConstructor:
4085  case Sema::CXXMoveConstructor:
4086    // For copy or move constructors, we need to perform overload resolution.
4087    break;
4088
4089  case Sema::CXXCopyAssignment:
4090  case Sema::CXXMoveAssignment:
4091  case Sema::CXXDestructor:
4092  case Sema::CXXInvalid:
4093    return false;
4094  }
4095
4096  //   -- if the class is a non-empty union, or for each non-empty anonymous
4097  //      union member of a non-union class, exactly one non-static data member
4098  //      shall be initialized; [DR1359]
4099  //
4100  // If we squint, this is guaranteed, since exactly one non-static data member
4101  // will be initialized (if the constructor isn't deleted), we just don't know
4102  // which one.
4103  if (ClassDecl->isUnion())
4104    return true;
4105
4106  //   -- the class shall not have any virtual base classes;
4107  if (ClassDecl->getNumVBases())
4108    return false;
4109
4110  //   -- every constructor involved in initializing [...] base class
4111  //      sub-objects shall be a constexpr constructor;
4112  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4113                                       BEnd = ClassDecl->bases_end();
4114       B != BEnd; ++B) {
4115    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4116    if (!BaseType) continue;
4117
4118    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4119    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4120      return false;
4121  }
4122
4123  //   -- every constructor involved in initializing non-static data members
4124  //      [...] shall be a constexpr constructor;
4125  //   -- every non-static data member and base class sub-object shall be
4126  //      initialized
4127  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4128                               FEnd = ClassDecl->field_end();
4129       F != FEnd; ++F) {
4130    if (F->isInvalidDecl())
4131      continue;
4132    if (const RecordType *RecordTy =
4133            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4134      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4135      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4136        return false;
4137    }
4138  }
4139
4140  // All OK, it's constexpr!
4141  return true;
4142}
4143
4144static Sema::ImplicitExceptionSpecification
4145computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4146  switch (S.getSpecialMember(MD)) {
4147  case Sema::CXXDefaultConstructor:
4148    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4149  case Sema::CXXCopyConstructor:
4150    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4151  case Sema::CXXCopyAssignment:
4152    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4153  case Sema::CXXMoveConstructor:
4154    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4155  case Sema::CXXMoveAssignment:
4156    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4157  case Sema::CXXDestructor:
4158    return S.ComputeDefaultedDtorExceptionSpec(MD);
4159  case Sema::CXXInvalid:
4160    break;
4161  }
4162  llvm_unreachable("only special members have implicit exception specs");
4163}
4164
4165static void
4166updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4167                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4168  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4169  ExceptSpec.getEPI(EPI);
4170  const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4171    S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4172                              FPT->getNumArgs(), EPI));
4173  FD->setType(QualType(NewFPT, 0));
4174}
4175
4176void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4177  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4178  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4179    return;
4180
4181  // Evaluate the exception specification.
4182  ImplicitExceptionSpecification ExceptSpec =
4183      computeImplicitExceptionSpec(*this, Loc, MD);
4184
4185  // Update the type of the special member to use it.
4186  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4187
4188  // A user-provided destructor can be defined outside the class. When that
4189  // happens, be sure to update the exception specification on both
4190  // declarations.
4191  const FunctionProtoType *CanonicalFPT =
4192    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4193  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4194    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4195                        CanonicalFPT, ExceptSpec);
4196}
4197
4198void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4199  CXXRecordDecl *RD = MD->getParent();
4200  CXXSpecialMember CSM = getSpecialMember(MD);
4201
4202  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4203         "not an explicitly-defaulted special member");
4204
4205  // Whether this was the first-declared instance of the constructor.
4206  // This affects whether we implicitly add an exception spec and constexpr.
4207  bool First = MD == MD->getCanonicalDecl();
4208
4209  bool HadError = false;
4210
4211  // C++11 [dcl.fct.def.default]p1:
4212  //   A function that is explicitly defaulted shall
4213  //     -- be a special member function (checked elsewhere),
4214  //     -- have the same type (except for ref-qualifiers, and except that a
4215  //        copy operation can take a non-const reference) as an implicit
4216  //        declaration, and
4217  //     -- not have default arguments.
4218  unsigned ExpectedParams = 1;
4219  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4220    ExpectedParams = 0;
4221  if (MD->getNumParams() != ExpectedParams) {
4222    // This also checks for default arguments: a copy or move constructor with a
4223    // default argument is classified as a default constructor, and assignment
4224    // operations and destructors can't have default arguments.
4225    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4226      << CSM << MD->getSourceRange();
4227    HadError = true;
4228  } else if (MD->isVariadic()) {
4229    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4230      << CSM << MD->getSourceRange();
4231    HadError = true;
4232  }
4233
4234  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4235
4236  bool CanHaveConstParam = false;
4237  if (CSM == CXXCopyConstructor)
4238    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4239  else if (CSM == CXXCopyAssignment)
4240    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4241
4242  QualType ReturnType = Context.VoidTy;
4243  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4244    // Check for return type matching.
4245    ReturnType = Type->getResultType();
4246    QualType ExpectedReturnType =
4247        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4248    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4249      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4250        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4251      HadError = true;
4252    }
4253
4254    // A defaulted special member cannot have cv-qualifiers.
4255    if (Type->getTypeQuals()) {
4256      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4257        << (CSM == CXXMoveAssignment);
4258      HadError = true;
4259    }
4260  }
4261
4262  // Check for parameter type matching.
4263  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4264  bool HasConstParam = false;
4265  if (ExpectedParams && ArgType->isReferenceType()) {
4266    // Argument must be reference to possibly-const T.
4267    QualType ReferentType = ArgType->getPointeeType();
4268    HasConstParam = ReferentType.isConstQualified();
4269
4270    if (ReferentType.isVolatileQualified()) {
4271      Diag(MD->getLocation(),
4272           diag::err_defaulted_special_member_volatile_param) << CSM;
4273      HadError = true;
4274    }
4275
4276    if (HasConstParam && !CanHaveConstParam) {
4277      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4278        Diag(MD->getLocation(),
4279             diag::err_defaulted_special_member_copy_const_param)
4280          << (CSM == CXXCopyAssignment);
4281        // FIXME: Explain why this special member can't be const.
4282      } else {
4283        Diag(MD->getLocation(),
4284             diag::err_defaulted_special_member_move_const_param)
4285          << (CSM == CXXMoveAssignment);
4286      }
4287      HadError = true;
4288    }
4289  } else if (ExpectedParams) {
4290    // A copy assignment operator can take its argument by value, but a
4291    // defaulted one cannot.
4292    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4293    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4294    HadError = true;
4295  }
4296
4297  // C++11 [dcl.fct.def.default]p2:
4298  //   An explicitly-defaulted function may be declared constexpr only if it
4299  //   would have been implicitly declared as constexpr,
4300  // Do not apply this rule to members of class templates, since core issue 1358
4301  // makes such functions always instantiate to constexpr functions. For
4302  // non-constructors, this is checked elsewhere.
4303  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4304                                                     HasConstParam);
4305  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4306      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4307    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4308    // FIXME: Explain why the constructor can't be constexpr.
4309    HadError = true;
4310  }
4311
4312  //   and may have an explicit exception-specification only if it is compatible
4313  //   with the exception-specification on the implicit declaration.
4314  if (Type->hasExceptionSpec()) {
4315    // Delay the check if this is the first declaration of the special member,
4316    // since we may not have parsed some necessary in-class initializers yet.
4317    if (First)
4318      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4319    else
4320      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4321  }
4322
4323  //   If a function is explicitly defaulted on its first declaration,
4324  if (First) {
4325    //  -- it is implicitly considered to be constexpr if the implicit
4326    //     definition would be,
4327    MD->setConstexpr(Constexpr);
4328
4329    //  -- it is implicitly considered to have the same exception-specification
4330    //     as if it had been implicitly declared,
4331    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4332    EPI.ExceptionSpecType = EST_Unevaluated;
4333    EPI.ExceptionSpecDecl = MD;
4334    MD->setType(Context.getFunctionType(ReturnType, &ArgType,
4335                                        ExpectedParams, EPI));
4336  }
4337
4338  if (ShouldDeleteSpecialMember(MD, CSM)) {
4339    if (First) {
4340      MD->setDeletedAsWritten();
4341    } else {
4342      // C++11 [dcl.fct.def.default]p4:
4343      //   [For a] user-provided explicitly-defaulted function [...] if such a
4344      //   function is implicitly defined as deleted, the program is ill-formed.
4345      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4346      HadError = true;
4347    }
4348  }
4349
4350  if (HadError)
4351    MD->setInvalidDecl();
4352}
4353
4354/// Check whether the exception specification provided for an
4355/// explicitly-defaulted special member matches the exception specification
4356/// that would have been generated for an implicit special member, per
4357/// C++11 [dcl.fct.def.default]p2.
4358void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4359    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4360  // Compute the implicit exception specification.
4361  FunctionProtoType::ExtProtoInfo EPI;
4362  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4363  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4364    Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4365
4366  // Ensure that it matches.
4367  CheckEquivalentExceptionSpec(
4368    PDiag(diag::err_incorrect_defaulted_exception_spec)
4369      << getSpecialMember(MD), PDiag(),
4370    ImplicitType, SourceLocation(),
4371    SpecifiedType, MD->getLocation());
4372}
4373
4374void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4375  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4376       I != N; ++I)
4377    CheckExplicitlyDefaultedMemberExceptionSpec(
4378      DelayedDefaultedMemberExceptionSpecs[I].first,
4379      DelayedDefaultedMemberExceptionSpecs[I].second);
4380
4381  DelayedDefaultedMemberExceptionSpecs.clear();
4382}
4383
4384namespace {
4385struct SpecialMemberDeletionInfo {
4386  Sema &S;
4387  CXXMethodDecl *MD;
4388  Sema::CXXSpecialMember CSM;
4389  bool Diagnose;
4390
4391  // Properties of the special member, computed for convenience.
4392  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4393  SourceLocation Loc;
4394
4395  bool AllFieldsAreConst;
4396
4397  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4398                            Sema::CXXSpecialMember CSM, bool Diagnose)
4399    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4400      IsConstructor(false), IsAssignment(false), IsMove(false),
4401      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4402      AllFieldsAreConst(true) {
4403    switch (CSM) {
4404      case Sema::CXXDefaultConstructor:
4405      case Sema::CXXCopyConstructor:
4406        IsConstructor = true;
4407        break;
4408      case Sema::CXXMoveConstructor:
4409        IsConstructor = true;
4410        IsMove = true;
4411        break;
4412      case Sema::CXXCopyAssignment:
4413        IsAssignment = true;
4414        break;
4415      case Sema::CXXMoveAssignment:
4416        IsAssignment = true;
4417        IsMove = true;
4418        break;
4419      case Sema::CXXDestructor:
4420        break;
4421      case Sema::CXXInvalid:
4422        llvm_unreachable("invalid special member kind");
4423    }
4424
4425    if (MD->getNumParams()) {
4426      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4427      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4428    }
4429  }
4430
4431  bool inUnion() const { return MD->getParent()->isUnion(); }
4432
4433  /// Look up the corresponding special member in the given class.
4434  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4435                                              unsigned Quals) {
4436    unsigned TQ = MD->getTypeQualifiers();
4437    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4438    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4439      Quals = 0;
4440    return S.LookupSpecialMember(Class, CSM,
4441                                 ConstArg || (Quals & Qualifiers::Const),
4442                                 VolatileArg || (Quals & Qualifiers::Volatile),
4443                                 MD->getRefQualifier() == RQ_RValue,
4444                                 TQ & Qualifiers::Const,
4445                                 TQ & Qualifiers::Volatile);
4446  }
4447
4448  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4449
4450  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4451  bool shouldDeleteForField(FieldDecl *FD);
4452  bool shouldDeleteForAllConstMembers();
4453
4454  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4455                                     unsigned Quals);
4456  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4457                                    Sema::SpecialMemberOverloadResult *SMOR,
4458                                    bool IsDtorCallInCtor);
4459
4460  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4461};
4462}
4463
4464/// Is the given special member inaccessible when used on the given
4465/// sub-object.
4466bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4467                                             CXXMethodDecl *target) {
4468  /// If we're operating on a base class, the object type is the
4469  /// type of this special member.
4470  QualType objectTy;
4471  AccessSpecifier access = target->getAccess();
4472  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4473    objectTy = S.Context.getTypeDeclType(MD->getParent());
4474    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4475
4476  // If we're operating on a field, the object type is the type of the field.
4477  } else {
4478    objectTy = S.Context.getTypeDeclType(target->getParent());
4479  }
4480
4481  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4482}
4483
4484/// Check whether we should delete a special member due to the implicit
4485/// definition containing a call to a special member of a subobject.
4486bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4487    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4488    bool IsDtorCallInCtor) {
4489  CXXMethodDecl *Decl = SMOR->getMethod();
4490  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4491
4492  int DiagKind = -1;
4493
4494  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4495    DiagKind = !Decl ? 0 : 1;
4496  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4497    DiagKind = 2;
4498  else if (!isAccessible(Subobj, Decl))
4499    DiagKind = 3;
4500  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4501           !Decl->isTrivial()) {
4502    // A member of a union must have a trivial corresponding special member.
4503    // As a weird special case, a destructor call from a union's constructor
4504    // must be accessible and non-deleted, but need not be trivial. Such a
4505    // destructor is never actually called, but is semantically checked as
4506    // if it were.
4507    DiagKind = 4;
4508  }
4509
4510  if (DiagKind == -1)
4511    return false;
4512
4513  if (Diagnose) {
4514    if (Field) {
4515      S.Diag(Field->getLocation(),
4516             diag::note_deleted_special_member_class_subobject)
4517        << CSM << MD->getParent() << /*IsField*/true
4518        << Field << DiagKind << IsDtorCallInCtor;
4519    } else {
4520      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4521      S.Diag(Base->getLocStart(),
4522             diag::note_deleted_special_member_class_subobject)
4523        << CSM << MD->getParent() << /*IsField*/false
4524        << Base->getType() << DiagKind << IsDtorCallInCtor;
4525    }
4526
4527    if (DiagKind == 1)
4528      S.NoteDeletedFunction(Decl);
4529    // FIXME: Explain inaccessibility if DiagKind == 3.
4530  }
4531
4532  return true;
4533}
4534
4535/// Check whether we should delete a special member function due to having a
4536/// direct or virtual base class or non-static data member of class type M.
4537bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4538    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4539  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4540
4541  // C++11 [class.ctor]p5:
4542  // -- any direct or virtual base class, or non-static data member with no
4543  //    brace-or-equal-initializer, has class type M (or array thereof) and
4544  //    either M has no default constructor or overload resolution as applied
4545  //    to M's default constructor results in an ambiguity or in a function
4546  //    that is deleted or inaccessible
4547  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4548  // -- a direct or virtual base class B that cannot be copied/moved because
4549  //    overload resolution, as applied to B's corresponding special member,
4550  //    results in an ambiguity or a function that is deleted or inaccessible
4551  //    from the defaulted special member
4552  // C++11 [class.dtor]p5:
4553  // -- any direct or virtual base class [...] has a type with a destructor
4554  //    that is deleted or inaccessible
4555  if (!(CSM == Sema::CXXDefaultConstructor &&
4556        Field && Field->hasInClassInitializer()) &&
4557      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4558    return true;
4559
4560  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4561  // -- any direct or virtual base class or non-static data member has a
4562  //    type with a destructor that is deleted or inaccessible
4563  if (IsConstructor) {
4564    Sema::SpecialMemberOverloadResult *SMOR =
4565        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4566                              false, false, false, false, false);
4567    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4568      return true;
4569  }
4570
4571  return false;
4572}
4573
4574/// Check whether we should delete a special member function due to the class
4575/// having a particular direct or virtual base class.
4576bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4577  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4578  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4579}
4580
4581/// Check whether we should delete a special member function due to the class
4582/// having a particular non-static data member.
4583bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4584  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4585  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4586
4587  if (CSM == Sema::CXXDefaultConstructor) {
4588    // For a default constructor, all references must be initialized in-class
4589    // and, if a union, it must have a non-const member.
4590    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4591      if (Diagnose)
4592        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4593          << MD->getParent() << FD << FieldType << /*Reference*/0;
4594      return true;
4595    }
4596    // C++11 [class.ctor]p5: any non-variant non-static data member of
4597    // const-qualified type (or array thereof) with no
4598    // brace-or-equal-initializer does not have a user-provided default
4599    // constructor.
4600    if (!inUnion() && FieldType.isConstQualified() &&
4601        !FD->hasInClassInitializer() &&
4602        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4603      if (Diagnose)
4604        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4605          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4606      return true;
4607    }
4608
4609    if (inUnion() && !FieldType.isConstQualified())
4610      AllFieldsAreConst = false;
4611  } else if (CSM == Sema::CXXCopyConstructor) {
4612    // For a copy constructor, data members must not be of rvalue reference
4613    // type.
4614    if (FieldType->isRValueReferenceType()) {
4615      if (Diagnose)
4616        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4617          << MD->getParent() << FD << FieldType;
4618      return true;
4619    }
4620  } else if (IsAssignment) {
4621    // For an assignment operator, data members must not be of reference type.
4622    if (FieldType->isReferenceType()) {
4623      if (Diagnose)
4624        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4625          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4626      return true;
4627    }
4628    if (!FieldRecord && FieldType.isConstQualified()) {
4629      // C++11 [class.copy]p23:
4630      // -- a non-static data member of const non-class type (or array thereof)
4631      if (Diagnose)
4632        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4633          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4634      return true;
4635    }
4636  }
4637
4638  if (FieldRecord) {
4639    // Some additional restrictions exist on the variant members.
4640    if (!inUnion() && FieldRecord->isUnion() &&
4641        FieldRecord->isAnonymousStructOrUnion()) {
4642      bool AllVariantFieldsAreConst = true;
4643
4644      // FIXME: Handle anonymous unions declared within anonymous unions.
4645      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4646                                         UE = FieldRecord->field_end();
4647           UI != UE; ++UI) {
4648        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4649
4650        if (!UnionFieldType.isConstQualified())
4651          AllVariantFieldsAreConst = false;
4652
4653        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4654        if (UnionFieldRecord &&
4655            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4656                                          UnionFieldType.getCVRQualifiers()))
4657          return true;
4658      }
4659
4660      // At least one member in each anonymous union must be non-const
4661      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4662          FieldRecord->field_begin() != FieldRecord->field_end()) {
4663        if (Diagnose)
4664          S.Diag(FieldRecord->getLocation(),
4665                 diag::note_deleted_default_ctor_all_const)
4666            << MD->getParent() << /*anonymous union*/1;
4667        return true;
4668      }
4669
4670      // Don't check the implicit member of the anonymous union type.
4671      // This is technically non-conformant, but sanity demands it.
4672      return false;
4673    }
4674
4675    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4676                                      FieldType.getCVRQualifiers()))
4677      return true;
4678  }
4679
4680  return false;
4681}
4682
4683/// C++11 [class.ctor] p5:
4684///   A defaulted default constructor for a class X is defined as deleted if
4685/// X is a union and all of its variant members are of const-qualified type.
4686bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4687  // This is a silly definition, because it gives an empty union a deleted
4688  // default constructor. Don't do that.
4689  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4690      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4691    if (Diagnose)
4692      S.Diag(MD->getParent()->getLocation(),
4693             diag::note_deleted_default_ctor_all_const)
4694        << MD->getParent() << /*not anonymous union*/0;
4695    return true;
4696  }
4697  return false;
4698}
4699
4700/// Determine whether a defaulted special member function should be defined as
4701/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4702/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4703bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4704                                     bool Diagnose) {
4705  if (MD->isInvalidDecl())
4706    return false;
4707  CXXRecordDecl *RD = MD->getParent();
4708  assert(!RD->isDependentType() && "do deletion after instantiation");
4709  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4710    return false;
4711
4712  // C++11 [expr.lambda.prim]p19:
4713  //   The closure type associated with a lambda-expression has a
4714  //   deleted (8.4.3) default constructor and a deleted copy
4715  //   assignment operator.
4716  if (RD->isLambda() &&
4717      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4718    if (Diagnose)
4719      Diag(RD->getLocation(), diag::note_lambda_decl);
4720    return true;
4721  }
4722
4723  // For an anonymous struct or union, the copy and assignment special members
4724  // will never be used, so skip the check. For an anonymous union declared at
4725  // namespace scope, the constructor and destructor are used.
4726  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4727      RD->isAnonymousStructOrUnion())
4728    return false;
4729
4730  // C++11 [class.copy]p7, p18:
4731  //   If the class definition declares a move constructor or move assignment
4732  //   operator, an implicitly declared copy constructor or copy assignment
4733  //   operator is defined as deleted.
4734  if (MD->isImplicit() &&
4735      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4736    CXXMethodDecl *UserDeclaredMove = 0;
4737
4738    // In Microsoft mode, a user-declared move only causes the deletion of the
4739    // corresponding copy operation, not both copy operations.
4740    if (RD->hasUserDeclaredMoveConstructor() &&
4741        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4742      if (!Diagnose) return true;
4743
4744      // Find any user-declared move constructor.
4745      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4746                                        E = RD->ctor_end(); I != E; ++I) {
4747        if (I->isMoveConstructor()) {
4748          UserDeclaredMove = *I;
4749          break;
4750        }
4751      }
4752      assert(UserDeclaredMove);
4753    } else if (RD->hasUserDeclaredMoveAssignment() &&
4754               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4755      if (!Diagnose) return true;
4756
4757      // Find any user-declared move assignment operator.
4758      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4759                                          E = RD->method_end(); I != E; ++I) {
4760        if (I->isMoveAssignmentOperator()) {
4761          UserDeclaredMove = *I;
4762          break;
4763        }
4764      }
4765      assert(UserDeclaredMove);
4766    }
4767
4768    if (UserDeclaredMove) {
4769      Diag(UserDeclaredMove->getLocation(),
4770           diag::note_deleted_copy_user_declared_move)
4771        << (CSM == CXXCopyAssignment) << RD
4772        << UserDeclaredMove->isMoveAssignmentOperator();
4773      return true;
4774    }
4775  }
4776
4777  // Do access control from the special member function
4778  ContextRAII MethodContext(*this, MD);
4779
4780  // C++11 [class.dtor]p5:
4781  // -- for a virtual destructor, lookup of the non-array deallocation function
4782  //    results in an ambiguity or in a function that is deleted or inaccessible
4783  if (CSM == CXXDestructor && MD->isVirtual()) {
4784    FunctionDecl *OperatorDelete = 0;
4785    DeclarationName Name =
4786      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4787    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4788                                 OperatorDelete, false)) {
4789      if (Diagnose)
4790        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4791      return true;
4792    }
4793  }
4794
4795  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4796
4797  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4798                                          BE = RD->bases_end(); BI != BE; ++BI)
4799    if (!BI->isVirtual() &&
4800        SMI.shouldDeleteForBase(BI))
4801      return true;
4802
4803  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4804                                          BE = RD->vbases_end(); BI != BE; ++BI)
4805    if (SMI.shouldDeleteForBase(BI))
4806      return true;
4807
4808  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4809                                     FE = RD->field_end(); FI != FE; ++FI)
4810    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4811        SMI.shouldDeleteForField(*FI))
4812      return true;
4813
4814  if (SMI.shouldDeleteForAllConstMembers())
4815    return true;
4816
4817  return false;
4818}
4819
4820/// Perform lookup for a special member of the specified kind, and determine
4821/// whether it is trivial. If the triviality can be determined without the
4822/// lookup, skip it. This is intended for use when determining whether a
4823/// special member of a containing object is trivial, and thus does not ever
4824/// perform overload resolution for default constructors.
4825///
4826/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
4827/// member that was most likely to be intended to be trivial, if any.
4828static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
4829                                     Sema::CXXSpecialMember CSM, unsigned Quals,
4830                                     CXXMethodDecl **Selected) {
4831  if (Selected)
4832    *Selected = 0;
4833
4834  switch (CSM) {
4835  case Sema::CXXInvalid:
4836    llvm_unreachable("not a special member");
4837
4838  case Sema::CXXDefaultConstructor:
4839    // C++11 [class.ctor]p5:
4840    //   A default constructor is trivial if:
4841    //    - all the [direct subobjects] have trivial default constructors
4842    //
4843    // Note, no overload resolution is performed in this case.
4844    if (RD->hasTrivialDefaultConstructor())
4845      return true;
4846
4847    if (Selected) {
4848      // If there's a default constructor which could have been trivial, dig it
4849      // out. Otherwise, if there's any user-provided default constructor, point
4850      // to that as an example of why there's not a trivial one.
4851      CXXConstructorDecl *DefCtor = 0;
4852      if (RD->needsImplicitDefaultConstructor())
4853        S.DeclareImplicitDefaultConstructor(RD);
4854      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
4855                                        CE = RD->ctor_end(); CI != CE; ++CI) {
4856        if (!CI->isDefaultConstructor())
4857          continue;
4858        DefCtor = *CI;
4859        if (!DefCtor->isUserProvided())
4860          break;
4861      }
4862
4863      *Selected = DefCtor;
4864    }
4865
4866    return false;
4867
4868  case Sema::CXXDestructor:
4869    // C++11 [class.dtor]p5:
4870    //   A destructor is trivial if:
4871    //    - all the direct [subobjects] have trivial destructors
4872    if (RD->hasTrivialDestructor())
4873      return true;
4874
4875    if (Selected) {
4876      if (RD->needsImplicitDestructor())
4877        S.DeclareImplicitDestructor(RD);
4878      *Selected = RD->getDestructor();
4879    }
4880
4881    return false;
4882
4883  case Sema::CXXCopyConstructor:
4884    // C++11 [class.copy]p12:
4885    //   A copy constructor is trivial if:
4886    //    - the constructor selected to copy each direct [subobject] is trivial
4887    if (RD->hasTrivialCopyConstructor()) {
4888      if (Quals == Qualifiers::Const)
4889        // We must either select the trivial copy constructor or reach an
4890        // ambiguity; no need to actually perform overload resolution.
4891        return true;
4892    } else if (!Selected) {
4893      return false;
4894    }
4895    // In C++98, we are not supposed to perform overload resolution here, but we
4896    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
4897    // cases like B as having a non-trivial copy constructor:
4898    //   struct A { template<typename T> A(T&); };
4899    //   struct B { mutable A a; };
4900    goto NeedOverloadResolution;
4901
4902  case Sema::CXXCopyAssignment:
4903    // C++11 [class.copy]p25:
4904    //   A copy assignment operator is trivial if:
4905    //    - the assignment operator selected to copy each direct [subobject] is
4906    //      trivial
4907    if (RD->hasTrivialCopyAssignment()) {
4908      if (Quals == Qualifiers::Const)
4909        return true;
4910    } else if (!Selected) {
4911      return false;
4912    }
4913    // In C++98, we are not supposed to perform overload resolution here, but we
4914    // treat that as a language defect.
4915    goto NeedOverloadResolution;
4916
4917  case Sema::CXXMoveConstructor:
4918  case Sema::CXXMoveAssignment:
4919  NeedOverloadResolution:
4920    Sema::SpecialMemberOverloadResult *SMOR =
4921      S.LookupSpecialMember(RD, CSM,
4922                            Quals & Qualifiers::Const,
4923                            Quals & Qualifiers::Volatile,
4924                            /*RValueThis*/false, /*ConstThis*/false,
4925                            /*VolatileThis*/false);
4926
4927    // The standard doesn't describe how to behave if the lookup is ambiguous.
4928    // We treat it as not making the member non-trivial, just like the standard
4929    // mandates for the default constructor. This should rarely matter, because
4930    // the member will also be deleted.
4931    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4932      return true;
4933
4934    if (!SMOR->getMethod()) {
4935      assert(SMOR->getKind() ==
4936             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
4937      return false;
4938    }
4939
4940    // We deliberately don't check if we found a deleted special member. We're
4941    // not supposed to!
4942    if (Selected)
4943      *Selected = SMOR->getMethod();
4944    return SMOR->getMethod()->isTrivial();
4945  }
4946
4947  llvm_unreachable("unknown special method kind");
4948}
4949
4950CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
4951  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
4952       CI != CE; ++CI)
4953    if (!CI->isImplicit())
4954      return *CI;
4955
4956  // Look for constructor templates.
4957  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
4958  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
4959    if (CXXConstructorDecl *CD =
4960          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
4961      return CD;
4962  }
4963
4964  return 0;
4965}
4966
4967/// The kind of subobject we are checking for triviality. The values of this
4968/// enumeration are used in diagnostics.
4969enum TrivialSubobjectKind {
4970  /// The subobject is a base class.
4971  TSK_BaseClass,
4972  /// The subobject is a non-static data member.
4973  TSK_Field,
4974  /// The object is actually the complete object.
4975  TSK_CompleteObject
4976};
4977
4978/// Check whether the special member selected for a given type would be trivial.
4979static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
4980                                      QualType SubType,
4981                                      Sema::CXXSpecialMember CSM,
4982                                      TrivialSubobjectKind Kind,
4983                                      bool Diagnose) {
4984  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
4985  if (!SubRD)
4986    return true;
4987
4988  CXXMethodDecl *Selected;
4989  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
4990                               Diagnose ? &Selected : 0))
4991    return true;
4992
4993  if (Diagnose) {
4994    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
4995      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
4996        << Kind << SubType.getUnqualifiedType();
4997      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
4998        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
4999    } else if (!Selected)
5000      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5001        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5002    else if (Selected->isUserProvided()) {
5003      if (Kind == TSK_CompleteObject)
5004        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5005          << Kind << SubType.getUnqualifiedType() << CSM;
5006      else {
5007        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5008          << Kind << SubType.getUnqualifiedType() << CSM;
5009        S.Diag(Selected->getLocation(), diag::note_declared_at);
5010      }
5011    } else {
5012      if (Kind != TSK_CompleteObject)
5013        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5014          << Kind << SubType.getUnqualifiedType() << CSM;
5015
5016      // Explain why the defaulted or deleted special member isn't trivial.
5017      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5018    }
5019  }
5020
5021  return false;
5022}
5023
5024/// Check whether the members of a class type allow a special member to be
5025/// trivial.
5026static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5027                                     Sema::CXXSpecialMember CSM,
5028                                     bool ConstArg, bool Diagnose) {
5029  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5030                                     FE = RD->field_end(); FI != FE; ++FI) {
5031    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5032      continue;
5033
5034    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5035
5036    // Pretend anonymous struct or union members are members of this class.
5037    if (FI->isAnonymousStructOrUnion()) {
5038      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5039                                    CSM, ConstArg, Diagnose))
5040        return false;
5041      continue;
5042    }
5043
5044    // C++11 [class.ctor]p5:
5045    //   A default constructor is trivial if [...]
5046    //    -- no non-static data member of its class has a
5047    //       brace-or-equal-initializer
5048    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5049      if (Diagnose)
5050        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5051      return false;
5052    }
5053
5054    // Objective C ARC 4.3.5:
5055    //   [...] nontrivally ownership-qualified types are [...] not trivially
5056    //   default constructible, copy constructible, move constructible, copy
5057    //   assignable, move assignable, or destructible [...]
5058    if (S.getLangOpts().ObjCAutoRefCount &&
5059        FieldType.hasNonTrivialObjCLifetime()) {
5060      if (Diagnose)
5061        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5062          << RD << FieldType.getObjCLifetime();
5063      return false;
5064    }
5065
5066    if (ConstArg && !FI->isMutable())
5067      FieldType.addConst();
5068    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5069                                   TSK_Field, Diagnose))
5070      return false;
5071  }
5072
5073  return true;
5074}
5075
5076/// Diagnose why the specified class does not have a trivial special member of
5077/// the given kind.
5078void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5079  QualType Ty = Context.getRecordType(RD);
5080  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5081    Ty.addConst();
5082
5083  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5084                            TSK_CompleteObject, /*Diagnose*/true);
5085}
5086
5087/// Determine whether a defaulted or deleted special member function is trivial,
5088/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5089/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5090bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5091                                  bool Diagnose) {
5092  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5093
5094  CXXRecordDecl *RD = MD->getParent();
5095
5096  bool ConstArg = false;
5097  ParmVarDecl *Param0 = MD->getNumParams() ? MD->getParamDecl(0) : 0;
5098
5099  // C++11 [class.copy]p12, p25:
5100  //   A [special member] is trivial if its declared parameter type is the same
5101  //   as if it had been implicitly declared [...]
5102  switch (CSM) {
5103  case CXXDefaultConstructor:
5104  case CXXDestructor:
5105    // Trivial default constructors and destructors cannot have parameters.
5106    break;
5107
5108  case CXXCopyConstructor:
5109  case CXXCopyAssignment: {
5110    // Trivial copy operations always have const, non-volatile parameter types.
5111    ConstArg = true;
5112    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5113    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5114      if (Diagnose)
5115        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5116          << Param0->getSourceRange() << Param0->getType()
5117          << Context.getLValueReferenceType(
5118               Context.getRecordType(RD).withConst());
5119      return false;
5120    }
5121    break;
5122  }
5123
5124  case CXXMoveConstructor:
5125  case CXXMoveAssignment: {
5126    // Trivial move operations always have non-cv-qualified parameters.
5127    const RValueReferenceType *RT =
5128      Param0->getType()->getAs<RValueReferenceType>();
5129    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5130      if (Diagnose)
5131        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5132          << Param0->getSourceRange() << Param0->getType()
5133          << Context.getRValueReferenceType(Context.getRecordType(RD));
5134      return false;
5135    }
5136    break;
5137  }
5138
5139  case CXXInvalid:
5140    llvm_unreachable("not a special member");
5141  }
5142
5143  // FIXME: We require that the parameter-declaration-clause is equivalent to
5144  // that of an implicit declaration, not just that the declared parameter type
5145  // matches, in order to prevent absuridities like a function simultaneously
5146  // being a trivial copy constructor and a non-trivial default constructor.
5147  // This issue has not yet been assigned a core issue number.
5148  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5149    if (Diagnose)
5150      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5151           diag::note_nontrivial_default_arg)
5152        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5153    return false;
5154  }
5155  if (MD->isVariadic()) {
5156    if (Diagnose)
5157      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5158    return false;
5159  }
5160
5161  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5162  //   A copy/move [constructor or assignment operator] is trivial if
5163  //    -- the [member] selected to copy/move each direct base class subobject
5164  //       is trivial
5165  //
5166  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5167  //   A [default constructor or destructor] is trivial if
5168  //    -- all the direct base classes have trivial [default constructors or
5169  //       destructors]
5170  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5171                                          BE = RD->bases_end(); BI != BE; ++BI)
5172    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5173                                   ConstArg ? BI->getType().withConst()
5174                                            : BI->getType(),
5175                                   CSM, TSK_BaseClass, Diagnose))
5176      return false;
5177
5178  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5179  //   A copy/move [constructor or assignment operator] for a class X is
5180  //   trivial if
5181  //    -- for each non-static data member of X that is of class type (or array
5182  //       thereof), the constructor selected to copy/move that member is
5183  //       trivial
5184  //
5185  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5186  //   A [default constructor or destructor] is trivial if
5187  //    -- for all of the non-static data members of its class that are of class
5188  //       type (or array thereof), each such class has a trivial [default
5189  //       constructor or destructor]
5190  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5191    return false;
5192
5193  // C++11 [class.dtor]p5:
5194  //   A destructor is trivial if [...]
5195  //    -- the destructor is not virtual
5196  if (CSM == CXXDestructor && MD->isVirtual()) {
5197    if (Diagnose)
5198      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5199    return false;
5200  }
5201
5202  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5203  //   A [special member] for class X is trivial if [...]
5204  //    -- class X has no virtual functions and no virtual base classes
5205  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5206    if (!Diagnose)
5207      return false;
5208
5209    if (RD->getNumVBases()) {
5210      // Check for virtual bases. We already know that the corresponding
5211      // member in all bases is trivial, so vbases must all be direct.
5212      CXXBaseSpecifier &BS = *RD->vbases_begin();
5213      assert(BS.isVirtual());
5214      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5215      return false;
5216    }
5217
5218    // Must have a virtual method.
5219    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5220                                        ME = RD->method_end(); MI != ME; ++MI) {
5221      if (MI->isVirtual()) {
5222        SourceLocation MLoc = MI->getLocStart();
5223        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5224        return false;
5225      }
5226    }
5227
5228    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5229  }
5230
5231  // Looks like it's trivial!
5232  return true;
5233}
5234
5235/// \brief Data used with FindHiddenVirtualMethod
5236namespace {
5237  struct FindHiddenVirtualMethodData {
5238    Sema *S;
5239    CXXMethodDecl *Method;
5240    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5241    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5242  };
5243}
5244
5245/// \brief Check whether any most overriden method from MD in Methods
5246static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5247                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5248  if (MD->size_overridden_methods() == 0)
5249    return Methods.count(MD->getCanonicalDecl());
5250  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5251                                      E = MD->end_overridden_methods();
5252       I != E; ++I)
5253    if (CheckMostOverridenMethods(*I, Methods))
5254      return true;
5255  return false;
5256}
5257
5258/// \brief Member lookup function that determines whether a given C++
5259/// method overloads virtual methods in a base class without overriding any,
5260/// to be used with CXXRecordDecl::lookupInBases().
5261static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5262                                    CXXBasePath &Path,
5263                                    void *UserData) {
5264  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5265
5266  FindHiddenVirtualMethodData &Data
5267    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5268
5269  DeclarationName Name = Data.Method->getDeclName();
5270  assert(Name.getNameKind() == DeclarationName::Identifier);
5271
5272  bool foundSameNameMethod = false;
5273  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5274  for (Path.Decls = BaseRecord->lookup(Name);
5275       !Path.Decls.empty();
5276       Path.Decls = Path.Decls.slice(1)) {
5277    NamedDecl *D = Path.Decls.front();
5278    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5279      MD = MD->getCanonicalDecl();
5280      foundSameNameMethod = true;
5281      // Interested only in hidden virtual methods.
5282      if (!MD->isVirtual())
5283        continue;
5284      // If the method we are checking overrides a method from its base
5285      // don't warn about the other overloaded methods.
5286      if (!Data.S->IsOverload(Data.Method, MD, false))
5287        return true;
5288      // Collect the overload only if its hidden.
5289      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5290        overloadedMethods.push_back(MD);
5291    }
5292  }
5293
5294  if (foundSameNameMethod)
5295    Data.OverloadedMethods.append(overloadedMethods.begin(),
5296                                   overloadedMethods.end());
5297  return foundSameNameMethod;
5298}
5299
5300/// \brief Add the most overriden methods from MD to Methods
5301static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5302                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5303  if (MD->size_overridden_methods() == 0)
5304    Methods.insert(MD->getCanonicalDecl());
5305  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5306                                      E = MD->end_overridden_methods();
5307       I != E; ++I)
5308    AddMostOverridenMethods(*I, Methods);
5309}
5310
5311/// \brief See if a method overloads virtual methods in a base class without
5312/// overriding any.
5313void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5314  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5315                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5316    return;
5317  if (!MD->getDeclName().isIdentifier())
5318    return;
5319
5320  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5321                     /*bool RecordPaths=*/false,
5322                     /*bool DetectVirtual=*/false);
5323  FindHiddenVirtualMethodData Data;
5324  Data.Method = MD;
5325  Data.S = this;
5326
5327  // Keep the base methods that were overriden or introduced in the subclass
5328  // by 'using' in a set. A base method not in this set is hidden.
5329  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5330  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5331    NamedDecl *ND = *I;
5332    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5333      ND = shad->getTargetDecl();
5334    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5335      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5336  }
5337
5338  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5339      !Data.OverloadedMethods.empty()) {
5340    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5341      << MD << (Data.OverloadedMethods.size() > 1);
5342
5343    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5344      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5345      Diag(overloadedMD->getLocation(),
5346           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5347    }
5348  }
5349}
5350
5351void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5352                                             Decl *TagDecl,
5353                                             SourceLocation LBrac,
5354                                             SourceLocation RBrac,
5355                                             AttributeList *AttrList) {
5356  if (!TagDecl)
5357    return;
5358
5359  AdjustDeclIfTemplate(TagDecl);
5360
5361  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5362    if (l->getKind() != AttributeList::AT_Visibility)
5363      continue;
5364    l->setInvalid();
5365    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5366      l->getName();
5367  }
5368
5369  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5370              // strict aliasing violation!
5371              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5372              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5373
5374  CheckCompletedCXXClass(
5375                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5376}
5377
5378/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5379/// special functions, such as the default constructor, copy
5380/// constructor, or destructor, to the given C++ class (C++
5381/// [special]p1).  This routine can only be executed just before the
5382/// definition of the class is complete.
5383void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5384  if (!ClassDecl->hasUserDeclaredConstructor())
5385    ++ASTContext::NumImplicitDefaultConstructors;
5386
5387  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5388    ++ASTContext::NumImplicitCopyConstructors;
5389
5390    // If the properties or semantics of the copy constructor couldn't be
5391    // determined while the class was being declared, force a declaration
5392    // of it now.
5393    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5394      DeclareImplicitCopyConstructor(ClassDecl);
5395  }
5396
5397  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5398    ++ASTContext::NumImplicitMoveConstructors;
5399
5400    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5401      DeclareImplicitMoveConstructor(ClassDecl);
5402  }
5403
5404  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5405    ++ASTContext::NumImplicitCopyAssignmentOperators;
5406
5407    // If we have a dynamic class, then the copy assignment operator may be
5408    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5409    // it shows up in the right place in the vtable and that we diagnose
5410    // problems with the implicit exception specification.
5411    if (ClassDecl->isDynamicClass() ||
5412        ClassDecl->needsOverloadResolutionForCopyAssignment())
5413      DeclareImplicitCopyAssignment(ClassDecl);
5414  }
5415
5416  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5417    ++ASTContext::NumImplicitMoveAssignmentOperators;
5418
5419    // Likewise for the move assignment operator.
5420    if (ClassDecl->isDynamicClass() ||
5421        ClassDecl->needsOverloadResolutionForMoveAssignment())
5422      DeclareImplicitMoveAssignment(ClassDecl);
5423  }
5424
5425  if (!ClassDecl->hasUserDeclaredDestructor()) {
5426    ++ASTContext::NumImplicitDestructors;
5427
5428    // If we have a dynamic class, then the destructor may be virtual, so we
5429    // have to declare the destructor immediately. This ensures that, e.g., it
5430    // shows up in the right place in the vtable and that we diagnose problems
5431    // with the implicit exception specification.
5432    if (ClassDecl->isDynamicClass() ||
5433        ClassDecl->needsOverloadResolutionForDestructor())
5434      DeclareImplicitDestructor(ClassDecl);
5435  }
5436}
5437
5438void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5439  if (!D)
5440    return;
5441
5442  int NumParamList = D->getNumTemplateParameterLists();
5443  for (int i = 0; i < NumParamList; i++) {
5444    TemplateParameterList* Params = D->getTemplateParameterList(i);
5445    for (TemplateParameterList::iterator Param = Params->begin(),
5446                                      ParamEnd = Params->end();
5447          Param != ParamEnd; ++Param) {
5448      NamedDecl *Named = cast<NamedDecl>(*Param);
5449      if (Named->getDeclName()) {
5450        S->AddDecl(Named);
5451        IdResolver.AddDecl(Named);
5452      }
5453    }
5454  }
5455}
5456
5457void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5458  if (!D)
5459    return;
5460
5461  TemplateParameterList *Params = 0;
5462  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5463    Params = Template->getTemplateParameters();
5464  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5465           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5466    Params = PartialSpec->getTemplateParameters();
5467  else
5468    return;
5469
5470  for (TemplateParameterList::iterator Param = Params->begin(),
5471                                    ParamEnd = Params->end();
5472       Param != ParamEnd; ++Param) {
5473    NamedDecl *Named = cast<NamedDecl>(*Param);
5474    if (Named->getDeclName()) {
5475      S->AddDecl(Named);
5476      IdResolver.AddDecl(Named);
5477    }
5478  }
5479}
5480
5481void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5482  if (!RecordD) return;
5483  AdjustDeclIfTemplate(RecordD);
5484  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5485  PushDeclContext(S, Record);
5486}
5487
5488void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5489  if (!RecordD) return;
5490  PopDeclContext();
5491}
5492
5493/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5494/// parsing a top-level (non-nested) C++ class, and we are now
5495/// parsing those parts of the given Method declaration that could
5496/// not be parsed earlier (C++ [class.mem]p2), such as default
5497/// arguments. This action should enter the scope of the given
5498/// Method declaration as if we had just parsed the qualified method
5499/// name. However, it should not bring the parameters into scope;
5500/// that will be performed by ActOnDelayedCXXMethodParameter.
5501void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5502}
5503
5504/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5505/// C++ method declaration. We're (re-)introducing the given
5506/// function parameter into scope for use in parsing later parts of
5507/// the method declaration. For example, we could see an
5508/// ActOnParamDefaultArgument event for this parameter.
5509void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5510  if (!ParamD)
5511    return;
5512
5513  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5514
5515  // If this parameter has an unparsed default argument, clear it out
5516  // to make way for the parsed default argument.
5517  if (Param->hasUnparsedDefaultArg())
5518    Param->setDefaultArg(0);
5519
5520  S->AddDecl(Param);
5521  if (Param->getDeclName())
5522    IdResolver.AddDecl(Param);
5523}
5524
5525/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5526/// processing the delayed method declaration for Method. The method
5527/// declaration is now considered finished. There may be a separate
5528/// ActOnStartOfFunctionDef action later (not necessarily
5529/// immediately!) for this method, if it was also defined inside the
5530/// class body.
5531void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5532  if (!MethodD)
5533    return;
5534
5535  AdjustDeclIfTemplate(MethodD);
5536
5537  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5538
5539  // Now that we have our default arguments, check the constructor
5540  // again. It could produce additional diagnostics or affect whether
5541  // the class has implicitly-declared destructors, among other
5542  // things.
5543  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5544    CheckConstructor(Constructor);
5545
5546  // Check the default arguments, which we may have added.
5547  if (!Method->isInvalidDecl())
5548    CheckCXXDefaultArguments(Method);
5549}
5550
5551/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5552/// the well-formedness of the constructor declarator @p D with type @p
5553/// R. If there are any errors in the declarator, this routine will
5554/// emit diagnostics and set the invalid bit to true.  In any case, the type
5555/// will be updated to reflect a well-formed type for the constructor and
5556/// returned.
5557QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5558                                          StorageClass &SC) {
5559  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5560
5561  // C++ [class.ctor]p3:
5562  //   A constructor shall not be virtual (10.3) or static (9.4). A
5563  //   constructor can be invoked for a const, volatile or const
5564  //   volatile object. A constructor shall not be declared const,
5565  //   volatile, or const volatile (9.3.2).
5566  if (isVirtual) {
5567    if (!D.isInvalidType())
5568      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5569        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5570        << SourceRange(D.getIdentifierLoc());
5571    D.setInvalidType();
5572  }
5573  if (SC == SC_Static) {
5574    if (!D.isInvalidType())
5575      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5576        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5577        << SourceRange(D.getIdentifierLoc());
5578    D.setInvalidType();
5579    SC = SC_None;
5580  }
5581
5582  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5583  if (FTI.TypeQuals != 0) {
5584    if (FTI.TypeQuals & Qualifiers::Const)
5585      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5586        << "const" << SourceRange(D.getIdentifierLoc());
5587    if (FTI.TypeQuals & Qualifiers::Volatile)
5588      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5589        << "volatile" << SourceRange(D.getIdentifierLoc());
5590    if (FTI.TypeQuals & Qualifiers::Restrict)
5591      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5592        << "restrict" << SourceRange(D.getIdentifierLoc());
5593    D.setInvalidType();
5594  }
5595
5596  // C++0x [class.ctor]p4:
5597  //   A constructor shall not be declared with a ref-qualifier.
5598  if (FTI.hasRefQualifier()) {
5599    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5600      << FTI.RefQualifierIsLValueRef
5601      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5602    D.setInvalidType();
5603  }
5604
5605  // Rebuild the function type "R" without any type qualifiers (in
5606  // case any of the errors above fired) and with "void" as the
5607  // return type, since constructors don't have return types.
5608  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5609  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5610    return R;
5611
5612  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5613  EPI.TypeQuals = 0;
5614  EPI.RefQualifier = RQ_None;
5615
5616  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5617                                 Proto->getNumArgs(), EPI);
5618}
5619
5620/// CheckConstructor - Checks a fully-formed constructor for
5621/// well-formedness, issuing any diagnostics required. Returns true if
5622/// the constructor declarator is invalid.
5623void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5624  CXXRecordDecl *ClassDecl
5625    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5626  if (!ClassDecl)
5627    return Constructor->setInvalidDecl();
5628
5629  // C++ [class.copy]p3:
5630  //   A declaration of a constructor for a class X is ill-formed if
5631  //   its first parameter is of type (optionally cv-qualified) X and
5632  //   either there are no other parameters or else all other
5633  //   parameters have default arguments.
5634  if (!Constructor->isInvalidDecl() &&
5635      ((Constructor->getNumParams() == 1) ||
5636       (Constructor->getNumParams() > 1 &&
5637        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5638      Constructor->getTemplateSpecializationKind()
5639                                              != TSK_ImplicitInstantiation) {
5640    QualType ParamType = Constructor->getParamDecl(0)->getType();
5641    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5642    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5643      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5644      const char *ConstRef
5645        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5646                                                        : " const &";
5647      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5648        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5649
5650      // FIXME: Rather that making the constructor invalid, we should endeavor
5651      // to fix the type.
5652      Constructor->setInvalidDecl();
5653    }
5654  }
5655}
5656
5657/// CheckDestructor - Checks a fully-formed destructor definition for
5658/// well-formedness, issuing any diagnostics required.  Returns true
5659/// on error.
5660bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5661  CXXRecordDecl *RD = Destructor->getParent();
5662
5663  if (Destructor->isVirtual()) {
5664    SourceLocation Loc;
5665
5666    if (!Destructor->isImplicit())
5667      Loc = Destructor->getLocation();
5668    else
5669      Loc = RD->getLocation();
5670
5671    // If we have a virtual destructor, look up the deallocation function
5672    FunctionDecl *OperatorDelete = 0;
5673    DeclarationName Name =
5674    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5675    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5676      return true;
5677
5678    MarkFunctionReferenced(Loc, OperatorDelete);
5679
5680    Destructor->setOperatorDelete(OperatorDelete);
5681  }
5682
5683  return false;
5684}
5685
5686static inline bool
5687FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5688  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5689          FTI.ArgInfo[0].Param &&
5690          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5691}
5692
5693/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5694/// the well-formednes of the destructor declarator @p D with type @p
5695/// R. If there are any errors in the declarator, this routine will
5696/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5697/// will be updated to reflect a well-formed type for the destructor and
5698/// returned.
5699QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5700                                         StorageClass& SC) {
5701  // C++ [class.dtor]p1:
5702  //   [...] A typedef-name that names a class is a class-name
5703  //   (7.1.3); however, a typedef-name that names a class shall not
5704  //   be used as the identifier in the declarator for a destructor
5705  //   declaration.
5706  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5707  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5708    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5709      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5710  else if (const TemplateSpecializationType *TST =
5711             DeclaratorType->getAs<TemplateSpecializationType>())
5712    if (TST->isTypeAlias())
5713      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5714        << DeclaratorType << 1;
5715
5716  // C++ [class.dtor]p2:
5717  //   A destructor is used to destroy objects of its class type. A
5718  //   destructor takes no parameters, and no return type can be
5719  //   specified for it (not even void). The address of a destructor
5720  //   shall not be taken. A destructor shall not be static. A
5721  //   destructor can be invoked for a const, volatile or const
5722  //   volatile object. A destructor shall not be declared const,
5723  //   volatile or const volatile (9.3.2).
5724  if (SC == SC_Static) {
5725    if (!D.isInvalidType())
5726      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5727        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5728        << SourceRange(D.getIdentifierLoc())
5729        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5730
5731    SC = SC_None;
5732  }
5733  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5734    // Destructors don't have return types, but the parser will
5735    // happily parse something like:
5736    //
5737    //   class X {
5738    //     float ~X();
5739    //   };
5740    //
5741    // The return type will be eliminated later.
5742    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5743      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5744      << SourceRange(D.getIdentifierLoc());
5745  }
5746
5747  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5748  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5749    if (FTI.TypeQuals & Qualifiers::Const)
5750      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5751        << "const" << SourceRange(D.getIdentifierLoc());
5752    if (FTI.TypeQuals & Qualifiers::Volatile)
5753      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5754        << "volatile" << SourceRange(D.getIdentifierLoc());
5755    if (FTI.TypeQuals & Qualifiers::Restrict)
5756      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5757        << "restrict" << SourceRange(D.getIdentifierLoc());
5758    D.setInvalidType();
5759  }
5760
5761  // C++0x [class.dtor]p2:
5762  //   A destructor shall not be declared with a ref-qualifier.
5763  if (FTI.hasRefQualifier()) {
5764    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5765      << FTI.RefQualifierIsLValueRef
5766      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5767    D.setInvalidType();
5768  }
5769
5770  // Make sure we don't have any parameters.
5771  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5772    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5773
5774    // Delete the parameters.
5775    FTI.freeArgs();
5776    D.setInvalidType();
5777  }
5778
5779  // Make sure the destructor isn't variadic.
5780  if (FTI.isVariadic) {
5781    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5782    D.setInvalidType();
5783  }
5784
5785  // Rebuild the function type "R" without any type qualifiers or
5786  // parameters (in case any of the errors above fired) and with
5787  // "void" as the return type, since destructors don't have return
5788  // types.
5789  if (!D.isInvalidType())
5790    return R;
5791
5792  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5793  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5794  EPI.Variadic = false;
5795  EPI.TypeQuals = 0;
5796  EPI.RefQualifier = RQ_None;
5797  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5798}
5799
5800/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5801/// well-formednes of the conversion function declarator @p D with
5802/// type @p R. If there are any errors in the declarator, this routine
5803/// will emit diagnostics and return true. Otherwise, it will return
5804/// false. Either way, the type @p R will be updated to reflect a
5805/// well-formed type for the conversion operator.
5806void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5807                                     StorageClass& SC) {
5808  // C++ [class.conv.fct]p1:
5809  //   Neither parameter types nor return type can be specified. The
5810  //   type of a conversion function (8.3.5) is "function taking no
5811  //   parameter returning conversion-type-id."
5812  if (SC == SC_Static) {
5813    if (!D.isInvalidType())
5814      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5815        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5816        << SourceRange(D.getIdentifierLoc());
5817    D.setInvalidType();
5818    SC = SC_None;
5819  }
5820
5821  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5822
5823  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5824    // Conversion functions don't have return types, but the parser will
5825    // happily parse something like:
5826    //
5827    //   class X {
5828    //     float operator bool();
5829    //   };
5830    //
5831    // The return type will be changed later anyway.
5832    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5833      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5834      << SourceRange(D.getIdentifierLoc());
5835    D.setInvalidType();
5836  }
5837
5838  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5839
5840  // Make sure we don't have any parameters.
5841  if (Proto->getNumArgs() > 0) {
5842    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5843
5844    // Delete the parameters.
5845    D.getFunctionTypeInfo().freeArgs();
5846    D.setInvalidType();
5847  } else if (Proto->isVariadic()) {
5848    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5849    D.setInvalidType();
5850  }
5851
5852  // Diagnose "&operator bool()" and other such nonsense.  This
5853  // is actually a gcc extension which we don't support.
5854  if (Proto->getResultType() != ConvType) {
5855    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5856      << Proto->getResultType();
5857    D.setInvalidType();
5858    ConvType = Proto->getResultType();
5859  }
5860
5861  // C++ [class.conv.fct]p4:
5862  //   The conversion-type-id shall not represent a function type nor
5863  //   an array type.
5864  if (ConvType->isArrayType()) {
5865    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5866    ConvType = Context.getPointerType(ConvType);
5867    D.setInvalidType();
5868  } else if (ConvType->isFunctionType()) {
5869    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5870    ConvType = Context.getPointerType(ConvType);
5871    D.setInvalidType();
5872  }
5873
5874  // Rebuild the function type "R" without any parameters (in case any
5875  // of the errors above fired) and with the conversion type as the
5876  // return type.
5877  if (D.isInvalidType())
5878    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5879
5880  // C++0x explicit conversion operators.
5881  if (D.getDeclSpec().isExplicitSpecified())
5882    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5883         getLangOpts().CPlusPlus11 ?
5884           diag::warn_cxx98_compat_explicit_conversion_functions :
5885           diag::ext_explicit_conversion_functions)
5886      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5887}
5888
5889/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5890/// the declaration of the given C++ conversion function. This routine
5891/// is responsible for recording the conversion function in the C++
5892/// class, if possible.
5893Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5894  assert(Conversion && "Expected to receive a conversion function declaration");
5895
5896  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5897
5898  // Make sure we aren't redeclaring the conversion function.
5899  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5900
5901  // C++ [class.conv.fct]p1:
5902  //   [...] A conversion function is never used to convert a
5903  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5904  //   same object type (or a reference to it), to a (possibly
5905  //   cv-qualified) base class of that type (or a reference to it),
5906  //   or to (possibly cv-qualified) void.
5907  // FIXME: Suppress this warning if the conversion function ends up being a
5908  // virtual function that overrides a virtual function in a base class.
5909  QualType ClassType
5910    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5911  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5912    ConvType = ConvTypeRef->getPointeeType();
5913  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5914      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5915    /* Suppress diagnostics for instantiations. */;
5916  else if (ConvType->isRecordType()) {
5917    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5918    if (ConvType == ClassType)
5919      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5920        << ClassType;
5921    else if (IsDerivedFrom(ClassType, ConvType))
5922      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5923        <<  ClassType << ConvType;
5924  } else if (ConvType->isVoidType()) {
5925    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5926      << ClassType << ConvType;
5927  }
5928
5929  if (FunctionTemplateDecl *ConversionTemplate
5930                                = Conversion->getDescribedFunctionTemplate())
5931    return ConversionTemplate;
5932
5933  return Conversion;
5934}
5935
5936//===----------------------------------------------------------------------===//
5937// Namespace Handling
5938//===----------------------------------------------------------------------===//
5939
5940/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
5941/// reopened.
5942static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
5943                                            SourceLocation Loc,
5944                                            IdentifierInfo *II, bool *IsInline,
5945                                            NamespaceDecl *PrevNS) {
5946  assert(*IsInline != PrevNS->isInline());
5947
5948  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
5949  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
5950  // inline namespaces, with the intention of bringing names into namespace std.
5951  //
5952  // We support this just well enough to get that case working; this is not
5953  // sufficient to support reopening namespaces as inline in general.
5954  if (*IsInline && II && II->getName().startswith("__atomic") &&
5955      S.getSourceManager().isInSystemHeader(Loc)) {
5956    // Mark all prior declarations of the namespace as inline.
5957    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
5958         NS = NS->getPreviousDecl())
5959      NS->setInline(*IsInline);
5960    // Patch up the lookup table for the containing namespace. This isn't really
5961    // correct, but it's good enough for this particular case.
5962    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
5963                                    E = PrevNS->decls_end(); I != E; ++I)
5964      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
5965        PrevNS->getParent()->makeDeclVisibleInContext(ND);
5966    return;
5967  }
5968
5969  if (PrevNS->isInline())
5970    // The user probably just forgot the 'inline', so suggest that it
5971    // be added back.
5972    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5973      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
5974  else
5975    S.Diag(Loc, diag::err_inline_namespace_mismatch)
5976      << IsInline;
5977
5978  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
5979  *IsInline = PrevNS->isInline();
5980}
5981
5982/// ActOnStartNamespaceDef - This is called at the start of a namespace
5983/// definition.
5984Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5985                                   SourceLocation InlineLoc,
5986                                   SourceLocation NamespaceLoc,
5987                                   SourceLocation IdentLoc,
5988                                   IdentifierInfo *II,
5989                                   SourceLocation LBrace,
5990                                   AttributeList *AttrList) {
5991  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5992  // For anonymous namespace, take the location of the left brace.
5993  SourceLocation Loc = II ? IdentLoc : LBrace;
5994  bool IsInline = InlineLoc.isValid();
5995  bool IsInvalid = false;
5996  bool IsStd = false;
5997  bool AddToKnown = false;
5998  Scope *DeclRegionScope = NamespcScope->getParent();
5999
6000  NamespaceDecl *PrevNS = 0;
6001  if (II) {
6002    // C++ [namespace.def]p2:
6003    //   The identifier in an original-namespace-definition shall not
6004    //   have been previously defined in the declarative region in
6005    //   which the original-namespace-definition appears. The
6006    //   identifier in an original-namespace-definition is the name of
6007    //   the namespace. Subsequently in that declarative region, it is
6008    //   treated as an original-namespace-name.
6009    //
6010    // Since namespace names are unique in their scope, and we don't
6011    // look through using directives, just look for any ordinary names.
6012
6013    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6014    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6015    Decl::IDNS_Namespace;
6016    NamedDecl *PrevDecl = 0;
6017    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6018    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6019         ++I) {
6020      if ((*I)->getIdentifierNamespace() & IDNS) {
6021        PrevDecl = *I;
6022        break;
6023      }
6024    }
6025
6026    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6027
6028    if (PrevNS) {
6029      // This is an extended namespace definition.
6030      if (IsInline != PrevNS->isInline())
6031        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6032                                        &IsInline, PrevNS);
6033    } else if (PrevDecl) {
6034      // This is an invalid name redefinition.
6035      Diag(Loc, diag::err_redefinition_different_kind)
6036        << II;
6037      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6038      IsInvalid = true;
6039      // Continue on to push Namespc as current DeclContext and return it.
6040    } else if (II->isStr("std") &&
6041               CurContext->getRedeclContext()->isTranslationUnit()) {
6042      // This is the first "real" definition of the namespace "std", so update
6043      // our cache of the "std" namespace to point at this definition.
6044      PrevNS = getStdNamespace();
6045      IsStd = true;
6046      AddToKnown = !IsInline;
6047    } else {
6048      // We've seen this namespace for the first time.
6049      AddToKnown = !IsInline;
6050    }
6051  } else {
6052    // Anonymous namespaces.
6053
6054    // Determine whether the parent already has an anonymous namespace.
6055    DeclContext *Parent = CurContext->getRedeclContext();
6056    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6057      PrevNS = TU->getAnonymousNamespace();
6058    } else {
6059      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6060      PrevNS = ND->getAnonymousNamespace();
6061    }
6062
6063    if (PrevNS && IsInline != PrevNS->isInline())
6064      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6065                                      &IsInline, PrevNS);
6066  }
6067
6068  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6069                                                 StartLoc, Loc, II, PrevNS);
6070  if (IsInvalid)
6071    Namespc->setInvalidDecl();
6072
6073  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6074
6075  // FIXME: Should we be merging attributes?
6076  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6077    PushNamespaceVisibilityAttr(Attr, Loc);
6078
6079  if (IsStd)
6080    StdNamespace = Namespc;
6081  if (AddToKnown)
6082    KnownNamespaces[Namespc] = false;
6083
6084  if (II) {
6085    PushOnScopeChains(Namespc, DeclRegionScope);
6086  } else {
6087    // Link the anonymous namespace into its parent.
6088    DeclContext *Parent = CurContext->getRedeclContext();
6089    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6090      TU->setAnonymousNamespace(Namespc);
6091    } else {
6092      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6093    }
6094
6095    CurContext->addDecl(Namespc);
6096
6097    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6098    //   behaves as if it were replaced by
6099    //     namespace unique { /* empty body */ }
6100    //     using namespace unique;
6101    //     namespace unique { namespace-body }
6102    //   where all occurrences of 'unique' in a translation unit are
6103    //   replaced by the same identifier and this identifier differs
6104    //   from all other identifiers in the entire program.
6105
6106    // We just create the namespace with an empty name and then add an
6107    // implicit using declaration, just like the standard suggests.
6108    //
6109    // CodeGen enforces the "universally unique" aspect by giving all
6110    // declarations semantically contained within an anonymous
6111    // namespace internal linkage.
6112
6113    if (!PrevNS) {
6114      UsingDirectiveDecl* UD
6115        = UsingDirectiveDecl::Create(Context, Parent,
6116                                     /* 'using' */ LBrace,
6117                                     /* 'namespace' */ SourceLocation(),
6118                                     /* qualifier */ NestedNameSpecifierLoc(),
6119                                     /* identifier */ SourceLocation(),
6120                                     Namespc,
6121                                     /* Ancestor */ Parent);
6122      UD->setImplicit();
6123      Parent->addDecl(UD);
6124    }
6125  }
6126
6127  ActOnDocumentableDecl(Namespc);
6128
6129  // Although we could have an invalid decl (i.e. the namespace name is a
6130  // redefinition), push it as current DeclContext and try to continue parsing.
6131  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6132  // for the namespace has the declarations that showed up in that particular
6133  // namespace definition.
6134  PushDeclContext(NamespcScope, Namespc);
6135  return Namespc;
6136}
6137
6138/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6139/// is a namespace alias, returns the namespace it points to.
6140static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6141  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6142    return AD->getNamespace();
6143  return dyn_cast_or_null<NamespaceDecl>(D);
6144}
6145
6146/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6147/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6148void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6149  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6150  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6151  Namespc->setRBraceLoc(RBrace);
6152  PopDeclContext();
6153  if (Namespc->hasAttr<VisibilityAttr>())
6154    PopPragmaVisibility(true, RBrace);
6155}
6156
6157CXXRecordDecl *Sema::getStdBadAlloc() const {
6158  return cast_or_null<CXXRecordDecl>(
6159                                  StdBadAlloc.get(Context.getExternalSource()));
6160}
6161
6162NamespaceDecl *Sema::getStdNamespace() const {
6163  return cast_or_null<NamespaceDecl>(
6164                                 StdNamespace.get(Context.getExternalSource()));
6165}
6166
6167/// \brief Retrieve the special "std" namespace, which may require us to
6168/// implicitly define the namespace.
6169NamespaceDecl *Sema::getOrCreateStdNamespace() {
6170  if (!StdNamespace) {
6171    // The "std" namespace has not yet been defined, so build one implicitly.
6172    StdNamespace = NamespaceDecl::Create(Context,
6173                                         Context.getTranslationUnitDecl(),
6174                                         /*Inline=*/false,
6175                                         SourceLocation(), SourceLocation(),
6176                                         &PP.getIdentifierTable().get("std"),
6177                                         /*PrevDecl=*/0);
6178    getStdNamespace()->setImplicit(true);
6179  }
6180
6181  return getStdNamespace();
6182}
6183
6184bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6185  assert(getLangOpts().CPlusPlus &&
6186         "Looking for std::initializer_list outside of C++.");
6187
6188  // We're looking for implicit instantiations of
6189  // template <typename E> class std::initializer_list.
6190
6191  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6192    return false;
6193
6194  ClassTemplateDecl *Template = 0;
6195  const TemplateArgument *Arguments = 0;
6196
6197  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6198
6199    ClassTemplateSpecializationDecl *Specialization =
6200        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6201    if (!Specialization)
6202      return false;
6203
6204    Template = Specialization->getSpecializedTemplate();
6205    Arguments = Specialization->getTemplateArgs().data();
6206  } else if (const TemplateSpecializationType *TST =
6207                 Ty->getAs<TemplateSpecializationType>()) {
6208    Template = dyn_cast_or_null<ClassTemplateDecl>(
6209        TST->getTemplateName().getAsTemplateDecl());
6210    Arguments = TST->getArgs();
6211  }
6212  if (!Template)
6213    return false;
6214
6215  if (!StdInitializerList) {
6216    // Haven't recognized std::initializer_list yet, maybe this is it.
6217    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6218    if (TemplateClass->getIdentifier() !=
6219            &PP.getIdentifierTable().get("initializer_list") ||
6220        !getStdNamespace()->InEnclosingNamespaceSetOf(
6221            TemplateClass->getDeclContext()))
6222      return false;
6223    // This is a template called std::initializer_list, but is it the right
6224    // template?
6225    TemplateParameterList *Params = Template->getTemplateParameters();
6226    if (Params->getMinRequiredArguments() != 1)
6227      return false;
6228    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6229      return false;
6230
6231    // It's the right template.
6232    StdInitializerList = Template;
6233  }
6234
6235  if (Template != StdInitializerList)
6236    return false;
6237
6238  // This is an instance of std::initializer_list. Find the argument type.
6239  if (Element)
6240    *Element = Arguments[0].getAsType();
6241  return true;
6242}
6243
6244static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6245  NamespaceDecl *Std = S.getStdNamespace();
6246  if (!Std) {
6247    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6248    return 0;
6249  }
6250
6251  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6252                      Loc, Sema::LookupOrdinaryName);
6253  if (!S.LookupQualifiedName(Result, Std)) {
6254    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6255    return 0;
6256  }
6257  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6258  if (!Template) {
6259    Result.suppressDiagnostics();
6260    // We found something weird. Complain about the first thing we found.
6261    NamedDecl *Found = *Result.begin();
6262    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6263    return 0;
6264  }
6265
6266  // We found some template called std::initializer_list. Now verify that it's
6267  // correct.
6268  TemplateParameterList *Params = Template->getTemplateParameters();
6269  if (Params->getMinRequiredArguments() != 1 ||
6270      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6271    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6272    return 0;
6273  }
6274
6275  return Template;
6276}
6277
6278QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6279  if (!StdInitializerList) {
6280    StdInitializerList = LookupStdInitializerList(*this, Loc);
6281    if (!StdInitializerList)
6282      return QualType();
6283  }
6284
6285  TemplateArgumentListInfo Args(Loc, Loc);
6286  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6287                                       Context.getTrivialTypeSourceInfo(Element,
6288                                                                        Loc)));
6289  return Context.getCanonicalType(
6290      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6291}
6292
6293bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6294  // C++ [dcl.init.list]p2:
6295  //   A constructor is an initializer-list constructor if its first parameter
6296  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6297  //   std::initializer_list<E> for some type E, and either there are no other
6298  //   parameters or else all other parameters have default arguments.
6299  if (Ctor->getNumParams() < 1 ||
6300      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6301    return false;
6302
6303  QualType ArgType = Ctor->getParamDecl(0)->getType();
6304  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6305    ArgType = RT->getPointeeType().getUnqualifiedType();
6306
6307  return isStdInitializerList(ArgType, 0);
6308}
6309
6310/// \brief Determine whether a using statement is in a context where it will be
6311/// apply in all contexts.
6312static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6313  switch (CurContext->getDeclKind()) {
6314    case Decl::TranslationUnit:
6315      return true;
6316    case Decl::LinkageSpec:
6317      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6318    default:
6319      return false;
6320  }
6321}
6322
6323namespace {
6324
6325// Callback to only accept typo corrections that are namespaces.
6326class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6327 public:
6328  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6329    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6330      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6331    }
6332    return false;
6333  }
6334};
6335
6336}
6337
6338static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6339                                       CXXScopeSpec &SS,
6340                                       SourceLocation IdentLoc,
6341                                       IdentifierInfo *Ident) {
6342  NamespaceValidatorCCC Validator;
6343  R.clear();
6344  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6345                                               R.getLookupKind(), Sc, &SS,
6346                                               Validator)) {
6347    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6348    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6349    if (DeclContext *DC = S.computeDeclContext(SS, false))
6350      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6351        << Ident << DC << CorrectedQuotedStr << SS.getRange()
6352        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6353                                        CorrectedStr);
6354    else
6355      S.Diag(IdentLoc, diag::err_using_directive_suggest)
6356        << Ident << CorrectedQuotedStr
6357        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6358
6359    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6360         diag::note_namespace_defined_here) << CorrectedQuotedStr;
6361
6362    R.addDecl(Corrected.getCorrectionDecl());
6363    return true;
6364  }
6365  return false;
6366}
6367
6368Decl *Sema::ActOnUsingDirective(Scope *S,
6369                                          SourceLocation UsingLoc,
6370                                          SourceLocation NamespcLoc,
6371                                          CXXScopeSpec &SS,
6372                                          SourceLocation IdentLoc,
6373                                          IdentifierInfo *NamespcName,
6374                                          AttributeList *AttrList) {
6375  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6376  assert(NamespcName && "Invalid NamespcName.");
6377  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6378
6379  // This can only happen along a recovery path.
6380  while (S->getFlags() & Scope::TemplateParamScope)
6381    S = S->getParent();
6382  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6383
6384  UsingDirectiveDecl *UDir = 0;
6385  NestedNameSpecifier *Qualifier = 0;
6386  if (SS.isSet())
6387    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6388
6389  // Lookup namespace name.
6390  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6391  LookupParsedName(R, S, &SS);
6392  if (R.isAmbiguous())
6393    return 0;
6394
6395  if (R.empty()) {
6396    R.clear();
6397    // Allow "using namespace std;" or "using namespace ::std;" even if
6398    // "std" hasn't been defined yet, for GCC compatibility.
6399    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6400        NamespcName->isStr("std")) {
6401      Diag(IdentLoc, diag::ext_using_undefined_std);
6402      R.addDecl(getOrCreateStdNamespace());
6403      R.resolveKind();
6404    }
6405    // Otherwise, attempt typo correction.
6406    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6407  }
6408
6409  if (!R.empty()) {
6410    NamedDecl *Named = R.getFoundDecl();
6411    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6412        && "expected namespace decl");
6413    // C++ [namespace.udir]p1:
6414    //   A using-directive specifies that the names in the nominated
6415    //   namespace can be used in the scope in which the
6416    //   using-directive appears after the using-directive. During
6417    //   unqualified name lookup (3.4.1), the names appear as if they
6418    //   were declared in the nearest enclosing namespace which
6419    //   contains both the using-directive and the nominated
6420    //   namespace. [Note: in this context, "contains" means "contains
6421    //   directly or indirectly". ]
6422
6423    // Find enclosing context containing both using-directive and
6424    // nominated namespace.
6425    NamespaceDecl *NS = getNamespaceDecl(Named);
6426    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6427    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6428      CommonAncestor = CommonAncestor->getParent();
6429
6430    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6431                                      SS.getWithLocInContext(Context),
6432                                      IdentLoc, Named, CommonAncestor);
6433
6434    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6435        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6436      Diag(IdentLoc, diag::warn_using_directive_in_header);
6437    }
6438
6439    PushUsingDirective(S, UDir);
6440  } else {
6441    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6442  }
6443
6444  // FIXME: We ignore attributes for now.
6445  return UDir;
6446}
6447
6448void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6449  // If the scope has an associated entity and the using directive is at
6450  // namespace or translation unit scope, add the UsingDirectiveDecl into
6451  // its lookup structure so qualified name lookup can find it.
6452  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6453  if (Ctx && !Ctx->isFunctionOrMethod())
6454    Ctx->addDecl(UDir);
6455  else
6456    // Otherwise, it is at block sope. The using-directives will affect lookup
6457    // only to the end of the scope.
6458    S->PushUsingDirective(UDir);
6459}
6460
6461
6462Decl *Sema::ActOnUsingDeclaration(Scope *S,
6463                                  AccessSpecifier AS,
6464                                  bool HasUsingKeyword,
6465                                  SourceLocation UsingLoc,
6466                                  CXXScopeSpec &SS,
6467                                  UnqualifiedId &Name,
6468                                  AttributeList *AttrList,
6469                                  bool IsTypeName,
6470                                  SourceLocation TypenameLoc) {
6471  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6472
6473  switch (Name.getKind()) {
6474  case UnqualifiedId::IK_ImplicitSelfParam:
6475  case UnqualifiedId::IK_Identifier:
6476  case UnqualifiedId::IK_OperatorFunctionId:
6477  case UnqualifiedId::IK_LiteralOperatorId:
6478  case UnqualifiedId::IK_ConversionFunctionId:
6479    break;
6480
6481  case UnqualifiedId::IK_ConstructorName:
6482  case UnqualifiedId::IK_ConstructorTemplateId:
6483    // C++11 inheriting constructors.
6484    Diag(Name.getLocStart(),
6485         getLangOpts().CPlusPlus11 ?
6486           // FIXME: Produce warn_cxx98_compat_using_decl_constructor
6487           //        instead once inheriting constructors work.
6488           diag::err_using_decl_constructor_unsupported :
6489           diag::err_using_decl_constructor)
6490      << SS.getRange();
6491
6492    if (getLangOpts().CPlusPlus11) break;
6493
6494    return 0;
6495
6496  case UnqualifiedId::IK_DestructorName:
6497    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6498      << SS.getRange();
6499    return 0;
6500
6501  case UnqualifiedId::IK_TemplateId:
6502    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6503      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6504    return 0;
6505  }
6506
6507  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6508  DeclarationName TargetName = TargetNameInfo.getName();
6509  if (!TargetName)
6510    return 0;
6511
6512  // Warn about using declarations.
6513  // TODO: store that the declaration was written without 'using' and
6514  // talk about access decls instead of using decls in the
6515  // diagnostics.
6516  if (!HasUsingKeyword) {
6517    UsingLoc = Name.getLocStart();
6518
6519    Diag(UsingLoc, diag::warn_access_decl_deprecated)
6520      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6521  }
6522
6523  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6524      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6525    return 0;
6526
6527  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6528                                        TargetNameInfo, AttrList,
6529                                        /* IsInstantiation */ false,
6530                                        IsTypeName, TypenameLoc);
6531  if (UD)
6532    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6533
6534  return UD;
6535}
6536
6537/// \brief Determine whether a using declaration considers the given
6538/// declarations as "equivalent", e.g., if they are redeclarations of
6539/// the same entity or are both typedefs of the same type.
6540static bool
6541IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6542                         bool &SuppressRedeclaration) {
6543  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6544    SuppressRedeclaration = false;
6545    return true;
6546  }
6547
6548  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6549    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6550      SuppressRedeclaration = true;
6551      return Context.hasSameType(TD1->getUnderlyingType(),
6552                                 TD2->getUnderlyingType());
6553    }
6554
6555  return false;
6556}
6557
6558
6559/// Determines whether to create a using shadow decl for a particular
6560/// decl, given the set of decls existing prior to this using lookup.
6561bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6562                                const LookupResult &Previous) {
6563  // Diagnose finding a decl which is not from a base class of the
6564  // current class.  We do this now because there are cases where this
6565  // function will silently decide not to build a shadow decl, which
6566  // will pre-empt further diagnostics.
6567  //
6568  // We don't need to do this in C++0x because we do the check once on
6569  // the qualifier.
6570  //
6571  // FIXME: diagnose the following if we care enough:
6572  //   struct A { int foo; };
6573  //   struct B : A { using A::foo; };
6574  //   template <class T> struct C : A {};
6575  //   template <class T> struct D : C<T> { using B::foo; } // <---
6576  // This is invalid (during instantiation) in C++03 because B::foo
6577  // resolves to the using decl in B, which is not a base class of D<T>.
6578  // We can't diagnose it immediately because C<T> is an unknown
6579  // specialization.  The UsingShadowDecl in D<T> then points directly
6580  // to A::foo, which will look well-formed when we instantiate.
6581  // The right solution is to not collapse the shadow-decl chain.
6582  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6583    DeclContext *OrigDC = Orig->getDeclContext();
6584
6585    // Handle enums and anonymous structs.
6586    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6587    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6588    while (OrigRec->isAnonymousStructOrUnion())
6589      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6590
6591    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6592      if (OrigDC == CurContext) {
6593        Diag(Using->getLocation(),
6594             diag::err_using_decl_nested_name_specifier_is_current_class)
6595          << Using->getQualifierLoc().getSourceRange();
6596        Diag(Orig->getLocation(), diag::note_using_decl_target);
6597        return true;
6598      }
6599
6600      Diag(Using->getQualifierLoc().getBeginLoc(),
6601           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6602        << Using->getQualifier()
6603        << cast<CXXRecordDecl>(CurContext)
6604        << Using->getQualifierLoc().getSourceRange();
6605      Diag(Orig->getLocation(), diag::note_using_decl_target);
6606      return true;
6607    }
6608  }
6609
6610  if (Previous.empty()) return false;
6611
6612  NamedDecl *Target = Orig;
6613  if (isa<UsingShadowDecl>(Target))
6614    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6615
6616  // If the target happens to be one of the previous declarations, we
6617  // don't have a conflict.
6618  //
6619  // FIXME: but we might be increasing its access, in which case we
6620  // should redeclare it.
6621  NamedDecl *NonTag = 0, *Tag = 0;
6622  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6623         I != E; ++I) {
6624    NamedDecl *D = (*I)->getUnderlyingDecl();
6625    bool Result;
6626    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6627      return Result;
6628
6629    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6630  }
6631
6632  if (Target->isFunctionOrFunctionTemplate()) {
6633    FunctionDecl *FD;
6634    if (isa<FunctionTemplateDecl>(Target))
6635      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6636    else
6637      FD = cast<FunctionDecl>(Target);
6638
6639    NamedDecl *OldDecl = 0;
6640    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6641    case Ovl_Overload:
6642      return false;
6643
6644    case Ovl_NonFunction:
6645      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6646      break;
6647
6648    // We found a decl with the exact signature.
6649    case Ovl_Match:
6650      // If we're in a record, we want to hide the target, so we
6651      // return true (without a diagnostic) to tell the caller not to
6652      // build a shadow decl.
6653      if (CurContext->isRecord())
6654        return true;
6655
6656      // If we're not in a record, this is an error.
6657      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6658      break;
6659    }
6660
6661    Diag(Target->getLocation(), diag::note_using_decl_target);
6662    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6663    return true;
6664  }
6665
6666  // Target is not a function.
6667
6668  if (isa<TagDecl>(Target)) {
6669    // No conflict between a tag and a non-tag.
6670    if (!Tag) return false;
6671
6672    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6673    Diag(Target->getLocation(), diag::note_using_decl_target);
6674    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6675    return true;
6676  }
6677
6678  // No conflict between a tag and a non-tag.
6679  if (!NonTag) return false;
6680
6681  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6682  Diag(Target->getLocation(), diag::note_using_decl_target);
6683  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6684  return true;
6685}
6686
6687/// Builds a shadow declaration corresponding to a 'using' declaration.
6688UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6689                                            UsingDecl *UD,
6690                                            NamedDecl *Orig) {
6691
6692  // If we resolved to another shadow declaration, just coalesce them.
6693  NamedDecl *Target = Orig;
6694  if (isa<UsingShadowDecl>(Target)) {
6695    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6696    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6697  }
6698
6699  UsingShadowDecl *Shadow
6700    = UsingShadowDecl::Create(Context, CurContext,
6701                              UD->getLocation(), UD, Target);
6702  UD->addShadowDecl(Shadow);
6703
6704  Shadow->setAccess(UD->getAccess());
6705  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6706    Shadow->setInvalidDecl();
6707
6708  if (S)
6709    PushOnScopeChains(Shadow, S);
6710  else
6711    CurContext->addDecl(Shadow);
6712
6713
6714  return Shadow;
6715}
6716
6717/// Hides a using shadow declaration.  This is required by the current
6718/// using-decl implementation when a resolvable using declaration in a
6719/// class is followed by a declaration which would hide or override
6720/// one or more of the using decl's targets; for example:
6721///
6722///   struct Base { void foo(int); };
6723///   struct Derived : Base {
6724///     using Base::foo;
6725///     void foo(int);
6726///   };
6727///
6728/// The governing language is C++03 [namespace.udecl]p12:
6729///
6730///   When a using-declaration brings names from a base class into a
6731///   derived class scope, member functions in the derived class
6732///   override and/or hide member functions with the same name and
6733///   parameter types in a base class (rather than conflicting).
6734///
6735/// There are two ways to implement this:
6736///   (1) optimistically create shadow decls when they're not hidden
6737///       by existing declarations, or
6738///   (2) don't create any shadow decls (or at least don't make them
6739///       visible) until we've fully parsed/instantiated the class.
6740/// The problem with (1) is that we might have to retroactively remove
6741/// a shadow decl, which requires several O(n) operations because the
6742/// decl structures are (very reasonably) not designed for removal.
6743/// (2) avoids this but is very fiddly and phase-dependent.
6744void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6745  if (Shadow->getDeclName().getNameKind() ==
6746        DeclarationName::CXXConversionFunctionName)
6747    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6748
6749  // Remove it from the DeclContext...
6750  Shadow->getDeclContext()->removeDecl(Shadow);
6751
6752  // ...and the scope, if applicable...
6753  if (S) {
6754    S->RemoveDecl(Shadow);
6755    IdResolver.RemoveDecl(Shadow);
6756  }
6757
6758  // ...and the using decl.
6759  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6760
6761  // TODO: complain somehow if Shadow was used.  It shouldn't
6762  // be possible for this to happen, because...?
6763}
6764
6765/// Builds a using declaration.
6766///
6767/// \param IsInstantiation - Whether this call arises from an
6768///   instantiation of an unresolved using declaration.  We treat
6769///   the lookup differently for these declarations.
6770NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6771                                       SourceLocation UsingLoc,
6772                                       CXXScopeSpec &SS,
6773                                       const DeclarationNameInfo &NameInfo,
6774                                       AttributeList *AttrList,
6775                                       bool IsInstantiation,
6776                                       bool IsTypeName,
6777                                       SourceLocation TypenameLoc) {
6778  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6779  SourceLocation IdentLoc = NameInfo.getLoc();
6780  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6781
6782  // FIXME: We ignore attributes for now.
6783
6784  if (SS.isEmpty()) {
6785    Diag(IdentLoc, diag::err_using_requires_qualname);
6786    return 0;
6787  }
6788
6789  // Do the redeclaration lookup in the current scope.
6790  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6791                        ForRedeclaration);
6792  Previous.setHideTags(false);
6793  if (S) {
6794    LookupName(Previous, S);
6795
6796    // It is really dumb that we have to do this.
6797    LookupResult::Filter F = Previous.makeFilter();
6798    while (F.hasNext()) {
6799      NamedDecl *D = F.next();
6800      if (!isDeclInScope(D, CurContext, S))
6801        F.erase();
6802    }
6803    F.done();
6804  } else {
6805    assert(IsInstantiation && "no scope in non-instantiation");
6806    assert(CurContext->isRecord() && "scope not record in instantiation");
6807    LookupQualifiedName(Previous, CurContext);
6808  }
6809
6810  // Check for invalid redeclarations.
6811  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6812    return 0;
6813
6814  // Check for bad qualifiers.
6815  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6816    return 0;
6817
6818  DeclContext *LookupContext = computeDeclContext(SS);
6819  NamedDecl *D;
6820  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6821  if (!LookupContext) {
6822    if (IsTypeName) {
6823      // FIXME: not all declaration name kinds are legal here
6824      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6825                                              UsingLoc, TypenameLoc,
6826                                              QualifierLoc,
6827                                              IdentLoc, NameInfo.getName());
6828    } else {
6829      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6830                                           QualifierLoc, NameInfo);
6831    }
6832  } else {
6833    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6834                          NameInfo, IsTypeName);
6835  }
6836  D->setAccess(AS);
6837  CurContext->addDecl(D);
6838
6839  if (!LookupContext) return D;
6840  UsingDecl *UD = cast<UsingDecl>(D);
6841
6842  if (RequireCompleteDeclContext(SS, LookupContext)) {
6843    UD->setInvalidDecl();
6844    return UD;
6845  }
6846
6847  // The normal rules do not apply to inheriting constructor declarations.
6848  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6849    if (CheckInheritingConstructorUsingDecl(UD))
6850      UD->setInvalidDecl();
6851    return UD;
6852  }
6853
6854  // Otherwise, look up the target name.
6855
6856  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6857
6858  // Unlike most lookups, we don't always want to hide tag
6859  // declarations: tag names are visible through the using declaration
6860  // even if hidden by ordinary names, *except* in a dependent context
6861  // where it's important for the sanity of two-phase lookup.
6862  if (!IsInstantiation)
6863    R.setHideTags(false);
6864
6865  // For the purposes of this lookup, we have a base object type
6866  // equal to that of the current context.
6867  if (CurContext->isRecord()) {
6868    R.setBaseObjectType(
6869                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6870  }
6871
6872  LookupQualifiedName(R, LookupContext);
6873
6874  if (R.empty()) {
6875    Diag(IdentLoc, diag::err_no_member)
6876      << NameInfo.getName() << LookupContext << SS.getRange();
6877    UD->setInvalidDecl();
6878    return UD;
6879  }
6880
6881  if (R.isAmbiguous()) {
6882    UD->setInvalidDecl();
6883    return UD;
6884  }
6885
6886  if (IsTypeName) {
6887    // If we asked for a typename and got a non-type decl, error out.
6888    if (!R.getAsSingle<TypeDecl>()) {
6889      Diag(IdentLoc, diag::err_using_typename_non_type);
6890      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6891        Diag((*I)->getUnderlyingDecl()->getLocation(),
6892             diag::note_using_decl_target);
6893      UD->setInvalidDecl();
6894      return UD;
6895    }
6896  } else {
6897    // If we asked for a non-typename and we got a type, error out,
6898    // but only if this is an instantiation of an unresolved using
6899    // decl.  Otherwise just silently find the type name.
6900    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6901      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6902      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6903      UD->setInvalidDecl();
6904      return UD;
6905    }
6906  }
6907
6908  // C++0x N2914 [namespace.udecl]p6:
6909  // A using-declaration shall not name a namespace.
6910  if (R.getAsSingle<NamespaceDecl>()) {
6911    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6912      << SS.getRange();
6913    UD->setInvalidDecl();
6914    return UD;
6915  }
6916
6917  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6918    if (!CheckUsingShadowDecl(UD, *I, Previous))
6919      BuildUsingShadowDecl(S, UD, *I);
6920  }
6921
6922  return UD;
6923}
6924
6925/// Additional checks for a using declaration referring to a constructor name.
6926bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6927  assert(!UD->isTypeName() && "expecting a constructor name");
6928
6929  const Type *SourceType = UD->getQualifier()->getAsType();
6930  assert(SourceType &&
6931         "Using decl naming constructor doesn't have type in scope spec.");
6932  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6933
6934  // Check whether the named type is a direct base class.
6935  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6936  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6937  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6938       BaseIt != BaseE; ++BaseIt) {
6939    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6940    if (CanonicalSourceType == BaseType)
6941      break;
6942    if (BaseIt->getType()->isDependentType())
6943      break;
6944  }
6945
6946  if (BaseIt == BaseE) {
6947    // Did not find SourceType in the bases.
6948    Diag(UD->getUsingLocation(),
6949         diag::err_using_decl_constructor_not_in_direct_base)
6950      << UD->getNameInfo().getSourceRange()
6951      << QualType(SourceType, 0) << TargetClass;
6952    return true;
6953  }
6954
6955  if (!CurContext->isDependentContext())
6956    BaseIt->setInheritConstructors();
6957
6958  return false;
6959}
6960
6961/// Checks that the given using declaration is not an invalid
6962/// redeclaration.  Note that this is checking only for the using decl
6963/// itself, not for any ill-formedness among the UsingShadowDecls.
6964bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6965                                       bool isTypeName,
6966                                       const CXXScopeSpec &SS,
6967                                       SourceLocation NameLoc,
6968                                       const LookupResult &Prev) {
6969  // C++03 [namespace.udecl]p8:
6970  // C++0x [namespace.udecl]p10:
6971  //   A using-declaration is a declaration and can therefore be used
6972  //   repeatedly where (and only where) multiple declarations are
6973  //   allowed.
6974  //
6975  // That's in non-member contexts.
6976  if (!CurContext->getRedeclContext()->isRecord())
6977    return false;
6978
6979  NestedNameSpecifier *Qual
6980    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6981
6982  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6983    NamedDecl *D = *I;
6984
6985    bool DTypename;
6986    NestedNameSpecifier *DQual;
6987    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6988      DTypename = UD->isTypeName();
6989      DQual = UD->getQualifier();
6990    } else if (UnresolvedUsingValueDecl *UD
6991                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6992      DTypename = false;
6993      DQual = UD->getQualifier();
6994    } else if (UnresolvedUsingTypenameDecl *UD
6995                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6996      DTypename = true;
6997      DQual = UD->getQualifier();
6998    } else continue;
6999
7000    // using decls differ if one says 'typename' and the other doesn't.
7001    // FIXME: non-dependent using decls?
7002    if (isTypeName != DTypename) continue;
7003
7004    // using decls differ if they name different scopes (but note that
7005    // template instantiation can cause this check to trigger when it
7006    // didn't before instantiation).
7007    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7008        Context.getCanonicalNestedNameSpecifier(DQual))
7009      continue;
7010
7011    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7012    Diag(D->getLocation(), diag::note_using_decl) << 1;
7013    return true;
7014  }
7015
7016  return false;
7017}
7018
7019
7020/// Checks that the given nested-name qualifier used in a using decl
7021/// in the current context is appropriately related to the current
7022/// scope.  If an error is found, diagnoses it and returns true.
7023bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7024                                   const CXXScopeSpec &SS,
7025                                   SourceLocation NameLoc) {
7026  DeclContext *NamedContext = computeDeclContext(SS);
7027
7028  if (!CurContext->isRecord()) {
7029    // C++03 [namespace.udecl]p3:
7030    // C++0x [namespace.udecl]p8:
7031    //   A using-declaration for a class member shall be a member-declaration.
7032
7033    // If we weren't able to compute a valid scope, it must be a
7034    // dependent class scope.
7035    if (!NamedContext || NamedContext->isRecord()) {
7036      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7037        << SS.getRange();
7038      return true;
7039    }
7040
7041    // Otherwise, everything is known to be fine.
7042    return false;
7043  }
7044
7045  // The current scope is a record.
7046
7047  // If the named context is dependent, we can't decide much.
7048  if (!NamedContext) {
7049    // FIXME: in C++0x, we can diagnose if we can prove that the
7050    // nested-name-specifier does not refer to a base class, which is
7051    // still possible in some cases.
7052
7053    // Otherwise we have to conservatively report that things might be
7054    // okay.
7055    return false;
7056  }
7057
7058  if (!NamedContext->isRecord()) {
7059    // Ideally this would point at the last name in the specifier,
7060    // but we don't have that level of source info.
7061    Diag(SS.getRange().getBegin(),
7062         diag::err_using_decl_nested_name_specifier_is_not_class)
7063      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7064    return true;
7065  }
7066
7067  if (!NamedContext->isDependentContext() &&
7068      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7069    return true;
7070
7071  if (getLangOpts().CPlusPlus11) {
7072    // C++0x [namespace.udecl]p3:
7073    //   In a using-declaration used as a member-declaration, the
7074    //   nested-name-specifier shall name a base class of the class
7075    //   being defined.
7076
7077    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7078                                 cast<CXXRecordDecl>(NamedContext))) {
7079      if (CurContext == NamedContext) {
7080        Diag(NameLoc,
7081             diag::err_using_decl_nested_name_specifier_is_current_class)
7082          << SS.getRange();
7083        return true;
7084      }
7085
7086      Diag(SS.getRange().getBegin(),
7087           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7088        << (NestedNameSpecifier*) SS.getScopeRep()
7089        << cast<CXXRecordDecl>(CurContext)
7090        << SS.getRange();
7091      return true;
7092    }
7093
7094    return false;
7095  }
7096
7097  // C++03 [namespace.udecl]p4:
7098  //   A using-declaration used as a member-declaration shall refer
7099  //   to a member of a base class of the class being defined [etc.].
7100
7101  // Salient point: SS doesn't have to name a base class as long as
7102  // lookup only finds members from base classes.  Therefore we can
7103  // diagnose here only if we can prove that that can't happen,
7104  // i.e. if the class hierarchies provably don't intersect.
7105
7106  // TODO: it would be nice if "definitely valid" results were cached
7107  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7108  // need to be repeated.
7109
7110  struct UserData {
7111    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7112
7113    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7114      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7115      Data->Bases.insert(Base);
7116      return true;
7117    }
7118
7119    bool hasDependentBases(const CXXRecordDecl *Class) {
7120      return !Class->forallBases(collect, this);
7121    }
7122
7123    /// Returns true if the base is dependent or is one of the
7124    /// accumulated base classes.
7125    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7126      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7127      return !Data->Bases.count(Base);
7128    }
7129
7130    bool mightShareBases(const CXXRecordDecl *Class) {
7131      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7132    }
7133  };
7134
7135  UserData Data;
7136
7137  // Returns false if we find a dependent base.
7138  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7139    return false;
7140
7141  // Returns false if the class has a dependent base or if it or one
7142  // of its bases is present in the base set of the current context.
7143  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7144    return false;
7145
7146  Diag(SS.getRange().getBegin(),
7147       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7148    << (NestedNameSpecifier*) SS.getScopeRep()
7149    << cast<CXXRecordDecl>(CurContext)
7150    << SS.getRange();
7151
7152  return true;
7153}
7154
7155Decl *Sema::ActOnAliasDeclaration(Scope *S,
7156                                  AccessSpecifier AS,
7157                                  MultiTemplateParamsArg TemplateParamLists,
7158                                  SourceLocation UsingLoc,
7159                                  UnqualifiedId &Name,
7160                                  TypeResult Type) {
7161  // Skip up to the relevant declaration scope.
7162  while (S->getFlags() & Scope::TemplateParamScope)
7163    S = S->getParent();
7164  assert((S->getFlags() & Scope::DeclScope) &&
7165         "got alias-declaration outside of declaration scope");
7166
7167  if (Type.isInvalid())
7168    return 0;
7169
7170  bool Invalid = false;
7171  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7172  TypeSourceInfo *TInfo = 0;
7173  GetTypeFromParser(Type.get(), &TInfo);
7174
7175  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7176    return 0;
7177
7178  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7179                                      UPPC_DeclarationType)) {
7180    Invalid = true;
7181    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7182                                             TInfo->getTypeLoc().getBeginLoc());
7183  }
7184
7185  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7186  LookupName(Previous, S);
7187
7188  // Warn about shadowing the name of a template parameter.
7189  if (Previous.isSingleResult() &&
7190      Previous.getFoundDecl()->isTemplateParameter()) {
7191    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7192    Previous.clear();
7193  }
7194
7195  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7196         "name in alias declaration must be an identifier");
7197  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7198                                               Name.StartLocation,
7199                                               Name.Identifier, TInfo);
7200
7201  NewTD->setAccess(AS);
7202
7203  if (Invalid)
7204    NewTD->setInvalidDecl();
7205
7206  CheckTypedefForVariablyModifiedType(S, NewTD);
7207  Invalid |= NewTD->isInvalidDecl();
7208
7209  bool Redeclaration = false;
7210
7211  NamedDecl *NewND;
7212  if (TemplateParamLists.size()) {
7213    TypeAliasTemplateDecl *OldDecl = 0;
7214    TemplateParameterList *OldTemplateParams = 0;
7215
7216    if (TemplateParamLists.size() != 1) {
7217      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7218        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7219         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7220    }
7221    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7222
7223    // Only consider previous declarations in the same scope.
7224    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7225                         /*ExplicitInstantiationOrSpecialization*/false);
7226    if (!Previous.empty()) {
7227      Redeclaration = true;
7228
7229      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7230      if (!OldDecl && !Invalid) {
7231        Diag(UsingLoc, diag::err_redefinition_different_kind)
7232          << Name.Identifier;
7233
7234        NamedDecl *OldD = Previous.getRepresentativeDecl();
7235        if (OldD->getLocation().isValid())
7236          Diag(OldD->getLocation(), diag::note_previous_definition);
7237
7238        Invalid = true;
7239      }
7240
7241      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7242        if (TemplateParameterListsAreEqual(TemplateParams,
7243                                           OldDecl->getTemplateParameters(),
7244                                           /*Complain=*/true,
7245                                           TPL_TemplateMatch))
7246          OldTemplateParams = OldDecl->getTemplateParameters();
7247        else
7248          Invalid = true;
7249
7250        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7251        if (!Invalid &&
7252            !Context.hasSameType(OldTD->getUnderlyingType(),
7253                                 NewTD->getUnderlyingType())) {
7254          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7255          // but we can't reasonably accept it.
7256          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7257            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7258          if (OldTD->getLocation().isValid())
7259            Diag(OldTD->getLocation(), diag::note_previous_definition);
7260          Invalid = true;
7261        }
7262      }
7263    }
7264
7265    // Merge any previous default template arguments into our parameters,
7266    // and check the parameter list.
7267    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7268                                   TPC_TypeAliasTemplate))
7269      return 0;
7270
7271    TypeAliasTemplateDecl *NewDecl =
7272      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7273                                    Name.Identifier, TemplateParams,
7274                                    NewTD);
7275
7276    NewDecl->setAccess(AS);
7277
7278    if (Invalid)
7279      NewDecl->setInvalidDecl();
7280    else if (OldDecl)
7281      NewDecl->setPreviousDeclaration(OldDecl);
7282
7283    NewND = NewDecl;
7284  } else {
7285    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7286    NewND = NewTD;
7287  }
7288
7289  if (!Redeclaration)
7290    PushOnScopeChains(NewND, S);
7291
7292  ActOnDocumentableDecl(NewND);
7293  return NewND;
7294}
7295
7296Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7297                                             SourceLocation NamespaceLoc,
7298                                             SourceLocation AliasLoc,
7299                                             IdentifierInfo *Alias,
7300                                             CXXScopeSpec &SS,
7301                                             SourceLocation IdentLoc,
7302                                             IdentifierInfo *Ident) {
7303
7304  // Lookup the namespace name.
7305  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7306  LookupParsedName(R, S, &SS);
7307
7308  // Check if we have a previous declaration with the same name.
7309  NamedDecl *PrevDecl
7310    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7311                       ForRedeclaration);
7312  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7313    PrevDecl = 0;
7314
7315  if (PrevDecl) {
7316    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7317      // We already have an alias with the same name that points to the same
7318      // namespace, so don't create a new one.
7319      // FIXME: At some point, we'll want to create the (redundant)
7320      // declaration to maintain better source information.
7321      if (!R.isAmbiguous() && !R.empty() &&
7322          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7323        return 0;
7324    }
7325
7326    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7327      diag::err_redefinition_different_kind;
7328    Diag(AliasLoc, DiagID) << Alias;
7329    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7330    return 0;
7331  }
7332
7333  if (R.isAmbiguous())
7334    return 0;
7335
7336  if (R.empty()) {
7337    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7338      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7339      return 0;
7340    }
7341  }
7342
7343  NamespaceAliasDecl *AliasDecl =
7344    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7345                               Alias, SS.getWithLocInContext(Context),
7346                               IdentLoc, R.getFoundDecl());
7347
7348  PushOnScopeChains(AliasDecl, S);
7349  return AliasDecl;
7350}
7351
7352Sema::ImplicitExceptionSpecification
7353Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7354                                               CXXMethodDecl *MD) {
7355  CXXRecordDecl *ClassDecl = MD->getParent();
7356
7357  // C++ [except.spec]p14:
7358  //   An implicitly declared special member function (Clause 12) shall have an
7359  //   exception-specification. [...]
7360  ImplicitExceptionSpecification ExceptSpec(*this);
7361  if (ClassDecl->isInvalidDecl())
7362    return ExceptSpec;
7363
7364  // Direct base-class constructors.
7365  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7366                                       BEnd = ClassDecl->bases_end();
7367       B != BEnd; ++B) {
7368    if (B->isVirtual()) // Handled below.
7369      continue;
7370
7371    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7372      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7373      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7374      // If this is a deleted function, add it anyway. This might be conformant
7375      // with the standard. This might not. I'm not sure. It might not matter.
7376      if (Constructor)
7377        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7378    }
7379  }
7380
7381  // Virtual base-class constructors.
7382  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7383                                       BEnd = ClassDecl->vbases_end();
7384       B != BEnd; ++B) {
7385    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7386      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7387      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7388      // If this is a deleted function, add it anyway. This might be conformant
7389      // with the standard. This might not. I'm not sure. It might not matter.
7390      if (Constructor)
7391        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7392    }
7393  }
7394
7395  // Field constructors.
7396  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7397                               FEnd = ClassDecl->field_end();
7398       F != FEnd; ++F) {
7399    if (F->hasInClassInitializer()) {
7400      if (Expr *E = F->getInClassInitializer())
7401        ExceptSpec.CalledExpr(E);
7402      else if (!F->isInvalidDecl())
7403        // DR1351:
7404        //   If the brace-or-equal-initializer of a non-static data member
7405        //   invokes a defaulted default constructor of its class or of an
7406        //   enclosing class in a potentially evaluated subexpression, the
7407        //   program is ill-formed.
7408        //
7409        // This resolution is unworkable: the exception specification of the
7410        // default constructor can be needed in an unevaluated context, in
7411        // particular, in the operand of a noexcept-expression, and we can be
7412        // unable to compute an exception specification for an enclosed class.
7413        //
7414        // We do not allow an in-class initializer to require the evaluation
7415        // of the exception specification for any in-class initializer whose
7416        // definition is not lexically complete.
7417        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7418    } else if (const RecordType *RecordTy
7419              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7420      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7421      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7422      // If this is a deleted function, add it anyway. This might be conformant
7423      // with the standard. This might not. I'm not sure. It might not matter.
7424      // In particular, the problem is that this function never gets called. It
7425      // might just be ill-formed because this function attempts to refer to
7426      // a deleted function here.
7427      if (Constructor)
7428        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7429    }
7430  }
7431
7432  return ExceptSpec;
7433}
7434
7435namespace {
7436/// RAII object to register a special member as being currently declared.
7437struct DeclaringSpecialMember {
7438  Sema &S;
7439  Sema::SpecialMemberDecl D;
7440  bool WasAlreadyBeingDeclared;
7441
7442  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7443    : S(S), D(RD, CSM) {
7444    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7445    if (WasAlreadyBeingDeclared)
7446      // This almost never happens, but if it does, ensure that our cache
7447      // doesn't contain a stale result.
7448      S.SpecialMemberCache.clear();
7449
7450    // FIXME: Register a note to be produced if we encounter an error while
7451    // declaring the special member.
7452  }
7453  ~DeclaringSpecialMember() {
7454    if (!WasAlreadyBeingDeclared)
7455      S.SpecialMembersBeingDeclared.erase(D);
7456  }
7457
7458  /// \brief Are we already trying to declare this special member?
7459  bool isAlreadyBeingDeclared() const {
7460    return WasAlreadyBeingDeclared;
7461  }
7462};
7463}
7464
7465CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7466                                                     CXXRecordDecl *ClassDecl) {
7467  // C++ [class.ctor]p5:
7468  //   A default constructor for a class X is a constructor of class X
7469  //   that can be called without an argument. If there is no
7470  //   user-declared constructor for class X, a default constructor is
7471  //   implicitly declared. An implicitly-declared default constructor
7472  //   is an inline public member of its class.
7473  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7474         "Should not build implicit default constructor!");
7475
7476  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7477  if (DSM.isAlreadyBeingDeclared())
7478    return 0;
7479
7480  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7481                                                     CXXDefaultConstructor,
7482                                                     false);
7483
7484  // Create the actual constructor declaration.
7485  CanQualType ClassType
7486    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7487  SourceLocation ClassLoc = ClassDecl->getLocation();
7488  DeclarationName Name
7489    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7490  DeclarationNameInfo NameInfo(Name, ClassLoc);
7491  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7492      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7493      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7494      Constexpr);
7495  DefaultCon->setAccess(AS_public);
7496  DefaultCon->setDefaulted();
7497  DefaultCon->setImplicit();
7498
7499  // Build an exception specification pointing back at this constructor.
7500  FunctionProtoType::ExtProtoInfo EPI;
7501  EPI.ExceptionSpecType = EST_Unevaluated;
7502  EPI.ExceptionSpecDecl = DefaultCon;
7503  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7504
7505  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7506  // constructors is easy to compute.
7507  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7508
7509  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7510    DefaultCon->setDeletedAsWritten();
7511
7512  // Note that we have declared this constructor.
7513  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7514
7515  if (Scope *S = getScopeForContext(ClassDecl))
7516    PushOnScopeChains(DefaultCon, S, false);
7517  ClassDecl->addDecl(DefaultCon);
7518
7519  return DefaultCon;
7520}
7521
7522void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7523                                            CXXConstructorDecl *Constructor) {
7524  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7525          !Constructor->doesThisDeclarationHaveABody() &&
7526          !Constructor->isDeleted()) &&
7527    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7528
7529  CXXRecordDecl *ClassDecl = Constructor->getParent();
7530  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7531
7532  SynthesizedFunctionScope Scope(*this, Constructor);
7533  DiagnosticErrorTrap Trap(Diags);
7534  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
7535      Trap.hasErrorOccurred()) {
7536    Diag(CurrentLocation, diag::note_member_synthesized_at)
7537      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7538    Constructor->setInvalidDecl();
7539    return;
7540  }
7541
7542  SourceLocation Loc = Constructor->getLocation();
7543  Constructor->setBody(new (Context) CompoundStmt(Loc));
7544
7545  Constructor->setUsed();
7546  MarkVTableUsed(CurrentLocation, ClassDecl);
7547
7548  if (ASTMutationListener *L = getASTMutationListener()) {
7549    L->CompletedImplicitDefinition(Constructor);
7550  }
7551}
7552
7553void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7554  // Check that any explicitly-defaulted methods have exception specifications
7555  // compatible with their implicit exception specifications.
7556  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7557}
7558
7559void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7560  // We start with an initial pass over the base classes to collect those that
7561  // inherit constructors from. If there are none, we can forgo all further
7562  // processing.
7563  typedef SmallVector<const RecordType *, 4> BasesVector;
7564  BasesVector BasesToInheritFrom;
7565  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7566                                          BaseE = ClassDecl->bases_end();
7567         BaseIt != BaseE; ++BaseIt) {
7568    if (BaseIt->getInheritConstructors()) {
7569      QualType Base = BaseIt->getType();
7570      if (Base->isDependentType()) {
7571        // If we inherit constructors from anything that is dependent, just
7572        // abort processing altogether. We'll get another chance for the
7573        // instantiations.
7574        return;
7575      }
7576      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7577    }
7578  }
7579  if (BasesToInheritFrom.empty())
7580    return;
7581
7582  // Now collect the constructors that we already have in the current class.
7583  // Those take precedence over inherited constructors.
7584  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7585  //   unless there is a user-declared constructor with the same signature in
7586  //   the class where the using-declaration appears.
7587  llvm::SmallSet<const Type *, 8> ExistingConstructors;
7588  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7589                                    CtorE = ClassDecl->ctor_end();
7590       CtorIt != CtorE; ++CtorIt) {
7591    ExistingConstructors.insert(
7592        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7593  }
7594
7595  DeclarationName CreatedCtorName =
7596      Context.DeclarationNames.getCXXConstructorName(
7597          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7598
7599  // Now comes the true work.
7600  // First, we keep a map from constructor types to the base that introduced
7601  // them. Needed for finding conflicting constructors. We also keep the
7602  // actually inserted declarations in there, for pretty diagnostics.
7603  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7604  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7605  ConstructorToSourceMap InheritedConstructors;
7606  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7607                             BaseE = BasesToInheritFrom.end();
7608       BaseIt != BaseE; ++BaseIt) {
7609    const RecordType *Base = *BaseIt;
7610    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7611    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7612    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7613                                      CtorE = BaseDecl->ctor_end();
7614         CtorIt != CtorE; ++CtorIt) {
7615      // Find the using declaration for inheriting this base's constructors.
7616      // FIXME: Don't perform name lookup just to obtain a source location!
7617      DeclarationName Name =
7618          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7619      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7620      LookupQualifiedName(Result, CurContext);
7621      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7622      SourceLocation UsingLoc = UD ? UD->getLocation() :
7623                                     ClassDecl->getLocation();
7624
7625      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7626      //   from the class X named in the using-declaration consists of actual
7627      //   constructors and notional constructors that result from the
7628      //   transformation of defaulted parameters as follows:
7629      //   - all non-template default constructors of X, and
7630      //   - for each non-template constructor of X that has at least one
7631      //     parameter with a default argument, the set of constructors that
7632      //     results from omitting any ellipsis parameter specification and
7633      //     successively omitting parameters with a default argument from the
7634      //     end of the parameter-type-list.
7635      CXXConstructorDecl *BaseCtor = *CtorIt;
7636      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7637      const FunctionProtoType *BaseCtorType =
7638          BaseCtor->getType()->getAs<FunctionProtoType>();
7639
7640      for (unsigned params = BaseCtor->getMinRequiredArguments(),
7641                    maxParams = BaseCtor->getNumParams();
7642           params <= maxParams; ++params) {
7643        // Skip default constructors. They're never inherited.
7644        if (params == 0)
7645          continue;
7646        // Skip copy and move constructors for the same reason.
7647        if (CanBeCopyOrMove && params == 1)
7648          continue;
7649
7650        // Build up a function type for this particular constructor.
7651        // FIXME: The working paper does not consider that the exception spec
7652        // for the inheriting constructor might be larger than that of the
7653        // source. This code doesn't yet, either. When it does, this code will
7654        // need to be delayed until after exception specifications and in-class
7655        // member initializers are attached.
7656        const Type *NewCtorType;
7657        if (params == maxParams)
7658          NewCtorType = BaseCtorType;
7659        else {
7660          SmallVector<QualType, 16> Args;
7661          for (unsigned i = 0; i < params; ++i) {
7662            Args.push_back(BaseCtorType->getArgType(i));
7663          }
7664          FunctionProtoType::ExtProtoInfo ExtInfo =
7665              BaseCtorType->getExtProtoInfo();
7666          ExtInfo.Variadic = false;
7667          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7668                                                Args.data(), params, ExtInfo)
7669                       .getTypePtr();
7670        }
7671        const Type *CanonicalNewCtorType =
7672            Context.getCanonicalType(NewCtorType);
7673
7674        // Now that we have the type, first check if the class already has a
7675        // constructor with this signature.
7676        if (ExistingConstructors.count(CanonicalNewCtorType))
7677          continue;
7678
7679        // Then we check if we have already declared an inherited constructor
7680        // with this signature.
7681        std::pair<ConstructorToSourceMap::iterator, bool> result =
7682            InheritedConstructors.insert(std::make_pair(
7683                CanonicalNewCtorType,
7684                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7685        if (!result.second) {
7686          // Already in the map. If it came from a different class, that's an
7687          // error. Not if it's from the same.
7688          CanQualType PreviousBase = result.first->second.first;
7689          if (CanonicalBase != PreviousBase) {
7690            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7691            const CXXConstructorDecl *PrevBaseCtor =
7692                PrevCtor->getInheritedConstructor();
7693            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7694
7695            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7696            Diag(BaseCtor->getLocation(),
7697                 diag::note_using_decl_constructor_conflict_current_ctor);
7698            Diag(PrevBaseCtor->getLocation(),
7699                 diag::note_using_decl_constructor_conflict_previous_ctor);
7700            Diag(PrevCtor->getLocation(),
7701                 diag::note_using_decl_constructor_conflict_previous_using);
7702          }
7703          continue;
7704        }
7705
7706        // OK, we're there, now add the constructor.
7707        // C++0x [class.inhctor]p8: [...] that would be performed by a
7708        //   user-written inline constructor [...]
7709        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7710        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7711            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7712            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7713            /*ImplicitlyDeclared=*/true,
7714            // FIXME: Due to a defect in the standard, we treat inherited
7715            // constructors as constexpr even if that makes them ill-formed.
7716            /*Constexpr=*/BaseCtor->isConstexpr());
7717        NewCtor->setAccess(BaseCtor->getAccess());
7718
7719        // Build up the parameter decls and add them.
7720        SmallVector<ParmVarDecl *, 16> ParamDecls;
7721        for (unsigned i = 0; i < params; ++i) {
7722          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7723                                                   UsingLoc, UsingLoc,
7724                                                   /*IdentifierInfo=*/0,
7725                                                   BaseCtorType->getArgType(i),
7726                                                   /*TInfo=*/0, SC_None,
7727                                                   SC_None, /*DefaultArg=*/0));
7728        }
7729        NewCtor->setParams(ParamDecls);
7730        NewCtor->setInheritedConstructor(BaseCtor);
7731
7732        ClassDecl->addDecl(NewCtor);
7733        result.first->second.second = NewCtor;
7734      }
7735    }
7736  }
7737}
7738
7739Sema::ImplicitExceptionSpecification
7740Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7741  CXXRecordDecl *ClassDecl = MD->getParent();
7742
7743  // C++ [except.spec]p14:
7744  //   An implicitly declared special member function (Clause 12) shall have
7745  //   an exception-specification.
7746  ImplicitExceptionSpecification ExceptSpec(*this);
7747  if (ClassDecl->isInvalidDecl())
7748    return ExceptSpec;
7749
7750  // Direct base-class destructors.
7751  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7752                                       BEnd = ClassDecl->bases_end();
7753       B != BEnd; ++B) {
7754    if (B->isVirtual()) // Handled below.
7755      continue;
7756
7757    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7758      ExceptSpec.CalledDecl(B->getLocStart(),
7759                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7760  }
7761
7762  // Virtual base-class destructors.
7763  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7764                                       BEnd = ClassDecl->vbases_end();
7765       B != BEnd; ++B) {
7766    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7767      ExceptSpec.CalledDecl(B->getLocStart(),
7768                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7769  }
7770
7771  // Field destructors.
7772  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7773                               FEnd = ClassDecl->field_end();
7774       F != FEnd; ++F) {
7775    if (const RecordType *RecordTy
7776        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7777      ExceptSpec.CalledDecl(F->getLocation(),
7778                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7779  }
7780
7781  return ExceptSpec;
7782}
7783
7784CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7785  // C++ [class.dtor]p2:
7786  //   If a class has no user-declared destructor, a destructor is
7787  //   declared implicitly. An implicitly-declared destructor is an
7788  //   inline public member of its class.
7789  assert(ClassDecl->needsImplicitDestructor());
7790
7791  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
7792  if (DSM.isAlreadyBeingDeclared())
7793    return 0;
7794
7795  // Create the actual destructor declaration.
7796  CanQualType ClassType
7797    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7798  SourceLocation ClassLoc = ClassDecl->getLocation();
7799  DeclarationName Name
7800    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7801  DeclarationNameInfo NameInfo(Name, ClassLoc);
7802  CXXDestructorDecl *Destructor
7803      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7804                                  QualType(), 0, /*isInline=*/true,
7805                                  /*isImplicitlyDeclared=*/true);
7806  Destructor->setAccess(AS_public);
7807  Destructor->setDefaulted();
7808  Destructor->setImplicit();
7809
7810  // Build an exception specification pointing back at this destructor.
7811  FunctionProtoType::ExtProtoInfo EPI;
7812  EPI.ExceptionSpecType = EST_Unevaluated;
7813  EPI.ExceptionSpecDecl = Destructor;
7814  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7815
7816  AddOverriddenMethods(ClassDecl, Destructor);
7817
7818  // We don't need to use SpecialMemberIsTrivial here; triviality for
7819  // destructors is easy to compute.
7820  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7821
7822  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7823    Destructor->setDeletedAsWritten();
7824
7825  // Note that we have declared this destructor.
7826  ++ASTContext::NumImplicitDestructorsDeclared;
7827
7828  // Introduce this destructor into its scope.
7829  if (Scope *S = getScopeForContext(ClassDecl))
7830    PushOnScopeChains(Destructor, S, false);
7831  ClassDecl->addDecl(Destructor);
7832
7833  return Destructor;
7834}
7835
7836void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7837                                    CXXDestructorDecl *Destructor) {
7838  assert((Destructor->isDefaulted() &&
7839          !Destructor->doesThisDeclarationHaveABody() &&
7840          !Destructor->isDeleted()) &&
7841         "DefineImplicitDestructor - call it for implicit default dtor");
7842  CXXRecordDecl *ClassDecl = Destructor->getParent();
7843  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7844
7845  if (Destructor->isInvalidDecl())
7846    return;
7847
7848  SynthesizedFunctionScope Scope(*this, Destructor);
7849
7850  DiagnosticErrorTrap Trap(Diags);
7851  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7852                                         Destructor->getParent());
7853
7854  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7855    Diag(CurrentLocation, diag::note_member_synthesized_at)
7856      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7857
7858    Destructor->setInvalidDecl();
7859    return;
7860  }
7861
7862  SourceLocation Loc = Destructor->getLocation();
7863  Destructor->setBody(new (Context) CompoundStmt(Loc));
7864  Destructor->setImplicitlyDefined(true);
7865  Destructor->setUsed();
7866  MarkVTableUsed(CurrentLocation, ClassDecl);
7867
7868  if (ASTMutationListener *L = getASTMutationListener()) {
7869    L->CompletedImplicitDefinition(Destructor);
7870  }
7871}
7872
7873/// \brief Perform any semantic analysis which needs to be delayed until all
7874/// pending class member declarations have been parsed.
7875void Sema::ActOnFinishCXXMemberDecls() {
7876  // Perform any deferred checking of exception specifications for virtual
7877  // destructors.
7878  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7879       i != e; ++i) {
7880    const CXXDestructorDecl *Dtor =
7881        DelayedDestructorExceptionSpecChecks[i].first;
7882    assert(!Dtor->getParent()->isDependentType() &&
7883           "Should not ever add destructors of templates into the list.");
7884    CheckOverridingFunctionExceptionSpec(Dtor,
7885        DelayedDestructorExceptionSpecChecks[i].second);
7886  }
7887  DelayedDestructorExceptionSpecChecks.clear();
7888}
7889
7890void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7891                                         CXXDestructorDecl *Destructor) {
7892  assert(getLangOpts().CPlusPlus11 &&
7893         "adjusting dtor exception specs was introduced in c++11");
7894
7895  // C++11 [class.dtor]p3:
7896  //   A declaration of a destructor that does not have an exception-
7897  //   specification is implicitly considered to have the same exception-
7898  //   specification as an implicit declaration.
7899  const FunctionProtoType *DtorType = Destructor->getType()->
7900                                        getAs<FunctionProtoType>();
7901  if (DtorType->hasExceptionSpec())
7902    return;
7903
7904  // Replace the destructor's type, building off the existing one. Fortunately,
7905  // the only thing of interest in the destructor type is its extended info.
7906  // The return and arguments are fixed.
7907  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7908  EPI.ExceptionSpecType = EST_Unevaluated;
7909  EPI.ExceptionSpecDecl = Destructor;
7910  Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7911
7912  // FIXME: If the destructor has a body that could throw, and the newly created
7913  // spec doesn't allow exceptions, we should emit a warning, because this
7914  // change in behavior can break conforming C++03 programs at runtime.
7915  // However, we don't have a body or an exception specification yet, so it
7916  // needs to be done somewhere else.
7917}
7918
7919/// When generating a defaulted copy or move assignment operator, if a field
7920/// should be copied with __builtin_memcpy rather than via explicit assignments,
7921/// do so. This optimization only applies for arrays of scalars, and for arrays
7922/// of class type where the selected copy/move-assignment operator is trivial.
7923static StmtResult
7924buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
7925                           Expr *To, Expr *From) {
7926  // Compute the size of the memory buffer to be copied.
7927  QualType SizeType = S.Context.getSizeType();
7928  llvm::APInt Size(S.Context.getTypeSize(SizeType),
7929                   S.Context.getTypeSizeInChars(T).getQuantity());
7930
7931  // Take the address of the field references for "from" and "to". We
7932  // directly construct UnaryOperators here because semantic analysis
7933  // does not permit us to take the address of an xvalue.
7934  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
7935                         S.Context.getPointerType(From->getType()),
7936                         VK_RValue, OK_Ordinary, Loc);
7937  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
7938                       S.Context.getPointerType(To->getType()),
7939                       VK_RValue, OK_Ordinary, Loc);
7940
7941  const Type *E = T->getBaseElementTypeUnsafe();
7942  bool NeedsCollectableMemCpy =
7943    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
7944
7945  // Create a reference to the __builtin_objc_memmove_collectable function
7946  StringRef MemCpyName = NeedsCollectableMemCpy ?
7947    "__builtin_objc_memmove_collectable" :
7948    "__builtin_memcpy";
7949  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
7950                 Sema::LookupOrdinaryName);
7951  S.LookupName(R, S.TUScope, true);
7952
7953  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
7954  if (!MemCpy)
7955    // Something went horribly wrong earlier, and we will have complained
7956    // about it.
7957    return StmtError();
7958
7959  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
7960                                            VK_RValue, Loc, 0);
7961  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
7962
7963  Expr *CallArgs[] = {
7964    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
7965  };
7966  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
7967                                    Loc, CallArgs, Loc);
7968
7969  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7970  return S.Owned(Call.takeAs<Stmt>());
7971}
7972
7973/// \brief Builds a statement that copies/moves the given entity from \p From to
7974/// \c To.
7975///
7976/// This routine is used to copy/move the members of a class with an
7977/// implicitly-declared copy/move assignment operator. When the entities being
7978/// copied are arrays, this routine builds for loops to copy them.
7979///
7980/// \param S The Sema object used for type-checking.
7981///
7982/// \param Loc The location where the implicit copy/move is being generated.
7983///
7984/// \param T The type of the expressions being copied/moved. Both expressions
7985/// must have this type.
7986///
7987/// \param To The expression we are copying/moving to.
7988///
7989/// \param From The expression we are copying/moving from.
7990///
7991/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7992/// Otherwise, it's a non-static member subobject.
7993///
7994/// \param Copying Whether we're copying or moving.
7995///
7996/// \param Depth Internal parameter recording the depth of the recursion.
7997///
7998/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
7999/// if a memcpy should be used instead.
8000static StmtResult
8001buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8002                                 Expr *To, Expr *From,
8003                                 bool CopyingBaseSubobject, bool Copying,
8004                                 unsigned Depth = 0) {
8005  // C++11 [class.copy]p28:
8006  //   Each subobject is assigned in the manner appropriate to its type:
8007  //
8008  //     - if the subobject is of class type, as if by a call to operator= with
8009  //       the subobject as the object expression and the corresponding
8010  //       subobject of x as a single function argument (as if by explicit
8011  //       qualification; that is, ignoring any possible virtual overriding
8012  //       functions in more derived classes);
8013  //
8014  // C++03 [class.copy]p13:
8015  //     - if the subobject is of class type, the copy assignment operator for
8016  //       the class is used (as if by explicit qualification; that is,
8017  //       ignoring any possible virtual overriding functions in more derived
8018  //       classes);
8019  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8020    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8021
8022    // Look for operator=.
8023    DeclarationName Name
8024      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8025    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8026    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8027
8028    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8029    // operator.
8030    if (!S.getLangOpts().CPlusPlus11) {
8031      LookupResult::Filter F = OpLookup.makeFilter();
8032      while (F.hasNext()) {
8033        NamedDecl *D = F.next();
8034        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8035          if (Method->isCopyAssignmentOperator() ||
8036              (!Copying && Method->isMoveAssignmentOperator()))
8037            continue;
8038
8039        F.erase();
8040      }
8041      F.done();
8042    }
8043
8044    // Suppress the protected check (C++ [class.protected]) for each of the
8045    // assignment operators we found. This strange dance is required when
8046    // we're assigning via a base classes's copy-assignment operator. To
8047    // ensure that we're getting the right base class subobject (without
8048    // ambiguities), we need to cast "this" to that subobject type; to
8049    // ensure that we don't go through the virtual call mechanism, we need
8050    // to qualify the operator= name with the base class (see below). However,
8051    // this means that if the base class has a protected copy assignment
8052    // operator, the protected member access check will fail. So, we
8053    // rewrite "protected" access to "public" access in this case, since we
8054    // know by construction that we're calling from a derived class.
8055    if (CopyingBaseSubobject) {
8056      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8057           L != LEnd; ++L) {
8058        if (L.getAccess() == AS_protected)
8059          L.setAccess(AS_public);
8060      }
8061    }
8062
8063    // Create the nested-name-specifier that will be used to qualify the
8064    // reference to operator=; this is required to suppress the virtual
8065    // call mechanism.
8066    CXXScopeSpec SS;
8067    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8068    SS.MakeTrivial(S.Context,
8069                   NestedNameSpecifier::Create(S.Context, 0, false,
8070                                               CanonicalT),
8071                   Loc);
8072
8073    // Create the reference to operator=.
8074    ExprResult OpEqualRef
8075      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8076                                   /*TemplateKWLoc=*/SourceLocation(),
8077                                   /*FirstQualifierInScope=*/0,
8078                                   OpLookup,
8079                                   /*TemplateArgs=*/0,
8080                                   /*SuppressQualifierCheck=*/true);
8081    if (OpEqualRef.isInvalid())
8082      return StmtError();
8083
8084    // Build the call to the assignment operator.
8085
8086    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8087                                                  OpEqualRef.takeAs<Expr>(),
8088                                                  Loc, &From, 1, Loc);
8089    if (Call.isInvalid())
8090      return StmtError();
8091
8092    // If we built a call to a trivial 'operator=' while copying an array,
8093    // bail out. We'll replace the whole shebang with a memcpy.
8094    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8095    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8096      return StmtResult((Stmt*)0);
8097
8098    // Convert to an expression-statement, and clean up any produced
8099    // temporaries.
8100    return S.ActOnExprStmt(S.MakeFullExpr(Call.take(), Loc));
8101  }
8102
8103  //     - if the subobject is of scalar type, the built-in assignment
8104  //       operator is used.
8105  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8106  if (!ArrayTy) {
8107    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8108    if (Assignment.isInvalid())
8109      return StmtError();
8110    return S.ActOnExprStmt(S.MakeFullExpr(Assignment.take(), Loc));
8111  }
8112
8113  //     - if the subobject is an array, each element is assigned, in the
8114  //       manner appropriate to the element type;
8115
8116  // Construct a loop over the array bounds, e.g.,
8117  //
8118  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8119  //
8120  // that will copy each of the array elements.
8121  QualType SizeType = S.Context.getSizeType();
8122
8123  // Create the iteration variable.
8124  IdentifierInfo *IterationVarName = 0;
8125  {
8126    SmallString<8> Str;
8127    llvm::raw_svector_ostream OS(Str);
8128    OS << "__i" << Depth;
8129    IterationVarName = &S.Context.Idents.get(OS.str());
8130  }
8131  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8132                                          IterationVarName, SizeType,
8133                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8134                                          SC_None, SC_None);
8135
8136  // Initialize the iteration variable to zero.
8137  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8138  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8139
8140  // Create a reference to the iteration variable; we'll use this several
8141  // times throughout.
8142  Expr *IterationVarRef
8143    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8144  assert(IterationVarRef && "Reference to invented variable cannot fail!");
8145  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8146  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8147
8148  // Create the DeclStmt that holds the iteration variable.
8149  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8150
8151  // Subscript the "from" and "to" expressions with the iteration variable.
8152  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8153                                                         IterationVarRefRVal,
8154                                                         Loc));
8155  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8156                                                       IterationVarRefRVal,
8157                                                       Loc));
8158  if (!Copying) // Cast to rvalue
8159    From = CastForMoving(S, From);
8160
8161  // Build the copy/move for an individual element of the array.
8162  StmtResult Copy =
8163    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8164                                     To, From, CopyingBaseSubobject,
8165                                     Copying, Depth + 1);
8166  // Bail out if copying fails or if we determined that we should use memcpy.
8167  if (Copy.isInvalid() || !Copy.get())
8168    return Copy;
8169
8170  // Create the comparison against the array bound.
8171  llvm::APInt Upper
8172    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8173  Expr *Comparison
8174    = new (S.Context) BinaryOperator(IterationVarRefRVal,
8175                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8176                                     BO_NE, S.Context.BoolTy,
8177                                     VK_RValue, OK_Ordinary, Loc, false);
8178
8179  // Create the pre-increment of the iteration variable.
8180  Expr *Increment
8181    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8182                                    VK_LValue, OK_Ordinary, Loc);
8183
8184  // Construct the loop that copies all elements of this array.
8185  return S.ActOnForStmt(Loc, Loc, InitStmt,
8186                        S.MakeFullExpr(Comparison),
8187                        0, S.MakeFullExpr(Increment),
8188                        Loc, Copy.take());
8189}
8190
8191static StmtResult
8192buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8193                      Expr *To, Expr *From,
8194                      bool CopyingBaseSubobject, bool Copying) {
8195  // Maybe we should use a memcpy?
8196  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8197      T.isTriviallyCopyableType(S.Context))
8198    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8199
8200  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8201                                                     CopyingBaseSubobject,
8202                                                     Copying, 0));
8203
8204  // If we ended up picking a trivial assignment operator for an array of a
8205  // non-trivially-copyable class type, just emit a memcpy.
8206  if (!Result.isInvalid() && !Result.get())
8207    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8208
8209  return Result;
8210}
8211
8212Sema::ImplicitExceptionSpecification
8213Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8214  CXXRecordDecl *ClassDecl = MD->getParent();
8215
8216  ImplicitExceptionSpecification ExceptSpec(*this);
8217  if (ClassDecl->isInvalidDecl())
8218    return ExceptSpec;
8219
8220  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8221  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8222  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8223
8224  // C++ [except.spec]p14:
8225  //   An implicitly declared special member function (Clause 12) shall have an
8226  //   exception-specification. [...]
8227
8228  // It is unspecified whether or not an implicit copy assignment operator
8229  // attempts to deduplicate calls to assignment operators of virtual bases are
8230  // made. As such, this exception specification is effectively unspecified.
8231  // Based on a similar decision made for constness in C++0x, we're erring on
8232  // the side of assuming such calls to be made regardless of whether they
8233  // actually happen.
8234  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8235                                       BaseEnd = ClassDecl->bases_end();
8236       Base != BaseEnd; ++Base) {
8237    if (Base->isVirtual())
8238      continue;
8239
8240    CXXRecordDecl *BaseClassDecl
8241      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8242    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8243                                                            ArgQuals, false, 0))
8244      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8245  }
8246
8247  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8248                                       BaseEnd = ClassDecl->vbases_end();
8249       Base != BaseEnd; ++Base) {
8250    CXXRecordDecl *BaseClassDecl
8251      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8252    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8253                                                            ArgQuals, false, 0))
8254      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8255  }
8256
8257  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8258                                  FieldEnd = ClassDecl->field_end();
8259       Field != FieldEnd;
8260       ++Field) {
8261    QualType FieldType = Context.getBaseElementType(Field->getType());
8262    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8263      if (CXXMethodDecl *CopyAssign =
8264          LookupCopyingAssignment(FieldClassDecl,
8265                                  ArgQuals | FieldType.getCVRQualifiers(),
8266                                  false, 0))
8267        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8268    }
8269  }
8270
8271  return ExceptSpec;
8272}
8273
8274CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8275  // Note: The following rules are largely analoguous to the copy
8276  // constructor rules. Note that virtual bases are not taken into account
8277  // for determining the argument type of the operator. Note also that
8278  // operators taking an object instead of a reference are allowed.
8279  assert(ClassDecl->needsImplicitCopyAssignment());
8280
8281  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8282  if (DSM.isAlreadyBeingDeclared())
8283    return 0;
8284
8285  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8286  QualType RetType = Context.getLValueReferenceType(ArgType);
8287  if (ClassDecl->implicitCopyAssignmentHasConstParam())
8288    ArgType = ArgType.withConst();
8289  ArgType = Context.getLValueReferenceType(ArgType);
8290
8291  //   An implicitly-declared copy assignment operator is an inline public
8292  //   member of its class.
8293  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8294  SourceLocation ClassLoc = ClassDecl->getLocation();
8295  DeclarationNameInfo NameInfo(Name, ClassLoc);
8296  CXXMethodDecl *CopyAssignment
8297    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8298                            /*TInfo=*/0, /*isStatic=*/false,
8299                            /*StorageClassAsWritten=*/SC_None,
8300                            /*isInline=*/true, /*isConstexpr=*/false,
8301                            SourceLocation());
8302  CopyAssignment->setAccess(AS_public);
8303  CopyAssignment->setDefaulted();
8304  CopyAssignment->setImplicit();
8305
8306  // Build an exception specification pointing back at this member.
8307  FunctionProtoType::ExtProtoInfo EPI;
8308  EPI.ExceptionSpecType = EST_Unevaluated;
8309  EPI.ExceptionSpecDecl = CopyAssignment;
8310  CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8311
8312  // Add the parameter to the operator.
8313  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8314                                               ClassLoc, ClassLoc, /*Id=*/0,
8315                                               ArgType, /*TInfo=*/0,
8316                                               SC_None,
8317                                               SC_None, 0);
8318  CopyAssignment->setParams(FromParam);
8319
8320  AddOverriddenMethods(ClassDecl, CopyAssignment);
8321
8322  CopyAssignment->setTrivial(
8323    ClassDecl->needsOverloadResolutionForCopyAssignment()
8324      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8325      : ClassDecl->hasTrivialCopyAssignment());
8326
8327  // C++0x [class.copy]p19:
8328  //   ....  If the class definition does not explicitly declare a copy
8329  //   assignment operator, there is no user-declared move constructor, and
8330  //   there is no user-declared move assignment operator, a copy assignment
8331  //   operator is implicitly declared as defaulted.
8332  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8333    CopyAssignment->setDeletedAsWritten();
8334
8335  // Note that we have added this copy-assignment operator.
8336  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8337
8338  if (Scope *S = getScopeForContext(ClassDecl))
8339    PushOnScopeChains(CopyAssignment, S, false);
8340  ClassDecl->addDecl(CopyAssignment);
8341
8342  return CopyAssignment;
8343}
8344
8345void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8346                                        CXXMethodDecl *CopyAssignOperator) {
8347  assert((CopyAssignOperator->isDefaulted() &&
8348          CopyAssignOperator->isOverloadedOperator() &&
8349          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8350          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8351          !CopyAssignOperator->isDeleted()) &&
8352         "DefineImplicitCopyAssignment called for wrong function");
8353
8354  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8355
8356  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8357    CopyAssignOperator->setInvalidDecl();
8358    return;
8359  }
8360
8361  CopyAssignOperator->setUsed();
8362
8363  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8364  DiagnosticErrorTrap Trap(Diags);
8365
8366  // C++0x [class.copy]p30:
8367  //   The implicitly-defined or explicitly-defaulted copy assignment operator
8368  //   for a non-union class X performs memberwise copy assignment of its
8369  //   subobjects. The direct base classes of X are assigned first, in the
8370  //   order of their declaration in the base-specifier-list, and then the
8371  //   immediate non-static data members of X are assigned, in the order in
8372  //   which they were declared in the class definition.
8373
8374  // The statements that form the synthesized function body.
8375  SmallVector<Stmt*, 8> Statements;
8376
8377  // The parameter for the "other" object, which we are copying from.
8378  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8379  Qualifiers OtherQuals = Other->getType().getQualifiers();
8380  QualType OtherRefType = Other->getType();
8381  if (const LValueReferenceType *OtherRef
8382                                = OtherRefType->getAs<LValueReferenceType>()) {
8383    OtherRefType = OtherRef->getPointeeType();
8384    OtherQuals = OtherRefType.getQualifiers();
8385  }
8386
8387  // Our location for everything implicitly-generated.
8388  SourceLocation Loc = CopyAssignOperator->getLocation();
8389
8390  // Construct a reference to the "other" object. We'll be using this
8391  // throughout the generated ASTs.
8392  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8393  assert(OtherRef && "Reference to parameter cannot fail!");
8394
8395  // Construct the "this" pointer. We'll be using this throughout the generated
8396  // ASTs.
8397  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8398  assert(This && "Reference to this cannot fail!");
8399
8400  // Assign base classes.
8401  bool Invalid = false;
8402  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8403       E = ClassDecl->bases_end(); Base != E; ++Base) {
8404    // Form the assignment:
8405    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8406    QualType BaseType = Base->getType().getUnqualifiedType();
8407    if (!BaseType->isRecordType()) {
8408      Invalid = true;
8409      continue;
8410    }
8411
8412    CXXCastPath BasePath;
8413    BasePath.push_back(Base);
8414
8415    // Construct the "from" expression, which is an implicit cast to the
8416    // appropriately-qualified base type.
8417    Expr *From = OtherRef;
8418    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8419                             CK_UncheckedDerivedToBase,
8420                             VK_LValue, &BasePath).take();
8421
8422    // Dereference "this".
8423    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8424
8425    // Implicitly cast "this" to the appropriately-qualified base type.
8426    To = ImpCastExprToType(To.take(),
8427                           Context.getCVRQualifiedType(BaseType,
8428                                     CopyAssignOperator->getTypeQualifiers()),
8429                           CK_UncheckedDerivedToBase,
8430                           VK_LValue, &BasePath);
8431
8432    // Build the copy.
8433    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8434                                            To.get(), From,
8435                                            /*CopyingBaseSubobject=*/true,
8436                                            /*Copying=*/true);
8437    if (Copy.isInvalid()) {
8438      Diag(CurrentLocation, diag::note_member_synthesized_at)
8439        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8440      CopyAssignOperator->setInvalidDecl();
8441      return;
8442    }
8443
8444    // Success! Record the copy.
8445    Statements.push_back(Copy.takeAs<Expr>());
8446  }
8447
8448  // Assign non-static members.
8449  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8450                                  FieldEnd = ClassDecl->field_end();
8451       Field != FieldEnd; ++Field) {
8452    if (Field->isUnnamedBitfield())
8453      continue;
8454
8455    // Check for members of reference type; we can't copy those.
8456    if (Field->getType()->isReferenceType()) {
8457      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8458        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8459      Diag(Field->getLocation(), diag::note_declared_at);
8460      Diag(CurrentLocation, diag::note_member_synthesized_at)
8461        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8462      Invalid = true;
8463      continue;
8464    }
8465
8466    // Check for members of const-qualified, non-class type.
8467    QualType BaseType = Context.getBaseElementType(Field->getType());
8468    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8469      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8470        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8471      Diag(Field->getLocation(), diag::note_declared_at);
8472      Diag(CurrentLocation, diag::note_member_synthesized_at)
8473        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8474      Invalid = true;
8475      continue;
8476    }
8477
8478    // Suppress assigning zero-width bitfields.
8479    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8480      continue;
8481
8482    QualType FieldType = Field->getType().getNonReferenceType();
8483    if (FieldType->isIncompleteArrayType()) {
8484      assert(ClassDecl->hasFlexibleArrayMember() &&
8485             "Incomplete array type is not valid");
8486      continue;
8487    }
8488
8489    // Build references to the field in the object we're copying from and to.
8490    CXXScopeSpec SS; // Intentionally empty
8491    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8492                              LookupMemberName);
8493    MemberLookup.addDecl(*Field);
8494    MemberLookup.resolveKind();
8495    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8496                                               Loc, /*IsArrow=*/false,
8497                                               SS, SourceLocation(), 0,
8498                                               MemberLookup, 0);
8499    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8500                                             Loc, /*IsArrow=*/true,
8501                                             SS, SourceLocation(), 0,
8502                                             MemberLookup, 0);
8503    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8504    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8505
8506    // Build the copy of this field.
8507    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8508                                            To.get(), From.get(),
8509                                            /*CopyingBaseSubobject=*/false,
8510                                            /*Copying=*/true);
8511    if (Copy.isInvalid()) {
8512      Diag(CurrentLocation, diag::note_member_synthesized_at)
8513        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8514      CopyAssignOperator->setInvalidDecl();
8515      return;
8516    }
8517
8518    // Success! Record the copy.
8519    Statements.push_back(Copy.takeAs<Stmt>());
8520  }
8521
8522  if (!Invalid) {
8523    // Add a "return *this;"
8524    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8525
8526    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8527    if (Return.isInvalid())
8528      Invalid = true;
8529    else {
8530      Statements.push_back(Return.takeAs<Stmt>());
8531
8532      if (Trap.hasErrorOccurred()) {
8533        Diag(CurrentLocation, diag::note_member_synthesized_at)
8534          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8535        Invalid = true;
8536      }
8537    }
8538  }
8539
8540  if (Invalid) {
8541    CopyAssignOperator->setInvalidDecl();
8542    return;
8543  }
8544
8545  StmtResult Body;
8546  {
8547    CompoundScopeRAII CompoundScope(*this);
8548    Body = ActOnCompoundStmt(Loc, Loc, Statements,
8549                             /*isStmtExpr=*/false);
8550    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8551  }
8552  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8553
8554  if (ASTMutationListener *L = getASTMutationListener()) {
8555    L->CompletedImplicitDefinition(CopyAssignOperator);
8556  }
8557}
8558
8559Sema::ImplicitExceptionSpecification
8560Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
8561  CXXRecordDecl *ClassDecl = MD->getParent();
8562
8563  ImplicitExceptionSpecification ExceptSpec(*this);
8564  if (ClassDecl->isInvalidDecl())
8565    return ExceptSpec;
8566
8567  // C++0x [except.spec]p14:
8568  //   An implicitly declared special member function (Clause 12) shall have an
8569  //   exception-specification. [...]
8570
8571  // It is unspecified whether or not an implicit move assignment operator
8572  // attempts to deduplicate calls to assignment operators of virtual bases are
8573  // made. As such, this exception specification is effectively unspecified.
8574  // Based on a similar decision made for constness in C++0x, we're erring on
8575  // the side of assuming such calls to be made regardless of whether they
8576  // actually happen.
8577  // Note that a move constructor is not implicitly declared when there are
8578  // virtual bases, but it can still be user-declared and explicitly defaulted.
8579  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8580                                       BaseEnd = ClassDecl->bases_end();
8581       Base != BaseEnd; ++Base) {
8582    if (Base->isVirtual())
8583      continue;
8584
8585    CXXRecordDecl *BaseClassDecl
8586      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8587    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8588                                                           0, false, 0))
8589      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8590  }
8591
8592  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8593                                       BaseEnd = ClassDecl->vbases_end();
8594       Base != BaseEnd; ++Base) {
8595    CXXRecordDecl *BaseClassDecl
8596      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8597    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8598                                                           0, false, 0))
8599      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
8600  }
8601
8602  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8603                                  FieldEnd = ClassDecl->field_end();
8604       Field != FieldEnd;
8605       ++Field) {
8606    QualType FieldType = Context.getBaseElementType(Field->getType());
8607    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8608      if (CXXMethodDecl *MoveAssign =
8609              LookupMovingAssignment(FieldClassDecl,
8610                                     FieldType.getCVRQualifiers(),
8611                                     false, 0))
8612        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
8613    }
8614  }
8615
8616  return ExceptSpec;
8617}
8618
8619/// Determine whether the class type has any direct or indirect virtual base
8620/// classes which have a non-trivial move assignment operator.
8621static bool
8622hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8623  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8624                                          BaseEnd = ClassDecl->vbases_end();
8625       Base != BaseEnd; ++Base) {
8626    CXXRecordDecl *BaseClass =
8627        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8628
8629    // Try to declare the move assignment. If it would be deleted, then the
8630    // class does not have a non-trivial move assignment.
8631    if (BaseClass->needsImplicitMoveAssignment())
8632      S.DeclareImplicitMoveAssignment(BaseClass);
8633
8634    if (BaseClass->hasNonTrivialMoveAssignment())
8635      return true;
8636  }
8637
8638  return false;
8639}
8640
8641/// Determine whether the given type either has a move constructor or is
8642/// trivially copyable.
8643static bool
8644hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8645  Type = S.Context.getBaseElementType(Type);
8646
8647  // FIXME: Technically, non-trivially-copyable non-class types, such as
8648  // reference types, are supposed to return false here, but that appears
8649  // to be a standard defect.
8650  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8651  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
8652    return true;
8653
8654  if (Type.isTriviallyCopyableType(S.Context))
8655    return true;
8656
8657  if (IsConstructor) {
8658    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
8659    // give the right answer.
8660    if (ClassDecl->needsImplicitMoveConstructor())
8661      S.DeclareImplicitMoveConstructor(ClassDecl);
8662    return ClassDecl->hasMoveConstructor();
8663  }
8664
8665  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
8666  // give the right answer.
8667  if (ClassDecl->needsImplicitMoveAssignment())
8668    S.DeclareImplicitMoveAssignment(ClassDecl);
8669  return ClassDecl->hasMoveAssignment();
8670}
8671
8672/// Determine whether all non-static data members and direct or virtual bases
8673/// of class \p ClassDecl have either a move operation, or are trivially
8674/// copyable.
8675static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8676                                            bool IsConstructor) {
8677  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8678                                          BaseEnd = ClassDecl->bases_end();
8679       Base != BaseEnd; ++Base) {
8680    if (Base->isVirtual())
8681      continue;
8682
8683    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8684      return false;
8685  }
8686
8687  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8688                                          BaseEnd = ClassDecl->vbases_end();
8689       Base != BaseEnd; ++Base) {
8690    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8691      return false;
8692  }
8693
8694  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8695                                     FieldEnd = ClassDecl->field_end();
8696       Field != FieldEnd; ++Field) {
8697    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8698      return false;
8699  }
8700
8701  return true;
8702}
8703
8704CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8705  // C++11 [class.copy]p20:
8706  //   If the definition of a class X does not explicitly declare a move
8707  //   assignment operator, one will be implicitly declared as defaulted
8708  //   if and only if:
8709  //
8710  //   - [first 4 bullets]
8711  assert(ClassDecl->needsImplicitMoveAssignment());
8712
8713  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
8714  if (DSM.isAlreadyBeingDeclared())
8715    return 0;
8716
8717  // [Checked after we build the declaration]
8718  //   - the move assignment operator would not be implicitly defined as
8719  //     deleted,
8720
8721  // [DR1402]:
8722  //   - X has no direct or indirect virtual base class with a non-trivial
8723  //     move assignment operator, and
8724  //   - each of X's non-static data members and direct or virtual base classes
8725  //     has a type that either has a move assignment operator or is trivially
8726  //     copyable.
8727  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8728      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8729    ClassDecl->setFailedImplicitMoveAssignment();
8730    return 0;
8731  }
8732
8733  // Note: The following rules are largely analoguous to the move
8734  // constructor rules.
8735
8736  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8737  QualType RetType = Context.getLValueReferenceType(ArgType);
8738  ArgType = Context.getRValueReferenceType(ArgType);
8739
8740  //   An implicitly-declared move assignment operator is an inline public
8741  //   member of its class.
8742  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8743  SourceLocation ClassLoc = ClassDecl->getLocation();
8744  DeclarationNameInfo NameInfo(Name, ClassLoc);
8745  CXXMethodDecl *MoveAssignment
8746    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8747                            /*TInfo=*/0, /*isStatic=*/false,
8748                            /*StorageClassAsWritten=*/SC_None,
8749                            /*isInline=*/true,
8750                            /*isConstexpr=*/false,
8751                            SourceLocation());
8752  MoveAssignment->setAccess(AS_public);
8753  MoveAssignment->setDefaulted();
8754  MoveAssignment->setImplicit();
8755
8756  // Build an exception specification pointing back at this member.
8757  FunctionProtoType::ExtProtoInfo EPI;
8758  EPI.ExceptionSpecType = EST_Unevaluated;
8759  EPI.ExceptionSpecDecl = MoveAssignment;
8760  MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8761
8762  // Add the parameter to the operator.
8763  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8764                                               ClassLoc, ClassLoc, /*Id=*/0,
8765                                               ArgType, /*TInfo=*/0,
8766                                               SC_None,
8767                                               SC_None, 0);
8768  MoveAssignment->setParams(FromParam);
8769
8770  AddOverriddenMethods(ClassDecl, MoveAssignment);
8771
8772  MoveAssignment->setTrivial(
8773    ClassDecl->needsOverloadResolutionForMoveAssignment()
8774      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
8775      : ClassDecl->hasTrivialMoveAssignment());
8776
8777  // C++0x [class.copy]p9:
8778  //   If the definition of a class X does not explicitly declare a move
8779  //   assignment operator, one will be implicitly declared as defaulted if and
8780  //   only if:
8781  //   [...]
8782  //   - the move assignment operator would not be implicitly defined as
8783  //     deleted.
8784  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8785    // Cache this result so that we don't try to generate this over and over
8786    // on every lookup, leaking memory and wasting time.
8787    ClassDecl->setFailedImplicitMoveAssignment();
8788    return 0;
8789  }
8790
8791  // Note that we have added this copy-assignment operator.
8792  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8793
8794  if (Scope *S = getScopeForContext(ClassDecl))
8795    PushOnScopeChains(MoveAssignment, S, false);
8796  ClassDecl->addDecl(MoveAssignment);
8797
8798  return MoveAssignment;
8799}
8800
8801void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8802                                        CXXMethodDecl *MoveAssignOperator) {
8803  assert((MoveAssignOperator->isDefaulted() &&
8804          MoveAssignOperator->isOverloadedOperator() &&
8805          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8806          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8807          !MoveAssignOperator->isDeleted()) &&
8808         "DefineImplicitMoveAssignment called for wrong function");
8809
8810  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8811
8812  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8813    MoveAssignOperator->setInvalidDecl();
8814    return;
8815  }
8816
8817  MoveAssignOperator->setUsed();
8818
8819  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
8820  DiagnosticErrorTrap Trap(Diags);
8821
8822  // C++0x [class.copy]p28:
8823  //   The implicitly-defined or move assignment operator for a non-union class
8824  //   X performs memberwise move assignment of its subobjects. The direct base
8825  //   classes of X are assigned first, in the order of their declaration in the
8826  //   base-specifier-list, and then the immediate non-static data members of X
8827  //   are assigned, in the order in which they were declared in the class
8828  //   definition.
8829
8830  // The statements that form the synthesized function body.
8831  SmallVector<Stmt*, 8> Statements;
8832
8833  // The parameter for the "other" object, which we are move from.
8834  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8835  QualType OtherRefType = Other->getType()->
8836      getAs<RValueReferenceType>()->getPointeeType();
8837  assert(OtherRefType.getQualifiers() == 0 &&
8838         "Bad argument type of defaulted move assignment");
8839
8840  // Our location for everything implicitly-generated.
8841  SourceLocation Loc = MoveAssignOperator->getLocation();
8842
8843  // Construct a reference to the "other" object. We'll be using this
8844  // throughout the generated ASTs.
8845  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8846  assert(OtherRef && "Reference to parameter cannot fail!");
8847  // Cast to rvalue.
8848  OtherRef = CastForMoving(*this, OtherRef);
8849
8850  // Construct the "this" pointer. We'll be using this throughout the generated
8851  // ASTs.
8852  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8853  assert(This && "Reference to this cannot fail!");
8854
8855  // Assign base classes.
8856  bool Invalid = false;
8857  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8858       E = ClassDecl->bases_end(); Base != E; ++Base) {
8859    // Form the assignment:
8860    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8861    QualType BaseType = Base->getType().getUnqualifiedType();
8862    if (!BaseType->isRecordType()) {
8863      Invalid = true;
8864      continue;
8865    }
8866
8867    CXXCastPath BasePath;
8868    BasePath.push_back(Base);
8869
8870    // Construct the "from" expression, which is an implicit cast to the
8871    // appropriately-qualified base type.
8872    Expr *From = OtherRef;
8873    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8874                             VK_XValue, &BasePath).take();
8875
8876    // Dereference "this".
8877    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8878
8879    // Implicitly cast "this" to the appropriately-qualified base type.
8880    To = ImpCastExprToType(To.take(),
8881                           Context.getCVRQualifiedType(BaseType,
8882                                     MoveAssignOperator->getTypeQualifiers()),
8883                           CK_UncheckedDerivedToBase,
8884                           VK_LValue, &BasePath);
8885
8886    // Build the move.
8887    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
8888                                            To.get(), From,
8889                                            /*CopyingBaseSubobject=*/true,
8890                                            /*Copying=*/false);
8891    if (Move.isInvalid()) {
8892      Diag(CurrentLocation, diag::note_member_synthesized_at)
8893        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8894      MoveAssignOperator->setInvalidDecl();
8895      return;
8896    }
8897
8898    // Success! Record the move.
8899    Statements.push_back(Move.takeAs<Expr>());
8900  }
8901
8902  // Assign non-static members.
8903  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8904                                  FieldEnd = ClassDecl->field_end();
8905       Field != FieldEnd; ++Field) {
8906    if (Field->isUnnamedBitfield())
8907      continue;
8908
8909    // Check for members of reference type; we can't move those.
8910    if (Field->getType()->isReferenceType()) {
8911      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8912        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8913      Diag(Field->getLocation(), diag::note_declared_at);
8914      Diag(CurrentLocation, diag::note_member_synthesized_at)
8915        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8916      Invalid = true;
8917      continue;
8918    }
8919
8920    // Check for members of const-qualified, non-class type.
8921    QualType BaseType = Context.getBaseElementType(Field->getType());
8922    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8923      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8924        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8925      Diag(Field->getLocation(), diag::note_declared_at);
8926      Diag(CurrentLocation, diag::note_member_synthesized_at)
8927        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8928      Invalid = true;
8929      continue;
8930    }
8931
8932    // Suppress assigning zero-width bitfields.
8933    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8934      continue;
8935
8936    QualType FieldType = Field->getType().getNonReferenceType();
8937    if (FieldType->isIncompleteArrayType()) {
8938      assert(ClassDecl->hasFlexibleArrayMember() &&
8939             "Incomplete array type is not valid");
8940      continue;
8941    }
8942
8943    // Build references to the field in the object we're copying from and to.
8944    CXXScopeSpec SS; // Intentionally empty
8945    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8946                              LookupMemberName);
8947    MemberLookup.addDecl(*Field);
8948    MemberLookup.resolveKind();
8949    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8950                                               Loc, /*IsArrow=*/false,
8951                                               SS, SourceLocation(), 0,
8952                                               MemberLookup, 0);
8953    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8954                                             Loc, /*IsArrow=*/true,
8955                                             SS, SourceLocation(), 0,
8956                                             MemberLookup, 0);
8957    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8958    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8959
8960    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8961        "Member reference with rvalue base must be rvalue except for reference "
8962        "members, which aren't allowed for move assignment.");
8963
8964    // Build the move of this field.
8965    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
8966                                            To.get(), From.get(),
8967                                            /*CopyingBaseSubobject=*/false,
8968                                            /*Copying=*/false);
8969    if (Move.isInvalid()) {
8970      Diag(CurrentLocation, diag::note_member_synthesized_at)
8971        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8972      MoveAssignOperator->setInvalidDecl();
8973      return;
8974    }
8975
8976    // Success! Record the copy.
8977    Statements.push_back(Move.takeAs<Stmt>());
8978  }
8979
8980  if (!Invalid) {
8981    // Add a "return *this;"
8982    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8983
8984    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8985    if (Return.isInvalid())
8986      Invalid = true;
8987    else {
8988      Statements.push_back(Return.takeAs<Stmt>());
8989
8990      if (Trap.hasErrorOccurred()) {
8991        Diag(CurrentLocation, diag::note_member_synthesized_at)
8992          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8993        Invalid = true;
8994      }
8995    }
8996  }
8997
8998  if (Invalid) {
8999    MoveAssignOperator->setInvalidDecl();
9000    return;
9001  }
9002
9003  StmtResult Body;
9004  {
9005    CompoundScopeRAII CompoundScope(*this);
9006    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9007                             /*isStmtExpr=*/false);
9008    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9009  }
9010  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9011
9012  if (ASTMutationListener *L = getASTMutationListener()) {
9013    L->CompletedImplicitDefinition(MoveAssignOperator);
9014  }
9015}
9016
9017Sema::ImplicitExceptionSpecification
9018Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9019  CXXRecordDecl *ClassDecl = MD->getParent();
9020
9021  ImplicitExceptionSpecification ExceptSpec(*this);
9022  if (ClassDecl->isInvalidDecl())
9023    return ExceptSpec;
9024
9025  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9026  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9027  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9028
9029  // C++ [except.spec]p14:
9030  //   An implicitly declared special member function (Clause 12) shall have an
9031  //   exception-specification. [...]
9032  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9033                                       BaseEnd = ClassDecl->bases_end();
9034       Base != BaseEnd;
9035       ++Base) {
9036    // Virtual bases are handled below.
9037    if (Base->isVirtual())
9038      continue;
9039
9040    CXXRecordDecl *BaseClassDecl
9041      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9042    if (CXXConstructorDecl *CopyConstructor =
9043          LookupCopyingConstructor(BaseClassDecl, Quals))
9044      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9045  }
9046  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9047                                       BaseEnd = ClassDecl->vbases_end();
9048       Base != BaseEnd;
9049       ++Base) {
9050    CXXRecordDecl *BaseClassDecl
9051      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9052    if (CXXConstructorDecl *CopyConstructor =
9053          LookupCopyingConstructor(BaseClassDecl, Quals))
9054      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9055  }
9056  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9057                                  FieldEnd = ClassDecl->field_end();
9058       Field != FieldEnd;
9059       ++Field) {
9060    QualType FieldType = Context.getBaseElementType(Field->getType());
9061    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9062      if (CXXConstructorDecl *CopyConstructor =
9063              LookupCopyingConstructor(FieldClassDecl,
9064                                       Quals | FieldType.getCVRQualifiers()))
9065      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9066    }
9067  }
9068
9069  return ExceptSpec;
9070}
9071
9072CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9073                                                    CXXRecordDecl *ClassDecl) {
9074  // C++ [class.copy]p4:
9075  //   If the class definition does not explicitly declare a copy
9076  //   constructor, one is declared implicitly.
9077  assert(ClassDecl->needsImplicitCopyConstructor());
9078
9079  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9080  if (DSM.isAlreadyBeingDeclared())
9081    return 0;
9082
9083  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9084  QualType ArgType = ClassType;
9085  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9086  if (Const)
9087    ArgType = ArgType.withConst();
9088  ArgType = Context.getLValueReferenceType(ArgType);
9089
9090  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9091                                                     CXXCopyConstructor,
9092                                                     Const);
9093
9094  DeclarationName Name
9095    = Context.DeclarationNames.getCXXConstructorName(
9096                                           Context.getCanonicalType(ClassType));
9097  SourceLocation ClassLoc = ClassDecl->getLocation();
9098  DeclarationNameInfo NameInfo(Name, ClassLoc);
9099
9100  //   An implicitly-declared copy constructor is an inline public
9101  //   member of its class.
9102  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9103      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9104      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9105      Constexpr);
9106  CopyConstructor->setAccess(AS_public);
9107  CopyConstructor->setDefaulted();
9108
9109  // Build an exception specification pointing back at this member.
9110  FunctionProtoType::ExtProtoInfo EPI;
9111  EPI.ExceptionSpecType = EST_Unevaluated;
9112  EPI.ExceptionSpecDecl = CopyConstructor;
9113  CopyConstructor->setType(
9114      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9115
9116  // Add the parameter to the constructor.
9117  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9118                                               ClassLoc, ClassLoc,
9119                                               /*IdentifierInfo=*/0,
9120                                               ArgType, /*TInfo=*/0,
9121                                               SC_None,
9122                                               SC_None, 0);
9123  CopyConstructor->setParams(FromParam);
9124
9125  CopyConstructor->setTrivial(
9126    ClassDecl->needsOverloadResolutionForCopyConstructor()
9127      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9128      : ClassDecl->hasTrivialCopyConstructor());
9129
9130  // C++11 [class.copy]p8:
9131  //   ... If the class definition does not explicitly declare a copy
9132  //   constructor, there is no user-declared move constructor, and there is no
9133  //   user-declared move assignment operator, a copy constructor is implicitly
9134  //   declared as defaulted.
9135  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9136    CopyConstructor->setDeletedAsWritten();
9137
9138  // Note that we have declared this constructor.
9139  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9140
9141  if (Scope *S = getScopeForContext(ClassDecl))
9142    PushOnScopeChains(CopyConstructor, S, false);
9143  ClassDecl->addDecl(CopyConstructor);
9144
9145  return CopyConstructor;
9146}
9147
9148void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9149                                   CXXConstructorDecl *CopyConstructor) {
9150  assert((CopyConstructor->isDefaulted() &&
9151          CopyConstructor->isCopyConstructor() &&
9152          !CopyConstructor->doesThisDeclarationHaveABody() &&
9153          !CopyConstructor->isDeleted()) &&
9154         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9155
9156  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9157  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9158
9159  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9160  DiagnosticErrorTrap Trap(Diags);
9161
9162  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
9163      Trap.hasErrorOccurred()) {
9164    Diag(CurrentLocation, diag::note_member_synthesized_at)
9165      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9166    CopyConstructor->setInvalidDecl();
9167  }  else {
9168    Sema::CompoundScopeRAII CompoundScope(*this);
9169    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9170                                               CopyConstructor->getLocation(),
9171                                               MultiStmtArg(),
9172                                               /*isStmtExpr=*/false)
9173                                                              .takeAs<Stmt>());
9174    CopyConstructor->setImplicitlyDefined(true);
9175  }
9176
9177  CopyConstructor->setUsed();
9178  if (ASTMutationListener *L = getASTMutationListener()) {
9179    L->CompletedImplicitDefinition(CopyConstructor);
9180  }
9181}
9182
9183Sema::ImplicitExceptionSpecification
9184Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9185  CXXRecordDecl *ClassDecl = MD->getParent();
9186
9187  // C++ [except.spec]p14:
9188  //   An implicitly declared special member function (Clause 12) shall have an
9189  //   exception-specification. [...]
9190  ImplicitExceptionSpecification ExceptSpec(*this);
9191  if (ClassDecl->isInvalidDecl())
9192    return ExceptSpec;
9193
9194  // Direct base-class constructors.
9195  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9196                                       BEnd = ClassDecl->bases_end();
9197       B != BEnd; ++B) {
9198    if (B->isVirtual()) // Handled below.
9199      continue;
9200
9201    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9202      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9203      CXXConstructorDecl *Constructor =
9204          LookupMovingConstructor(BaseClassDecl, 0);
9205      // If this is a deleted function, add it anyway. This might be conformant
9206      // with the standard. This might not. I'm not sure. It might not matter.
9207      if (Constructor)
9208        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9209    }
9210  }
9211
9212  // Virtual base-class constructors.
9213  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9214                                       BEnd = ClassDecl->vbases_end();
9215       B != BEnd; ++B) {
9216    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9217      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9218      CXXConstructorDecl *Constructor =
9219          LookupMovingConstructor(BaseClassDecl, 0);
9220      // If this is a deleted function, add it anyway. This might be conformant
9221      // with the standard. This might not. I'm not sure. It might not matter.
9222      if (Constructor)
9223        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9224    }
9225  }
9226
9227  // Field constructors.
9228  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9229                               FEnd = ClassDecl->field_end();
9230       F != FEnd; ++F) {
9231    QualType FieldType = Context.getBaseElementType(F->getType());
9232    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9233      CXXConstructorDecl *Constructor =
9234          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9235      // If this is a deleted function, add it anyway. This might be conformant
9236      // with the standard. This might not. I'm not sure. It might not matter.
9237      // In particular, the problem is that this function never gets called. It
9238      // might just be ill-formed because this function attempts to refer to
9239      // a deleted function here.
9240      if (Constructor)
9241        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9242    }
9243  }
9244
9245  return ExceptSpec;
9246}
9247
9248CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9249                                                    CXXRecordDecl *ClassDecl) {
9250  // C++11 [class.copy]p9:
9251  //   If the definition of a class X does not explicitly declare a move
9252  //   constructor, one will be implicitly declared as defaulted if and only if:
9253  //
9254  //   - [first 4 bullets]
9255  assert(ClassDecl->needsImplicitMoveConstructor());
9256
9257  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9258  if (DSM.isAlreadyBeingDeclared())
9259    return 0;
9260
9261  // [Checked after we build the declaration]
9262  //   - the move assignment operator would not be implicitly defined as
9263  //     deleted,
9264
9265  // [DR1402]:
9266  //   - each of X's non-static data members and direct or virtual base classes
9267  //     has a type that either has a move constructor or is trivially copyable.
9268  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9269    ClassDecl->setFailedImplicitMoveConstructor();
9270    return 0;
9271  }
9272
9273  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9274  QualType ArgType = Context.getRValueReferenceType(ClassType);
9275
9276  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9277                                                     CXXMoveConstructor,
9278                                                     false);
9279
9280  DeclarationName Name
9281    = Context.DeclarationNames.getCXXConstructorName(
9282                                           Context.getCanonicalType(ClassType));
9283  SourceLocation ClassLoc = ClassDecl->getLocation();
9284  DeclarationNameInfo NameInfo(Name, ClassLoc);
9285
9286  // C++0x [class.copy]p11:
9287  //   An implicitly-declared copy/move constructor is an inline public
9288  //   member of its class.
9289  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9290      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9291      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9292      Constexpr);
9293  MoveConstructor->setAccess(AS_public);
9294  MoveConstructor->setDefaulted();
9295
9296  // Build an exception specification pointing back at this member.
9297  FunctionProtoType::ExtProtoInfo EPI;
9298  EPI.ExceptionSpecType = EST_Unevaluated;
9299  EPI.ExceptionSpecDecl = MoveConstructor;
9300  MoveConstructor->setType(
9301      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
9302
9303  // Add the parameter to the constructor.
9304  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9305                                               ClassLoc, ClassLoc,
9306                                               /*IdentifierInfo=*/0,
9307                                               ArgType, /*TInfo=*/0,
9308                                               SC_None,
9309                                               SC_None, 0);
9310  MoveConstructor->setParams(FromParam);
9311
9312  MoveConstructor->setTrivial(
9313    ClassDecl->needsOverloadResolutionForMoveConstructor()
9314      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9315      : ClassDecl->hasTrivialMoveConstructor());
9316
9317  // C++0x [class.copy]p9:
9318  //   If the definition of a class X does not explicitly declare a move
9319  //   constructor, one will be implicitly declared as defaulted if and only if:
9320  //   [...]
9321  //   - the move constructor would not be implicitly defined as deleted.
9322  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9323    // Cache this result so that we don't try to generate this over and over
9324    // on every lookup, leaking memory and wasting time.
9325    ClassDecl->setFailedImplicitMoveConstructor();
9326    return 0;
9327  }
9328
9329  // Note that we have declared this constructor.
9330  ++ASTContext::NumImplicitMoveConstructorsDeclared;
9331
9332  if (Scope *S = getScopeForContext(ClassDecl))
9333    PushOnScopeChains(MoveConstructor, S, false);
9334  ClassDecl->addDecl(MoveConstructor);
9335
9336  return MoveConstructor;
9337}
9338
9339void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9340                                   CXXConstructorDecl *MoveConstructor) {
9341  assert((MoveConstructor->isDefaulted() &&
9342          MoveConstructor->isMoveConstructor() &&
9343          !MoveConstructor->doesThisDeclarationHaveABody() &&
9344          !MoveConstructor->isDeleted()) &&
9345         "DefineImplicitMoveConstructor - call it for implicit move ctor");
9346
9347  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9348  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9349
9350  SynthesizedFunctionScope Scope(*this, MoveConstructor);
9351  DiagnosticErrorTrap Trap(Diags);
9352
9353  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
9354      Trap.hasErrorOccurred()) {
9355    Diag(CurrentLocation, diag::note_member_synthesized_at)
9356      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9357    MoveConstructor->setInvalidDecl();
9358  }  else {
9359    Sema::CompoundScopeRAII CompoundScope(*this);
9360    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9361                                               MoveConstructor->getLocation(),
9362                                               MultiStmtArg(),
9363                                               /*isStmtExpr=*/false)
9364                                                              .takeAs<Stmt>());
9365    MoveConstructor->setImplicitlyDefined(true);
9366  }
9367
9368  MoveConstructor->setUsed();
9369
9370  if (ASTMutationListener *L = getASTMutationListener()) {
9371    L->CompletedImplicitDefinition(MoveConstructor);
9372  }
9373}
9374
9375bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9376  return FD->isDeleted() &&
9377         (FD->isDefaulted() || FD->isImplicit()) &&
9378         isa<CXXMethodDecl>(FD);
9379}
9380
9381/// \brief Mark the call operator of the given lambda closure type as "used".
9382static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9383  CXXMethodDecl *CallOperator
9384    = cast<CXXMethodDecl>(
9385        Lambda->lookup(
9386          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9387  CallOperator->setReferenced();
9388  CallOperator->setUsed();
9389}
9390
9391void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9392       SourceLocation CurrentLocation,
9393       CXXConversionDecl *Conv)
9394{
9395  CXXRecordDecl *Lambda = Conv->getParent();
9396
9397  // Make sure that the lambda call operator is marked used.
9398  markLambdaCallOperatorUsed(*this, Lambda);
9399
9400  Conv->setUsed();
9401
9402  SynthesizedFunctionScope Scope(*this, Conv);
9403  DiagnosticErrorTrap Trap(Diags);
9404
9405  // Return the address of the __invoke function.
9406  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9407  CXXMethodDecl *Invoke
9408    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9409  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9410                                       VK_LValue, Conv->getLocation()).take();
9411  assert(FunctionRef && "Can't refer to __invoke function?");
9412  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9413  Conv->setBody(new (Context) CompoundStmt(Context, Return,
9414                                           Conv->getLocation(),
9415                                           Conv->getLocation()));
9416
9417  // Fill in the __invoke function with a dummy implementation. IR generation
9418  // will fill in the actual details.
9419  Invoke->setUsed();
9420  Invoke->setReferenced();
9421  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9422
9423  if (ASTMutationListener *L = getASTMutationListener()) {
9424    L->CompletedImplicitDefinition(Conv);
9425    L->CompletedImplicitDefinition(Invoke);
9426  }
9427}
9428
9429void Sema::DefineImplicitLambdaToBlockPointerConversion(
9430       SourceLocation CurrentLocation,
9431       CXXConversionDecl *Conv)
9432{
9433  Conv->setUsed();
9434
9435  SynthesizedFunctionScope Scope(*this, Conv);
9436  DiagnosticErrorTrap Trap(Diags);
9437
9438  // Copy-initialize the lambda object as needed to capture it.
9439  Expr *This = ActOnCXXThis(CurrentLocation).take();
9440  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9441
9442  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9443                                                        Conv->getLocation(),
9444                                                        Conv, DerefThis);
9445
9446  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9447  // behavior.  Note that only the general conversion function does this
9448  // (since it's unusable otherwise); in the case where we inline the
9449  // block literal, it has block literal lifetime semantics.
9450  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9451    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9452                                          CK_CopyAndAutoreleaseBlockObject,
9453                                          BuildBlock.get(), 0, VK_RValue);
9454
9455  if (BuildBlock.isInvalid()) {
9456    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9457    Conv->setInvalidDecl();
9458    return;
9459  }
9460
9461  // Create the return statement that returns the block from the conversion
9462  // function.
9463  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9464  if (Return.isInvalid()) {
9465    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9466    Conv->setInvalidDecl();
9467    return;
9468  }
9469
9470  // Set the body of the conversion function.
9471  Stmt *ReturnS = Return.take();
9472  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9473                                           Conv->getLocation(),
9474                                           Conv->getLocation()));
9475
9476  // We're done; notify the mutation listener, if any.
9477  if (ASTMutationListener *L = getASTMutationListener()) {
9478    L->CompletedImplicitDefinition(Conv);
9479  }
9480}
9481
9482/// \brief Determine whether the given list arguments contains exactly one
9483/// "real" (non-default) argument.
9484static bool hasOneRealArgument(MultiExprArg Args) {
9485  switch (Args.size()) {
9486  case 0:
9487    return false;
9488
9489  default:
9490    if (!Args[1]->isDefaultArgument())
9491      return false;
9492
9493    // fall through
9494  case 1:
9495    return !Args[0]->isDefaultArgument();
9496  }
9497
9498  return false;
9499}
9500
9501ExprResult
9502Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9503                            CXXConstructorDecl *Constructor,
9504                            MultiExprArg ExprArgs,
9505                            bool HadMultipleCandidates,
9506                            bool IsListInitialization,
9507                            bool RequiresZeroInit,
9508                            unsigned ConstructKind,
9509                            SourceRange ParenRange) {
9510  bool Elidable = false;
9511
9512  // C++0x [class.copy]p34:
9513  //   When certain criteria are met, an implementation is allowed to
9514  //   omit the copy/move construction of a class object, even if the
9515  //   copy/move constructor and/or destructor for the object have
9516  //   side effects. [...]
9517  //     - when a temporary class object that has not been bound to a
9518  //       reference (12.2) would be copied/moved to a class object
9519  //       with the same cv-unqualified type, the copy/move operation
9520  //       can be omitted by constructing the temporary object
9521  //       directly into the target of the omitted copy/move
9522  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9523      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9524    Expr *SubExpr = ExprArgs[0];
9525    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9526  }
9527
9528  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9529                               Elidable, ExprArgs, HadMultipleCandidates,
9530                               IsListInitialization, RequiresZeroInit,
9531                               ConstructKind, ParenRange);
9532}
9533
9534/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9535/// including handling of its default argument expressions.
9536ExprResult
9537Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9538                            CXXConstructorDecl *Constructor, bool Elidable,
9539                            MultiExprArg ExprArgs,
9540                            bool HadMultipleCandidates,
9541                            bool IsListInitialization,
9542                            bool RequiresZeroInit,
9543                            unsigned ConstructKind,
9544                            SourceRange ParenRange) {
9545  MarkFunctionReferenced(ConstructLoc, Constructor);
9546  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9547                                        Constructor, Elidable, ExprArgs,
9548                                        HadMultipleCandidates,
9549                                        IsListInitialization, RequiresZeroInit,
9550              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9551                                        ParenRange));
9552}
9553
9554void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9555  if (VD->isInvalidDecl()) return;
9556
9557  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9558  if (ClassDecl->isInvalidDecl()) return;
9559  if (ClassDecl->hasIrrelevantDestructor()) return;
9560  if (ClassDecl->isDependentContext()) return;
9561
9562  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9563  MarkFunctionReferenced(VD->getLocation(), Destructor);
9564  CheckDestructorAccess(VD->getLocation(), Destructor,
9565                        PDiag(diag::err_access_dtor_var)
9566                        << VD->getDeclName()
9567                        << VD->getType());
9568  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9569
9570  if (!VD->hasGlobalStorage()) return;
9571
9572  // Emit warning for non-trivial dtor in global scope (a real global,
9573  // class-static, function-static).
9574  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9575
9576  // TODO: this should be re-enabled for static locals by !CXAAtExit
9577  if (!VD->isStaticLocal())
9578    Diag(VD->getLocation(), diag::warn_global_destructor);
9579}
9580
9581/// \brief Given a constructor and the set of arguments provided for the
9582/// constructor, convert the arguments and add any required default arguments
9583/// to form a proper call to this constructor.
9584///
9585/// \returns true if an error occurred, false otherwise.
9586bool
9587Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9588                              MultiExprArg ArgsPtr,
9589                              SourceLocation Loc,
9590                              SmallVectorImpl<Expr*> &ConvertedArgs,
9591                              bool AllowExplicit) {
9592  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9593  unsigned NumArgs = ArgsPtr.size();
9594  Expr **Args = ArgsPtr.data();
9595
9596  const FunctionProtoType *Proto
9597    = Constructor->getType()->getAs<FunctionProtoType>();
9598  assert(Proto && "Constructor without a prototype?");
9599  unsigned NumArgsInProto = Proto->getNumArgs();
9600
9601  // If too few arguments are available, we'll fill in the rest with defaults.
9602  if (NumArgs < NumArgsInProto)
9603    ConvertedArgs.reserve(NumArgsInProto);
9604  else
9605    ConvertedArgs.reserve(NumArgs);
9606
9607  VariadicCallType CallType =
9608    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9609  SmallVector<Expr *, 8> AllArgs;
9610  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9611                                        Proto, 0, Args, NumArgs, AllArgs,
9612                                        CallType, AllowExplicit);
9613  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9614
9615  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9616
9617  CheckConstructorCall(Constructor,
9618                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
9619                                                        AllArgs.size()),
9620                       Proto, Loc);
9621
9622  return Invalid;
9623}
9624
9625static inline bool
9626CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9627                                       const FunctionDecl *FnDecl) {
9628  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9629  if (isa<NamespaceDecl>(DC)) {
9630    return SemaRef.Diag(FnDecl->getLocation(),
9631                        diag::err_operator_new_delete_declared_in_namespace)
9632      << FnDecl->getDeclName();
9633  }
9634
9635  if (isa<TranslationUnitDecl>(DC) &&
9636      FnDecl->getStorageClass() == SC_Static) {
9637    return SemaRef.Diag(FnDecl->getLocation(),
9638                        diag::err_operator_new_delete_declared_static)
9639      << FnDecl->getDeclName();
9640  }
9641
9642  return false;
9643}
9644
9645static inline bool
9646CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9647                            CanQualType ExpectedResultType,
9648                            CanQualType ExpectedFirstParamType,
9649                            unsigned DependentParamTypeDiag,
9650                            unsigned InvalidParamTypeDiag) {
9651  QualType ResultType =
9652    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9653
9654  // Check that the result type is not dependent.
9655  if (ResultType->isDependentType())
9656    return SemaRef.Diag(FnDecl->getLocation(),
9657                        diag::err_operator_new_delete_dependent_result_type)
9658    << FnDecl->getDeclName() << ExpectedResultType;
9659
9660  // Check that the result type is what we expect.
9661  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9662    return SemaRef.Diag(FnDecl->getLocation(),
9663                        diag::err_operator_new_delete_invalid_result_type)
9664    << FnDecl->getDeclName() << ExpectedResultType;
9665
9666  // A function template must have at least 2 parameters.
9667  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9668    return SemaRef.Diag(FnDecl->getLocation(),
9669                      diag::err_operator_new_delete_template_too_few_parameters)
9670        << FnDecl->getDeclName();
9671
9672  // The function decl must have at least 1 parameter.
9673  if (FnDecl->getNumParams() == 0)
9674    return SemaRef.Diag(FnDecl->getLocation(),
9675                        diag::err_operator_new_delete_too_few_parameters)
9676      << FnDecl->getDeclName();
9677
9678  // Check the first parameter type is not dependent.
9679  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9680  if (FirstParamType->isDependentType())
9681    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9682      << FnDecl->getDeclName() << ExpectedFirstParamType;
9683
9684  // Check that the first parameter type is what we expect.
9685  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9686      ExpectedFirstParamType)
9687    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9688    << FnDecl->getDeclName() << ExpectedFirstParamType;
9689
9690  return false;
9691}
9692
9693static bool
9694CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9695  // C++ [basic.stc.dynamic.allocation]p1:
9696  //   A program is ill-formed if an allocation function is declared in a
9697  //   namespace scope other than global scope or declared static in global
9698  //   scope.
9699  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9700    return true;
9701
9702  CanQualType SizeTy =
9703    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9704
9705  // C++ [basic.stc.dynamic.allocation]p1:
9706  //  The return type shall be void*. The first parameter shall have type
9707  //  std::size_t.
9708  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9709                                  SizeTy,
9710                                  diag::err_operator_new_dependent_param_type,
9711                                  diag::err_operator_new_param_type))
9712    return true;
9713
9714  // C++ [basic.stc.dynamic.allocation]p1:
9715  //  The first parameter shall not have an associated default argument.
9716  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9717    return SemaRef.Diag(FnDecl->getLocation(),
9718                        diag::err_operator_new_default_arg)
9719      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9720
9721  return false;
9722}
9723
9724static bool
9725CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
9726  // C++ [basic.stc.dynamic.deallocation]p1:
9727  //   A program is ill-formed if deallocation functions are declared in a
9728  //   namespace scope other than global scope or declared static in global
9729  //   scope.
9730  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9731    return true;
9732
9733  // C++ [basic.stc.dynamic.deallocation]p2:
9734  //   Each deallocation function shall return void and its first parameter
9735  //   shall be void*.
9736  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9737                                  SemaRef.Context.VoidPtrTy,
9738                                 diag::err_operator_delete_dependent_param_type,
9739                                 diag::err_operator_delete_param_type))
9740    return true;
9741
9742  return false;
9743}
9744
9745/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9746/// of this overloaded operator is well-formed. If so, returns false;
9747/// otherwise, emits appropriate diagnostics and returns true.
9748bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9749  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9750         "Expected an overloaded operator declaration");
9751
9752  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9753
9754  // C++ [over.oper]p5:
9755  //   The allocation and deallocation functions, operator new,
9756  //   operator new[], operator delete and operator delete[], are
9757  //   described completely in 3.7.3. The attributes and restrictions
9758  //   found in the rest of this subclause do not apply to them unless
9759  //   explicitly stated in 3.7.3.
9760  if (Op == OO_Delete || Op == OO_Array_Delete)
9761    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9762
9763  if (Op == OO_New || Op == OO_Array_New)
9764    return CheckOperatorNewDeclaration(*this, FnDecl);
9765
9766  // C++ [over.oper]p6:
9767  //   An operator function shall either be a non-static member
9768  //   function or be a non-member function and have at least one
9769  //   parameter whose type is a class, a reference to a class, an
9770  //   enumeration, or a reference to an enumeration.
9771  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9772    if (MethodDecl->isStatic())
9773      return Diag(FnDecl->getLocation(),
9774                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9775  } else {
9776    bool ClassOrEnumParam = false;
9777    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9778                                   ParamEnd = FnDecl->param_end();
9779         Param != ParamEnd; ++Param) {
9780      QualType ParamType = (*Param)->getType().getNonReferenceType();
9781      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9782          ParamType->isEnumeralType()) {
9783        ClassOrEnumParam = true;
9784        break;
9785      }
9786    }
9787
9788    if (!ClassOrEnumParam)
9789      return Diag(FnDecl->getLocation(),
9790                  diag::err_operator_overload_needs_class_or_enum)
9791        << FnDecl->getDeclName();
9792  }
9793
9794  // C++ [over.oper]p8:
9795  //   An operator function cannot have default arguments (8.3.6),
9796  //   except where explicitly stated below.
9797  //
9798  // Only the function-call operator allows default arguments
9799  // (C++ [over.call]p1).
9800  if (Op != OO_Call) {
9801    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9802         Param != FnDecl->param_end(); ++Param) {
9803      if ((*Param)->hasDefaultArg())
9804        return Diag((*Param)->getLocation(),
9805                    diag::err_operator_overload_default_arg)
9806          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9807    }
9808  }
9809
9810  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9811    { false, false, false }
9812#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9813    , { Unary, Binary, MemberOnly }
9814#include "clang/Basic/OperatorKinds.def"
9815  };
9816
9817  bool CanBeUnaryOperator = OperatorUses[Op][0];
9818  bool CanBeBinaryOperator = OperatorUses[Op][1];
9819  bool MustBeMemberOperator = OperatorUses[Op][2];
9820
9821  // C++ [over.oper]p8:
9822  //   [...] Operator functions cannot have more or fewer parameters
9823  //   than the number required for the corresponding operator, as
9824  //   described in the rest of this subclause.
9825  unsigned NumParams = FnDecl->getNumParams()
9826                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9827  if (Op != OO_Call &&
9828      ((NumParams == 1 && !CanBeUnaryOperator) ||
9829       (NumParams == 2 && !CanBeBinaryOperator) ||
9830       (NumParams < 1) || (NumParams > 2))) {
9831    // We have the wrong number of parameters.
9832    unsigned ErrorKind;
9833    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9834      ErrorKind = 2;  // 2 -> unary or binary.
9835    } else if (CanBeUnaryOperator) {
9836      ErrorKind = 0;  // 0 -> unary
9837    } else {
9838      assert(CanBeBinaryOperator &&
9839             "All non-call overloaded operators are unary or binary!");
9840      ErrorKind = 1;  // 1 -> binary
9841    }
9842
9843    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9844      << FnDecl->getDeclName() << NumParams << ErrorKind;
9845  }
9846
9847  // Overloaded operators other than operator() cannot be variadic.
9848  if (Op != OO_Call &&
9849      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9850    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9851      << FnDecl->getDeclName();
9852  }
9853
9854  // Some operators must be non-static member functions.
9855  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9856    return Diag(FnDecl->getLocation(),
9857                diag::err_operator_overload_must_be_member)
9858      << FnDecl->getDeclName();
9859  }
9860
9861  // C++ [over.inc]p1:
9862  //   The user-defined function called operator++ implements the
9863  //   prefix and postfix ++ operator. If this function is a member
9864  //   function with no parameters, or a non-member function with one
9865  //   parameter of class or enumeration type, it defines the prefix
9866  //   increment operator ++ for objects of that type. If the function
9867  //   is a member function with one parameter (which shall be of type
9868  //   int) or a non-member function with two parameters (the second
9869  //   of which shall be of type int), it defines the postfix
9870  //   increment operator ++ for objects of that type.
9871  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9872    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9873    bool ParamIsInt = false;
9874    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9875      ParamIsInt = BT->getKind() == BuiltinType::Int;
9876
9877    if (!ParamIsInt)
9878      return Diag(LastParam->getLocation(),
9879                  diag::err_operator_overload_post_incdec_must_be_int)
9880        << LastParam->getType() << (Op == OO_MinusMinus);
9881  }
9882
9883  return false;
9884}
9885
9886/// CheckLiteralOperatorDeclaration - Check whether the declaration
9887/// of this literal operator function is well-formed. If so, returns
9888/// false; otherwise, emits appropriate diagnostics and returns true.
9889bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9890  if (isa<CXXMethodDecl>(FnDecl)) {
9891    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9892      << FnDecl->getDeclName();
9893    return true;
9894  }
9895
9896  if (FnDecl->isExternC()) {
9897    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9898    return true;
9899  }
9900
9901  bool Valid = false;
9902
9903  // This might be the definition of a literal operator template.
9904  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9905  // This might be a specialization of a literal operator template.
9906  if (!TpDecl)
9907    TpDecl = FnDecl->getPrimaryTemplate();
9908
9909  // template <char...> type operator "" name() is the only valid template
9910  // signature, and the only valid signature with no parameters.
9911  if (TpDecl) {
9912    if (FnDecl->param_size() == 0) {
9913      // Must have only one template parameter
9914      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9915      if (Params->size() == 1) {
9916        NonTypeTemplateParmDecl *PmDecl =
9917          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9918
9919        // The template parameter must be a char parameter pack.
9920        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9921            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9922          Valid = true;
9923      }
9924    }
9925  } else if (FnDecl->param_size()) {
9926    // Check the first parameter
9927    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9928
9929    QualType T = (*Param)->getType().getUnqualifiedType();
9930
9931    // unsigned long long int, long double, and any character type are allowed
9932    // as the only parameters.
9933    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9934        Context.hasSameType(T, Context.LongDoubleTy) ||
9935        Context.hasSameType(T, Context.CharTy) ||
9936        Context.hasSameType(T, Context.WCharTy) ||
9937        Context.hasSameType(T, Context.Char16Ty) ||
9938        Context.hasSameType(T, Context.Char32Ty)) {
9939      if (++Param == FnDecl->param_end())
9940        Valid = true;
9941      goto FinishedParams;
9942    }
9943
9944    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9945    const PointerType *PT = T->getAs<PointerType>();
9946    if (!PT)
9947      goto FinishedParams;
9948    T = PT->getPointeeType();
9949    if (!T.isConstQualified() || T.isVolatileQualified())
9950      goto FinishedParams;
9951    T = T.getUnqualifiedType();
9952
9953    // Move on to the second parameter;
9954    ++Param;
9955
9956    // If there is no second parameter, the first must be a const char *
9957    if (Param == FnDecl->param_end()) {
9958      if (Context.hasSameType(T, Context.CharTy))
9959        Valid = true;
9960      goto FinishedParams;
9961    }
9962
9963    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9964    // are allowed as the first parameter to a two-parameter function
9965    if (!(Context.hasSameType(T, Context.CharTy) ||
9966          Context.hasSameType(T, Context.WCharTy) ||
9967          Context.hasSameType(T, Context.Char16Ty) ||
9968          Context.hasSameType(T, Context.Char32Ty)))
9969      goto FinishedParams;
9970
9971    // The second and final parameter must be an std::size_t
9972    T = (*Param)->getType().getUnqualifiedType();
9973    if (Context.hasSameType(T, Context.getSizeType()) &&
9974        ++Param == FnDecl->param_end())
9975      Valid = true;
9976  }
9977
9978  // FIXME: This diagnostic is absolutely terrible.
9979FinishedParams:
9980  if (!Valid) {
9981    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9982      << FnDecl->getDeclName();
9983    return true;
9984  }
9985
9986  // A parameter-declaration-clause containing a default argument is not
9987  // equivalent to any of the permitted forms.
9988  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9989                                    ParamEnd = FnDecl->param_end();
9990       Param != ParamEnd; ++Param) {
9991    if ((*Param)->hasDefaultArg()) {
9992      Diag((*Param)->getDefaultArgRange().getBegin(),
9993           diag::err_literal_operator_default_argument)
9994        << (*Param)->getDefaultArgRange();
9995      break;
9996    }
9997  }
9998
9999  StringRef LiteralName
10000    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10001  if (LiteralName[0] != '_') {
10002    // C++11 [usrlit.suffix]p1:
10003    //   Literal suffix identifiers that do not start with an underscore
10004    //   are reserved for future standardization.
10005    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10006  }
10007
10008  return false;
10009}
10010
10011/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10012/// linkage specification, including the language and (if present)
10013/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10014/// the location of the language string literal, which is provided
10015/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10016/// the '{' brace. Otherwise, this linkage specification does not
10017/// have any braces.
10018Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10019                                           SourceLocation LangLoc,
10020                                           StringRef Lang,
10021                                           SourceLocation LBraceLoc) {
10022  LinkageSpecDecl::LanguageIDs Language;
10023  if (Lang == "\"C\"")
10024    Language = LinkageSpecDecl::lang_c;
10025  else if (Lang == "\"C++\"")
10026    Language = LinkageSpecDecl::lang_cxx;
10027  else {
10028    Diag(LangLoc, diag::err_bad_language);
10029    return 0;
10030  }
10031
10032  // FIXME: Add all the various semantics of linkage specifications
10033
10034  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10035                                               ExternLoc, LangLoc, Language);
10036  CurContext->addDecl(D);
10037  PushDeclContext(S, D);
10038  return D;
10039}
10040
10041/// ActOnFinishLinkageSpecification - Complete the definition of
10042/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10043/// valid, it's the position of the closing '}' brace in a linkage
10044/// specification that uses braces.
10045Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10046                                            Decl *LinkageSpec,
10047                                            SourceLocation RBraceLoc) {
10048  if (LinkageSpec) {
10049    if (RBraceLoc.isValid()) {
10050      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10051      LSDecl->setRBraceLoc(RBraceLoc);
10052    }
10053    PopDeclContext();
10054  }
10055  return LinkageSpec;
10056}
10057
10058/// \brief Perform semantic analysis for the variable declaration that
10059/// occurs within a C++ catch clause, returning the newly-created
10060/// variable.
10061VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10062                                         TypeSourceInfo *TInfo,
10063                                         SourceLocation StartLoc,
10064                                         SourceLocation Loc,
10065                                         IdentifierInfo *Name) {
10066  bool Invalid = false;
10067  QualType ExDeclType = TInfo->getType();
10068
10069  // Arrays and functions decay.
10070  if (ExDeclType->isArrayType())
10071    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10072  else if (ExDeclType->isFunctionType())
10073    ExDeclType = Context.getPointerType(ExDeclType);
10074
10075  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10076  // The exception-declaration shall not denote a pointer or reference to an
10077  // incomplete type, other than [cv] void*.
10078  // N2844 forbids rvalue references.
10079  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10080    Diag(Loc, diag::err_catch_rvalue_ref);
10081    Invalid = true;
10082  }
10083
10084  QualType BaseType = ExDeclType;
10085  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10086  unsigned DK = diag::err_catch_incomplete;
10087  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10088    BaseType = Ptr->getPointeeType();
10089    Mode = 1;
10090    DK = diag::err_catch_incomplete_ptr;
10091  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10092    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10093    BaseType = Ref->getPointeeType();
10094    Mode = 2;
10095    DK = diag::err_catch_incomplete_ref;
10096  }
10097  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10098      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10099    Invalid = true;
10100
10101  if (!Invalid && !ExDeclType->isDependentType() &&
10102      RequireNonAbstractType(Loc, ExDeclType,
10103                             diag::err_abstract_type_in_decl,
10104                             AbstractVariableType))
10105    Invalid = true;
10106
10107  // Only the non-fragile NeXT runtime currently supports C++ catches
10108  // of ObjC types, and no runtime supports catching ObjC types by value.
10109  if (!Invalid && getLangOpts().ObjC1) {
10110    QualType T = ExDeclType;
10111    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10112      T = RT->getPointeeType();
10113
10114    if (T->isObjCObjectType()) {
10115      Diag(Loc, diag::err_objc_object_catch);
10116      Invalid = true;
10117    } else if (T->isObjCObjectPointerType()) {
10118      // FIXME: should this be a test for macosx-fragile specifically?
10119      if (getLangOpts().ObjCRuntime.isFragile())
10120        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10121    }
10122  }
10123
10124  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10125                                    ExDeclType, TInfo, SC_None, SC_None);
10126  ExDecl->setExceptionVariable(true);
10127
10128  // In ARC, infer 'retaining' for variables of retainable type.
10129  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10130    Invalid = true;
10131
10132  if (!Invalid && !ExDeclType->isDependentType()) {
10133    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10134      // C++ [except.handle]p16:
10135      //   The object declared in an exception-declaration or, if the
10136      //   exception-declaration does not specify a name, a temporary (12.2) is
10137      //   copy-initialized (8.5) from the exception object. [...]
10138      //   The object is destroyed when the handler exits, after the destruction
10139      //   of any automatic objects initialized within the handler.
10140      //
10141      // We just pretend to initialize the object with itself, then make sure
10142      // it can be destroyed later.
10143      QualType initType = ExDeclType;
10144
10145      InitializedEntity entity =
10146        InitializedEntity::InitializeVariable(ExDecl);
10147      InitializationKind initKind =
10148        InitializationKind::CreateCopy(Loc, SourceLocation());
10149
10150      Expr *opaqueValue =
10151        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10152      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
10153      ExprResult result = sequence.Perform(*this, entity, initKind,
10154                                           MultiExprArg(&opaqueValue, 1));
10155      if (result.isInvalid())
10156        Invalid = true;
10157      else {
10158        // If the constructor used was non-trivial, set this as the
10159        // "initializer".
10160        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10161        if (!construct->getConstructor()->isTrivial()) {
10162          Expr *init = MaybeCreateExprWithCleanups(construct);
10163          ExDecl->setInit(init);
10164        }
10165
10166        // And make sure it's destructable.
10167        FinalizeVarWithDestructor(ExDecl, recordType);
10168      }
10169    }
10170  }
10171
10172  if (Invalid)
10173    ExDecl->setInvalidDecl();
10174
10175  return ExDecl;
10176}
10177
10178/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10179/// handler.
10180Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10181  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10182  bool Invalid = D.isInvalidType();
10183
10184  // Check for unexpanded parameter packs.
10185  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10186                                               UPPC_ExceptionType)) {
10187    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10188                                             D.getIdentifierLoc());
10189    Invalid = true;
10190  }
10191
10192  IdentifierInfo *II = D.getIdentifier();
10193  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10194                                             LookupOrdinaryName,
10195                                             ForRedeclaration)) {
10196    // The scope should be freshly made just for us. There is just no way
10197    // it contains any previous declaration.
10198    assert(!S->isDeclScope(PrevDecl));
10199    if (PrevDecl->isTemplateParameter()) {
10200      // Maybe we will complain about the shadowed template parameter.
10201      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10202      PrevDecl = 0;
10203    }
10204  }
10205
10206  if (D.getCXXScopeSpec().isSet() && !Invalid) {
10207    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10208      << D.getCXXScopeSpec().getRange();
10209    Invalid = true;
10210  }
10211
10212  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10213                                              D.getLocStart(),
10214                                              D.getIdentifierLoc(),
10215                                              D.getIdentifier());
10216  if (Invalid)
10217    ExDecl->setInvalidDecl();
10218
10219  // Add the exception declaration into this scope.
10220  if (II)
10221    PushOnScopeChains(ExDecl, S);
10222  else
10223    CurContext->addDecl(ExDecl);
10224
10225  ProcessDeclAttributes(S, ExDecl, D);
10226  return ExDecl;
10227}
10228
10229Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10230                                         Expr *AssertExpr,
10231                                         Expr *AssertMessageExpr,
10232                                         SourceLocation RParenLoc) {
10233  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10234
10235  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10236    return 0;
10237
10238  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10239                                      AssertMessage, RParenLoc, false);
10240}
10241
10242Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10243                                         Expr *AssertExpr,
10244                                         StringLiteral *AssertMessage,
10245                                         SourceLocation RParenLoc,
10246                                         bool Failed) {
10247  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10248      !Failed) {
10249    // In a static_assert-declaration, the constant-expression shall be a
10250    // constant expression that can be contextually converted to bool.
10251    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10252    if (Converted.isInvalid())
10253      Failed = true;
10254
10255    llvm::APSInt Cond;
10256    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10257          diag::err_static_assert_expression_is_not_constant,
10258          /*AllowFold=*/false).isInvalid())
10259      Failed = true;
10260
10261    if (!Failed && !Cond) {
10262      SmallString<256> MsgBuffer;
10263      llvm::raw_svector_ostream Msg(MsgBuffer);
10264      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10265      Diag(StaticAssertLoc, diag::err_static_assert_failed)
10266        << Msg.str() << AssertExpr->getSourceRange();
10267      Failed = true;
10268    }
10269  }
10270
10271  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10272                                        AssertExpr, AssertMessage, RParenLoc,
10273                                        Failed);
10274
10275  CurContext->addDecl(Decl);
10276  return Decl;
10277}
10278
10279/// \brief Perform semantic analysis of the given friend type declaration.
10280///
10281/// \returns A friend declaration that.
10282FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10283                                      SourceLocation FriendLoc,
10284                                      TypeSourceInfo *TSInfo) {
10285  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10286
10287  QualType T = TSInfo->getType();
10288  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10289
10290  // C++03 [class.friend]p2:
10291  //   An elaborated-type-specifier shall be used in a friend declaration
10292  //   for a class.*
10293  //
10294  //   * The class-key of the elaborated-type-specifier is required.
10295  if (!ActiveTemplateInstantiations.empty()) {
10296    // Do not complain about the form of friend template types during
10297    // template instantiation; we will already have complained when the
10298    // template was declared.
10299  } else if (!T->isElaboratedTypeSpecifier()) {
10300    // If we evaluated the type to a record type, suggest putting
10301    // a tag in front.
10302    if (const RecordType *RT = T->getAs<RecordType>()) {
10303      RecordDecl *RD = RT->getDecl();
10304
10305      std::string InsertionText = std::string(" ") + RD->getKindName();
10306
10307      Diag(TypeRange.getBegin(),
10308           getLangOpts().CPlusPlus11 ?
10309             diag::warn_cxx98_compat_unelaborated_friend_type :
10310             diag::ext_unelaborated_friend_type)
10311        << (unsigned) RD->getTagKind()
10312        << T
10313        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10314                                      InsertionText);
10315    } else {
10316      Diag(FriendLoc,
10317           getLangOpts().CPlusPlus11 ?
10318             diag::warn_cxx98_compat_nonclass_type_friend :
10319             diag::ext_nonclass_type_friend)
10320        << T
10321        << TypeRange;
10322    }
10323  } else if (T->getAs<EnumType>()) {
10324    Diag(FriendLoc,
10325         getLangOpts().CPlusPlus11 ?
10326           diag::warn_cxx98_compat_enum_friend :
10327           diag::ext_enum_friend)
10328      << T
10329      << TypeRange;
10330  }
10331
10332  // C++11 [class.friend]p3:
10333  //   A friend declaration that does not declare a function shall have one
10334  //   of the following forms:
10335  //     friend elaborated-type-specifier ;
10336  //     friend simple-type-specifier ;
10337  //     friend typename-specifier ;
10338  if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10339    Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10340
10341  //   If the type specifier in a friend declaration designates a (possibly
10342  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10343  //   the friend declaration is ignored.
10344  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10345}
10346
10347/// Handle a friend tag declaration where the scope specifier was
10348/// templated.
10349Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10350                                    unsigned TagSpec, SourceLocation TagLoc,
10351                                    CXXScopeSpec &SS,
10352                                    IdentifierInfo *Name, SourceLocation NameLoc,
10353                                    AttributeList *Attr,
10354                                    MultiTemplateParamsArg TempParamLists) {
10355  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10356
10357  bool isExplicitSpecialization = false;
10358  bool Invalid = false;
10359
10360  if (TemplateParameterList *TemplateParams
10361        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10362                                                  TempParamLists.data(),
10363                                                  TempParamLists.size(),
10364                                                  /*friend*/ true,
10365                                                  isExplicitSpecialization,
10366                                                  Invalid)) {
10367    if (TemplateParams->size() > 0) {
10368      // This is a declaration of a class template.
10369      if (Invalid)
10370        return 0;
10371
10372      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10373                                SS, Name, NameLoc, Attr,
10374                                TemplateParams, AS_public,
10375                                /*ModulePrivateLoc=*/SourceLocation(),
10376                                TempParamLists.size() - 1,
10377                                TempParamLists.data()).take();
10378    } else {
10379      // The "template<>" header is extraneous.
10380      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10381        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10382      isExplicitSpecialization = true;
10383    }
10384  }
10385
10386  if (Invalid) return 0;
10387
10388  bool isAllExplicitSpecializations = true;
10389  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10390    if (TempParamLists[I]->size()) {
10391      isAllExplicitSpecializations = false;
10392      break;
10393    }
10394  }
10395
10396  // FIXME: don't ignore attributes.
10397
10398  // If it's explicit specializations all the way down, just forget
10399  // about the template header and build an appropriate non-templated
10400  // friend.  TODO: for source fidelity, remember the headers.
10401  if (isAllExplicitSpecializations) {
10402    if (SS.isEmpty()) {
10403      bool Owned = false;
10404      bool IsDependent = false;
10405      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10406                      Attr, AS_public,
10407                      /*ModulePrivateLoc=*/SourceLocation(),
10408                      MultiTemplateParamsArg(), Owned, IsDependent,
10409                      /*ScopedEnumKWLoc=*/SourceLocation(),
10410                      /*ScopedEnumUsesClassTag=*/false,
10411                      /*UnderlyingType=*/TypeResult());
10412    }
10413
10414    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10415    ElaboratedTypeKeyword Keyword
10416      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10417    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10418                                   *Name, NameLoc);
10419    if (T.isNull())
10420      return 0;
10421
10422    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10423    if (isa<DependentNameType>(T)) {
10424      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10425      TL.setElaboratedKeywordLoc(TagLoc);
10426      TL.setQualifierLoc(QualifierLoc);
10427      TL.setNameLoc(NameLoc);
10428    } else {
10429      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10430      TL.setElaboratedKeywordLoc(TagLoc);
10431      TL.setQualifierLoc(QualifierLoc);
10432      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10433    }
10434
10435    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10436                                            TSI, FriendLoc);
10437    Friend->setAccess(AS_public);
10438    CurContext->addDecl(Friend);
10439    return Friend;
10440  }
10441
10442  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10443
10444
10445
10446  // Handle the case of a templated-scope friend class.  e.g.
10447  //   template <class T> class A<T>::B;
10448  // FIXME: we don't support these right now.
10449  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10450  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10451  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10452  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10453  TL.setElaboratedKeywordLoc(TagLoc);
10454  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10455  TL.setNameLoc(NameLoc);
10456
10457  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10458                                          TSI, FriendLoc);
10459  Friend->setAccess(AS_public);
10460  Friend->setUnsupportedFriend(true);
10461  CurContext->addDecl(Friend);
10462  return Friend;
10463}
10464
10465
10466/// Handle a friend type declaration.  This works in tandem with
10467/// ActOnTag.
10468///
10469/// Notes on friend class templates:
10470///
10471/// We generally treat friend class declarations as if they were
10472/// declaring a class.  So, for example, the elaborated type specifier
10473/// in a friend declaration is required to obey the restrictions of a
10474/// class-head (i.e. no typedefs in the scope chain), template
10475/// parameters are required to match up with simple template-ids, &c.
10476/// However, unlike when declaring a template specialization, it's
10477/// okay to refer to a template specialization without an empty
10478/// template parameter declaration, e.g.
10479///   friend class A<T>::B<unsigned>;
10480/// We permit this as a special case; if there are any template
10481/// parameters present at all, require proper matching, i.e.
10482///   template <> template \<class T> friend class A<int>::B;
10483Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10484                                MultiTemplateParamsArg TempParams) {
10485  SourceLocation Loc = DS.getLocStart();
10486
10487  assert(DS.isFriendSpecified());
10488  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10489
10490  // Try to convert the decl specifier to a type.  This works for
10491  // friend templates because ActOnTag never produces a ClassTemplateDecl
10492  // for a TUK_Friend.
10493  Declarator TheDeclarator(DS, Declarator::MemberContext);
10494  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10495  QualType T = TSI->getType();
10496  if (TheDeclarator.isInvalidType())
10497    return 0;
10498
10499  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10500    return 0;
10501
10502  // This is definitely an error in C++98.  It's probably meant to
10503  // be forbidden in C++0x, too, but the specification is just
10504  // poorly written.
10505  //
10506  // The problem is with declarations like the following:
10507  //   template <T> friend A<T>::foo;
10508  // where deciding whether a class C is a friend or not now hinges
10509  // on whether there exists an instantiation of A that causes
10510  // 'foo' to equal C.  There are restrictions on class-heads
10511  // (which we declare (by fiat) elaborated friend declarations to
10512  // be) that makes this tractable.
10513  //
10514  // FIXME: handle "template <> friend class A<T>;", which
10515  // is possibly well-formed?  Who even knows?
10516  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10517    Diag(Loc, diag::err_tagless_friend_type_template)
10518      << DS.getSourceRange();
10519    return 0;
10520  }
10521
10522  // C++98 [class.friend]p1: A friend of a class is a function
10523  //   or class that is not a member of the class . . .
10524  // This is fixed in DR77, which just barely didn't make the C++03
10525  // deadline.  It's also a very silly restriction that seriously
10526  // affects inner classes and which nobody else seems to implement;
10527  // thus we never diagnose it, not even in -pedantic.
10528  //
10529  // But note that we could warn about it: it's always useless to
10530  // friend one of your own members (it's not, however, worthless to
10531  // friend a member of an arbitrary specialization of your template).
10532
10533  Decl *D;
10534  if (unsigned NumTempParamLists = TempParams.size())
10535    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10536                                   NumTempParamLists,
10537                                   TempParams.data(),
10538                                   TSI,
10539                                   DS.getFriendSpecLoc());
10540  else
10541    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10542
10543  if (!D)
10544    return 0;
10545
10546  D->setAccess(AS_public);
10547  CurContext->addDecl(D);
10548
10549  return D;
10550}
10551
10552NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10553                                        MultiTemplateParamsArg TemplateParams) {
10554  const DeclSpec &DS = D.getDeclSpec();
10555
10556  assert(DS.isFriendSpecified());
10557  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10558
10559  SourceLocation Loc = D.getIdentifierLoc();
10560  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10561
10562  // C++ [class.friend]p1
10563  //   A friend of a class is a function or class....
10564  // Note that this sees through typedefs, which is intended.
10565  // It *doesn't* see through dependent types, which is correct
10566  // according to [temp.arg.type]p3:
10567  //   If a declaration acquires a function type through a
10568  //   type dependent on a template-parameter and this causes
10569  //   a declaration that does not use the syntactic form of a
10570  //   function declarator to have a function type, the program
10571  //   is ill-formed.
10572  if (!TInfo->getType()->isFunctionType()) {
10573    Diag(Loc, diag::err_unexpected_friend);
10574
10575    // It might be worthwhile to try to recover by creating an
10576    // appropriate declaration.
10577    return 0;
10578  }
10579
10580  // C++ [namespace.memdef]p3
10581  //  - If a friend declaration in a non-local class first declares a
10582  //    class or function, the friend class or function is a member
10583  //    of the innermost enclosing namespace.
10584  //  - The name of the friend is not found by simple name lookup
10585  //    until a matching declaration is provided in that namespace
10586  //    scope (either before or after the class declaration granting
10587  //    friendship).
10588  //  - If a friend function is called, its name may be found by the
10589  //    name lookup that considers functions from namespaces and
10590  //    classes associated with the types of the function arguments.
10591  //  - When looking for a prior declaration of a class or a function
10592  //    declared as a friend, scopes outside the innermost enclosing
10593  //    namespace scope are not considered.
10594
10595  CXXScopeSpec &SS = D.getCXXScopeSpec();
10596  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10597  DeclarationName Name = NameInfo.getName();
10598  assert(Name);
10599
10600  // Check for unexpanded parameter packs.
10601  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10602      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10603      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10604    return 0;
10605
10606  // The context we found the declaration in, or in which we should
10607  // create the declaration.
10608  DeclContext *DC;
10609  Scope *DCScope = S;
10610  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10611                        ForRedeclaration);
10612
10613  // FIXME: there are different rules in local classes
10614
10615  // There are four cases here.
10616  //   - There's no scope specifier, in which case we just go to the
10617  //     appropriate scope and look for a function or function template
10618  //     there as appropriate.
10619  // Recover from invalid scope qualifiers as if they just weren't there.
10620  if (SS.isInvalid() || !SS.isSet()) {
10621    // C++0x [namespace.memdef]p3:
10622    //   If the name in a friend declaration is neither qualified nor
10623    //   a template-id and the declaration is a function or an
10624    //   elaborated-type-specifier, the lookup to determine whether
10625    //   the entity has been previously declared shall not consider
10626    //   any scopes outside the innermost enclosing namespace.
10627    // C++0x [class.friend]p11:
10628    //   If a friend declaration appears in a local class and the name
10629    //   specified is an unqualified name, a prior declaration is
10630    //   looked up without considering scopes that are outside the
10631    //   innermost enclosing non-class scope. For a friend function
10632    //   declaration, if there is no prior declaration, the program is
10633    //   ill-formed.
10634    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10635    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10636
10637    // Find the appropriate context according to the above.
10638    DC = CurContext;
10639    while (true) {
10640      // Skip class contexts.  If someone can cite chapter and verse
10641      // for this behavior, that would be nice --- it's what GCC and
10642      // EDG do, and it seems like a reasonable intent, but the spec
10643      // really only says that checks for unqualified existing
10644      // declarations should stop at the nearest enclosing namespace,
10645      // not that they should only consider the nearest enclosing
10646      // namespace.
10647      while (DC->isRecord() || DC->isTransparentContext())
10648        DC = DC->getParent();
10649
10650      LookupQualifiedName(Previous, DC);
10651
10652      // TODO: decide what we think about using declarations.
10653      if (isLocal || !Previous.empty())
10654        break;
10655
10656      if (isTemplateId) {
10657        if (isa<TranslationUnitDecl>(DC)) break;
10658      } else {
10659        if (DC->isFileContext()) break;
10660      }
10661      DC = DC->getParent();
10662    }
10663
10664    // C++ [class.friend]p1: A friend of a class is a function or
10665    //   class that is not a member of the class . . .
10666    // C++11 changes this for both friend types and functions.
10667    // Most C++ 98 compilers do seem to give an error here, so
10668    // we do, too.
10669    if (!Previous.empty() && DC->Equals(CurContext))
10670      Diag(DS.getFriendSpecLoc(),
10671           getLangOpts().CPlusPlus11 ?
10672             diag::warn_cxx98_compat_friend_is_member :
10673             diag::err_friend_is_member);
10674
10675    DCScope = getScopeForDeclContext(S, DC);
10676
10677    // C++ [class.friend]p6:
10678    //   A function can be defined in a friend declaration of a class if and
10679    //   only if the class is a non-local class (9.8), the function name is
10680    //   unqualified, and the function has namespace scope.
10681    if (isLocal && D.isFunctionDefinition()) {
10682      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10683    }
10684
10685  //   - There's a non-dependent scope specifier, in which case we
10686  //     compute it and do a previous lookup there for a function
10687  //     or function template.
10688  } else if (!SS.getScopeRep()->isDependent()) {
10689    DC = computeDeclContext(SS);
10690    if (!DC) return 0;
10691
10692    if (RequireCompleteDeclContext(SS, DC)) return 0;
10693
10694    LookupQualifiedName(Previous, DC);
10695
10696    // Ignore things found implicitly in the wrong scope.
10697    // TODO: better diagnostics for this case.  Suggesting the right
10698    // qualified scope would be nice...
10699    LookupResult::Filter F = Previous.makeFilter();
10700    while (F.hasNext()) {
10701      NamedDecl *D = F.next();
10702      if (!DC->InEnclosingNamespaceSetOf(
10703              D->getDeclContext()->getRedeclContext()))
10704        F.erase();
10705    }
10706    F.done();
10707
10708    if (Previous.empty()) {
10709      D.setInvalidType();
10710      Diag(Loc, diag::err_qualified_friend_not_found)
10711          << Name << TInfo->getType();
10712      return 0;
10713    }
10714
10715    // C++ [class.friend]p1: A friend of a class is a function or
10716    //   class that is not a member of the class . . .
10717    if (DC->Equals(CurContext))
10718      Diag(DS.getFriendSpecLoc(),
10719           getLangOpts().CPlusPlus11 ?
10720             diag::warn_cxx98_compat_friend_is_member :
10721             diag::err_friend_is_member);
10722
10723    if (D.isFunctionDefinition()) {
10724      // C++ [class.friend]p6:
10725      //   A function can be defined in a friend declaration of a class if and
10726      //   only if the class is a non-local class (9.8), the function name is
10727      //   unqualified, and the function has namespace scope.
10728      SemaDiagnosticBuilder DB
10729        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10730
10731      DB << SS.getScopeRep();
10732      if (DC->isFileContext())
10733        DB << FixItHint::CreateRemoval(SS.getRange());
10734      SS.clear();
10735    }
10736
10737  //   - There's a scope specifier that does not match any template
10738  //     parameter lists, in which case we use some arbitrary context,
10739  //     create a method or method template, and wait for instantiation.
10740  //   - There's a scope specifier that does match some template
10741  //     parameter lists, which we don't handle right now.
10742  } else {
10743    if (D.isFunctionDefinition()) {
10744      // C++ [class.friend]p6:
10745      //   A function can be defined in a friend declaration of a class if and
10746      //   only if the class is a non-local class (9.8), the function name is
10747      //   unqualified, and the function has namespace scope.
10748      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10749        << SS.getScopeRep();
10750    }
10751
10752    DC = CurContext;
10753    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10754  }
10755
10756  if (!DC->isRecord()) {
10757    // This implies that it has to be an operator or function.
10758    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10759        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10760        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10761      Diag(Loc, diag::err_introducing_special_friend) <<
10762        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10763         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10764      return 0;
10765    }
10766  }
10767
10768  // FIXME: This is an egregious hack to cope with cases where the scope stack
10769  // does not contain the declaration context, i.e., in an out-of-line
10770  // definition of a class.
10771  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10772  if (!DCScope) {
10773    FakeDCScope.setEntity(DC);
10774    DCScope = &FakeDCScope;
10775  }
10776
10777  bool AddToScope = true;
10778  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10779                                          TemplateParams, AddToScope);
10780  if (!ND) return 0;
10781
10782  assert(ND->getDeclContext() == DC);
10783  assert(ND->getLexicalDeclContext() == CurContext);
10784
10785  // Add the function declaration to the appropriate lookup tables,
10786  // adjusting the redeclarations list as necessary.  We don't
10787  // want to do this yet if the friending class is dependent.
10788  //
10789  // Also update the scope-based lookup if the target context's
10790  // lookup context is in lexical scope.
10791  if (!CurContext->isDependentContext()) {
10792    DC = DC->getRedeclContext();
10793    DC->makeDeclVisibleInContext(ND);
10794    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10795      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10796  }
10797
10798  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10799                                       D.getIdentifierLoc(), ND,
10800                                       DS.getFriendSpecLoc());
10801  FrD->setAccess(AS_public);
10802  CurContext->addDecl(FrD);
10803
10804  if (ND->isInvalidDecl()) {
10805    FrD->setInvalidDecl();
10806  } else {
10807    if (DC->isRecord()) CheckFriendAccess(ND);
10808
10809    FunctionDecl *FD;
10810    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10811      FD = FTD->getTemplatedDecl();
10812    else
10813      FD = cast<FunctionDecl>(ND);
10814
10815    // Mark templated-scope function declarations as unsupported.
10816    if (FD->getNumTemplateParameterLists())
10817      FrD->setUnsupportedFriend(true);
10818  }
10819
10820  return ND;
10821}
10822
10823void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10824  AdjustDeclIfTemplate(Dcl);
10825
10826  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10827  if (!Fn) {
10828    Diag(DelLoc, diag::err_deleted_non_function);
10829    return;
10830  }
10831  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10832    // Don't consider the implicit declaration we generate for explicit
10833    // specializations. FIXME: Do not generate these implicit declarations.
10834    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10835        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
10836      Diag(DelLoc, diag::err_deleted_decl_not_first);
10837      Diag(Prev->getLocation(), diag::note_previous_declaration);
10838    }
10839    // If the declaration wasn't the first, we delete the function anyway for
10840    // recovery.
10841  }
10842  Fn->setDeletedAsWritten();
10843}
10844
10845void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10846  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10847
10848  if (MD) {
10849    if (MD->getParent()->isDependentType()) {
10850      MD->setDefaulted();
10851      MD->setExplicitlyDefaulted();
10852      return;
10853    }
10854
10855    CXXSpecialMember Member = getSpecialMember(MD);
10856    if (Member == CXXInvalid) {
10857      Diag(DefaultLoc, diag::err_default_special_members);
10858      return;
10859    }
10860
10861    MD->setDefaulted();
10862    MD->setExplicitlyDefaulted();
10863
10864    // If this definition appears within the record, do the checking when
10865    // the record is complete.
10866    const FunctionDecl *Primary = MD;
10867    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
10868      // Find the uninstantiated declaration that actually had the '= default'
10869      // on it.
10870      Pattern->isDefined(Primary);
10871
10872    if (Primary == Primary->getCanonicalDecl())
10873      return;
10874
10875    CheckExplicitlyDefaultedSpecialMember(MD);
10876
10877    // The exception specification is needed because we are defining the
10878    // function.
10879    ResolveExceptionSpec(DefaultLoc,
10880                         MD->getType()->castAs<FunctionProtoType>());
10881
10882    switch (Member) {
10883    case CXXDefaultConstructor: {
10884      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10885      if (!CD->isInvalidDecl())
10886        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10887      break;
10888    }
10889
10890    case CXXCopyConstructor: {
10891      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10892      if (!CD->isInvalidDecl())
10893        DefineImplicitCopyConstructor(DefaultLoc, CD);
10894      break;
10895    }
10896
10897    case CXXCopyAssignment: {
10898      if (!MD->isInvalidDecl())
10899        DefineImplicitCopyAssignment(DefaultLoc, MD);
10900      break;
10901    }
10902
10903    case CXXDestructor: {
10904      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10905      if (!DD->isInvalidDecl())
10906        DefineImplicitDestructor(DefaultLoc, DD);
10907      break;
10908    }
10909
10910    case CXXMoveConstructor: {
10911      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10912      if (!CD->isInvalidDecl())
10913        DefineImplicitMoveConstructor(DefaultLoc, CD);
10914      break;
10915    }
10916
10917    case CXXMoveAssignment: {
10918      if (!MD->isInvalidDecl())
10919        DefineImplicitMoveAssignment(DefaultLoc, MD);
10920      break;
10921    }
10922
10923    case CXXInvalid:
10924      llvm_unreachable("Invalid special member.");
10925    }
10926  } else {
10927    Diag(DefaultLoc, diag::err_default_special_members);
10928  }
10929}
10930
10931static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10932  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10933    Stmt *SubStmt = *CI;
10934    if (!SubStmt)
10935      continue;
10936    if (isa<ReturnStmt>(SubStmt))
10937      Self.Diag(SubStmt->getLocStart(),
10938           diag::err_return_in_constructor_handler);
10939    if (!isa<Expr>(SubStmt))
10940      SearchForReturnInStmt(Self, SubStmt);
10941  }
10942}
10943
10944void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10945  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10946    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10947    SearchForReturnInStmt(*this, Handler);
10948  }
10949}
10950
10951bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
10952                                             const CXXMethodDecl *Old) {
10953  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
10954  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
10955
10956  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
10957
10958  // If the calling conventions match, everything is fine
10959  if (NewCC == OldCC)
10960    return false;
10961
10962  // If either of the calling conventions are set to "default", we need to pick
10963  // something more sensible based on the target. This supports code where the
10964  // one method explicitly sets thiscall, and another has no explicit calling
10965  // convention.
10966  CallingConv Default =
10967    Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
10968  if (NewCC == CC_Default)
10969    NewCC = Default;
10970  if (OldCC == CC_Default)
10971    OldCC = Default;
10972
10973  // If the calling conventions still don't match, then report the error
10974  if (NewCC != OldCC) {
10975    Diag(New->getLocation(),
10976         diag::err_conflicting_overriding_cc_attributes)
10977      << New->getDeclName() << New->getType() << Old->getType();
10978    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10979    return true;
10980  }
10981
10982  return false;
10983}
10984
10985bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10986                                             const CXXMethodDecl *Old) {
10987  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10988  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10989
10990  if (Context.hasSameType(NewTy, OldTy) ||
10991      NewTy->isDependentType() || OldTy->isDependentType())
10992    return false;
10993
10994  // Check if the return types are covariant
10995  QualType NewClassTy, OldClassTy;
10996
10997  /// Both types must be pointers or references to classes.
10998  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10999    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11000      NewClassTy = NewPT->getPointeeType();
11001      OldClassTy = OldPT->getPointeeType();
11002    }
11003  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11004    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11005      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11006        NewClassTy = NewRT->getPointeeType();
11007        OldClassTy = OldRT->getPointeeType();
11008      }
11009    }
11010  }
11011
11012  // The return types aren't either both pointers or references to a class type.
11013  if (NewClassTy.isNull()) {
11014    Diag(New->getLocation(),
11015         diag::err_different_return_type_for_overriding_virtual_function)
11016      << New->getDeclName() << NewTy << OldTy;
11017    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11018
11019    return true;
11020  }
11021
11022  // C++ [class.virtual]p6:
11023  //   If the return type of D::f differs from the return type of B::f, the
11024  //   class type in the return type of D::f shall be complete at the point of
11025  //   declaration of D::f or shall be the class type D.
11026  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11027    if (!RT->isBeingDefined() &&
11028        RequireCompleteType(New->getLocation(), NewClassTy,
11029                            diag::err_covariant_return_incomplete,
11030                            New->getDeclName()))
11031    return true;
11032  }
11033
11034  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11035    // Check if the new class derives from the old class.
11036    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11037      Diag(New->getLocation(),
11038           diag::err_covariant_return_not_derived)
11039      << New->getDeclName() << NewTy << OldTy;
11040      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11041      return true;
11042    }
11043
11044    // Check if we the conversion from derived to base is valid.
11045    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11046                    diag::err_covariant_return_inaccessible_base,
11047                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11048                    // FIXME: Should this point to the return type?
11049                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11050      // FIXME: this note won't trigger for delayed access control
11051      // diagnostics, and it's impossible to get an undelayed error
11052      // here from access control during the original parse because
11053      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11054      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11055      return true;
11056    }
11057  }
11058
11059  // The qualifiers of the return types must be the same.
11060  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11061    Diag(New->getLocation(),
11062         diag::err_covariant_return_type_different_qualifications)
11063    << New->getDeclName() << NewTy << OldTy;
11064    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11065    return true;
11066  };
11067
11068
11069  // The new class type must have the same or less qualifiers as the old type.
11070  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11071    Diag(New->getLocation(),
11072         diag::err_covariant_return_type_class_type_more_qualified)
11073    << New->getDeclName() << NewTy << OldTy;
11074    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11075    return true;
11076  };
11077
11078  return false;
11079}
11080
11081/// \brief Mark the given method pure.
11082///
11083/// \param Method the method to be marked pure.
11084///
11085/// \param InitRange the source range that covers the "0" initializer.
11086bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11087  SourceLocation EndLoc = InitRange.getEnd();
11088  if (EndLoc.isValid())
11089    Method->setRangeEnd(EndLoc);
11090
11091  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11092    Method->setPure();
11093    return false;
11094  }
11095
11096  if (!Method->isInvalidDecl())
11097    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11098      << Method->getDeclName() << InitRange;
11099  return true;
11100}
11101
11102/// \brief Determine whether the given declaration is a static data member.
11103static bool isStaticDataMember(Decl *D) {
11104  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11105  if (!Var)
11106    return false;
11107
11108  return Var->isStaticDataMember();
11109}
11110/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11111/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11112/// is a fresh scope pushed for just this purpose.
11113///
11114/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11115/// static data member of class X, names should be looked up in the scope of
11116/// class X.
11117void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11118  // If there is no declaration, there was an error parsing it.
11119  if (D == 0 || D->isInvalidDecl()) return;
11120
11121  // We should only get called for declarations with scope specifiers, like:
11122  //   int foo::bar;
11123  assert(D->isOutOfLine());
11124  EnterDeclaratorContext(S, D->getDeclContext());
11125
11126  // If we are parsing the initializer for a static data member, push a
11127  // new expression evaluation context that is associated with this static
11128  // data member.
11129  if (isStaticDataMember(D))
11130    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11131}
11132
11133/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11134/// initializer for the out-of-line declaration 'D'.
11135void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11136  // If there is no declaration, there was an error parsing it.
11137  if (D == 0 || D->isInvalidDecl()) return;
11138
11139  if (isStaticDataMember(D))
11140    PopExpressionEvaluationContext();
11141
11142  assert(D->isOutOfLine());
11143  ExitDeclaratorContext(S);
11144}
11145
11146/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11147/// C++ if/switch/while/for statement.
11148/// e.g: "if (int x = f()) {...}"
11149DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11150  // C++ 6.4p2:
11151  // The declarator shall not specify a function or an array.
11152  // The type-specifier-seq shall not contain typedef and shall not declare a
11153  // new class or enumeration.
11154  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11155         "Parser allowed 'typedef' as storage class of condition decl.");
11156
11157  Decl *Dcl = ActOnDeclarator(S, D);
11158  if (!Dcl)
11159    return true;
11160
11161  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11162    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11163      << D.getSourceRange();
11164    return true;
11165  }
11166
11167  return Dcl;
11168}
11169
11170void Sema::LoadExternalVTableUses() {
11171  if (!ExternalSource)
11172    return;
11173
11174  SmallVector<ExternalVTableUse, 4> VTables;
11175  ExternalSource->ReadUsedVTables(VTables);
11176  SmallVector<VTableUse, 4> NewUses;
11177  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11178    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11179      = VTablesUsed.find(VTables[I].Record);
11180    // Even if a definition wasn't required before, it may be required now.
11181    if (Pos != VTablesUsed.end()) {
11182      if (!Pos->second && VTables[I].DefinitionRequired)
11183        Pos->second = true;
11184      continue;
11185    }
11186
11187    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11188    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11189  }
11190
11191  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11192}
11193
11194void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11195                          bool DefinitionRequired) {
11196  // Ignore any vtable uses in unevaluated operands or for classes that do
11197  // not have a vtable.
11198  if (!Class->isDynamicClass() || Class->isDependentContext() ||
11199      CurContext->isDependentContext() ||
11200      ExprEvalContexts.back().Context == Unevaluated)
11201    return;
11202
11203  // Try to insert this class into the map.
11204  LoadExternalVTableUses();
11205  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11206  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11207    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11208  if (!Pos.second) {
11209    // If we already had an entry, check to see if we are promoting this vtable
11210    // to required a definition. If so, we need to reappend to the VTableUses
11211    // list, since we may have already processed the first entry.
11212    if (DefinitionRequired && !Pos.first->second) {
11213      Pos.first->second = true;
11214    } else {
11215      // Otherwise, we can early exit.
11216      return;
11217    }
11218  }
11219
11220  // Local classes need to have their virtual members marked
11221  // immediately. For all other classes, we mark their virtual members
11222  // at the end of the translation unit.
11223  if (Class->isLocalClass())
11224    MarkVirtualMembersReferenced(Loc, Class);
11225  else
11226    VTableUses.push_back(std::make_pair(Class, Loc));
11227}
11228
11229bool Sema::DefineUsedVTables() {
11230  LoadExternalVTableUses();
11231  if (VTableUses.empty())
11232    return false;
11233
11234  // Note: The VTableUses vector could grow as a result of marking
11235  // the members of a class as "used", so we check the size each
11236  // time through the loop and prefer indices (which are stable) to
11237  // iterators (which are not).
11238  bool DefinedAnything = false;
11239  for (unsigned I = 0; I != VTableUses.size(); ++I) {
11240    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11241    if (!Class)
11242      continue;
11243
11244    SourceLocation Loc = VTableUses[I].second;
11245
11246    bool DefineVTable = true;
11247
11248    // If this class has a key function, but that key function is
11249    // defined in another translation unit, we don't need to emit the
11250    // vtable even though we're using it.
11251    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
11252    if (KeyFunction && !KeyFunction->hasBody()) {
11253      switch (KeyFunction->getTemplateSpecializationKind()) {
11254      case TSK_Undeclared:
11255      case TSK_ExplicitSpecialization:
11256      case TSK_ExplicitInstantiationDeclaration:
11257        // The key function is in another translation unit.
11258        DefineVTable = false;
11259        break;
11260
11261      case TSK_ExplicitInstantiationDefinition:
11262      case TSK_ImplicitInstantiation:
11263        // We will be instantiating the key function.
11264        break;
11265      }
11266    } else if (!KeyFunction) {
11267      // If we have a class with no key function that is the subject
11268      // of an explicit instantiation declaration, suppress the
11269      // vtable; it will live with the explicit instantiation
11270      // definition.
11271      bool IsExplicitInstantiationDeclaration
11272        = Class->getTemplateSpecializationKind()
11273                                      == TSK_ExplicitInstantiationDeclaration;
11274      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11275                                 REnd = Class->redecls_end();
11276           R != REnd; ++R) {
11277        TemplateSpecializationKind TSK
11278          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11279        if (TSK == TSK_ExplicitInstantiationDeclaration)
11280          IsExplicitInstantiationDeclaration = true;
11281        else if (TSK == TSK_ExplicitInstantiationDefinition) {
11282          IsExplicitInstantiationDeclaration = false;
11283          break;
11284        }
11285      }
11286
11287      if (IsExplicitInstantiationDeclaration)
11288        DefineVTable = false;
11289    }
11290
11291    // The exception specifications for all virtual members may be needed even
11292    // if we are not providing an authoritative form of the vtable in this TU.
11293    // We may choose to emit it available_externally anyway.
11294    if (!DefineVTable) {
11295      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11296      continue;
11297    }
11298
11299    // Mark all of the virtual members of this class as referenced, so
11300    // that we can build a vtable. Then, tell the AST consumer that a
11301    // vtable for this class is required.
11302    DefinedAnything = true;
11303    MarkVirtualMembersReferenced(Loc, Class);
11304    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11305    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11306
11307    // Optionally warn if we're emitting a weak vtable.
11308    if (Class->getLinkage() == ExternalLinkage &&
11309        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11310      const FunctionDecl *KeyFunctionDef = 0;
11311      if (!KeyFunction ||
11312          (KeyFunction->hasBody(KeyFunctionDef) &&
11313           KeyFunctionDef->isInlined()))
11314        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11315             TSK_ExplicitInstantiationDefinition
11316             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11317          << Class;
11318    }
11319  }
11320  VTableUses.clear();
11321
11322  return DefinedAnything;
11323}
11324
11325void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11326                                                 const CXXRecordDecl *RD) {
11327  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11328                                      E = RD->method_end(); I != E; ++I)
11329    if ((*I)->isVirtual() && !(*I)->isPure())
11330      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11331}
11332
11333void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11334                                        const CXXRecordDecl *RD) {
11335  // Mark all functions which will appear in RD's vtable as used.
11336  CXXFinalOverriderMap FinalOverriders;
11337  RD->getFinalOverriders(FinalOverriders);
11338  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11339                                            E = FinalOverriders.end();
11340       I != E; ++I) {
11341    for (OverridingMethods::const_iterator OI = I->second.begin(),
11342                                           OE = I->second.end();
11343         OI != OE; ++OI) {
11344      assert(OI->second.size() > 0 && "no final overrider");
11345      CXXMethodDecl *Overrider = OI->second.front().Method;
11346
11347      // C++ [basic.def.odr]p2:
11348      //   [...] A virtual member function is used if it is not pure. [...]
11349      if (!Overrider->isPure())
11350        MarkFunctionReferenced(Loc, Overrider);
11351    }
11352  }
11353
11354  // Only classes that have virtual bases need a VTT.
11355  if (RD->getNumVBases() == 0)
11356    return;
11357
11358  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11359           e = RD->bases_end(); i != e; ++i) {
11360    const CXXRecordDecl *Base =
11361        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11362    if (Base->getNumVBases() == 0)
11363      continue;
11364    MarkVirtualMembersReferenced(Loc, Base);
11365  }
11366}
11367
11368/// SetIvarInitializers - This routine builds initialization ASTs for the
11369/// Objective-C implementation whose ivars need be initialized.
11370void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11371  if (!getLangOpts().CPlusPlus)
11372    return;
11373  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11374    SmallVector<ObjCIvarDecl*, 8> ivars;
11375    CollectIvarsToConstructOrDestruct(OID, ivars);
11376    if (ivars.empty())
11377      return;
11378    SmallVector<CXXCtorInitializer*, 32> AllToInit;
11379    for (unsigned i = 0; i < ivars.size(); i++) {
11380      FieldDecl *Field = ivars[i];
11381      if (Field->isInvalidDecl())
11382        continue;
11383
11384      CXXCtorInitializer *Member;
11385      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11386      InitializationKind InitKind =
11387        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11388
11389      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
11390      ExprResult MemberInit =
11391        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
11392      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11393      // Note, MemberInit could actually come back empty if no initialization
11394      // is required (e.g., because it would call a trivial default constructor)
11395      if (!MemberInit.get() || MemberInit.isInvalid())
11396        continue;
11397
11398      Member =
11399        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11400                                         SourceLocation(),
11401                                         MemberInit.takeAs<Expr>(),
11402                                         SourceLocation());
11403      AllToInit.push_back(Member);
11404
11405      // Be sure that the destructor is accessible and is marked as referenced.
11406      if (const RecordType *RecordTy
11407                  = Context.getBaseElementType(Field->getType())
11408                                                        ->getAs<RecordType>()) {
11409                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11410        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11411          MarkFunctionReferenced(Field->getLocation(), Destructor);
11412          CheckDestructorAccess(Field->getLocation(), Destructor,
11413                            PDiag(diag::err_access_dtor_ivar)
11414                              << Context.getBaseElementType(Field->getType()));
11415        }
11416      }
11417    }
11418    ObjCImplementation->setIvarInitializers(Context,
11419                                            AllToInit.data(), AllToInit.size());
11420  }
11421}
11422
11423static
11424void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11425                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11426                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11427                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11428                           Sema &S) {
11429  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11430                                                   CE = Current.end();
11431  if (Ctor->isInvalidDecl())
11432    return;
11433
11434  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11435
11436  // Target may not be determinable yet, for instance if this is a dependent
11437  // call in an uninstantiated template.
11438  if (Target) {
11439    const FunctionDecl *FNTarget = 0;
11440    (void)Target->hasBody(FNTarget);
11441    Target = const_cast<CXXConstructorDecl*>(
11442      cast_or_null<CXXConstructorDecl>(FNTarget));
11443  }
11444
11445  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11446                     // Avoid dereferencing a null pointer here.
11447                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11448
11449  if (!Current.insert(Canonical))
11450    return;
11451
11452  // We know that beyond here, we aren't chaining into a cycle.
11453  if (!Target || !Target->isDelegatingConstructor() ||
11454      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11455    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11456      Valid.insert(*CI);
11457    Current.clear();
11458  // We've hit a cycle.
11459  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11460             Current.count(TCanonical)) {
11461    // If we haven't diagnosed this cycle yet, do so now.
11462    if (!Invalid.count(TCanonical)) {
11463      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11464             diag::warn_delegating_ctor_cycle)
11465        << Ctor;
11466
11467      // Don't add a note for a function delegating directly to itself.
11468      if (TCanonical != Canonical)
11469        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11470
11471      CXXConstructorDecl *C = Target;
11472      while (C->getCanonicalDecl() != Canonical) {
11473        const FunctionDecl *FNTarget = 0;
11474        (void)C->getTargetConstructor()->hasBody(FNTarget);
11475        assert(FNTarget && "Ctor cycle through bodiless function");
11476
11477        C = const_cast<CXXConstructorDecl*>(
11478          cast<CXXConstructorDecl>(FNTarget));
11479        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11480      }
11481    }
11482
11483    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11484      Invalid.insert(*CI);
11485    Current.clear();
11486  } else {
11487    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11488  }
11489}
11490
11491
11492void Sema::CheckDelegatingCtorCycles() {
11493  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11494
11495  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11496                                                   CE = Current.end();
11497
11498  for (DelegatingCtorDeclsType::iterator
11499         I = DelegatingCtorDecls.begin(ExternalSource),
11500         E = DelegatingCtorDecls.end();
11501       I != E; ++I)
11502    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11503
11504  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11505    (*CI)->setInvalidDecl();
11506}
11507
11508namespace {
11509  /// \brief AST visitor that finds references to the 'this' expression.
11510  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11511    Sema &S;
11512
11513  public:
11514    explicit FindCXXThisExpr(Sema &S) : S(S) { }
11515
11516    bool VisitCXXThisExpr(CXXThisExpr *E) {
11517      S.Diag(E->getLocation(), diag::err_this_static_member_func)
11518        << E->isImplicit();
11519      return false;
11520    }
11521  };
11522}
11523
11524bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11525  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11526  if (!TSInfo)
11527    return false;
11528
11529  TypeLoc TL = TSInfo->getTypeLoc();
11530  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11531  if (!ProtoTL)
11532    return false;
11533
11534  // C++11 [expr.prim.general]p3:
11535  //   [The expression this] shall not appear before the optional
11536  //   cv-qualifier-seq and it shall not appear within the declaration of a
11537  //   static member function (although its type and value category are defined
11538  //   within a static member function as they are within a non-static member
11539  //   function). [ Note: this is because declaration matching does not occur
11540  //  until the complete declarator is known. - end note ]
11541  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11542  FindCXXThisExpr Finder(*this);
11543
11544  // If the return type came after the cv-qualifier-seq, check it now.
11545  if (Proto->hasTrailingReturn() &&
11546      !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11547    return true;
11548
11549  // Check the exception specification.
11550  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11551    return true;
11552
11553  return checkThisInStaticMemberFunctionAttributes(Method);
11554}
11555
11556bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11557  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11558  if (!TSInfo)
11559    return false;
11560
11561  TypeLoc TL = TSInfo->getTypeLoc();
11562  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11563  if (!ProtoTL)
11564    return false;
11565
11566  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11567  FindCXXThisExpr Finder(*this);
11568
11569  switch (Proto->getExceptionSpecType()) {
11570  case EST_Uninstantiated:
11571  case EST_Unevaluated:
11572  case EST_BasicNoexcept:
11573  case EST_DynamicNone:
11574  case EST_MSAny:
11575  case EST_None:
11576    break;
11577
11578  case EST_ComputedNoexcept:
11579    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11580      return true;
11581
11582  case EST_Dynamic:
11583    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11584         EEnd = Proto->exception_end();
11585         E != EEnd; ++E) {
11586      if (!Finder.TraverseType(*E))
11587        return true;
11588    }
11589    break;
11590  }
11591
11592  return false;
11593}
11594
11595bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11596  FindCXXThisExpr Finder(*this);
11597
11598  // Check attributes.
11599  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11600       A != AEnd; ++A) {
11601    // FIXME: This should be emitted by tblgen.
11602    Expr *Arg = 0;
11603    ArrayRef<Expr *> Args;
11604    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11605      Arg = G->getArg();
11606    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11607      Arg = G->getArg();
11608    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11609      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11610    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11611      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11612    else if (ExclusiveLockFunctionAttr *ELF
11613               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11614      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11615    else if (SharedLockFunctionAttr *SLF
11616               = dyn_cast<SharedLockFunctionAttr>(*A))
11617      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11618    else if (ExclusiveTrylockFunctionAttr *ETLF
11619               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11620      Arg = ETLF->getSuccessValue();
11621      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11622    } else if (SharedTrylockFunctionAttr *STLF
11623                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11624      Arg = STLF->getSuccessValue();
11625      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11626    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11627      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11628    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11629      Arg = LR->getArg();
11630    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11631      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11632    else if (ExclusiveLocksRequiredAttr *ELR
11633               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11634      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11635    else if (SharedLocksRequiredAttr *SLR
11636               = dyn_cast<SharedLocksRequiredAttr>(*A))
11637      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11638
11639    if (Arg && !Finder.TraverseStmt(Arg))
11640      return true;
11641
11642    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11643      if (!Finder.TraverseStmt(Args[I]))
11644        return true;
11645    }
11646  }
11647
11648  return false;
11649}
11650
11651void
11652Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11653                                  ArrayRef<ParsedType> DynamicExceptions,
11654                                  ArrayRef<SourceRange> DynamicExceptionRanges,
11655                                  Expr *NoexceptExpr,
11656                                  SmallVectorImpl<QualType> &Exceptions,
11657                                  FunctionProtoType::ExtProtoInfo &EPI) {
11658  Exceptions.clear();
11659  EPI.ExceptionSpecType = EST;
11660  if (EST == EST_Dynamic) {
11661    Exceptions.reserve(DynamicExceptions.size());
11662    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11663      // FIXME: Preserve type source info.
11664      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11665
11666      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11667      collectUnexpandedParameterPacks(ET, Unexpanded);
11668      if (!Unexpanded.empty()) {
11669        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11670                                         UPPC_ExceptionType,
11671                                         Unexpanded);
11672        continue;
11673      }
11674
11675      // Check that the type is valid for an exception spec, and
11676      // drop it if not.
11677      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11678        Exceptions.push_back(ET);
11679    }
11680    EPI.NumExceptions = Exceptions.size();
11681    EPI.Exceptions = Exceptions.data();
11682    return;
11683  }
11684
11685  if (EST == EST_ComputedNoexcept) {
11686    // If an error occurred, there's no expression here.
11687    if (NoexceptExpr) {
11688      assert((NoexceptExpr->isTypeDependent() ||
11689              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11690              Context.BoolTy) &&
11691             "Parser should have made sure that the expression is boolean");
11692      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11693        EPI.ExceptionSpecType = EST_BasicNoexcept;
11694        return;
11695      }
11696
11697      if (!NoexceptExpr->isValueDependent())
11698        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11699                         diag::err_noexcept_needs_constant_expression,
11700                         /*AllowFold*/ false).take();
11701      EPI.NoexceptExpr = NoexceptExpr;
11702    }
11703    return;
11704  }
11705}
11706
11707/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11708Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11709  // Implicitly declared functions (e.g. copy constructors) are
11710  // __host__ __device__
11711  if (D->isImplicit())
11712    return CFT_HostDevice;
11713
11714  if (D->hasAttr<CUDAGlobalAttr>())
11715    return CFT_Global;
11716
11717  if (D->hasAttr<CUDADeviceAttr>()) {
11718    if (D->hasAttr<CUDAHostAttr>())
11719      return CFT_HostDevice;
11720    else
11721      return CFT_Device;
11722  }
11723
11724  return CFT_Host;
11725}
11726
11727bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11728                           CUDAFunctionTarget CalleeTarget) {
11729  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11730  // Callable from the device only."
11731  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11732    return true;
11733
11734  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11735  // Callable from the host only."
11736  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11737  // Callable from the host only."
11738  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11739      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11740    return true;
11741
11742  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11743    return true;
11744
11745  return false;
11746}
11747