SemaDeclCXX.cpp revision e761230ae3751b525cadd8066c74ec278ee4ef57
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/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/AST/ASTConsumer.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/ASTMutationListener.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/CXXInheritance.h"
24#include "clang/AST/DeclVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
32#include "clang/Basic/PartialDiagnostic.h"
33#include "clang/Lex/Preprocessor.h"
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/STLExtras.h"
36#include <map>
37#include <set>
38
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// CheckDefaultArgumentVisitor
43//===----------------------------------------------------------------------===//
44
45namespace {
46  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47  /// the default argument of a parameter to determine whether it
48  /// contains any ill-formed subexpressions. For example, this will
49  /// diagnose the use of local variables or parameters within the
50  /// default argument expression.
51  class CheckDefaultArgumentVisitor
52    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
53    Expr *DefaultArg;
54    Sema *S;
55
56  public:
57    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58      : DefaultArg(defarg), S(s) {}
59
60    bool VisitExpr(Expr *Node);
61    bool VisitDeclRefExpr(DeclRefExpr *DRE);
62    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
63  };
64
65  /// VisitExpr - Visit all of the children of this expression.
66  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67    bool IsInvalid = false;
68    for (Stmt::child_range I = Node->children(); I; ++I)
69      IsInvalid |= Visit(*I);
70    return IsInvalid;
71  }
72
73  /// VisitDeclRefExpr - Visit a reference to a declaration, to
74  /// determine whether this declaration can be used in the default
75  /// argument expression.
76  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77    NamedDecl *Decl = DRE->getDecl();
78    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79      // C++ [dcl.fct.default]p9
80      //   Default arguments are evaluated each time the function is
81      //   called. The order of evaluation of function arguments is
82      //   unspecified. Consequently, parameters of a function shall not
83      //   be used in default argument expressions, even if they are not
84      //   evaluated. Parameters of a function declared before a default
85      //   argument expression are in scope and can hide namespace and
86      //   class member names.
87      return S->Diag(DRE->getSourceRange().getBegin(),
88                     diag::err_param_default_argument_references_param)
89         << Param->getDeclName() << DefaultArg->getSourceRange();
90    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91      // C++ [dcl.fct.default]p7
92      //   Local variables shall not be used in default argument
93      //   expressions.
94      if (VDecl->isLocalVarDecl())
95        return S->Diag(DRE->getSourceRange().getBegin(),
96                       diag::err_param_default_argument_references_local)
97          << VDecl->getDeclName() << DefaultArg->getSourceRange();
98    }
99
100    return false;
101  }
102
103  /// VisitCXXThisExpr - Visit a C++ "this" expression.
104  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105    // C++ [dcl.fct.default]p8:
106    //   The keyword this shall not be used in a default argument of a
107    //   member function.
108    return S->Diag(ThisE->getSourceRange().getBegin(),
109                   diag::err_param_default_argument_references_this)
110               << ThisE->getSourceRange();
111  }
112}
113
114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115  assert(Context && "ImplicitExceptionSpecification without an ASTContext");
116  // If we have an MSAny or unknown spec already, don't bother.
117  if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
118    return;
119
120  const FunctionProtoType *Proto
121    = Method->getType()->getAs<FunctionProtoType>();
122
123  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
124
125  // If this function can throw any exceptions, make a note of that.
126  if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
127    ClearExceptions();
128    ComputedEST = EST;
129    return;
130  }
131
132  // FIXME: If the call to this decl is using any of its default arguments, we
133  // need to search them for potentially-throwing calls.
134
135  // If this function has a basic noexcept, it doesn't affect the outcome.
136  if (EST == EST_BasicNoexcept)
137    return;
138
139  // If we have a throw-all spec at this point, ignore the function.
140  if (ComputedEST == EST_None)
141    return;
142
143  // If we're still at noexcept(true) and there's a nothrow() callee,
144  // change to that specification.
145  if (EST == EST_DynamicNone) {
146    if (ComputedEST == EST_BasicNoexcept)
147      ComputedEST = EST_DynamicNone;
148    return;
149  }
150
151  // Check out noexcept specs.
152  if (EST == EST_ComputedNoexcept) {
153    FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
154    assert(NR != FunctionProtoType::NR_NoNoexcept &&
155           "Must have noexcept result for EST_ComputedNoexcept.");
156    assert(NR != FunctionProtoType::NR_Dependent &&
157           "Should not generate implicit declarations for dependent cases, "
158           "and don't know how to handle them anyway.");
159
160    // noexcept(false) -> no spec on the new function
161    if (NR == FunctionProtoType::NR_Throw) {
162      ClearExceptions();
163      ComputedEST = EST_None;
164    }
165    // noexcept(true) won't change anything either.
166    return;
167  }
168
169  assert(EST == EST_Dynamic && "EST case not considered earlier.");
170  assert(ComputedEST != EST_None &&
171         "Shouldn't collect exceptions when throw-all is guaranteed.");
172  ComputedEST = EST_Dynamic;
173  // Record the exceptions in this function's exception specification.
174  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175                                          EEnd = Proto->exception_end();
176       E != EEnd; ++E)
177    if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178      Exceptions.push_back(*E);
179}
180
181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182  if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
183    return;
184
185  // FIXME:
186  //
187  // C++0x [except.spec]p14:
188  //   [An] implicit exception-specification specifies the type-id T if and
189  // only if T is allowed by the exception-specification of a function directly
190  // invoked by f's implicit definition; f shall allow all exceptions if any
191  // function it directly invokes allows all exceptions, and f shall allow no
192  // exceptions if every function it directly invokes allows no exceptions.
193  //
194  // Note in particular that if an implicit exception-specification is generated
195  // for a function containing a throw-expression, that specification can still
196  // be noexcept(true).
197  //
198  // Note also that 'directly invoked' is not defined in the standard, and there
199  // is no indication that we should only consider potentially-evaluated calls.
200  //
201  // Ultimately we should implement the intent of the standard: the exception
202  // specification should be the set of exceptions which can be thrown by the
203  // implicit definition. For now, we assume that any non-nothrow expression can
204  // throw any exception.
205
206  if (E->CanThrow(*Context))
207    ComputedEST = EST_None;
208}
209
210bool
211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
212                              SourceLocation EqualLoc) {
213  if (RequireCompleteType(Param->getLocation(), Param->getType(),
214                          diag::err_typecheck_decl_incomplete_type)) {
215    Param->setInvalidDecl();
216    return true;
217  }
218
219  // C++ [dcl.fct.default]p5
220  //   A default argument expression is implicitly converted (clause
221  //   4) to the parameter type. The default argument expression has
222  //   the same semantic constraints as the initializer expression in
223  //   a declaration of a variable of the parameter type, using the
224  //   copy-initialization semantics (8.5).
225  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
226                                                                    Param);
227  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
228                                                           EqualLoc);
229  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
230  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
231                                      MultiExprArg(*this, &Arg, 1));
232  if (Result.isInvalid())
233    return true;
234  Arg = Result.takeAs<Expr>();
235
236  CheckImplicitConversions(Arg, EqualLoc);
237  Arg = MaybeCreateExprWithCleanups(Arg);
238
239  // Okay: add the default argument to the parameter
240  Param->setDefaultArg(Arg);
241
242  // We have already instantiated this parameter; provide each of the
243  // instantiations with the uninstantiated default argument.
244  UnparsedDefaultArgInstantiationsMap::iterator InstPos
245    = UnparsedDefaultArgInstantiations.find(Param);
246  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
249
250    // We're done tracking this parameter's instantiations.
251    UnparsedDefaultArgInstantiations.erase(InstPos);
252  }
253
254  return false;
255}
256
257/// ActOnParamDefaultArgument - Check whether the default argument
258/// provided for a function parameter is well-formed. If so, attach it
259/// to the parameter declaration.
260void
261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
262                                Expr *DefaultArg) {
263  if (!param || !DefaultArg)
264    return;
265
266  ParmVarDecl *Param = cast<ParmVarDecl>(param);
267  UnparsedDefaultArgLocs.erase(Param);
268
269  // Default arguments are only permitted in C++
270  if (!getLangOptions().CPlusPlus) {
271    Diag(EqualLoc, diag::err_param_default_argument)
272      << DefaultArg->getSourceRange();
273    Param->setInvalidDecl();
274    return;
275  }
276
277  // Check for unexpanded parameter packs.
278  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279    Param->setInvalidDecl();
280    return;
281  }
282
283  // Check that the default argument is well-formed
284  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285  if (DefaultArgChecker.Visit(DefaultArg)) {
286    Param->setInvalidDecl();
287    return;
288  }
289
290  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
291}
292
293/// ActOnParamUnparsedDefaultArgument - We've seen a default
294/// argument for a function parameter, but we can't parse it yet
295/// because we're inside a class definition. Note that this default
296/// argument will be parsed later.
297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298                                             SourceLocation EqualLoc,
299                                             SourceLocation ArgLoc) {
300  if (!param)
301    return;
302
303  ParmVarDecl *Param = cast<ParmVarDecl>(param);
304  if (Param)
305    Param->setUnparsedDefaultArg();
306
307  UnparsedDefaultArgLocs[Param] = ArgLoc;
308}
309
310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311/// the default argument for the parameter param failed.
312void Sema::ActOnParamDefaultArgumentError(Decl *param) {
313  if (!param)
314    return;
315
316  ParmVarDecl *Param = cast<ParmVarDecl>(param);
317
318  Param->setInvalidDecl();
319
320  UnparsedDefaultArgLocs.erase(Param);
321}
322
323/// CheckExtraCXXDefaultArguments - Check for any extra default
324/// arguments in the declarator, which is not a function declaration
325/// or definition and therefore is not permitted to have default
326/// arguments. This routine should be invoked for every declarator
327/// that is not a function declaration or definition.
328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329  // C++ [dcl.fct.default]p3
330  //   A default argument expression shall be specified only in the
331  //   parameter-declaration-clause of a function declaration or in a
332  //   template-parameter (14.1). It shall not be specified for a
333  //   parameter pack. If it is specified in a
334  //   parameter-declaration-clause, it shall not occur within a
335  //   declarator or abstract-declarator of a parameter-declaration.
336  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
337    DeclaratorChunk &chunk = D.getTypeObject(i);
338    if (chunk.Kind == DeclaratorChunk::Function) {
339      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
340        ParmVarDecl *Param =
341          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
342        if (Param->hasUnparsedDefaultArg()) {
343          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
344          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
346          delete Toks;
347          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
348        } else if (Param->getDefaultArg()) {
349          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350            << Param->getDefaultArg()->getSourceRange();
351          Param->setDefaultArg(0);
352        }
353      }
354    }
355  }
356}
357
358// MergeCXXFunctionDecl - Merge two declarations of the same C++
359// function, once we already know that they have the same
360// type. Subroutine of MergeFunctionDecl. Returns true if there was an
361// error, false otherwise.
362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363  bool Invalid = false;
364
365  // C++ [dcl.fct.default]p4:
366  //   For non-template functions, default arguments can be added in
367  //   later declarations of a function in the same
368  //   scope. Declarations in different scopes have completely
369  //   distinct sets of default arguments. That is, declarations in
370  //   inner scopes do not acquire default arguments from
371  //   declarations in outer scopes, and vice versa. In a given
372  //   function declaration, all parameters subsequent to a
373  //   parameter with a default argument shall have default
374  //   arguments supplied in this or previous declarations. A
375  //   default argument shall not be redefined by a later
376  //   declaration (not even to the same value).
377  //
378  // C++ [dcl.fct.default]p6:
379  //   Except for member functions of class templates, the default arguments
380  //   in a member function definition that appears outside of the class
381  //   definition are added to the set of default arguments provided by the
382  //   member function declaration in the class definition.
383  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384    ParmVarDecl *OldParam = Old->getParamDecl(p);
385    ParmVarDecl *NewParam = New->getParamDecl(p);
386
387    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
388
389      unsigned DiagDefaultParamID =
390        diag::err_param_default_argument_redefinition;
391
392      // MSVC accepts that default parameters be redefined for member functions
393      // of template class. The new default parameter's value is ignored.
394      Invalid = true;
395      if (getLangOptions().Microsoft) {
396        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397        if (MD && MD->getParent()->getDescribedClassTemplate()) {
398          // Merge the old default argument into the new parameter.
399          NewParam->setHasInheritedDefaultArg();
400          if (OldParam->hasUninstantiatedDefaultArg())
401            NewParam->setUninstantiatedDefaultArg(
402                                      OldParam->getUninstantiatedDefaultArg());
403          else
404            NewParam->setDefaultArg(OldParam->getInit());
405          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
406          Invalid = false;
407        }
408      }
409
410      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411      // hint here. Alternatively, we could walk the type-source information
412      // for NewParam to find the last source location in the type... but it
413      // isn't worth the effort right now. This is the kind of test case that
414      // is hard to get right:
415      //   int f(int);
416      //   void g(int (*fp)(int) = f);
417      //   void g(int (*fp)(int) = &f);
418      Diag(NewParam->getLocation(), DiagDefaultParamID)
419        << NewParam->getDefaultArgRange();
420
421      // Look for the function declaration where the default argument was
422      // actually written, which may be a declaration prior to Old.
423      for (FunctionDecl *Older = Old->getPreviousDeclaration();
424           Older; Older = Older->getPreviousDeclaration()) {
425        if (!Older->getParamDecl(p)->hasDefaultArg())
426          break;
427
428        OldParam = Older->getParamDecl(p);
429      }
430
431      Diag(OldParam->getLocation(), diag::note_previous_definition)
432        << OldParam->getDefaultArgRange();
433    } else if (OldParam->hasDefaultArg()) {
434      // Merge the old default argument into the new parameter.
435      // It's important to use getInit() here;  getDefaultArg()
436      // strips off any top-level ExprWithCleanups.
437      NewParam->setHasInheritedDefaultArg();
438      if (OldParam->hasUninstantiatedDefaultArg())
439        NewParam->setUninstantiatedDefaultArg(
440                                      OldParam->getUninstantiatedDefaultArg());
441      else
442        NewParam->setDefaultArg(OldParam->getInit());
443    } else if (NewParam->hasDefaultArg()) {
444      if (New->getDescribedFunctionTemplate()) {
445        // Paragraph 4, quoted above, only applies to non-template functions.
446        Diag(NewParam->getLocation(),
447             diag::err_param_default_argument_template_redecl)
448          << NewParam->getDefaultArgRange();
449        Diag(Old->getLocation(), diag::note_template_prev_declaration)
450          << false;
451      } else if (New->getTemplateSpecializationKind()
452                   != TSK_ImplicitInstantiation &&
453                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454        // C++ [temp.expr.spec]p21:
455        //   Default function arguments shall not be specified in a declaration
456        //   or a definition for one of the following explicit specializations:
457        //     - the explicit specialization of a function template;
458        //     - the explicit specialization of a member function template;
459        //     - the explicit specialization of a member function of a class
460        //       template where the class template specialization to which the
461        //       member function specialization belongs is implicitly
462        //       instantiated.
463        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465          << New->getDeclName()
466          << NewParam->getDefaultArgRange();
467      } else if (New->getDeclContext()->isDependentContext()) {
468        // C++ [dcl.fct.default]p6 (DR217):
469        //   Default arguments for a member function of a class template shall
470        //   be specified on the initial declaration of the member function
471        //   within the class template.
472        //
473        // Reading the tea leaves a bit in DR217 and its reference to DR205
474        // leads me to the conclusion that one cannot add default function
475        // arguments for an out-of-line definition of a member function of a
476        // dependent type.
477        int WhichKind = 2;
478        if (CXXRecordDecl *Record
479              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480          if (Record->getDescribedClassTemplate())
481            WhichKind = 0;
482          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
483            WhichKind = 1;
484          else
485            WhichKind = 2;
486        }
487
488        Diag(NewParam->getLocation(),
489             diag::err_param_default_argument_member_template_redecl)
490          << WhichKind
491          << NewParam->getDefaultArgRange();
492      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493        CXXSpecialMember NewSM = getSpecialMember(Ctor),
494                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495        if (NewSM != OldSM) {
496          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497            << NewParam->getDefaultArgRange() << NewSM;
498          Diag(Old->getLocation(), diag::note_previous_declaration_special)
499            << OldSM;
500        }
501      }
502    }
503  }
504
505  if (CheckEquivalentExceptionSpec(Old, New))
506    Invalid = true;
507
508  return Invalid;
509}
510
511/// \brief Merge the exception specifications of two variable declarations.
512///
513/// This is called when there's a redeclaration of a VarDecl. The function
514/// checks if the redeclaration might have an exception specification and
515/// validates compatibility and merges the specs if necessary.
516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517  // Shortcut if exceptions are disabled.
518  if (!getLangOptions().CXXExceptions)
519    return;
520
521  assert(Context.hasSameType(New->getType(), Old->getType()) &&
522         "Should only be called if types are otherwise the same.");
523
524  QualType NewType = New->getType();
525  QualType OldType = Old->getType();
526
527  // We're only interested in pointers and references to functions, as well
528  // as pointers to member functions.
529  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530    NewType = R->getPointeeType();
531    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533    NewType = P->getPointeeType();
534    OldType = OldType->getAs<PointerType>()->getPointeeType();
535  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536    NewType = M->getPointeeType();
537    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
538  }
539
540  if (!NewType->isFunctionProtoType())
541    return;
542
543  // There's lots of special cases for functions. For function pointers, system
544  // libraries are hopefully not as broken so that we don't need these
545  // workarounds.
546  if (CheckEquivalentExceptionSpec(
547        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549    New->setInvalidDecl();
550  }
551}
552
553/// CheckCXXDefaultArguments - Verify that the default arguments for a
554/// function declaration are well-formed according to C++
555/// [dcl.fct.default].
556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557  unsigned NumParams = FD->getNumParams();
558  unsigned p;
559
560  // Find first parameter with a default argument
561  for (p = 0; p < NumParams; ++p) {
562    ParmVarDecl *Param = FD->getParamDecl(p);
563    if (Param->hasDefaultArg())
564      break;
565  }
566
567  // C++ [dcl.fct.default]p4:
568  //   In a given function declaration, all parameters
569  //   subsequent to a parameter with a default argument shall
570  //   have default arguments supplied in this or previous
571  //   declarations. A default argument shall not be redefined
572  //   by a later declaration (not even to the same value).
573  unsigned LastMissingDefaultArg = 0;
574  for (; p < NumParams; ++p) {
575    ParmVarDecl *Param = FD->getParamDecl(p);
576    if (!Param->hasDefaultArg()) {
577      if (Param->isInvalidDecl())
578        /* We already complained about this parameter. */;
579      else if (Param->getIdentifier())
580        Diag(Param->getLocation(),
581             diag::err_param_default_argument_missing_name)
582          << Param->getIdentifier();
583      else
584        Diag(Param->getLocation(),
585             diag::err_param_default_argument_missing);
586
587      LastMissingDefaultArg = p;
588    }
589  }
590
591  if (LastMissingDefaultArg > 0) {
592    // Some default arguments were missing. Clear out all of the
593    // default arguments up to (and including) the last missing
594    // default argument, so that we leave the function parameters
595    // in a semantically valid state.
596    for (p = 0; p <= LastMissingDefaultArg; ++p) {
597      ParmVarDecl *Param = FD->getParamDecl(p);
598      if (Param->hasDefaultArg()) {
599        Param->setDefaultArg(0);
600      }
601    }
602  }
603}
604
605/// isCurrentClassName - Determine whether the identifier II is the
606/// name of the class type currently being defined. In the case of
607/// nested classes, this will only return true if II is the name of
608/// the innermost class.
609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610                              const CXXScopeSpec *SS) {
611  assert(getLangOptions().CPlusPlus && "No class names in C!");
612
613  CXXRecordDecl *CurDecl;
614  if (SS && SS->isSet() && !SS->isInvalid()) {
615    DeclContext *DC = computeDeclContext(*SS, true);
616    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
617  } else
618    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
619
620  if (CurDecl && CurDecl->getIdentifier())
621    return &II == CurDecl->getIdentifier();
622  else
623    return false;
624}
625
626/// \brief Check the validity of a C++ base class specifier.
627///
628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629/// and returns NULL otherwise.
630CXXBaseSpecifier *
631Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632                         SourceRange SpecifierRange,
633                         bool Virtual, AccessSpecifier Access,
634                         TypeSourceInfo *TInfo,
635                         SourceLocation EllipsisLoc) {
636  QualType BaseType = TInfo->getType();
637
638  // C++ [class.union]p1:
639  //   A union shall not have base classes.
640  if (Class->isUnion()) {
641    Diag(Class->getLocation(), diag::err_base_clause_on_union)
642      << SpecifierRange;
643    return 0;
644  }
645
646  if (EllipsisLoc.isValid() &&
647      !TInfo->getType()->containsUnexpandedParameterPack()) {
648    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649      << TInfo->getTypeLoc().getSourceRange();
650    EllipsisLoc = SourceLocation();
651  }
652
653  if (BaseType->isDependentType())
654    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
655                                          Class->getTagKind() == TTK_Class,
656                                          Access, TInfo, EllipsisLoc);
657
658  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
659
660  // Base specifiers must be record types.
661  if (!BaseType->isRecordType()) {
662    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
663    return 0;
664  }
665
666  // C++ [class.union]p1:
667  //   A union shall not be used as a base class.
668  if (BaseType->isUnionType()) {
669    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
670    return 0;
671  }
672
673  // C++ [class.derived]p2:
674  //   The class-name in a base-specifier shall not be an incompletely
675  //   defined class.
676  if (RequireCompleteType(BaseLoc, BaseType,
677                          PDiag(diag::err_incomplete_base_class)
678                            << SpecifierRange)) {
679    Class->setInvalidDecl();
680    return 0;
681  }
682
683  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
684  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
685  assert(BaseDecl && "Record type has no declaration");
686  BaseDecl = BaseDecl->getDefinition();
687  assert(BaseDecl && "Base type is not incomplete, but has no definition");
688  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689  assert(CXXBaseDecl && "Base type is not a C++ type");
690
691  // C++ [class]p3:
692  //   If a class is marked final and it appears as a base-type-specifier in
693  //   base-clause, the program is ill-formed.
694  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
695    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696      << CXXBaseDecl->getDeclName();
697    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698      << CXXBaseDecl->getDeclName();
699    return 0;
700  }
701
702  if (BaseDecl->isInvalidDecl())
703    Class->setInvalidDecl();
704
705  // Create the base specifier.
706  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
707                                        Class->getTagKind() == TTK_Class,
708                                        Access, TInfo, EllipsisLoc);
709}
710
711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712/// one entry in the base class list of a class specifier, for
713/// example:
714///    class foo : public bar, virtual private baz {
715/// 'public bar' and 'virtual private baz' are each base-specifiers.
716BaseResult
717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
718                         bool Virtual, AccessSpecifier Access,
719                         ParsedType basetype, SourceLocation BaseLoc,
720                         SourceLocation EllipsisLoc) {
721  if (!classdecl)
722    return true;
723
724  AdjustDeclIfTemplate(classdecl);
725  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
726  if (!Class)
727    return true;
728
729  TypeSourceInfo *TInfo = 0;
730  GetTypeFromParser(basetype, &TInfo);
731
732  if (EllipsisLoc.isInvalid() &&
733      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
734                                      UPPC_BaseType))
735    return true;
736
737  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
738                                                      Virtual, Access, TInfo,
739                                                      EllipsisLoc))
740    return BaseSpec;
741
742  return true;
743}
744
745/// \brief Performs the actual work of attaching the given base class
746/// specifiers to a C++ class.
747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
748                                unsigned NumBases) {
749 if (NumBases == 0)
750    return false;
751
752  // Used to keep track of which base types we have already seen, so
753  // that we can properly diagnose redundant direct base types. Note
754  // that the key is always the unqualified canonical type of the base
755  // class.
756  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
757
758  // Copy non-redundant base specifiers into permanent storage.
759  unsigned NumGoodBases = 0;
760  bool Invalid = false;
761  for (unsigned idx = 0; idx < NumBases; ++idx) {
762    QualType NewBaseType
763      = Context.getCanonicalType(Bases[idx]->getType());
764    NewBaseType = NewBaseType.getLocalUnqualifiedType();
765    if (KnownBaseTypes[NewBaseType]) {
766      // C++ [class.mi]p3:
767      //   A class shall not be specified as a direct base class of a
768      //   derived class more than once.
769      Diag(Bases[idx]->getSourceRange().getBegin(),
770           diag::err_duplicate_base_class)
771        << KnownBaseTypes[NewBaseType]->getType()
772        << Bases[idx]->getSourceRange();
773
774      // Delete the duplicate base class specifier; we're going to
775      // overwrite its pointer later.
776      Context.Deallocate(Bases[idx]);
777
778      Invalid = true;
779    } else {
780      // Okay, add this new base class.
781      KnownBaseTypes[NewBaseType] = Bases[idx];
782      Bases[NumGoodBases++] = Bases[idx];
783    }
784  }
785
786  // Attach the remaining base class specifiers to the derived class.
787  Class->setBases(Bases, NumGoodBases);
788
789  // Delete the remaining (good) base class specifiers, since their
790  // data has been copied into the CXXRecordDecl.
791  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
792    Context.Deallocate(Bases[idx]);
793
794  return Invalid;
795}
796
797/// ActOnBaseSpecifiers - Attach the given base specifiers to the
798/// class, after checking whether there are any duplicate base
799/// classes.
800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
801                               unsigned NumBases) {
802  if (!ClassDecl || !Bases || !NumBases)
803    return;
804
805  AdjustDeclIfTemplate(ClassDecl);
806  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
807                       (CXXBaseSpecifier**)(Bases), NumBases);
808}
809
810static CXXRecordDecl *GetClassForType(QualType T) {
811  if (const RecordType *RT = T->getAs<RecordType>())
812    return cast<CXXRecordDecl>(RT->getDecl());
813  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
814    return ICT->getDecl();
815  else
816    return 0;
817}
818
819/// \brief Determine whether the type \p Derived is a C++ class that is
820/// derived from the type \p Base.
821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
822  if (!getLangOptions().CPlusPlus)
823    return false;
824
825  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
826  if (!DerivedRD)
827    return false;
828
829  CXXRecordDecl *BaseRD = GetClassForType(Base);
830  if (!BaseRD)
831    return false;
832
833  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
834  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
835}
836
837/// \brief Determine whether the type \p Derived is a C++ class that is
838/// derived from the type \p Base.
839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
840  if (!getLangOptions().CPlusPlus)
841    return false;
842
843  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
844  if (!DerivedRD)
845    return false;
846
847  CXXRecordDecl *BaseRD = GetClassForType(Base);
848  if (!BaseRD)
849    return false;
850
851  return DerivedRD->isDerivedFrom(BaseRD, Paths);
852}
853
854void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
855                              CXXCastPath &BasePathArray) {
856  assert(BasePathArray.empty() && "Base path array must be empty!");
857  assert(Paths.isRecordingPaths() && "Must record paths!");
858
859  const CXXBasePath &Path = Paths.front();
860
861  // We first go backward and check if we have a virtual base.
862  // FIXME: It would be better if CXXBasePath had the base specifier for
863  // the nearest virtual base.
864  unsigned Start = 0;
865  for (unsigned I = Path.size(); I != 0; --I) {
866    if (Path[I - 1].Base->isVirtual()) {
867      Start = I - 1;
868      break;
869    }
870  }
871
872  // Now add all bases.
873  for (unsigned I = Start, E = Path.size(); I != E; ++I)
874    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
875}
876
877/// \brief Determine whether the given base path includes a virtual
878/// base class.
879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
880  for (CXXCastPath::const_iterator B = BasePath.begin(),
881                                BEnd = BasePath.end();
882       B != BEnd; ++B)
883    if ((*B)->isVirtual())
884      return true;
885
886  return false;
887}
888
889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
890/// conversion (where Derived and Base are class types) is
891/// well-formed, meaning that the conversion is unambiguous (and
892/// that all of the base classes are accessible). Returns true
893/// and emits a diagnostic if the code is ill-formed, returns false
894/// otherwise. Loc is the location where this routine should point to
895/// if there is an error, and Range is the source range to highlight
896/// if there is an error.
897bool
898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
899                                   unsigned InaccessibleBaseID,
900                                   unsigned AmbigiousBaseConvID,
901                                   SourceLocation Loc, SourceRange Range,
902                                   DeclarationName Name,
903                                   CXXCastPath *BasePath) {
904  // First, determine whether the path from Derived to Base is
905  // ambiguous. This is slightly more expensive than checking whether
906  // the Derived to Base conversion exists, because here we need to
907  // explore multiple paths to determine if there is an ambiguity.
908  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
909                     /*DetectVirtual=*/false);
910  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
911  assert(DerivationOkay &&
912         "Can only be used with a derived-to-base conversion");
913  (void)DerivationOkay;
914
915  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
916    if (InaccessibleBaseID) {
917      // Check that the base class can be accessed.
918      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
919                                   InaccessibleBaseID)) {
920        case AR_inaccessible:
921          return true;
922        case AR_accessible:
923        case AR_dependent:
924        case AR_delayed:
925          break;
926      }
927    }
928
929    // Build a base path if necessary.
930    if (BasePath)
931      BuildBasePathArray(Paths, *BasePath);
932    return false;
933  }
934
935  // We know that the derived-to-base conversion is ambiguous, and
936  // we're going to produce a diagnostic. Perform the derived-to-base
937  // search just one more time to compute all of the possible paths so
938  // that we can print them out. This is more expensive than any of
939  // the previous derived-to-base checks we've done, but at this point
940  // performance isn't as much of an issue.
941  Paths.clear();
942  Paths.setRecordingPaths(true);
943  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
944  assert(StillOkay && "Can only be used with a derived-to-base conversion");
945  (void)StillOkay;
946
947  // Build up a textual representation of the ambiguous paths, e.g.,
948  // D -> B -> A, that will be used to illustrate the ambiguous
949  // conversions in the diagnostic. We only print one of the paths
950  // to each base class subobject.
951  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
952
953  Diag(Loc, AmbigiousBaseConvID)
954  << Derived << Base << PathDisplayStr << Range << Name;
955  return true;
956}
957
958bool
959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
960                                   SourceLocation Loc, SourceRange Range,
961                                   CXXCastPath *BasePath,
962                                   bool IgnoreAccess) {
963  return CheckDerivedToBaseConversion(Derived, Base,
964                                      IgnoreAccess ? 0
965                                       : diag::err_upcast_to_inaccessible_base,
966                                      diag::err_ambiguous_derived_to_base_conv,
967                                      Loc, Range, DeclarationName(),
968                                      BasePath);
969}
970
971
972/// @brief Builds a string representing ambiguous paths from a
973/// specific derived class to different subobjects of the same base
974/// class.
975///
976/// This function builds a string that can be used in error messages
977/// to show the different paths that one can take through the
978/// inheritance hierarchy to go from the derived class to different
979/// subobjects of a base class. The result looks something like this:
980/// @code
981/// struct D -> struct B -> struct A
982/// struct D -> struct C -> struct A
983/// @endcode
984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
985  std::string PathDisplayStr;
986  std::set<unsigned> DisplayedPaths;
987  for (CXXBasePaths::paths_iterator Path = Paths.begin();
988       Path != Paths.end(); ++Path) {
989    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
990      // We haven't displayed a path to this particular base
991      // class subobject yet.
992      PathDisplayStr += "\n    ";
993      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
994      for (CXXBasePath::const_iterator Element = Path->begin();
995           Element != Path->end(); ++Element)
996        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
997    }
998  }
999
1000  return PathDisplayStr;
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// C++ class member Handling
1005//===----------------------------------------------------------------------===//
1006
1007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1009                                 SourceLocation ASLoc,
1010                                 SourceLocation ColonLoc) {
1011  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1012  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1013                                                  ASLoc, ColonLoc);
1014  CurContext->addHiddenDecl(ASDecl);
1015  return ASDecl;
1016}
1017
1018/// CheckOverrideControl - Check C++0x override control semantics.
1019void Sema::CheckOverrideControl(const Decl *D) {
1020  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1021  if (!MD || !MD->isVirtual())
1022    return;
1023
1024  if (MD->isDependentContext())
1025    return;
1026
1027  // C++0x [class.virtual]p3:
1028  //   If a virtual function is marked with the virt-specifier override and does
1029  //   not override a member function of a base class,
1030  //   the program is ill-formed.
1031  bool HasOverriddenMethods =
1032    MD->begin_overridden_methods() != MD->end_overridden_methods();
1033  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1034    Diag(MD->getLocation(),
1035                 diag::err_function_marked_override_not_overriding)
1036      << MD->getDeclName();
1037    return;
1038  }
1039}
1040
1041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1042/// function overrides a virtual member function marked 'final', according to
1043/// C++0x [class.virtual]p3.
1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1045                                                  const CXXMethodDecl *Old) {
1046  if (!Old->hasAttr<FinalAttr>())
1047    return false;
1048
1049  Diag(New->getLocation(), diag::err_final_function_overridden)
1050    << New->getDeclName();
1051  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1052  return true;
1053}
1054
1055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1057/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1059/// present but parsing it has been deferred.
1060Decl *
1061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1062                               MultiTemplateParamsArg TemplateParameterLists,
1063                               Expr *BW, const VirtSpecifiers &VS,
1064                               Expr *InitExpr, bool HasDeferredInit,
1065                               bool IsDefinition) {
1066  const DeclSpec &DS = D.getDeclSpec();
1067  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1068  DeclarationName Name = NameInfo.getName();
1069  SourceLocation Loc = NameInfo.getLoc();
1070
1071  // For anonymous bitfields, the location should point to the type.
1072  if (Loc.isInvalid())
1073    Loc = D.getSourceRange().getBegin();
1074
1075  Expr *BitWidth = static_cast<Expr*>(BW);
1076  Expr *Init = static_cast<Expr*>(InitExpr);
1077
1078  assert(isa<CXXRecordDecl>(CurContext));
1079  assert(!DS.isFriendSpecified());
1080  assert(!Init || !HasDeferredInit);
1081
1082  bool isFunc = D.isDeclarationOfFunction();
1083
1084  // C++ 9.2p6: A member shall not be declared to have automatic storage
1085  // duration (auto, register) or with the extern storage-class-specifier.
1086  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1087  // data members and cannot be applied to names declared const or static,
1088  // and cannot be applied to reference members.
1089  switch (DS.getStorageClassSpec()) {
1090    case DeclSpec::SCS_unspecified:
1091    case DeclSpec::SCS_typedef:
1092    case DeclSpec::SCS_static:
1093      // FALL THROUGH.
1094      break;
1095    case DeclSpec::SCS_mutable:
1096      if (isFunc) {
1097        if (DS.getStorageClassSpecLoc().isValid())
1098          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1099        else
1100          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1101
1102        // FIXME: It would be nicer if the keyword was ignored only for this
1103        // declarator. Otherwise we could get follow-up errors.
1104        D.getMutableDeclSpec().ClearStorageClassSpecs();
1105      }
1106      break;
1107    default:
1108      if (DS.getStorageClassSpecLoc().isValid())
1109        Diag(DS.getStorageClassSpecLoc(),
1110             diag::err_storageclass_invalid_for_member);
1111      else
1112        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1113      D.getMutableDeclSpec().ClearStorageClassSpecs();
1114  }
1115
1116  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1117                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1118                      !isFunc);
1119
1120  Decl *Member;
1121  if (isInstField) {
1122    CXXScopeSpec &SS = D.getCXXScopeSpec();
1123
1124    if (SS.isSet() && !SS.isInvalid()) {
1125      // The user provided a superfluous scope specifier inside a class
1126      // definition:
1127      //
1128      // class X {
1129      //   int X::member;
1130      // };
1131      DeclContext *DC = 0;
1132      if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1133        Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1134        << Name << FixItHint::CreateRemoval(SS.getRange());
1135      else
1136        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1137          << Name << SS.getRange();
1138
1139      SS.clear();
1140    }
1141
1142    // FIXME: Check for template parameters!
1143    // FIXME: Check that the name is an identifier!
1144    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1145                         HasDeferredInit, AS);
1146    assert(Member && "HandleField never returns null");
1147  } else {
1148    assert(!HasDeferredInit);
1149
1150    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
1151    if (!Member) {
1152      return 0;
1153    }
1154
1155    // Non-instance-fields can't have a bitfield.
1156    if (BitWidth) {
1157      if (Member->isInvalidDecl()) {
1158        // don't emit another diagnostic.
1159      } else if (isa<VarDecl>(Member)) {
1160        // C++ 9.6p3: A bit-field shall not be a static member.
1161        // "static member 'A' cannot be a bit-field"
1162        Diag(Loc, diag::err_static_not_bitfield)
1163          << Name << BitWidth->getSourceRange();
1164      } else if (isa<TypedefDecl>(Member)) {
1165        // "typedef member 'x' cannot be a bit-field"
1166        Diag(Loc, diag::err_typedef_not_bitfield)
1167          << Name << BitWidth->getSourceRange();
1168      } else {
1169        // A function typedef ("typedef int f(); f a;").
1170        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1171        Diag(Loc, diag::err_not_integral_type_bitfield)
1172          << Name << cast<ValueDecl>(Member)->getType()
1173          << BitWidth->getSourceRange();
1174      }
1175
1176      BitWidth = 0;
1177      Member->setInvalidDecl();
1178    }
1179
1180    Member->setAccess(AS);
1181
1182    // If we have declared a member function template, set the access of the
1183    // templated declaration as well.
1184    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1185      FunTmpl->getTemplatedDecl()->setAccess(AS);
1186  }
1187
1188  if (VS.isOverrideSpecified()) {
1189    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1190    if (!MD || !MD->isVirtual()) {
1191      Diag(Member->getLocStart(),
1192           diag::override_keyword_only_allowed_on_virtual_member_functions)
1193        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1194    } else
1195      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1196  }
1197  if (VS.isFinalSpecified()) {
1198    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1199    if (!MD || !MD->isVirtual()) {
1200      Diag(Member->getLocStart(),
1201           diag::override_keyword_only_allowed_on_virtual_member_functions)
1202      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1203    } else
1204      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1205  }
1206
1207  if (VS.getLastLocation().isValid()) {
1208    // Update the end location of a method that has a virt-specifiers.
1209    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1210      MD->setRangeEnd(VS.getLastLocation());
1211  }
1212
1213  CheckOverrideControl(Member);
1214
1215  assert((Name || isInstField) && "No identifier for non-field ?");
1216
1217  if (Init)
1218    AddInitializerToDecl(Member, Init, false,
1219                         DS.getTypeSpecType() == DeclSpec::TST_auto);
1220  else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1221           DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1222    // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1223    // data member if a brace-or-equal-initializer is provided.
1224    Diag(Loc, diag::err_auto_var_requires_init)
1225      << Name << cast<ValueDecl>(Member)->getType();
1226    Member->setInvalidDecl();
1227  }
1228
1229  FinalizeDeclaration(Member);
1230
1231  if (isInstField)
1232    FieldCollector->Add(cast<FieldDecl>(Member));
1233  return Member;
1234}
1235
1236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1237/// in-class initializer for a non-static C++ class member, and after
1238/// instantiating an in-class initializer in a class template. Such actions
1239/// are deferred until the class is complete.
1240void
1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1242                                       Expr *InitExpr) {
1243  FieldDecl *FD = cast<FieldDecl>(D);
1244
1245  if (!InitExpr) {
1246    FD->setInvalidDecl();
1247    FD->removeInClassInitializer();
1248    return;
1249  }
1250
1251  ExprResult Init = InitExpr;
1252  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1253    // FIXME: if there is no EqualLoc, this is list-initialization.
1254    Init = PerformCopyInitialization(
1255      InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1256    if (Init.isInvalid()) {
1257      FD->setInvalidDecl();
1258      return;
1259    }
1260
1261    CheckImplicitConversions(Init.get(), EqualLoc);
1262  }
1263
1264  // C++0x [class.base.init]p7:
1265  //   The initialization of each base and member constitutes a
1266  //   full-expression.
1267  Init = MaybeCreateExprWithCleanups(Init);
1268  if (Init.isInvalid()) {
1269    FD->setInvalidDecl();
1270    return;
1271  }
1272
1273  InitExpr = Init.release();
1274
1275  FD->setInClassInitializer(InitExpr);
1276}
1277
1278/// \brief Find the direct and/or virtual base specifiers that
1279/// correspond to the given base type, for use in base initialization
1280/// within a constructor.
1281static bool FindBaseInitializer(Sema &SemaRef,
1282                                CXXRecordDecl *ClassDecl,
1283                                QualType BaseType,
1284                                const CXXBaseSpecifier *&DirectBaseSpec,
1285                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1286  // First, check for a direct base class.
1287  DirectBaseSpec = 0;
1288  for (CXXRecordDecl::base_class_const_iterator Base
1289         = ClassDecl->bases_begin();
1290       Base != ClassDecl->bases_end(); ++Base) {
1291    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1292      // We found a direct base of this type. That's what we're
1293      // initializing.
1294      DirectBaseSpec = &*Base;
1295      break;
1296    }
1297  }
1298
1299  // Check for a virtual base class.
1300  // FIXME: We might be able to short-circuit this if we know in advance that
1301  // there are no virtual bases.
1302  VirtualBaseSpec = 0;
1303  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1304    // We haven't found a base yet; search the class hierarchy for a
1305    // virtual base class.
1306    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307                       /*DetectVirtual=*/false);
1308    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1309                              BaseType, Paths)) {
1310      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1311           Path != Paths.end(); ++Path) {
1312        if (Path->back().Base->isVirtual()) {
1313          VirtualBaseSpec = Path->back().Base;
1314          break;
1315        }
1316      }
1317    }
1318  }
1319
1320  return DirectBaseSpec || VirtualBaseSpec;
1321}
1322
1323/// ActOnMemInitializer - Handle a C++ member initializer.
1324MemInitResult
1325Sema::ActOnMemInitializer(Decl *ConstructorD,
1326                          Scope *S,
1327                          CXXScopeSpec &SS,
1328                          IdentifierInfo *MemberOrBase,
1329                          ParsedType TemplateTypeTy,
1330                          SourceLocation IdLoc,
1331                          SourceLocation LParenLoc,
1332                          Expr **Args, unsigned NumArgs,
1333                          SourceLocation RParenLoc,
1334                          SourceLocation EllipsisLoc) {
1335  if (!ConstructorD)
1336    return true;
1337
1338  AdjustDeclIfTemplate(ConstructorD);
1339
1340  CXXConstructorDecl *Constructor
1341    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1342  if (!Constructor) {
1343    // The user wrote a constructor initializer on a function that is
1344    // not a C++ constructor. Ignore the error for now, because we may
1345    // have more member initializers coming; we'll diagnose it just
1346    // once in ActOnMemInitializers.
1347    return true;
1348  }
1349
1350  CXXRecordDecl *ClassDecl = Constructor->getParent();
1351
1352  // C++ [class.base.init]p2:
1353  //   Names in a mem-initializer-id are looked up in the scope of the
1354  //   constructor's class and, if not found in that scope, are looked
1355  //   up in the scope containing the constructor's definition.
1356  //   [Note: if the constructor's class contains a member with the
1357  //   same name as a direct or virtual base class of the class, a
1358  //   mem-initializer-id naming the member or base class and composed
1359  //   of a single identifier refers to the class member. A
1360  //   mem-initializer-id for the hidden base class may be specified
1361  //   using a qualified name. ]
1362  if (!SS.getScopeRep() && !TemplateTypeTy) {
1363    // Look for a member, first.
1364    FieldDecl *Member = 0;
1365    DeclContext::lookup_result Result
1366      = ClassDecl->lookup(MemberOrBase);
1367    if (Result.first != Result.second) {
1368      Member = dyn_cast<FieldDecl>(*Result.first);
1369
1370      if (Member) {
1371        if (EllipsisLoc.isValid())
1372          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1373            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1374
1375        return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1376                                    LParenLoc, RParenLoc);
1377      }
1378
1379      // Handle anonymous union case.
1380      if (IndirectFieldDecl* IndirectField
1381            = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1382        if (EllipsisLoc.isValid())
1383          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1384            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1385
1386         return BuildMemberInitializer(IndirectField, (Expr**)Args,
1387                                       NumArgs, IdLoc,
1388                                       LParenLoc, RParenLoc);
1389      }
1390    }
1391  }
1392  // It didn't name a member, so see if it names a class.
1393  QualType BaseType;
1394  TypeSourceInfo *TInfo = 0;
1395
1396  if (TemplateTypeTy) {
1397    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1398  } else {
1399    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1400    LookupParsedName(R, S, &SS);
1401
1402    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1403    if (!TyD) {
1404      if (R.isAmbiguous()) return true;
1405
1406      // We don't want access-control diagnostics here.
1407      R.suppressDiagnostics();
1408
1409      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1410        bool NotUnknownSpecialization = false;
1411        DeclContext *DC = computeDeclContext(SS, false);
1412        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1413          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1414
1415        if (!NotUnknownSpecialization) {
1416          // When the scope specifier can refer to a member of an unknown
1417          // specialization, we take it as a type name.
1418          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1419                                       SS.getWithLocInContext(Context),
1420                                       *MemberOrBase, IdLoc);
1421          if (BaseType.isNull())
1422            return true;
1423
1424          R.clear();
1425          R.setLookupName(MemberOrBase);
1426        }
1427      }
1428
1429      // If no results were found, try to correct typos.
1430      TypoCorrection Corr;
1431      if (R.empty() && BaseType.isNull() &&
1432          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1433                              ClassDecl, false, CTC_NoKeywords))) {
1434        std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1435        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1436        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1437          if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1438            // We have found a non-static data member with a similar
1439            // name to what was typed; complain and initialize that
1440            // member.
1441            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1442              << MemberOrBase << true << CorrectedQuotedStr
1443              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1444            Diag(Member->getLocation(), diag::note_previous_decl)
1445              << CorrectedQuotedStr;
1446
1447            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1448                                          LParenLoc, RParenLoc);
1449          }
1450        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1451          const CXXBaseSpecifier *DirectBaseSpec;
1452          const CXXBaseSpecifier *VirtualBaseSpec;
1453          if (FindBaseInitializer(*this, ClassDecl,
1454                                  Context.getTypeDeclType(Type),
1455                                  DirectBaseSpec, VirtualBaseSpec)) {
1456            // We have found a direct or virtual base class with a
1457            // similar name to what was typed; complain and initialize
1458            // that base class.
1459            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1460              << MemberOrBase << false << CorrectedQuotedStr
1461              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1462
1463            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1464                                                             : VirtualBaseSpec;
1465            Diag(BaseSpec->getSourceRange().getBegin(),
1466                 diag::note_base_class_specified_here)
1467              << BaseSpec->getType()
1468              << BaseSpec->getSourceRange();
1469
1470            TyD = Type;
1471          }
1472        }
1473      }
1474
1475      if (!TyD && BaseType.isNull()) {
1476        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1477          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1478        return true;
1479      }
1480    }
1481
1482    if (BaseType.isNull()) {
1483      BaseType = Context.getTypeDeclType(TyD);
1484      if (SS.isSet()) {
1485        NestedNameSpecifier *Qualifier =
1486          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1487
1488        // FIXME: preserve source range information
1489        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1490      }
1491    }
1492  }
1493
1494  if (!TInfo)
1495    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1496
1497  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1498                              LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1499}
1500
1501/// Checks a member initializer expression for cases where reference (or
1502/// pointer) members are bound to by-value parameters (or their addresses).
1503static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1504                                               Expr *Init,
1505                                               SourceLocation IdLoc) {
1506  QualType MemberTy = Member->getType();
1507
1508  // We only handle pointers and references currently.
1509  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1510  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1511    return;
1512
1513  const bool IsPointer = MemberTy->isPointerType();
1514  if (IsPointer) {
1515    if (const UnaryOperator *Op
1516          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1517      // The only case we're worried about with pointers requires taking the
1518      // address.
1519      if (Op->getOpcode() != UO_AddrOf)
1520        return;
1521
1522      Init = Op->getSubExpr();
1523    } else {
1524      // We only handle address-of expression initializers for pointers.
1525      return;
1526    }
1527  }
1528
1529  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1530    // Taking the address of a temporary will be diagnosed as a hard error.
1531    if (IsPointer)
1532      return;
1533
1534    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1535      << Member << Init->getSourceRange();
1536  } else if (const DeclRefExpr *DRE
1537               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1538    // We only warn when referring to a non-reference parameter declaration.
1539    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1540    if (!Parameter || Parameter->getType()->isReferenceType())
1541      return;
1542
1543    S.Diag(Init->getExprLoc(),
1544           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1545                     : diag::warn_bind_ref_member_to_parameter)
1546      << Member << Parameter << Init->getSourceRange();
1547  } else {
1548    // Other initializers are fine.
1549    return;
1550  }
1551
1552  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1553    << (unsigned)IsPointer;
1554}
1555
1556/// Checks an initializer expression for use of uninitialized fields, such as
1557/// containing the field that is being initialized. Returns true if there is an
1558/// uninitialized field was used an updates the SourceLocation parameter; false
1559/// otherwise.
1560static bool InitExprContainsUninitializedFields(const Stmt *S,
1561                                                const ValueDecl *LhsField,
1562                                                SourceLocation *L) {
1563  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1564
1565  if (isa<CallExpr>(S)) {
1566    // Do not descend into function calls or constructors, as the use
1567    // of an uninitialized field may be valid. One would have to inspect
1568    // the contents of the function/ctor to determine if it is safe or not.
1569    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1570    // may be safe, depending on what the function/ctor does.
1571    return false;
1572  }
1573  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1574    const NamedDecl *RhsField = ME->getMemberDecl();
1575
1576    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1577      // The member expression points to a static data member.
1578      assert(VD->isStaticDataMember() &&
1579             "Member points to non-static data member!");
1580      (void)VD;
1581      return false;
1582    }
1583
1584    if (isa<EnumConstantDecl>(RhsField)) {
1585      // The member expression points to an enum.
1586      return false;
1587    }
1588
1589    if (RhsField == LhsField) {
1590      // Initializing a field with itself. Throw a warning.
1591      // But wait; there are exceptions!
1592      // Exception #1:  The field may not belong to this record.
1593      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1594      const Expr *base = ME->getBase();
1595      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1596        // Even though the field matches, it does not belong to this record.
1597        return false;
1598      }
1599      // None of the exceptions triggered; return true to indicate an
1600      // uninitialized field was used.
1601      *L = ME->getMemberLoc();
1602      return true;
1603    }
1604  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1605    // sizeof/alignof doesn't reference contents, do not warn.
1606    return false;
1607  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1608    // address-of doesn't reference contents (the pointer may be dereferenced
1609    // in the same expression but it would be rare; and weird).
1610    if (UOE->getOpcode() == UO_AddrOf)
1611      return false;
1612  }
1613  for (Stmt::const_child_range it = S->children(); it; ++it) {
1614    if (!*it) {
1615      // An expression such as 'member(arg ?: "")' may trigger this.
1616      continue;
1617    }
1618    if (InitExprContainsUninitializedFields(*it, LhsField, L))
1619      return true;
1620  }
1621  return false;
1622}
1623
1624MemInitResult
1625Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1626                             unsigned NumArgs, SourceLocation IdLoc,
1627                             SourceLocation LParenLoc,
1628                             SourceLocation RParenLoc) {
1629  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1630  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1631  assert((DirectMember || IndirectMember) &&
1632         "Member must be a FieldDecl or IndirectFieldDecl");
1633
1634  if (Member->isInvalidDecl())
1635    return true;
1636
1637  // Diagnose value-uses of fields to initialize themselves, e.g.
1638  //   foo(foo)
1639  // where foo is not also a parameter to the constructor.
1640  // TODO: implement -Wuninitialized and fold this into that framework.
1641  for (unsigned i = 0; i < NumArgs; ++i) {
1642    SourceLocation L;
1643    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1644      // FIXME: Return true in the case when other fields are used before being
1645      // uninitialized. For example, let this field be the i'th field. When
1646      // initializing the i'th field, throw a warning if any of the >= i'th
1647      // fields are used, as they are not yet initialized.
1648      // Right now we are only handling the case where the i'th field uses
1649      // itself in its initializer.
1650      Diag(L, diag::warn_field_is_uninit);
1651    }
1652  }
1653
1654  bool HasDependentArg = false;
1655  for (unsigned i = 0; i < NumArgs; i++)
1656    HasDependentArg |= Args[i]->isTypeDependent();
1657
1658  Expr *Init;
1659  if (Member->getType()->isDependentType() || HasDependentArg) {
1660    // Can't check initialization for a member of dependent type or when
1661    // any of the arguments are type-dependent expressions.
1662    Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1663                                       RParenLoc,
1664                                       Member->getType().getNonReferenceType());
1665
1666    DiscardCleanupsInEvaluationContext();
1667  } else {
1668    // Initialize the member.
1669    InitializedEntity MemberEntity =
1670      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1671                   : InitializedEntity::InitializeMember(IndirectMember, 0);
1672    InitializationKind Kind =
1673      InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1674
1675    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1676
1677    ExprResult MemberInit =
1678      InitSeq.Perform(*this, MemberEntity, Kind,
1679                      MultiExprArg(*this, Args, NumArgs), 0);
1680    if (MemberInit.isInvalid())
1681      return true;
1682
1683    CheckImplicitConversions(MemberInit.get(), LParenLoc);
1684
1685    // C++0x [class.base.init]p7:
1686    //   The initialization of each base and member constitutes a
1687    //   full-expression.
1688    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1689    if (MemberInit.isInvalid())
1690      return true;
1691
1692    // If we are in a dependent context, template instantiation will
1693    // perform this type-checking again. Just save the arguments that we
1694    // received in a ParenListExpr.
1695    // FIXME: This isn't quite ideal, since our ASTs don't capture all
1696    // of the information that we have about the member
1697    // initializer. However, deconstructing the ASTs is a dicey process,
1698    // and this approach is far more likely to get the corner cases right.
1699    if (CurContext->isDependentContext()) {
1700      Init = new (Context) ParenListExpr(
1701          Context, LParenLoc, Args, NumArgs, RParenLoc,
1702          Member->getType().getNonReferenceType());
1703    } else {
1704      Init = MemberInit.get();
1705      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
1706    }
1707  }
1708
1709  if (DirectMember) {
1710    return new (Context) CXXCtorInitializer(Context, DirectMember,
1711                                                    IdLoc, LParenLoc, Init,
1712                                                    RParenLoc);
1713  } else {
1714    return new (Context) CXXCtorInitializer(Context, IndirectMember,
1715                                                    IdLoc, LParenLoc, Init,
1716                                                    RParenLoc);
1717  }
1718}
1719
1720MemInitResult
1721Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1722                                 Expr **Args, unsigned NumArgs,
1723                                 SourceLocation NameLoc,
1724                                 SourceLocation LParenLoc,
1725                                 SourceLocation RParenLoc,
1726                                 CXXRecordDecl *ClassDecl) {
1727  SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1728  if (!LangOpts.CPlusPlus0x)
1729    return Diag(Loc, diag::err_delegation_0x_only)
1730      << TInfo->getTypeLoc().getLocalSourceRange();
1731
1732  // Initialize the object.
1733  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1734                                     QualType(ClassDecl->getTypeForDecl(), 0));
1735  InitializationKind Kind =
1736    InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1737
1738  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1739
1740  ExprResult DelegationInit =
1741    InitSeq.Perform(*this, DelegationEntity, Kind,
1742                    MultiExprArg(*this, Args, NumArgs), 0);
1743  if (DelegationInit.isInvalid())
1744    return true;
1745
1746  CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1747  CXXConstructorDecl *Constructor
1748    = ConExpr->getConstructor();
1749  assert(Constructor && "Delegating constructor with no target?");
1750
1751  CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1752
1753  // C++0x [class.base.init]p7:
1754  //   The initialization of each base and member constitutes a
1755  //   full-expression.
1756  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1757  if (DelegationInit.isInvalid())
1758    return true;
1759
1760  assert(!CurContext->isDependentContext());
1761  return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1762                                          DelegationInit.takeAs<Expr>(),
1763                                          RParenLoc);
1764}
1765
1766MemInitResult
1767Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1768                           Expr **Args, unsigned NumArgs,
1769                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1770                           CXXRecordDecl *ClassDecl,
1771                           SourceLocation EllipsisLoc) {
1772  bool HasDependentArg = false;
1773  for (unsigned i = 0; i < NumArgs; i++)
1774    HasDependentArg |= Args[i]->isTypeDependent();
1775
1776  SourceLocation BaseLoc
1777    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1778
1779  if (!BaseType->isDependentType() && !BaseType->isRecordType())
1780    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1781             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1782
1783  // C++ [class.base.init]p2:
1784  //   [...] Unless the mem-initializer-id names a nonstatic data
1785  //   member of the constructor's class or a direct or virtual base
1786  //   of that class, the mem-initializer is ill-formed. A
1787  //   mem-initializer-list can initialize a base class using any
1788  //   name that denotes that base class type.
1789  bool Dependent = BaseType->isDependentType() || HasDependentArg;
1790
1791  if (EllipsisLoc.isValid()) {
1792    // This is a pack expansion.
1793    if (!BaseType->containsUnexpandedParameterPack())  {
1794      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1795        << SourceRange(BaseLoc, RParenLoc);
1796
1797      EllipsisLoc = SourceLocation();
1798    }
1799  } else {
1800    // Check for any unexpanded parameter packs.
1801    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1802      return true;
1803
1804    for (unsigned I = 0; I != NumArgs; ++I)
1805      if (DiagnoseUnexpandedParameterPack(Args[I]))
1806        return true;
1807  }
1808
1809  // Check for direct and virtual base classes.
1810  const CXXBaseSpecifier *DirectBaseSpec = 0;
1811  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1812  if (!Dependent) {
1813    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1814                                       BaseType))
1815      return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1816                                        LParenLoc, RParenLoc, ClassDecl);
1817
1818    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1819                        VirtualBaseSpec);
1820
1821    // C++ [base.class.init]p2:
1822    // Unless the mem-initializer-id names a nonstatic data member of the
1823    // constructor's class or a direct or virtual base of that class, the
1824    // mem-initializer is ill-formed.
1825    if (!DirectBaseSpec && !VirtualBaseSpec) {
1826      // If the class has any dependent bases, then it's possible that
1827      // one of those types will resolve to the same type as
1828      // BaseType. Therefore, just treat this as a dependent base
1829      // class initialization.  FIXME: Should we try to check the
1830      // initialization anyway? It seems odd.
1831      if (ClassDecl->hasAnyDependentBases())
1832        Dependent = true;
1833      else
1834        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1835          << BaseType << Context.getTypeDeclType(ClassDecl)
1836          << BaseTInfo->getTypeLoc().getLocalSourceRange();
1837    }
1838  }
1839
1840  if (Dependent) {
1841    // Can't check initialization for a base of dependent type or when
1842    // any of the arguments are type-dependent expressions.
1843    ExprResult BaseInit
1844      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1845                                          RParenLoc, BaseType));
1846
1847    DiscardCleanupsInEvaluationContext();
1848
1849    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1850                                                    /*IsVirtual=*/false,
1851                                                    LParenLoc,
1852                                                    BaseInit.takeAs<Expr>(),
1853                                                    RParenLoc,
1854                                                    EllipsisLoc);
1855  }
1856
1857  // C++ [base.class.init]p2:
1858  //   If a mem-initializer-id is ambiguous because it designates both
1859  //   a direct non-virtual base class and an inherited virtual base
1860  //   class, the mem-initializer is ill-formed.
1861  if (DirectBaseSpec && VirtualBaseSpec)
1862    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1863      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1864
1865  CXXBaseSpecifier *BaseSpec
1866    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1867  if (!BaseSpec)
1868    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1869
1870  // Initialize the base.
1871  InitializedEntity BaseEntity =
1872    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1873  InitializationKind Kind =
1874    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1875
1876  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1877
1878  ExprResult BaseInit =
1879    InitSeq.Perform(*this, BaseEntity, Kind,
1880                    MultiExprArg(*this, Args, NumArgs), 0);
1881  if (BaseInit.isInvalid())
1882    return true;
1883
1884  CheckImplicitConversions(BaseInit.get(), LParenLoc);
1885
1886  // C++0x [class.base.init]p7:
1887  //   The initialization of each base and member constitutes a
1888  //   full-expression.
1889  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1890  if (BaseInit.isInvalid())
1891    return true;
1892
1893  // If we are in a dependent context, template instantiation will
1894  // perform this type-checking again. Just save the arguments that we
1895  // received in a ParenListExpr.
1896  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1897  // of the information that we have about the base
1898  // initializer. However, deconstructing the ASTs is a dicey process,
1899  // and this approach is far more likely to get the corner cases right.
1900  if (CurContext->isDependentContext()) {
1901    ExprResult Init
1902      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1903                                          RParenLoc, BaseType));
1904    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1905                                                    BaseSpec->isVirtual(),
1906                                                    LParenLoc,
1907                                                    Init.takeAs<Expr>(),
1908                                                    RParenLoc,
1909                                                    EllipsisLoc);
1910  }
1911
1912  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1913                                                  BaseSpec->isVirtual(),
1914                                                  LParenLoc,
1915                                                  BaseInit.takeAs<Expr>(),
1916                                                  RParenLoc,
1917                                                  EllipsisLoc);
1918}
1919
1920// Create a static_cast\<T&&>(expr).
1921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
1922  QualType ExprType = E->getType();
1923  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
1924  SourceLocation ExprLoc = E->getLocStart();
1925  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
1926      TargetType, ExprLoc);
1927
1928  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1929                                   SourceRange(ExprLoc, ExprLoc),
1930                                   E->getSourceRange()).take();
1931}
1932
1933/// ImplicitInitializerKind - How an implicit base or member initializer should
1934/// initialize its base or member.
1935enum ImplicitInitializerKind {
1936  IIK_Default,
1937  IIK_Copy,
1938  IIK_Move
1939};
1940
1941static bool
1942BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1943                             ImplicitInitializerKind ImplicitInitKind,
1944                             CXXBaseSpecifier *BaseSpec,
1945                             bool IsInheritedVirtualBase,
1946                             CXXCtorInitializer *&CXXBaseInit) {
1947  InitializedEntity InitEntity
1948    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1949                                        IsInheritedVirtualBase);
1950
1951  ExprResult BaseInit;
1952
1953  switch (ImplicitInitKind) {
1954  case IIK_Default: {
1955    InitializationKind InitKind
1956      = InitializationKind::CreateDefault(Constructor->getLocation());
1957    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1958    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1959                               MultiExprArg(SemaRef, 0, 0));
1960    break;
1961  }
1962
1963  case IIK_Move:
1964  case IIK_Copy: {
1965    bool Moving = ImplicitInitKind == IIK_Move;
1966    ParmVarDecl *Param = Constructor->getParamDecl(0);
1967    QualType ParamType = Param->getType().getNonReferenceType();
1968
1969    Expr *CopyCtorArg =
1970      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1971                          Constructor->getLocation(), ParamType,
1972                          VK_LValue, 0);
1973
1974    // Cast to the base class to avoid ambiguities.
1975    QualType ArgTy =
1976      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1977                                       ParamType.getQualifiers());
1978
1979    if (Moving) {
1980      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
1981    }
1982
1983    CXXCastPath BasePath;
1984    BasePath.push_back(BaseSpec);
1985    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1986                                            CK_UncheckedDerivedToBase,
1987                                            Moving ? VK_XValue : VK_LValue,
1988                                            &BasePath).take();
1989
1990    InitializationKind InitKind
1991      = InitializationKind::CreateDirect(Constructor->getLocation(),
1992                                         SourceLocation(), SourceLocation());
1993    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1994                                   &CopyCtorArg, 1);
1995    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1996                               MultiExprArg(&CopyCtorArg, 1));
1997    break;
1998  }
1999  }
2000
2001  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2002  if (BaseInit.isInvalid())
2003    return true;
2004
2005  CXXBaseInit =
2006    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2007               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2008                                                        SourceLocation()),
2009                                             BaseSpec->isVirtual(),
2010                                             SourceLocation(),
2011                                             BaseInit.takeAs<Expr>(),
2012                                             SourceLocation(),
2013                                             SourceLocation());
2014
2015  return false;
2016}
2017
2018static bool RefersToRValueRef(Expr *MemRef) {
2019  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2020  return Referenced->getType()->isRValueReferenceType();
2021}
2022
2023static bool
2024BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2025                               ImplicitInitializerKind ImplicitInitKind,
2026                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2027                               CXXCtorInitializer *&CXXMemberInit) {
2028  if (Field->isInvalidDecl())
2029    return true;
2030
2031  SourceLocation Loc = Constructor->getLocation();
2032
2033  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2034    bool Moving = ImplicitInitKind == IIK_Move;
2035    ParmVarDecl *Param = Constructor->getParamDecl(0);
2036    QualType ParamType = Param->getType().getNonReferenceType();
2037
2038    // Suppress copying zero-width bitfields.
2039    if (const Expr *Width = Field->getBitWidth())
2040      if (Width->EvaluateAsInt(SemaRef.Context) == 0)
2041        return false;
2042
2043    Expr *MemberExprBase =
2044      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
2045                          Loc, ParamType, VK_LValue, 0);
2046
2047    if (Moving) {
2048      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2049    }
2050
2051    // Build a reference to this field within the parameter.
2052    CXXScopeSpec SS;
2053    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2054                              Sema::LookupMemberName);
2055    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2056                                  : cast<ValueDecl>(Field), AS_public);
2057    MemberLookup.resolveKind();
2058    ExprResult CtorArg
2059      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2060                                         ParamType, Loc,
2061                                         /*IsArrow=*/false,
2062                                         SS,
2063                                         /*FirstQualifierInScope=*/0,
2064                                         MemberLookup,
2065                                         /*TemplateArgs=*/0);
2066    if (CtorArg.isInvalid())
2067      return true;
2068
2069    // C++11 [class.copy]p15:
2070    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2071    //     with static_cast<T&&>(x.m);
2072    if (RefersToRValueRef(CtorArg.get())) {
2073      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2074    }
2075
2076    // When the field we are copying is an array, create index variables for
2077    // each dimension of the array. We use these index variables to subscript
2078    // the source array, and other clients (e.g., CodeGen) will perform the
2079    // necessary iteration with these index variables.
2080    SmallVector<VarDecl *, 4> IndexVariables;
2081    QualType BaseType = Field->getType();
2082    QualType SizeType = SemaRef.Context.getSizeType();
2083    bool InitializingArray = false;
2084    while (const ConstantArrayType *Array
2085                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2086      InitializingArray = true;
2087      // Create the iteration variable for this array index.
2088      IdentifierInfo *IterationVarName = 0;
2089      {
2090        llvm::SmallString<8> Str;
2091        llvm::raw_svector_ostream OS(Str);
2092        OS << "__i" << IndexVariables.size();
2093        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2094      }
2095      VarDecl *IterationVar
2096        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2097                          IterationVarName, SizeType,
2098                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2099                          SC_None, SC_None);
2100      IndexVariables.push_back(IterationVar);
2101
2102      // Create a reference to the iteration variable.
2103      ExprResult IterationVarRef
2104        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2105      assert(!IterationVarRef.isInvalid() &&
2106             "Reference to invented variable cannot fail!");
2107
2108      // Subscript the array with this iteration variable.
2109      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2110                                                        IterationVarRef.take(),
2111                                                        Loc);
2112      if (CtorArg.isInvalid())
2113        return true;
2114
2115      BaseType = Array->getElementType();
2116    }
2117
2118    // The array subscript expression is an lvalue, which is wrong for moving.
2119    if (Moving && InitializingArray)
2120      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2121
2122    // Construct the entity that we will be initializing. For an array, this
2123    // will be first element in the array, which may require several levels
2124    // of array-subscript entities.
2125    SmallVector<InitializedEntity, 4> Entities;
2126    Entities.reserve(1 + IndexVariables.size());
2127    if (Indirect)
2128      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2129    else
2130      Entities.push_back(InitializedEntity::InitializeMember(Field));
2131    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2132      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2133                                                              0,
2134                                                              Entities.back()));
2135
2136    // Direct-initialize to use the copy constructor.
2137    InitializationKind InitKind =
2138      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2139
2140    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2141    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2142                                   &CtorArgE, 1);
2143
2144    ExprResult MemberInit
2145      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2146                        MultiExprArg(&CtorArgE, 1));
2147    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2148    if (MemberInit.isInvalid())
2149      return true;
2150
2151    if (Indirect) {
2152      assert(IndexVariables.size() == 0 &&
2153             "Indirect field improperly initialized");
2154      CXXMemberInit
2155        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2156                                                   Loc, Loc,
2157                                                   MemberInit.takeAs<Expr>(),
2158                                                   Loc);
2159    } else
2160      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2161                                                 Loc, MemberInit.takeAs<Expr>(),
2162                                                 Loc,
2163                                                 IndexVariables.data(),
2164                                                 IndexVariables.size());
2165    return false;
2166  }
2167
2168  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2169
2170  QualType FieldBaseElementType =
2171    SemaRef.Context.getBaseElementType(Field->getType());
2172
2173  if (FieldBaseElementType->isRecordType()) {
2174    InitializedEntity InitEntity
2175      = Indirect? InitializedEntity::InitializeMember(Indirect)
2176                : InitializedEntity::InitializeMember(Field);
2177    InitializationKind InitKind =
2178      InitializationKind::CreateDefault(Loc);
2179
2180    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2181    ExprResult MemberInit =
2182      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2183
2184    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2185    if (MemberInit.isInvalid())
2186      return true;
2187
2188    if (Indirect)
2189      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2190                                                               Indirect, Loc,
2191                                                               Loc,
2192                                                               MemberInit.get(),
2193                                                               Loc);
2194    else
2195      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2196                                                               Field, Loc, Loc,
2197                                                               MemberInit.get(),
2198                                                               Loc);
2199    return false;
2200  }
2201
2202  if (!Field->getParent()->isUnion()) {
2203    if (FieldBaseElementType->isReferenceType()) {
2204      SemaRef.Diag(Constructor->getLocation(),
2205                   diag::err_uninitialized_member_in_ctor)
2206      << (int)Constructor->isImplicit()
2207      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2208      << 0 << Field->getDeclName();
2209      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2210      return true;
2211    }
2212
2213    if (FieldBaseElementType.isConstQualified()) {
2214      SemaRef.Diag(Constructor->getLocation(),
2215                   diag::err_uninitialized_member_in_ctor)
2216      << (int)Constructor->isImplicit()
2217      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2218      << 1 << Field->getDeclName();
2219      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2220      return true;
2221    }
2222  }
2223
2224  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2225      FieldBaseElementType->isObjCRetainableType() &&
2226      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2227      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2228    // Instant objects:
2229    //   Default-initialize Objective-C pointers to NULL.
2230    CXXMemberInit
2231      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2232                                                 Loc, Loc,
2233                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2234                                                 Loc);
2235    return false;
2236  }
2237
2238  // Nothing to initialize.
2239  CXXMemberInit = 0;
2240  return false;
2241}
2242
2243namespace {
2244struct BaseAndFieldInfo {
2245  Sema &S;
2246  CXXConstructorDecl *Ctor;
2247  bool AnyErrorsInInits;
2248  ImplicitInitializerKind IIK;
2249  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2250  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2251
2252  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2253    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2254    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2255    if (Generated && Ctor->isCopyConstructor())
2256      IIK = IIK_Copy;
2257    else if (Generated && Ctor->isMoveConstructor())
2258      IIK = IIK_Move;
2259    else
2260      IIK = IIK_Default;
2261  }
2262};
2263}
2264
2265static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2266                                    FieldDecl *Field,
2267                                    IndirectFieldDecl *Indirect = 0) {
2268
2269  // Overwhelmingly common case: we have a direct initializer for this field.
2270  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2271    Info.AllToInit.push_back(Init);
2272    return false;
2273  }
2274
2275  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2276  // has a brace-or-equal-initializer, the entity is initialized as specified
2277  // in [dcl.init].
2278  if (Field->hasInClassInitializer()) {
2279    CXXCtorInitializer *Init;
2280    if (Indirect)
2281      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2282                                                      SourceLocation(),
2283                                                      SourceLocation(), 0,
2284                                                      SourceLocation());
2285    else
2286      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2287                                                      SourceLocation(),
2288                                                      SourceLocation(), 0,
2289                                                      SourceLocation());
2290    Info.AllToInit.push_back(Init);
2291    return false;
2292  }
2293
2294  // Don't try to build an implicit initializer if there were semantic
2295  // errors in any of the initializers (and therefore we might be
2296  // missing some that the user actually wrote).
2297  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2298    return false;
2299
2300  CXXCtorInitializer *Init = 0;
2301  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2302                                     Indirect, Init))
2303    return true;
2304
2305  if (Init)
2306    Info.AllToInit.push_back(Init);
2307
2308  return false;
2309}
2310
2311bool
2312Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2313                               CXXCtorInitializer *Initializer) {
2314  assert(Initializer->isDelegatingInitializer());
2315  Constructor->setNumCtorInitializers(1);
2316  CXXCtorInitializer **initializer =
2317    new (Context) CXXCtorInitializer*[1];
2318  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2319  Constructor->setCtorInitializers(initializer);
2320
2321  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2322    MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2323    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2324  }
2325
2326  DelegatingCtorDecls.push_back(Constructor);
2327
2328  return false;
2329}
2330
2331/// \brief Determine whether the given indirect field declaration is somewhere
2332/// within an anonymous union.
2333static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2334  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2335                                      CEnd = F->chain_end();
2336       C != CEnd; ++C)
2337    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2338      if (Record->isUnion())
2339        return true;
2340
2341  return false;
2342}
2343
2344bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2345                               CXXCtorInitializer **Initializers,
2346                               unsigned NumInitializers,
2347                               bool AnyErrors) {
2348  if (Constructor->getDeclContext()->isDependentContext()) {
2349    // Just store the initializers as written, they will be checked during
2350    // instantiation.
2351    if (NumInitializers > 0) {
2352      Constructor->setNumCtorInitializers(NumInitializers);
2353      CXXCtorInitializer **baseOrMemberInitializers =
2354        new (Context) CXXCtorInitializer*[NumInitializers];
2355      memcpy(baseOrMemberInitializers, Initializers,
2356             NumInitializers * sizeof(CXXCtorInitializer*));
2357      Constructor->setCtorInitializers(baseOrMemberInitializers);
2358    }
2359
2360    return false;
2361  }
2362
2363  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2364
2365  // We need to build the initializer AST according to order of construction
2366  // and not what user specified in the Initializers list.
2367  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2368  if (!ClassDecl)
2369    return true;
2370
2371  bool HadError = false;
2372
2373  for (unsigned i = 0; i < NumInitializers; i++) {
2374    CXXCtorInitializer *Member = Initializers[i];
2375
2376    if (Member->isBaseInitializer())
2377      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2378    else
2379      Info.AllBaseFields[Member->getAnyMember()] = Member;
2380  }
2381
2382  // Keep track of the direct virtual bases.
2383  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2384  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2385       E = ClassDecl->bases_end(); I != E; ++I) {
2386    if (I->isVirtual())
2387      DirectVBases.insert(I);
2388  }
2389
2390  // Push virtual bases before others.
2391  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2392       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2393
2394    if (CXXCtorInitializer *Value
2395        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2396      Info.AllToInit.push_back(Value);
2397    } else if (!AnyErrors) {
2398      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2399      CXXCtorInitializer *CXXBaseInit;
2400      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2401                                       VBase, IsInheritedVirtualBase,
2402                                       CXXBaseInit)) {
2403        HadError = true;
2404        continue;
2405      }
2406
2407      Info.AllToInit.push_back(CXXBaseInit);
2408    }
2409  }
2410
2411  // Non-virtual bases.
2412  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2413       E = ClassDecl->bases_end(); Base != E; ++Base) {
2414    // Virtuals are in the virtual base list and already constructed.
2415    if (Base->isVirtual())
2416      continue;
2417
2418    if (CXXCtorInitializer *Value
2419          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2420      Info.AllToInit.push_back(Value);
2421    } else if (!AnyErrors) {
2422      CXXCtorInitializer *CXXBaseInit;
2423      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2424                                       Base, /*IsInheritedVirtualBase=*/false,
2425                                       CXXBaseInit)) {
2426        HadError = true;
2427        continue;
2428      }
2429
2430      Info.AllToInit.push_back(CXXBaseInit);
2431    }
2432  }
2433
2434  // Fields.
2435  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2436                               MemEnd = ClassDecl->decls_end();
2437       Mem != MemEnd; ++Mem) {
2438    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2439      if (F->getType()->isIncompleteArrayType()) {
2440        assert(ClassDecl->hasFlexibleArrayMember() &&
2441               "Incomplete array type is not valid");
2442        continue;
2443      }
2444
2445      // If we're not generating the implicit copy/move constructor, then we'll
2446      // handle anonymous struct/union fields based on their individual
2447      // indirect fields.
2448      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2449        continue;
2450
2451      if (CollectFieldInitializer(*this, Info, F))
2452        HadError = true;
2453      continue;
2454    }
2455
2456    // Beyond this point, we only consider default initialization.
2457    if (Info.IIK != IIK_Default)
2458      continue;
2459
2460    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2461      if (F->getType()->isIncompleteArrayType()) {
2462        assert(ClassDecl->hasFlexibleArrayMember() &&
2463               "Incomplete array type is not valid");
2464        continue;
2465      }
2466
2467      // If this field is somewhere within an anonymous union, we only
2468      // initialize it if there's an explicit initializer.
2469      if (isWithinAnonymousUnion(F)) {
2470        if (CXXCtorInitializer *Init
2471              = Info.AllBaseFields.lookup(F->getAnonField())) {
2472          Info.AllToInit.push_back(Init);
2473        }
2474
2475        continue;
2476      }
2477
2478      // Initialize each field of an anonymous struct individually.
2479      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2480        HadError = true;
2481
2482      continue;
2483    }
2484  }
2485
2486  NumInitializers = Info.AllToInit.size();
2487  if (NumInitializers > 0) {
2488    Constructor->setNumCtorInitializers(NumInitializers);
2489    CXXCtorInitializer **baseOrMemberInitializers =
2490      new (Context) CXXCtorInitializer*[NumInitializers];
2491    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2492           NumInitializers * sizeof(CXXCtorInitializer*));
2493    Constructor->setCtorInitializers(baseOrMemberInitializers);
2494
2495    // Constructors implicitly reference the base and member
2496    // destructors.
2497    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2498                                           Constructor->getParent());
2499  }
2500
2501  return HadError;
2502}
2503
2504static void *GetKeyForTopLevelField(FieldDecl *Field) {
2505  // For anonymous unions, use the class declaration as the key.
2506  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2507    if (RT->getDecl()->isAnonymousStructOrUnion())
2508      return static_cast<void *>(RT->getDecl());
2509  }
2510  return static_cast<void *>(Field);
2511}
2512
2513static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2514  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2515}
2516
2517static void *GetKeyForMember(ASTContext &Context,
2518                             CXXCtorInitializer *Member) {
2519  if (!Member->isAnyMemberInitializer())
2520    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2521
2522  // For fields injected into the class via declaration of an anonymous union,
2523  // use its anonymous union class declaration as the unique key.
2524  FieldDecl *Field = Member->getAnyMember();
2525
2526  // If the field is a member of an anonymous struct or union, our key
2527  // is the anonymous record decl that's a direct child of the class.
2528  RecordDecl *RD = Field->getParent();
2529  if (RD->isAnonymousStructOrUnion()) {
2530    while (true) {
2531      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2532      if (Parent->isAnonymousStructOrUnion())
2533        RD = Parent;
2534      else
2535        break;
2536    }
2537
2538    return static_cast<void *>(RD);
2539  }
2540
2541  return static_cast<void *>(Field);
2542}
2543
2544static void
2545DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2546                                  const CXXConstructorDecl *Constructor,
2547                                  CXXCtorInitializer **Inits,
2548                                  unsigned NumInits) {
2549  if (Constructor->getDeclContext()->isDependentContext())
2550    return;
2551
2552  // Don't check initializers order unless the warning is enabled at the
2553  // location of at least one initializer.
2554  bool ShouldCheckOrder = false;
2555  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2556    CXXCtorInitializer *Init = Inits[InitIndex];
2557    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2558                                         Init->getSourceLocation())
2559          != Diagnostic::Ignored) {
2560      ShouldCheckOrder = true;
2561      break;
2562    }
2563  }
2564  if (!ShouldCheckOrder)
2565    return;
2566
2567  // Build the list of bases and members in the order that they'll
2568  // actually be initialized.  The explicit initializers should be in
2569  // this same order but may be missing things.
2570  SmallVector<const void*, 32> IdealInitKeys;
2571
2572  const CXXRecordDecl *ClassDecl = Constructor->getParent();
2573
2574  // 1. Virtual bases.
2575  for (CXXRecordDecl::base_class_const_iterator VBase =
2576       ClassDecl->vbases_begin(),
2577       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2578    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2579
2580  // 2. Non-virtual bases.
2581  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2582       E = ClassDecl->bases_end(); Base != E; ++Base) {
2583    if (Base->isVirtual())
2584      continue;
2585    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2586  }
2587
2588  // 3. Direct fields.
2589  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2590       E = ClassDecl->field_end(); Field != E; ++Field)
2591    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2592
2593  unsigned NumIdealInits = IdealInitKeys.size();
2594  unsigned IdealIndex = 0;
2595
2596  CXXCtorInitializer *PrevInit = 0;
2597  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2598    CXXCtorInitializer *Init = Inits[InitIndex];
2599    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2600
2601    // Scan forward to try to find this initializer in the idealized
2602    // initializers list.
2603    for (; IdealIndex != NumIdealInits; ++IdealIndex)
2604      if (InitKey == IdealInitKeys[IdealIndex])
2605        break;
2606
2607    // If we didn't find this initializer, it must be because we
2608    // scanned past it on a previous iteration.  That can only
2609    // happen if we're out of order;  emit a warning.
2610    if (IdealIndex == NumIdealInits && PrevInit) {
2611      Sema::SemaDiagnosticBuilder D =
2612        SemaRef.Diag(PrevInit->getSourceLocation(),
2613                     diag::warn_initializer_out_of_order);
2614
2615      if (PrevInit->isAnyMemberInitializer())
2616        D << 0 << PrevInit->getAnyMember()->getDeclName();
2617      else
2618        D << 1 << PrevInit->getBaseClassInfo()->getType();
2619
2620      if (Init->isAnyMemberInitializer())
2621        D << 0 << Init->getAnyMember()->getDeclName();
2622      else
2623        D << 1 << Init->getBaseClassInfo()->getType();
2624
2625      // Move back to the initializer's location in the ideal list.
2626      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2627        if (InitKey == IdealInitKeys[IdealIndex])
2628          break;
2629
2630      assert(IdealIndex != NumIdealInits &&
2631             "initializer not found in initializer list");
2632    }
2633
2634    PrevInit = Init;
2635  }
2636}
2637
2638namespace {
2639bool CheckRedundantInit(Sema &S,
2640                        CXXCtorInitializer *Init,
2641                        CXXCtorInitializer *&PrevInit) {
2642  if (!PrevInit) {
2643    PrevInit = Init;
2644    return false;
2645  }
2646
2647  if (FieldDecl *Field = Init->getMember())
2648    S.Diag(Init->getSourceLocation(),
2649           diag::err_multiple_mem_initialization)
2650      << Field->getDeclName()
2651      << Init->getSourceRange();
2652  else {
2653    const Type *BaseClass = Init->getBaseClass();
2654    assert(BaseClass && "neither field nor base");
2655    S.Diag(Init->getSourceLocation(),
2656           diag::err_multiple_base_initialization)
2657      << QualType(BaseClass, 0)
2658      << Init->getSourceRange();
2659  }
2660  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2661    << 0 << PrevInit->getSourceRange();
2662
2663  return true;
2664}
2665
2666typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2667typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2668
2669bool CheckRedundantUnionInit(Sema &S,
2670                             CXXCtorInitializer *Init,
2671                             RedundantUnionMap &Unions) {
2672  FieldDecl *Field = Init->getAnyMember();
2673  RecordDecl *Parent = Field->getParent();
2674  if (!Parent->isAnonymousStructOrUnion())
2675    return false;
2676
2677  NamedDecl *Child = Field;
2678  do {
2679    if (Parent->isUnion()) {
2680      UnionEntry &En = Unions[Parent];
2681      if (En.first && En.first != Child) {
2682        S.Diag(Init->getSourceLocation(),
2683               diag::err_multiple_mem_union_initialization)
2684          << Field->getDeclName()
2685          << Init->getSourceRange();
2686        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2687          << 0 << En.second->getSourceRange();
2688        return true;
2689      } else if (!En.first) {
2690        En.first = Child;
2691        En.second = Init;
2692      }
2693    }
2694
2695    Child = Parent;
2696    Parent = cast<RecordDecl>(Parent->getDeclContext());
2697  } while (Parent->isAnonymousStructOrUnion());
2698
2699  return false;
2700}
2701}
2702
2703/// ActOnMemInitializers - Handle the member initializers for a constructor.
2704void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2705                                SourceLocation ColonLoc,
2706                                CXXCtorInitializer **meminits,
2707                                unsigned NumMemInits,
2708                                bool AnyErrors) {
2709  if (!ConstructorDecl)
2710    return;
2711
2712  AdjustDeclIfTemplate(ConstructorDecl);
2713
2714  CXXConstructorDecl *Constructor
2715    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2716
2717  if (!Constructor) {
2718    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2719    return;
2720  }
2721
2722  CXXCtorInitializer **MemInits =
2723    reinterpret_cast<CXXCtorInitializer **>(meminits);
2724
2725  // Mapping for the duplicate initializers check.
2726  // For member initializers, this is keyed with a FieldDecl*.
2727  // For base initializers, this is keyed with a Type*.
2728  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2729
2730  // Mapping for the inconsistent anonymous-union initializers check.
2731  RedundantUnionMap MemberUnions;
2732
2733  bool HadError = false;
2734  for (unsigned i = 0; i < NumMemInits; i++) {
2735    CXXCtorInitializer *Init = MemInits[i];
2736
2737    // Set the source order index.
2738    Init->setSourceOrder(i);
2739
2740    if (Init->isAnyMemberInitializer()) {
2741      FieldDecl *Field = Init->getAnyMember();
2742      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2743          CheckRedundantUnionInit(*this, Init, MemberUnions))
2744        HadError = true;
2745    } else if (Init->isBaseInitializer()) {
2746      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2747      if (CheckRedundantInit(*this, Init, Members[Key]))
2748        HadError = true;
2749    } else {
2750      assert(Init->isDelegatingInitializer());
2751      // This must be the only initializer
2752      if (i != 0 || NumMemInits > 1) {
2753        Diag(MemInits[0]->getSourceLocation(),
2754             diag::err_delegating_initializer_alone)
2755          << MemInits[0]->getSourceRange();
2756        HadError = true;
2757        // We will treat this as being the only initializer.
2758      }
2759      SetDelegatingInitializer(Constructor, MemInits[i]);
2760      // Return immediately as the initializer is set.
2761      return;
2762    }
2763  }
2764
2765  if (HadError)
2766    return;
2767
2768  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2769
2770  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2771}
2772
2773void
2774Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2775                                             CXXRecordDecl *ClassDecl) {
2776  // Ignore dependent contexts.
2777  if (ClassDecl->isDependentContext())
2778    return;
2779
2780  // FIXME: all the access-control diagnostics are positioned on the
2781  // field/base declaration.  That's probably good; that said, the
2782  // user might reasonably want to know why the destructor is being
2783  // emitted, and we currently don't say.
2784
2785  // Non-static data members.
2786  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2787       E = ClassDecl->field_end(); I != E; ++I) {
2788    FieldDecl *Field = *I;
2789    if (Field->isInvalidDecl())
2790      continue;
2791    QualType FieldType = Context.getBaseElementType(Field->getType());
2792
2793    const RecordType* RT = FieldType->getAs<RecordType>();
2794    if (!RT)
2795      continue;
2796
2797    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2798    if (FieldClassDecl->isInvalidDecl())
2799      continue;
2800    if (FieldClassDecl->hasTrivialDestructor())
2801      continue;
2802
2803    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2804    assert(Dtor && "No dtor found for FieldClassDecl!");
2805    CheckDestructorAccess(Field->getLocation(), Dtor,
2806                          PDiag(diag::err_access_dtor_field)
2807                            << Field->getDeclName()
2808                            << FieldType);
2809
2810    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2811  }
2812
2813  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2814
2815  // Bases.
2816  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2817       E = ClassDecl->bases_end(); Base != E; ++Base) {
2818    // Bases are always records in a well-formed non-dependent class.
2819    const RecordType *RT = Base->getType()->getAs<RecordType>();
2820
2821    // Remember direct virtual bases.
2822    if (Base->isVirtual())
2823      DirectVirtualBases.insert(RT);
2824
2825    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2826    // If our base class is invalid, we probably can't get its dtor anyway.
2827    if (BaseClassDecl->isInvalidDecl())
2828      continue;
2829    // Ignore trivial destructors.
2830    if (BaseClassDecl->hasTrivialDestructor())
2831      continue;
2832
2833    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2834    assert(Dtor && "No dtor found for BaseClassDecl!");
2835
2836    // FIXME: caret should be on the start of the class name
2837    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2838                          PDiag(diag::err_access_dtor_base)
2839                            << Base->getType()
2840                            << Base->getSourceRange());
2841
2842    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2843  }
2844
2845  // Virtual bases.
2846  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2847       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2848
2849    // Bases are always records in a well-formed non-dependent class.
2850    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2851
2852    // Ignore direct virtual bases.
2853    if (DirectVirtualBases.count(RT))
2854      continue;
2855
2856    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2857    // If our base class is invalid, we probably can't get its dtor anyway.
2858    if (BaseClassDecl->isInvalidDecl())
2859      continue;
2860    // Ignore trivial destructors.
2861    if (BaseClassDecl->hasTrivialDestructor())
2862      continue;
2863
2864    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2865    assert(Dtor && "No dtor found for BaseClassDecl!");
2866    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2867                          PDiag(diag::err_access_dtor_vbase)
2868                            << VBase->getType());
2869
2870    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2871  }
2872}
2873
2874void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2875  if (!CDtorDecl)
2876    return;
2877
2878  if (CXXConstructorDecl *Constructor
2879      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2880    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2881}
2882
2883bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2884                                  unsigned DiagID, AbstractDiagSelID SelID) {
2885  if (SelID == -1)
2886    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2887  else
2888    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2889}
2890
2891bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2892                                  const PartialDiagnostic &PD) {
2893  if (!getLangOptions().CPlusPlus)
2894    return false;
2895
2896  if (const ArrayType *AT = Context.getAsArrayType(T))
2897    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2898
2899  if (const PointerType *PT = T->getAs<PointerType>()) {
2900    // Find the innermost pointer type.
2901    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2902      PT = T;
2903
2904    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2905      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2906  }
2907
2908  const RecordType *RT = T->getAs<RecordType>();
2909  if (!RT)
2910    return false;
2911
2912  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2913
2914  // We can't answer whether something is abstract until it has a
2915  // definition.  If it's currently being defined, we'll walk back
2916  // over all the declarations when we have a full definition.
2917  const CXXRecordDecl *Def = RD->getDefinition();
2918  if (!Def || Def->isBeingDefined())
2919    return false;
2920
2921  if (!RD->isAbstract())
2922    return false;
2923
2924  Diag(Loc, PD) << RD->getDeclName();
2925  DiagnoseAbstractType(RD);
2926
2927  return true;
2928}
2929
2930void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2931  // Check if we've already emitted the list of pure virtual functions
2932  // for this class.
2933  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2934    return;
2935
2936  CXXFinalOverriderMap FinalOverriders;
2937  RD->getFinalOverriders(FinalOverriders);
2938
2939  // Keep a set of seen pure methods so we won't diagnose the same method
2940  // more than once.
2941  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2942
2943  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2944                                   MEnd = FinalOverriders.end();
2945       M != MEnd;
2946       ++M) {
2947    for (OverridingMethods::iterator SO = M->second.begin(),
2948                                  SOEnd = M->second.end();
2949         SO != SOEnd; ++SO) {
2950      // C++ [class.abstract]p4:
2951      //   A class is abstract if it contains or inherits at least one
2952      //   pure virtual function for which the final overrider is pure
2953      //   virtual.
2954
2955      //
2956      if (SO->second.size() != 1)
2957        continue;
2958
2959      if (!SO->second.front().Method->isPure())
2960        continue;
2961
2962      if (!SeenPureMethods.insert(SO->second.front().Method))
2963        continue;
2964
2965      Diag(SO->second.front().Method->getLocation(),
2966           diag::note_pure_virtual_function)
2967        << SO->second.front().Method->getDeclName() << RD->getDeclName();
2968    }
2969  }
2970
2971  if (!PureVirtualClassDiagSet)
2972    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2973  PureVirtualClassDiagSet->insert(RD);
2974}
2975
2976namespace {
2977struct AbstractUsageInfo {
2978  Sema &S;
2979  CXXRecordDecl *Record;
2980  CanQualType AbstractType;
2981  bool Invalid;
2982
2983  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2984    : S(S), Record(Record),
2985      AbstractType(S.Context.getCanonicalType(
2986                   S.Context.getTypeDeclType(Record))),
2987      Invalid(false) {}
2988
2989  void DiagnoseAbstractType() {
2990    if (Invalid) return;
2991    S.DiagnoseAbstractType(Record);
2992    Invalid = true;
2993  }
2994
2995  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2996};
2997
2998struct CheckAbstractUsage {
2999  AbstractUsageInfo &Info;
3000  const NamedDecl *Ctx;
3001
3002  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3003    : Info(Info), Ctx(Ctx) {}
3004
3005  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3006    switch (TL.getTypeLocClass()) {
3007#define ABSTRACT_TYPELOC(CLASS, PARENT)
3008#define TYPELOC(CLASS, PARENT) \
3009    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3010#include "clang/AST/TypeLocNodes.def"
3011    }
3012  }
3013
3014  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3015    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3016    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3017      if (!TL.getArg(I))
3018        continue;
3019
3020      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3021      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3022    }
3023  }
3024
3025  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3026    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3027  }
3028
3029  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3030    // Visit the type parameters from a permissive context.
3031    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3032      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3033      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3034        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3035          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3036      // TODO: other template argument types?
3037    }
3038  }
3039
3040  // Visit pointee types from a permissive context.
3041#define CheckPolymorphic(Type) \
3042  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3043    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3044  }
3045  CheckPolymorphic(PointerTypeLoc)
3046  CheckPolymorphic(ReferenceTypeLoc)
3047  CheckPolymorphic(MemberPointerTypeLoc)
3048  CheckPolymorphic(BlockPointerTypeLoc)
3049
3050  /// Handle all the types we haven't given a more specific
3051  /// implementation for above.
3052  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3053    // Every other kind of type that we haven't called out already
3054    // that has an inner type is either (1) sugar or (2) contains that
3055    // inner type in some way as a subobject.
3056    if (TypeLoc Next = TL.getNextTypeLoc())
3057      return Visit(Next, Sel);
3058
3059    // If there's no inner type and we're in a permissive context,
3060    // don't diagnose.
3061    if (Sel == Sema::AbstractNone) return;
3062
3063    // Check whether the type matches the abstract type.
3064    QualType T = TL.getType();
3065    if (T->isArrayType()) {
3066      Sel = Sema::AbstractArrayType;
3067      T = Info.S.Context.getBaseElementType(T);
3068    }
3069    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3070    if (CT != Info.AbstractType) return;
3071
3072    // It matched; do some magic.
3073    if (Sel == Sema::AbstractArrayType) {
3074      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3075        << T << TL.getSourceRange();
3076    } else {
3077      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3078        << Sel << T << TL.getSourceRange();
3079    }
3080    Info.DiagnoseAbstractType();
3081  }
3082};
3083
3084void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3085                                  Sema::AbstractDiagSelID Sel) {
3086  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3087}
3088
3089}
3090
3091/// Check for invalid uses of an abstract type in a method declaration.
3092static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3093                                    CXXMethodDecl *MD) {
3094  // No need to do the check on definitions, which require that
3095  // the return/param types be complete.
3096  if (MD->doesThisDeclarationHaveABody())
3097    return;
3098
3099  // For safety's sake, just ignore it if we don't have type source
3100  // information.  This should never happen for non-implicit methods,
3101  // but...
3102  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3103    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3104}
3105
3106/// Check for invalid uses of an abstract type within a class definition.
3107static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3108                                    CXXRecordDecl *RD) {
3109  for (CXXRecordDecl::decl_iterator
3110         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3111    Decl *D = *I;
3112    if (D->isImplicit()) continue;
3113
3114    // Methods and method templates.
3115    if (isa<CXXMethodDecl>(D)) {
3116      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3117    } else if (isa<FunctionTemplateDecl>(D)) {
3118      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3119      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3120
3121    // Fields and static variables.
3122    } else if (isa<FieldDecl>(D)) {
3123      FieldDecl *FD = cast<FieldDecl>(D);
3124      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3125        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3126    } else if (isa<VarDecl>(D)) {
3127      VarDecl *VD = cast<VarDecl>(D);
3128      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3129        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3130
3131    // Nested classes and class templates.
3132    } else if (isa<CXXRecordDecl>(D)) {
3133      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3134    } else if (isa<ClassTemplateDecl>(D)) {
3135      CheckAbstractClassUsage(Info,
3136                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3137    }
3138  }
3139}
3140
3141/// \brief Perform semantic checks on a class definition that has been
3142/// completing, introducing implicitly-declared members, checking for
3143/// abstract types, etc.
3144void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3145  if (!Record)
3146    return;
3147
3148  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3149    AbstractUsageInfo Info(*this, Record);
3150    CheckAbstractClassUsage(Info, Record);
3151  }
3152
3153  // If this is not an aggregate type and has no user-declared constructor,
3154  // complain about any non-static data members of reference or const scalar
3155  // type, since they will never get initializers.
3156  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3157      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3158    bool Complained = false;
3159    for (RecordDecl::field_iterator F = Record->field_begin(),
3160                                 FEnd = Record->field_end();
3161         F != FEnd; ++F) {
3162      if (F->hasInClassInitializer())
3163        continue;
3164
3165      if (F->getType()->isReferenceType() ||
3166          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3167        if (!Complained) {
3168          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3169            << Record->getTagKind() << Record;
3170          Complained = true;
3171        }
3172
3173        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3174          << F->getType()->isReferenceType()
3175          << F->getDeclName();
3176      }
3177    }
3178  }
3179
3180  if (Record->isDynamicClass() && !Record->isDependentType())
3181    DynamicClasses.push_back(Record);
3182
3183  if (Record->getIdentifier()) {
3184    // C++ [class.mem]p13:
3185    //   If T is the name of a class, then each of the following shall have a
3186    //   name different from T:
3187    //     - every member of every anonymous union that is a member of class T.
3188    //
3189    // C++ [class.mem]p14:
3190    //   In addition, if class T has a user-declared constructor (12.1), every
3191    //   non-static data member of class T shall have a name different from T.
3192    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3193         R.first != R.second; ++R.first) {
3194      NamedDecl *D = *R.first;
3195      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3196          isa<IndirectFieldDecl>(D)) {
3197        Diag(D->getLocation(), diag::err_member_name_of_class)
3198          << D->getDeclName();
3199        break;
3200      }
3201    }
3202  }
3203
3204  // Warn if the class has virtual methods but non-virtual public destructor.
3205  if (Record->isPolymorphic() && !Record->isDependentType()) {
3206    CXXDestructorDecl *dtor = Record->getDestructor();
3207    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3208      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3209           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3210  }
3211
3212  // See if a method overloads virtual methods in a base
3213  /// class without overriding any.
3214  if (!Record->isDependentType()) {
3215    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3216                                     MEnd = Record->method_end();
3217         M != MEnd; ++M) {
3218      if (!(*M)->isStatic())
3219        DiagnoseHiddenVirtualMethods(Record, *M);
3220    }
3221  }
3222
3223  // Declare inherited constructors. We do this eagerly here because:
3224  // - The standard requires an eager diagnostic for conflicting inherited
3225  //   constructors from different classes.
3226  // - The lazy declaration of the other implicit constructors is so as to not
3227  //   waste space and performance on classes that are not meant to be
3228  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3229  //   have inherited constructors.
3230  DeclareInheritedConstructors(Record);
3231
3232  if (!Record->isDependentType())
3233    CheckExplicitlyDefaultedMethods(Record);
3234}
3235
3236void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3237  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3238                                      ME = Record->method_end();
3239       MI != ME; ++MI) {
3240    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3241      switch (getSpecialMember(*MI)) {
3242      case CXXDefaultConstructor:
3243        CheckExplicitlyDefaultedDefaultConstructor(
3244                                                  cast<CXXConstructorDecl>(*MI));
3245        break;
3246
3247      case CXXDestructor:
3248        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3249        break;
3250
3251      case CXXCopyConstructor:
3252        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3253        break;
3254
3255      case CXXCopyAssignment:
3256        CheckExplicitlyDefaultedCopyAssignment(*MI);
3257        break;
3258
3259      case CXXMoveConstructor:
3260        CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
3261        break;
3262
3263      case CXXMoveAssignment:
3264        CheckExplicitlyDefaultedMoveAssignment(*MI);
3265        break;
3266
3267      case CXXInvalid:
3268        llvm_unreachable("non-special member explicitly defaulted!");
3269      }
3270    }
3271  }
3272
3273}
3274
3275void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3276  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3277
3278  // Whether this was the first-declared instance of the constructor.
3279  // This affects whether we implicitly add an exception spec (and, eventually,
3280  // constexpr). It is also ill-formed to explicitly default a constructor such
3281  // that it would be deleted. (C++0x [decl.fct.def.default])
3282  bool First = CD == CD->getCanonicalDecl();
3283
3284  bool HadError = false;
3285  if (CD->getNumParams() != 0) {
3286    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3287      << CD->getSourceRange();
3288    HadError = true;
3289  }
3290
3291  ImplicitExceptionSpecification Spec
3292    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3293  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3294  if (EPI.ExceptionSpecType == EST_Delayed) {
3295    // Exception specification depends on some deferred part of the class. We'll
3296    // try again when the class's definition has been fully processed.
3297    return;
3298  }
3299  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3300                          *ExceptionType = Context.getFunctionType(
3301                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3302
3303  if (CtorType->hasExceptionSpec()) {
3304    if (CheckEquivalentExceptionSpec(
3305          PDiag(diag::err_incorrect_defaulted_exception_spec)
3306            << CXXDefaultConstructor,
3307          PDiag(),
3308          ExceptionType, SourceLocation(),
3309          CtorType, CD->getLocation())) {
3310      HadError = true;
3311    }
3312  } else if (First) {
3313    // We set the declaration to have the computed exception spec here.
3314    // We know there are no parameters.
3315    EPI.ExtInfo = CtorType->getExtInfo();
3316    CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3317  }
3318
3319  if (HadError) {
3320    CD->setInvalidDecl();
3321    return;
3322  }
3323
3324  if (ShouldDeleteDefaultConstructor(CD)) {
3325    if (First) {
3326      CD->setDeletedAsWritten();
3327    } else {
3328      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3329        << CXXDefaultConstructor;
3330      CD->setInvalidDecl();
3331    }
3332  }
3333}
3334
3335void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3336  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3337
3338  // Whether this was the first-declared instance of the constructor.
3339  bool First = CD == CD->getCanonicalDecl();
3340
3341  bool HadError = false;
3342  if (CD->getNumParams() != 1) {
3343    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3344      << CD->getSourceRange();
3345    HadError = true;
3346  }
3347
3348  ImplicitExceptionSpecification Spec(Context);
3349  bool Const;
3350  llvm::tie(Spec, Const) =
3351    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3352
3353  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3354  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3355                          *ExceptionType = Context.getFunctionType(
3356                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3357
3358  // Check for parameter type matching.
3359  // This is a copy ctor so we know it's a cv-qualified reference to T.
3360  QualType ArgType = CtorType->getArgType(0);
3361  if (ArgType->getPointeeType().isVolatileQualified()) {
3362    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3363    HadError = true;
3364  }
3365  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3366    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3367    HadError = true;
3368  }
3369
3370  if (CtorType->hasExceptionSpec()) {
3371    if (CheckEquivalentExceptionSpec(
3372          PDiag(diag::err_incorrect_defaulted_exception_spec)
3373            << CXXCopyConstructor,
3374          PDiag(),
3375          ExceptionType, SourceLocation(),
3376          CtorType, CD->getLocation())) {
3377      HadError = true;
3378    }
3379  } else if (First) {
3380    // We set the declaration to have the computed exception spec here.
3381    // We duplicate the one parameter type.
3382    EPI.ExtInfo = CtorType->getExtInfo();
3383    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3384  }
3385
3386  if (HadError) {
3387    CD->setInvalidDecl();
3388    return;
3389  }
3390
3391  if (ShouldDeleteCopyConstructor(CD)) {
3392    if (First) {
3393      CD->setDeletedAsWritten();
3394    } else {
3395      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3396        << CXXCopyConstructor;
3397      CD->setInvalidDecl();
3398    }
3399  }
3400}
3401
3402void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3403  assert(MD->isExplicitlyDefaulted());
3404
3405  // Whether this was the first-declared instance of the operator
3406  bool First = MD == MD->getCanonicalDecl();
3407
3408  bool HadError = false;
3409  if (MD->getNumParams() != 1) {
3410    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3411      << MD->getSourceRange();
3412    HadError = true;
3413  }
3414
3415  QualType ReturnType =
3416    MD->getType()->getAs<FunctionType>()->getResultType();
3417  if (!ReturnType->isLValueReferenceType() ||
3418      !Context.hasSameType(
3419        Context.getCanonicalType(ReturnType->getPointeeType()),
3420        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3421    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3422    HadError = true;
3423  }
3424
3425  ImplicitExceptionSpecification Spec(Context);
3426  bool Const;
3427  llvm::tie(Spec, Const) =
3428    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3429
3430  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3431  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3432                          *ExceptionType = Context.getFunctionType(
3433                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3434
3435  QualType ArgType = OperType->getArgType(0);
3436  if (!ArgType->isLValueReferenceType()) {
3437    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3438    HadError = true;
3439  } else {
3440    if (ArgType->getPointeeType().isVolatileQualified()) {
3441      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3442      HadError = true;
3443    }
3444    if (ArgType->getPointeeType().isConstQualified() && !Const) {
3445      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3446      HadError = true;
3447    }
3448  }
3449
3450  if (OperType->getTypeQuals()) {
3451    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3452    HadError = true;
3453  }
3454
3455  if (OperType->hasExceptionSpec()) {
3456    if (CheckEquivalentExceptionSpec(
3457          PDiag(diag::err_incorrect_defaulted_exception_spec)
3458            << CXXCopyAssignment,
3459          PDiag(),
3460          ExceptionType, SourceLocation(),
3461          OperType, MD->getLocation())) {
3462      HadError = true;
3463    }
3464  } else if (First) {
3465    // We set the declaration to have the computed exception spec here.
3466    // We duplicate the one parameter type.
3467    EPI.RefQualifier = OperType->getRefQualifier();
3468    EPI.ExtInfo = OperType->getExtInfo();
3469    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3470  }
3471
3472  if (HadError) {
3473    MD->setInvalidDecl();
3474    return;
3475  }
3476
3477  if (ShouldDeleteCopyAssignmentOperator(MD)) {
3478    if (First) {
3479      MD->setDeletedAsWritten();
3480    } else {
3481      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3482        << CXXCopyAssignment;
3483      MD->setInvalidDecl();
3484    }
3485  }
3486}
3487
3488void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3489  assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3490
3491  // Whether this was the first-declared instance of the constructor.
3492  bool First = CD == CD->getCanonicalDecl();
3493
3494  bool HadError = false;
3495  if (CD->getNumParams() != 1) {
3496    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3497      << CD->getSourceRange();
3498    HadError = true;
3499  }
3500
3501  ImplicitExceptionSpecification Spec(
3502      ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3503
3504  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3505  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3506                          *ExceptionType = Context.getFunctionType(
3507                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3508
3509  // Check for parameter type matching.
3510  // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3511  QualType ArgType = CtorType->getArgType(0);
3512  if (ArgType->getPointeeType().isVolatileQualified()) {
3513    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3514    HadError = true;
3515  }
3516  if (ArgType->getPointeeType().isConstQualified()) {
3517    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3518    HadError = true;
3519  }
3520
3521  if (CtorType->hasExceptionSpec()) {
3522    if (CheckEquivalentExceptionSpec(
3523          PDiag(diag::err_incorrect_defaulted_exception_spec)
3524            << CXXMoveConstructor,
3525          PDiag(),
3526          ExceptionType, SourceLocation(),
3527          CtorType, CD->getLocation())) {
3528      HadError = true;
3529    }
3530  } else if (First) {
3531    // We set the declaration to have the computed exception spec here.
3532    // We duplicate the one parameter type.
3533    EPI.ExtInfo = CtorType->getExtInfo();
3534    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3535  }
3536
3537  if (HadError) {
3538    CD->setInvalidDecl();
3539    return;
3540  }
3541
3542  if (ShouldDeleteMoveConstructor(CD)) {
3543    if (First) {
3544      CD->setDeletedAsWritten();
3545    } else {
3546      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3547        << CXXMoveConstructor;
3548      CD->setInvalidDecl();
3549    }
3550  }
3551}
3552
3553void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3554  assert(MD->isExplicitlyDefaulted());
3555
3556  // Whether this was the first-declared instance of the operator
3557  bool First = MD == MD->getCanonicalDecl();
3558
3559  bool HadError = false;
3560  if (MD->getNumParams() != 1) {
3561    Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3562      << MD->getSourceRange();
3563    HadError = true;
3564  }
3565
3566  QualType ReturnType =
3567    MD->getType()->getAs<FunctionType>()->getResultType();
3568  if (!ReturnType->isLValueReferenceType() ||
3569      !Context.hasSameType(
3570        Context.getCanonicalType(ReturnType->getPointeeType()),
3571        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3572    Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
3573    HadError = true;
3574  }
3575
3576  ImplicitExceptionSpecification Spec(
3577      ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
3578
3579  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3580  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3581                          *ExceptionType = Context.getFunctionType(
3582                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3583
3584  QualType ArgType = OperType->getArgType(0);
3585  if (!ArgType->isRValueReferenceType()) {
3586    Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
3587    HadError = true;
3588  } else {
3589    if (ArgType->getPointeeType().isVolatileQualified()) {
3590      Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
3591      HadError = true;
3592    }
3593    if (ArgType->getPointeeType().isConstQualified()) {
3594      Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
3595      HadError = true;
3596    }
3597  }
3598
3599  if (OperType->getTypeQuals()) {
3600    Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
3601    HadError = true;
3602  }
3603
3604  if (OperType->hasExceptionSpec()) {
3605    if (CheckEquivalentExceptionSpec(
3606          PDiag(diag::err_incorrect_defaulted_exception_spec)
3607            << CXXMoveAssignment,
3608          PDiag(),
3609          ExceptionType, SourceLocation(),
3610          OperType, MD->getLocation())) {
3611      HadError = true;
3612    }
3613  } else if (First) {
3614    // We set the declaration to have the computed exception spec here.
3615    // We duplicate the one parameter type.
3616    EPI.RefQualifier = OperType->getRefQualifier();
3617    EPI.ExtInfo = OperType->getExtInfo();
3618    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3619  }
3620
3621  if (HadError) {
3622    MD->setInvalidDecl();
3623    return;
3624  }
3625
3626  if (ShouldDeleteMoveAssignmentOperator(MD)) {
3627    if (First) {
3628      MD->setDeletedAsWritten();
3629    } else {
3630      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3631        << CXXMoveAssignment;
3632      MD->setInvalidDecl();
3633    }
3634  }
3635}
3636
3637void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3638  assert(DD->isExplicitlyDefaulted());
3639
3640  // Whether this was the first-declared instance of the destructor.
3641  bool First = DD == DD->getCanonicalDecl();
3642
3643  ImplicitExceptionSpecification Spec
3644    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3645  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3646  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3647                          *ExceptionType = Context.getFunctionType(
3648                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3649
3650  if (DtorType->hasExceptionSpec()) {
3651    if (CheckEquivalentExceptionSpec(
3652          PDiag(diag::err_incorrect_defaulted_exception_spec)
3653            << CXXDestructor,
3654          PDiag(),
3655          ExceptionType, SourceLocation(),
3656          DtorType, DD->getLocation())) {
3657      DD->setInvalidDecl();
3658      return;
3659    }
3660  } else if (First) {
3661    // We set the declaration to have the computed exception spec here.
3662    // There are no parameters.
3663    EPI.ExtInfo = DtorType->getExtInfo();
3664    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3665  }
3666
3667  if (ShouldDeleteDestructor(DD)) {
3668    if (First) {
3669      DD->setDeletedAsWritten();
3670    } else {
3671      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3672        << CXXDestructor;
3673      DD->setInvalidDecl();
3674    }
3675  }
3676}
3677
3678bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3679  CXXRecordDecl *RD = CD->getParent();
3680  assert(!RD->isDependentType() && "do deletion after instantiation");
3681  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3682    return false;
3683
3684  SourceLocation Loc = CD->getLocation();
3685
3686  // Do access control from the constructor
3687  ContextRAII CtorContext(*this, CD);
3688
3689  bool Union = RD->isUnion();
3690  bool AllConst = true;
3691
3692  // We do this because we should never actually use an anonymous
3693  // union's constructor.
3694  if (Union && RD->isAnonymousStructOrUnion())
3695    return false;
3696
3697  // FIXME: We should put some diagnostic logic right into this function.
3698
3699  // C++0x [class.ctor]/5
3700  //    A defaulted default constructor for class X is defined as deleted if:
3701
3702  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3703                                          BE = RD->bases_end();
3704       BI != BE; ++BI) {
3705    // We'll handle this one later
3706    if (BI->isVirtual())
3707      continue;
3708
3709    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3710    assert(BaseDecl && "base isn't a CXXRecordDecl");
3711
3712    // -- any [direct base class] has a type with a destructor that is
3713    //    deleted or inaccessible from the defaulted default constructor
3714    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3715    if (BaseDtor->isDeleted())
3716      return true;
3717    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3718        AR_accessible)
3719      return true;
3720
3721    // -- any [direct base class either] has no default constructor or
3722    //    overload resolution as applied to [its] default constructor
3723    //    results in an ambiguity or in a function that is deleted or
3724    //    inaccessible from the defaulted default constructor
3725    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3726    if (!BaseDefault || BaseDefault->isDeleted())
3727      return true;
3728
3729    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3730                               PDiag()) != AR_accessible)
3731      return true;
3732  }
3733
3734  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3735                                          BE = RD->vbases_end();
3736       BI != BE; ++BI) {
3737    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3738    assert(BaseDecl && "base isn't a CXXRecordDecl");
3739
3740    // -- any [virtual base class] has a type with a destructor that is
3741    //    delete or inaccessible from the defaulted default constructor
3742    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3743    if (BaseDtor->isDeleted())
3744      return true;
3745    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3746        AR_accessible)
3747      return true;
3748
3749    // -- any [virtual base class either] has no default constructor or
3750    //    overload resolution as applied to [its] default constructor
3751    //    results in an ambiguity or in a function that is deleted or
3752    //    inaccessible from the defaulted default constructor
3753    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3754    if (!BaseDefault || BaseDefault->isDeleted())
3755      return true;
3756
3757    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3758                               PDiag()) != AR_accessible)
3759      return true;
3760  }
3761
3762  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3763                                     FE = RD->field_end();
3764       FI != FE; ++FI) {
3765    if (FI->isInvalidDecl())
3766      continue;
3767
3768    QualType FieldType = Context.getBaseElementType(FI->getType());
3769    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3770
3771    // -- any non-static data member with no brace-or-equal-initializer is of
3772    //    reference type
3773    if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3774      return true;
3775
3776    // -- X is a union and all its variant members are of const-qualified type
3777    //    (or array thereof)
3778    if (Union && !FieldType.isConstQualified())
3779      AllConst = false;
3780
3781    if (FieldRecord) {
3782      // -- X is a union-like class that has a variant member with a non-trivial
3783      //    default constructor
3784      if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3785        return true;
3786
3787      CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3788      if (FieldDtor->isDeleted())
3789        return true;
3790      if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3791          AR_accessible)
3792        return true;
3793
3794      // -- any non-variant non-static data member of const-qualified type (or
3795      //    array thereof) with no brace-or-equal-initializer does not have a
3796      //    user-provided default constructor
3797      if (FieldType.isConstQualified() &&
3798          !FI->hasInClassInitializer() &&
3799          !FieldRecord->hasUserProvidedDefaultConstructor())
3800        return true;
3801
3802      if (!Union && FieldRecord->isUnion() &&
3803          FieldRecord->isAnonymousStructOrUnion()) {
3804        // We're okay to reuse AllConst here since we only care about the
3805        // value otherwise if we're in a union.
3806        AllConst = true;
3807
3808        for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3809                                           UE = FieldRecord->field_end();
3810             UI != UE; ++UI) {
3811          QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3812          CXXRecordDecl *UnionFieldRecord =
3813            UnionFieldType->getAsCXXRecordDecl();
3814
3815          if (!UnionFieldType.isConstQualified())
3816            AllConst = false;
3817
3818          if (UnionFieldRecord &&
3819              !UnionFieldRecord->hasTrivialDefaultConstructor())
3820            return true;
3821        }
3822
3823        if (AllConst)
3824          return true;
3825
3826        // Don't try to initialize the anonymous union
3827        // This is technically non-conformant, but sanity demands it.
3828        continue;
3829      }
3830
3831      // -- any non-static data member with no brace-or-equal-initializer has
3832      //    class type M (or array thereof) and either M has no default
3833      //    constructor or overload resolution as applied to M's default
3834      //    constructor results in an ambiguity or in a function that is deleted
3835      //    or inaccessible from the defaulted default constructor.
3836      if (!FI->hasInClassInitializer()) {
3837        CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3838        if (!FieldDefault || FieldDefault->isDeleted())
3839          return true;
3840        if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3841                                   PDiag()) != AR_accessible)
3842          return true;
3843      }
3844    } else if (!Union && FieldType.isConstQualified() &&
3845               !FI->hasInClassInitializer()) {
3846      // -- any non-variant non-static data member of const-qualified type (or
3847      //    array thereof) with no brace-or-equal-initializer does not have a
3848      //    user-provided default constructor
3849      return true;
3850    }
3851  }
3852
3853  if (Union && AllConst)
3854    return true;
3855
3856  return false;
3857}
3858
3859bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3860  CXXRecordDecl *RD = CD->getParent();
3861  assert(!RD->isDependentType() && "do deletion after instantiation");
3862  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3863    return false;
3864
3865  SourceLocation Loc = CD->getLocation();
3866
3867  // Do access control from the constructor
3868  ContextRAII CtorContext(*this, CD);
3869
3870  bool Union = RD->isUnion();
3871
3872  assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3873         "copy assignment arg has no pointee type");
3874  unsigned ArgQuals =
3875    CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3876      Qualifiers::Const : 0;
3877
3878  // We do this because we should never actually use an anonymous
3879  // union's constructor.
3880  if (Union && RD->isAnonymousStructOrUnion())
3881    return false;
3882
3883  // FIXME: We should put some diagnostic logic right into this function.
3884
3885  // C++0x [class.copy]/11
3886  //    A defaulted [copy] constructor for class X is defined as delete if X has:
3887
3888  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3889                                          BE = RD->bases_end();
3890       BI != BE; ++BI) {
3891    // We'll handle this one later
3892    if (BI->isVirtual())
3893      continue;
3894
3895    QualType BaseType = BI->getType();
3896    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3897    assert(BaseDecl && "base isn't a CXXRecordDecl");
3898
3899    // -- any [direct base class] of a type with a destructor that is deleted or
3900    //    inaccessible from the defaulted constructor
3901    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3902    if (BaseDtor->isDeleted())
3903      return true;
3904    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3905        AR_accessible)
3906      return true;
3907
3908    // -- a [direct base class] B that cannot be [copied] because overload
3909    //    resolution, as applied to B's [copy] constructor, results in an
3910    //    ambiguity or a function that is deleted or inaccessible from the
3911    //    defaulted constructor
3912    CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3913    if (!BaseCtor || BaseCtor->isDeleted())
3914      return true;
3915    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3916        AR_accessible)
3917      return true;
3918  }
3919
3920  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3921                                          BE = RD->vbases_end();
3922       BI != BE; ++BI) {
3923    QualType BaseType = BI->getType();
3924    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3925    assert(BaseDecl && "base isn't a CXXRecordDecl");
3926
3927    // -- any [virtual base class] of a type with a destructor that is deleted or
3928    //    inaccessible from the defaulted constructor
3929    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3930    if (BaseDtor->isDeleted())
3931      return true;
3932    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3933        AR_accessible)
3934      return true;
3935
3936    // -- a [virtual base class] B that cannot be [copied] because overload
3937    //    resolution, as applied to B's [copy] constructor, results in an
3938    //    ambiguity or a function that is deleted or inaccessible from the
3939    //    defaulted constructor
3940    CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3941    if (!BaseCtor || BaseCtor->isDeleted())
3942      return true;
3943    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3944        AR_accessible)
3945      return true;
3946  }
3947
3948  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3949                                     FE = RD->field_end();
3950       FI != FE; ++FI) {
3951    QualType FieldType = Context.getBaseElementType(FI->getType());
3952
3953    // -- for a copy constructor, a non-static data member of rvalue reference
3954    //    type
3955    if (FieldType->isRValueReferenceType())
3956      return true;
3957
3958    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3959
3960    if (FieldRecord) {
3961      // This is an anonymous union
3962      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3963        // Anonymous unions inside unions do not variant members create
3964        if (!Union) {
3965          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3966                                             UE = FieldRecord->field_end();
3967               UI != UE; ++UI) {
3968            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3969            CXXRecordDecl *UnionFieldRecord =
3970              UnionFieldType->getAsCXXRecordDecl();
3971
3972            // -- a variant member with a non-trivial [copy] constructor and X
3973            //    is a union-like class
3974            if (UnionFieldRecord &&
3975                !UnionFieldRecord->hasTrivialCopyConstructor())
3976              return true;
3977          }
3978        }
3979
3980        // Don't try to initalize an anonymous union
3981        continue;
3982      } else {
3983         // -- a variant member with a non-trivial [copy] constructor and X is a
3984         //    union-like class
3985        if (Union && !FieldRecord->hasTrivialCopyConstructor())
3986          return true;
3987
3988        // -- any [non-static data member] of a type with a destructor that is
3989        //    deleted or inaccessible from the defaulted constructor
3990        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3991        if (FieldDtor->isDeleted())
3992          return true;
3993        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3994            AR_accessible)
3995          return true;
3996      }
3997
3998    // -- a [non-static data member of class type (or array thereof)] B that
3999    //    cannot be [copied] because overload resolution, as applied to B's
4000    //    [copy] constructor, results in an ambiguity or a function that is
4001    //    deleted or inaccessible from the defaulted constructor
4002      CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
4003                                                               ArgQuals);
4004      if (!FieldCtor || FieldCtor->isDeleted())
4005        return true;
4006      if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4007                                 PDiag()) != AR_accessible)
4008        return true;
4009    }
4010  }
4011
4012  return false;
4013}
4014
4015bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4016  CXXRecordDecl *RD = MD->getParent();
4017  assert(!RD->isDependentType() && "do deletion after instantiation");
4018  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4019    return false;
4020
4021  SourceLocation Loc = MD->getLocation();
4022
4023  // Do access control from the constructor
4024  ContextRAII MethodContext(*this, MD);
4025
4026  bool Union = RD->isUnion();
4027
4028  unsigned ArgQuals =
4029    MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4030      Qualifiers::Const : 0;
4031
4032  // We do this because we should never actually use an anonymous
4033  // union's constructor.
4034  if (Union && RD->isAnonymousStructOrUnion())
4035    return false;
4036
4037  // FIXME: We should put some diagnostic logic right into this function.
4038
4039  // C++0x [class.copy]/20
4040  //    A defaulted [copy] assignment operator for class X is defined as deleted
4041  //    if X has:
4042
4043  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4044                                          BE = RD->bases_end();
4045       BI != BE; ++BI) {
4046    // We'll handle this one later
4047    if (BI->isVirtual())
4048      continue;
4049
4050    QualType BaseType = BI->getType();
4051    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4052    assert(BaseDecl && "base isn't a CXXRecordDecl");
4053
4054    // -- a [direct base class] B that cannot be [copied] because overload
4055    //    resolution, as applied to B's [copy] assignment operator, results in
4056    //    an ambiguity or a function that is deleted or inaccessible from the
4057    //    assignment operator
4058    CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4059                                                      0);
4060    if (!CopyOper || CopyOper->isDeleted())
4061      return true;
4062    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4063      return true;
4064  }
4065
4066  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4067                                          BE = RD->vbases_end();
4068       BI != BE; ++BI) {
4069    QualType BaseType = BI->getType();
4070    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4071    assert(BaseDecl && "base isn't a CXXRecordDecl");
4072
4073    // -- a [virtual base class] B that cannot be [copied] because overload
4074    //    resolution, as applied to B's [copy] assignment operator, results in
4075    //    an ambiguity or a function that is deleted or inaccessible from the
4076    //    assignment operator
4077    CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4078                                                      0);
4079    if (!CopyOper || CopyOper->isDeleted())
4080      return true;
4081    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4082      return true;
4083  }
4084
4085  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4086                                     FE = RD->field_end();
4087       FI != FE; ++FI) {
4088    QualType FieldType = Context.getBaseElementType(FI->getType());
4089
4090    // -- a non-static data member of reference type
4091    if (FieldType->isReferenceType())
4092      return true;
4093
4094    // -- a non-static data member of const non-class type (or array thereof)
4095    if (FieldType.isConstQualified() && !FieldType->isRecordType())
4096      return true;
4097
4098    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4099
4100    if (FieldRecord) {
4101      // This is an anonymous union
4102      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4103        // Anonymous unions inside unions do not variant members create
4104        if (!Union) {
4105          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4106                                             UE = FieldRecord->field_end();
4107               UI != UE; ++UI) {
4108            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4109            CXXRecordDecl *UnionFieldRecord =
4110              UnionFieldType->getAsCXXRecordDecl();
4111
4112            // -- a variant member with a non-trivial [copy] assignment operator
4113            //    and X is a union-like class
4114            if (UnionFieldRecord &&
4115                !UnionFieldRecord->hasTrivialCopyAssignment())
4116              return true;
4117          }
4118        }
4119
4120        // Don't try to initalize an anonymous union
4121        continue;
4122      // -- a variant member with a non-trivial [copy] assignment operator
4123      //    and X is a union-like class
4124      } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4125          return true;
4126      }
4127
4128      CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4129                                                        false, 0);
4130      if (!CopyOper || CopyOper->isDeleted())
4131        return true;
4132      if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4133        return true;
4134    }
4135  }
4136
4137  return false;
4138}
4139
4140bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) {
4141  CXXRecordDecl *RD = CD->getParent();
4142  assert(!RD->isDependentType() && "do deletion after instantiation");
4143  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4144    return false;
4145
4146  SourceLocation Loc = CD->getLocation();
4147
4148  // Do access control from the constructor
4149  ContextRAII CtorContext(*this, CD);
4150
4151  bool Union = RD->isUnion();
4152
4153  assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
4154         "copy assignment arg has no pointee type");
4155
4156  // We do this because we should never actually use an anonymous
4157  // union's constructor.
4158  if (Union && RD->isAnonymousStructOrUnion())
4159    return false;
4160
4161  // C++0x [class.copy]/11
4162  //    A defaulted [move] constructor for class X is defined as deleted
4163  //    if X has:
4164
4165  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4166                                          BE = RD->bases_end();
4167       BI != BE; ++BI) {
4168    // We'll handle this one later
4169    if (BI->isVirtual())
4170      continue;
4171
4172    QualType BaseType = BI->getType();
4173    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4174    assert(BaseDecl && "base isn't a CXXRecordDecl");
4175
4176    // -- any [direct base class] of a type with a destructor that is deleted or
4177    //    inaccessible from the defaulted constructor
4178    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4179    if (BaseDtor->isDeleted())
4180      return true;
4181    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4182        AR_accessible)
4183      return true;
4184
4185    // -- a [direct base class] B that cannot be [moved] because overload
4186    //    resolution, as applied to B's [move] constructor, results in an
4187    //    ambiguity or a function that is deleted or inaccessible from the
4188    //    defaulted constructor
4189    CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4190    if (!BaseCtor || BaseCtor->isDeleted())
4191      return true;
4192    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4193        AR_accessible)
4194      return true;
4195
4196    // -- for a move constructor, a [direct base class] with a type that
4197    //    does not have a move constructor and is not trivially copyable.
4198    // If the field isn't a record, it's always trivially copyable.
4199    // A moving constructor could be a copy constructor instead.
4200    if (!BaseCtor->isMoveConstructor() &&
4201        !BaseDecl->isTriviallyCopyable())
4202      return true;
4203  }
4204
4205  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4206                                          BE = RD->vbases_end();
4207       BI != BE; ++BI) {
4208    QualType BaseType = BI->getType();
4209    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4210    assert(BaseDecl && "base isn't a CXXRecordDecl");
4211
4212    // -- any [virtual base class] of a type with a destructor that is deleted
4213    //    or inaccessible from the defaulted constructor
4214    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4215    if (BaseDtor->isDeleted())
4216      return true;
4217    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4218        AR_accessible)
4219      return true;
4220
4221    // -- a [virtual base class] B that cannot be [moved] because overload
4222    //    resolution, as applied to B's [move] constructor, results in an
4223    //    ambiguity or a function that is deleted or inaccessible from the
4224    //    defaulted constructor
4225    CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl);
4226    if (!BaseCtor || BaseCtor->isDeleted())
4227      return true;
4228    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
4229        AR_accessible)
4230      return true;
4231
4232    // -- for a move constructor, a [virtual base class] with a type that
4233    //    does not have a move constructor and is not trivially copyable.
4234    // If the field isn't a record, it's always trivially copyable.
4235    // A moving constructor could be a copy constructor instead.
4236    if (!BaseCtor->isMoveConstructor() &&
4237        !BaseDecl->isTriviallyCopyable())
4238      return true;
4239  }
4240
4241  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4242                                     FE = RD->field_end();
4243       FI != FE; ++FI) {
4244    QualType FieldType = Context.getBaseElementType(FI->getType());
4245
4246    if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) {
4247      // This is an anonymous union
4248      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4249        // Anonymous unions inside unions do not variant members create
4250        if (!Union) {
4251          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4252                                             UE = FieldRecord->field_end();
4253               UI != UE; ++UI) {
4254            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4255            CXXRecordDecl *UnionFieldRecord =
4256              UnionFieldType->getAsCXXRecordDecl();
4257
4258            // -- a variant member with a non-trivial [move] constructor and X
4259            //    is a union-like class
4260            if (UnionFieldRecord &&
4261                !UnionFieldRecord->hasTrivialMoveConstructor())
4262              return true;
4263          }
4264        }
4265
4266        // Don't try to initalize an anonymous union
4267        continue;
4268      } else {
4269         // -- a variant member with a non-trivial [move] constructor and X is a
4270         //    union-like class
4271        if (Union && !FieldRecord->hasTrivialMoveConstructor())
4272          return true;
4273
4274        // -- any [non-static data member] of a type with a destructor that is
4275        //    deleted or inaccessible from the defaulted constructor
4276        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4277        if (FieldDtor->isDeleted())
4278          return true;
4279        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4280            AR_accessible)
4281          return true;
4282      }
4283
4284      // -- a [non-static data member of class type (or array thereof)] B that
4285      //    cannot be [moved] because overload resolution, as applied to B's
4286      //    [move] constructor, results in an ambiguity or a function that is
4287      //    deleted or inaccessible from the defaulted constructor
4288      CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord);
4289      if (!FieldCtor || FieldCtor->isDeleted())
4290        return true;
4291      if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4292                                 PDiag()) != AR_accessible)
4293        return true;
4294
4295      // -- for a move constructor, a [non-static data member] with a type that
4296      //    does not have a move constructor and is not trivially copyable.
4297      // If the field isn't a record, it's always trivially copyable.
4298      // A moving constructor could be a copy constructor instead.
4299      if (!FieldCtor->isMoveConstructor() &&
4300          !FieldRecord->isTriviallyCopyable())
4301        return true;
4302    }
4303  }
4304
4305  return false;
4306}
4307
4308bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4309  CXXRecordDecl *RD = MD->getParent();
4310  assert(!RD->isDependentType() && "do deletion after instantiation");
4311  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4312    return false;
4313
4314  SourceLocation Loc = MD->getLocation();
4315
4316  // Do access control from the constructor
4317  ContextRAII MethodContext(*this, MD);
4318
4319  bool Union = RD->isUnion();
4320
4321  // We do this because we should never actually use an anonymous
4322  // union's constructor.
4323  if (Union && RD->isAnonymousStructOrUnion())
4324    return false;
4325
4326  // C++0x [class.copy]/20
4327  //    A defaulted [move] assignment operator for class X is defined as deleted
4328  //    if X has:
4329
4330  //    -- for the move constructor, [...] any direct or indirect virtual base
4331  //       class.
4332  if (RD->getNumVBases() != 0)
4333    return true;
4334
4335  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4336                                          BE = RD->bases_end();
4337       BI != BE; ++BI) {
4338
4339    QualType BaseType = BI->getType();
4340    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4341    assert(BaseDecl && "base isn't a CXXRecordDecl");
4342
4343    // -- a [direct base class] B that cannot be [moved] because overload
4344    //    resolution, as applied to B's [move] assignment operator, results in
4345    //    an ambiguity or a function that is deleted or inaccessible from the
4346    //    assignment operator
4347    CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4348    if (!MoveOper || MoveOper->isDeleted())
4349      return true;
4350    if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4351      return true;
4352
4353    // -- for the move assignment operator, a [direct base class] with a type
4354    //    that does not have a move assignment operator and is not trivially
4355    //    copyable.
4356    if (!MoveOper->isMoveAssignmentOperator() &&
4357        !BaseDecl->isTriviallyCopyable())
4358      return true;
4359  }
4360
4361  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4362                                     FE = RD->field_end();
4363       FI != FE; ++FI) {
4364    QualType FieldType = Context.getBaseElementType(FI->getType());
4365
4366    // -- a non-static data member of reference type
4367    if (FieldType->isReferenceType())
4368      return true;
4369
4370    // -- a non-static data member of const non-class type (or array thereof)
4371    if (FieldType.isConstQualified() && !FieldType->isRecordType())
4372      return true;
4373
4374    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4375
4376    if (FieldRecord) {
4377      // This is an anonymous union
4378      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4379        // Anonymous unions inside unions do not variant members create
4380        if (!Union) {
4381          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4382                                             UE = FieldRecord->field_end();
4383               UI != UE; ++UI) {
4384            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4385            CXXRecordDecl *UnionFieldRecord =
4386              UnionFieldType->getAsCXXRecordDecl();
4387
4388            // -- a variant member with a non-trivial [move] assignment operator
4389            //    and X is a union-like class
4390            if (UnionFieldRecord &&
4391                !UnionFieldRecord->hasTrivialMoveAssignment())
4392              return true;
4393          }
4394        }
4395
4396        // Don't try to initalize an anonymous union
4397        continue;
4398      // -- a variant member with a non-trivial [move] assignment operator
4399      //    and X is a union-like class
4400      } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4401          return true;
4402      }
4403
4404      CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4405      if (!MoveOper || MoveOper->isDeleted())
4406        return true;
4407      if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4408        return true;
4409
4410      // -- for the move assignment operator, a [non-static data member] with a
4411      //    type that does not have a move assignment operator and is not
4412      //    trivially copyable.
4413      if (!MoveOper->isMoveAssignmentOperator() &&
4414          !FieldRecord->isTriviallyCopyable())
4415        return true;
4416    }
4417  }
4418
4419  return false;
4420}
4421
4422bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4423  CXXRecordDecl *RD = DD->getParent();
4424  assert(!RD->isDependentType() && "do deletion after instantiation");
4425  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4426    return false;
4427
4428  SourceLocation Loc = DD->getLocation();
4429
4430  // Do access control from the destructor
4431  ContextRAII CtorContext(*this, DD);
4432
4433  bool Union = RD->isUnion();
4434
4435  // We do this because we should never actually use an anonymous
4436  // union's destructor.
4437  if (Union && RD->isAnonymousStructOrUnion())
4438    return false;
4439
4440  // C++0x [class.dtor]p5
4441  //    A defaulted destructor for a class X is defined as deleted if:
4442  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4443                                          BE = RD->bases_end();
4444       BI != BE; ++BI) {
4445    // We'll handle this one later
4446    if (BI->isVirtual())
4447      continue;
4448
4449    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4450    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4451    assert(BaseDtor && "base has no destructor");
4452
4453    // -- any direct or virtual base class has a deleted destructor or
4454    //    a destructor that is inaccessible from the defaulted destructor
4455    if (BaseDtor->isDeleted())
4456      return true;
4457    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4458        AR_accessible)
4459      return true;
4460  }
4461
4462  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4463                                          BE = RD->vbases_end();
4464       BI != BE; ++BI) {
4465    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4466    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4467    assert(BaseDtor && "base has no destructor");
4468
4469    // -- any direct or virtual base class has a deleted destructor or
4470    //    a destructor that is inaccessible from the defaulted destructor
4471    if (BaseDtor->isDeleted())
4472      return true;
4473    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4474        AR_accessible)
4475      return true;
4476  }
4477
4478  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4479                                     FE = RD->field_end();
4480       FI != FE; ++FI) {
4481    QualType FieldType = Context.getBaseElementType(FI->getType());
4482    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4483    if (FieldRecord) {
4484      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4485         for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4486                                            UE = FieldRecord->field_end();
4487              UI != UE; ++UI) {
4488           QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4489           CXXRecordDecl *UnionFieldRecord =
4490             UnionFieldType->getAsCXXRecordDecl();
4491
4492           // -- X is a union-like class that has a variant member with a non-
4493           //    trivial destructor.
4494           if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4495             return true;
4496         }
4497      // Technically we are supposed to do this next check unconditionally.
4498      // But that makes absolutely no sense.
4499      } else {
4500        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4501
4502        // -- any of the non-static data members has class type M (or array
4503        //    thereof) and M has a deleted destructor or a destructor that is
4504        //    inaccessible from the defaulted destructor
4505        if (FieldDtor->isDeleted())
4506          return true;
4507        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4508          AR_accessible)
4509        return true;
4510
4511        // -- X is a union-like class that has a variant member with a non-
4512        //    trivial destructor.
4513        if (Union && !FieldDtor->isTrivial())
4514          return true;
4515      }
4516    }
4517  }
4518
4519  if (DD->isVirtual()) {
4520    FunctionDecl *OperatorDelete = 0;
4521    DeclarationName Name =
4522      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4523    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
4524          false))
4525      return true;
4526  }
4527
4528
4529  return false;
4530}
4531
4532/// \brief Data used with FindHiddenVirtualMethod
4533namespace {
4534  struct FindHiddenVirtualMethodData {
4535    Sema *S;
4536    CXXMethodDecl *Method;
4537    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4538    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4539  };
4540}
4541
4542/// \brief Member lookup function that determines whether a given C++
4543/// method overloads virtual methods in a base class without overriding any,
4544/// to be used with CXXRecordDecl::lookupInBases().
4545static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4546                                    CXXBasePath &Path,
4547                                    void *UserData) {
4548  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4549
4550  FindHiddenVirtualMethodData &Data
4551    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4552
4553  DeclarationName Name = Data.Method->getDeclName();
4554  assert(Name.getNameKind() == DeclarationName::Identifier);
4555
4556  bool foundSameNameMethod = false;
4557  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4558  for (Path.Decls = BaseRecord->lookup(Name);
4559       Path.Decls.first != Path.Decls.second;
4560       ++Path.Decls.first) {
4561    NamedDecl *D = *Path.Decls.first;
4562    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4563      MD = MD->getCanonicalDecl();
4564      foundSameNameMethod = true;
4565      // Interested only in hidden virtual methods.
4566      if (!MD->isVirtual())
4567        continue;
4568      // If the method we are checking overrides a method from its base
4569      // don't warn about the other overloaded methods.
4570      if (!Data.S->IsOverload(Data.Method, MD, false))
4571        return true;
4572      // Collect the overload only if its hidden.
4573      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4574        overloadedMethods.push_back(MD);
4575    }
4576  }
4577
4578  if (foundSameNameMethod)
4579    Data.OverloadedMethods.append(overloadedMethods.begin(),
4580                                   overloadedMethods.end());
4581  return foundSameNameMethod;
4582}
4583
4584/// \brief See if a method overloads virtual methods in a base class without
4585/// overriding any.
4586void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4587  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4588                               MD->getLocation()) == Diagnostic::Ignored)
4589    return;
4590  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4591    return;
4592
4593  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4594                     /*bool RecordPaths=*/false,
4595                     /*bool DetectVirtual=*/false);
4596  FindHiddenVirtualMethodData Data;
4597  Data.Method = MD;
4598  Data.S = this;
4599
4600  // Keep the base methods that were overriden or introduced in the subclass
4601  // by 'using' in a set. A base method not in this set is hidden.
4602  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4603       res.first != res.second; ++res.first) {
4604    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4605      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4606                                          E = MD->end_overridden_methods();
4607           I != E; ++I)
4608        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4609    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4610      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4611        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4612  }
4613
4614  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4615      !Data.OverloadedMethods.empty()) {
4616    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4617      << MD << (Data.OverloadedMethods.size() > 1);
4618
4619    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4620      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4621      Diag(overloadedMD->getLocation(),
4622           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4623    }
4624  }
4625}
4626
4627void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4628                                             Decl *TagDecl,
4629                                             SourceLocation LBrac,
4630                                             SourceLocation RBrac,
4631                                             AttributeList *AttrList) {
4632  if (!TagDecl)
4633    return;
4634
4635  AdjustDeclIfTemplate(TagDecl);
4636
4637  ActOnFields(S, RLoc, TagDecl,
4638              // strict aliasing violation!
4639              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4640              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4641
4642  CheckCompletedCXXClass(
4643                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4644}
4645
4646/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4647/// special functions, such as the default constructor, copy
4648/// constructor, or destructor, to the given C++ class (C++
4649/// [special]p1).  This routine can only be executed just before the
4650/// definition of the class is complete.
4651void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4652  if (!ClassDecl->hasUserDeclaredConstructor())
4653    ++ASTContext::NumImplicitDefaultConstructors;
4654
4655  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4656    ++ASTContext::NumImplicitCopyConstructors;
4657
4658  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4659    ++ASTContext::NumImplicitCopyAssignmentOperators;
4660
4661    // If we have a dynamic class, then the copy assignment operator may be
4662    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4663    // it shows up in the right place in the vtable and that we diagnose
4664    // problems with the implicit exception specification.
4665    if (ClassDecl->isDynamicClass())
4666      DeclareImplicitCopyAssignment(ClassDecl);
4667  }
4668
4669  if (!ClassDecl->hasUserDeclaredDestructor()) {
4670    ++ASTContext::NumImplicitDestructors;
4671
4672    // If we have a dynamic class, then the destructor may be virtual, so we
4673    // have to declare the destructor immediately. This ensures that, e.g., it
4674    // shows up in the right place in the vtable and that we diagnose problems
4675    // with the implicit exception specification.
4676    if (ClassDecl->isDynamicClass())
4677      DeclareImplicitDestructor(ClassDecl);
4678  }
4679}
4680
4681void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4682  if (!D)
4683    return;
4684
4685  int NumParamList = D->getNumTemplateParameterLists();
4686  for (int i = 0; i < NumParamList; i++) {
4687    TemplateParameterList* Params = D->getTemplateParameterList(i);
4688    for (TemplateParameterList::iterator Param = Params->begin(),
4689                                      ParamEnd = Params->end();
4690          Param != ParamEnd; ++Param) {
4691      NamedDecl *Named = cast<NamedDecl>(*Param);
4692      if (Named->getDeclName()) {
4693        S->AddDecl(Named);
4694        IdResolver.AddDecl(Named);
4695      }
4696    }
4697  }
4698}
4699
4700void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4701  if (!D)
4702    return;
4703
4704  TemplateParameterList *Params = 0;
4705  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4706    Params = Template->getTemplateParameters();
4707  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4708           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4709    Params = PartialSpec->getTemplateParameters();
4710  else
4711    return;
4712
4713  for (TemplateParameterList::iterator Param = Params->begin(),
4714                                    ParamEnd = Params->end();
4715       Param != ParamEnd; ++Param) {
4716    NamedDecl *Named = cast<NamedDecl>(*Param);
4717    if (Named->getDeclName()) {
4718      S->AddDecl(Named);
4719      IdResolver.AddDecl(Named);
4720    }
4721  }
4722}
4723
4724void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4725  if (!RecordD) return;
4726  AdjustDeclIfTemplate(RecordD);
4727  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4728  PushDeclContext(S, Record);
4729}
4730
4731void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4732  if (!RecordD) return;
4733  PopDeclContext();
4734}
4735
4736/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4737/// parsing a top-level (non-nested) C++ class, and we are now
4738/// parsing those parts of the given Method declaration that could
4739/// not be parsed earlier (C++ [class.mem]p2), such as default
4740/// arguments. This action should enter the scope of the given
4741/// Method declaration as if we had just parsed the qualified method
4742/// name. However, it should not bring the parameters into scope;
4743/// that will be performed by ActOnDelayedCXXMethodParameter.
4744void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4745}
4746
4747/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4748/// C++ method declaration. We're (re-)introducing the given
4749/// function parameter into scope for use in parsing later parts of
4750/// the method declaration. For example, we could see an
4751/// ActOnParamDefaultArgument event for this parameter.
4752void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4753  if (!ParamD)
4754    return;
4755
4756  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4757
4758  // If this parameter has an unparsed default argument, clear it out
4759  // to make way for the parsed default argument.
4760  if (Param->hasUnparsedDefaultArg())
4761    Param->setDefaultArg(0);
4762
4763  S->AddDecl(Param);
4764  if (Param->getDeclName())
4765    IdResolver.AddDecl(Param);
4766}
4767
4768/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4769/// processing the delayed method declaration for Method. The method
4770/// declaration is now considered finished. There may be a separate
4771/// ActOnStartOfFunctionDef action later (not necessarily
4772/// immediately!) for this method, if it was also defined inside the
4773/// class body.
4774void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4775  if (!MethodD)
4776    return;
4777
4778  AdjustDeclIfTemplate(MethodD);
4779
4780  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4781
4782  // Now that we have our default arguments, check the constructor
4783  // again. It could produce additional diagnostics or affect whether
4784  // the class has implicitly-declared destructors, among other
4785  // things.
4786  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4787    CheckConstructor(Constructor);
4788
4789  // Check the default arguments, which we may have added.
4790  if (!Method->isInvalidDecl())
4791    CheckCXXDefaultArguments(Method);
4792}
4793
4794/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4795/// the well-formedness of the constructor declarator @p D with type @p
4796/// R. If there are any errors in the declarator, this routine will
4797/// emit diagnostics and set the invalid bit to true.  In any case, the type
4798/// will be updated to reflect a well-formed type for the constructor and
4799/// returned.
4800QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4801                                          StorageClass &SC) {
4802  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4803
4804  // C++ [class.ctor]p3:
4805  //   A constructor shall not be virtual (10.3) or static (9.4). A
4806  //   constructor can be invoked for a const, volatile or const
4807  //   volatile object. A constructor shall not be declared const,
4808  //   volatile, or const volatile (9.3.2).
4809  if (isVirtual) {
4810    if (!D.isInvalidType())
4811      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4812        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4813        << SourceRange(D.getIdentifierLoc());
4814    D.setInvalidType();
4815  }
4816  if (SC == SC_Static) {
4817    if (!D.isInvalidType())
4818      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4819        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4820        << SourceRange(D.getIdentifierLoc());
4821    D.setInvalidType();
4822    SC = SC_None;
4823  }
4824
4825  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4826  if (FTI.TypeQuals != 0) {
4827    if (FTI.TypeQuals & Qualifiers::Const)
4828      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4829        << "const" << SourceRange(D.getIdentifierLoc());
4830    if (FTI.TypeQuals & Qualifiers::Volatile)
4831      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4832        << "volatile" << SourceRange(D.getIdentifierLoc());
4833    if (FTI.TypeQuals & Qualifiers::Restrict)
4834      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4835        << "restrict" << SourceRange(D.getIdentifierLoc());
4836    D.setInvalidType();
4837  }
4838
4839  // C++0x [class.ctor]p4:
4840  //   A constructor shall not be declared with a ref-qualifier.
4841  if (FTI.hasRefQualifier()) {
4842    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4843      << FTI.RefQualifierIsLValueRef
4844      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4845    D.setInvalidType();
4846  }
4847
4848  // Rebuild the function type "R" without any type qualifiers (in
4849  // case any of the errors above fired) and with "void" as the
4850  // return type, since constructors don't have return types.
4851  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4852  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4853    return R;
4854
4855  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4856  EPI.TypeQuals = 0;
4857  EPI.RefQualifier = RQ_None;
4858
4859  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4860                                 Proto->getNumArgs(), EPI);
4861}
4862
4863/// CheckConstructor - Checks a fully-formed constructor for
4864/// well-formedness, issuing any diagnostics required. Returns true if
4865/// the constructor declarator is invalid.
4866void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4867  CXXRecordDecl *ClassDecl
4868    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4869  if (!ClassDecl)
4870    return Constructor->setInvalidDecl();
4871
4872  // C++ [class.copy]p3:
4873  //   A declaration of a constructor for a class X is ill-formed if
4874  //   its first parameter is of type (optionally cv-qualified) X and
4875  //   either there are no other parameters or else all other
4876  //   parameters have default arguments.
4877  if (!Constructor->isInvalidDecl() &&
4878      ((Constructor->getNumParams() == 1) ||
4879       (Constructor->getNumParams() > 1 &&
4880        Constructor->getParamDecl(1)->hasDefaultArg())) &&
4881      Constructor->getTemplateSpecializationKind()
4882                                              != TSK_ImplicitInstantiation) {
4883    QualType ParamType = Constructor->getParamDecl(0)->getType();
4884    QualType ClassTy = Context.getTagDeclType(ClassDecl);
4885    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4886      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4887      const char *ConstRef
4888        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4889                                                        : " const &";
4890      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4891        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4892
4893      // FIXME: Rather that making the constructor invalid, we should endeavor
4894      // to fix the type.
4895      Constructor->setInvalidDecl();
4896    }
4897  }
4898}
4899
4900/// CheckDestructor - Checks a fully-formed destructor definition for
4901/// well-formedness, issuing any diagnostics required.  Returns true
4902/// on error.
4903bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4904  CXXRecordDecl *RD = Destructor->getParent();
4905
4906  if (Destructor->isVirtual()) {
4907    SourceLocation Loc;
4908
4909    if (!Destructor->isImplicit())
4910      Loc = Destructor->getLocation();
4911    else
4912      Loc = RD->getLocation();
4913
4914    // If we have a virtual destructor, look up the deallocation function
4915    FunctionDecl *OperatorDelete = 0;
4916    DeclarationName Name =
4917    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4918    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4919      return true;
4920
4921    MarkDeclarationReferenced(Loc, OperatorDelete);
4922
4923    Destructor->setOperatorDelete(OperatorDelete);
4924  }
4925
4926  return false;
4927}
4928
4929static inline bool
4930FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4931  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4932          FTI.ArgInfo[0].Param &&
4933          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4934}
4935
4936/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4937/// the well-formednes of the destructor declarator @p D with type @p
4938/// R. If there are any errors in the declarator, this routine will
4939/// emit diagnostics and set the declarator to invalid.  Even if this happens,
4940/// will be updated to reflect a well-formed type for the destructor and
4941/// returned.
4942QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4943                                         StorageClass& SC) {
4944  // C++ [class.dtor]p1:
4945  //   [...] A typedef-name that names a class is a class-name
4946  //   (7.1.3); however, a typedef-name that names a class shall not
4947  //   be used as the identifier in the declarator for a destructor
4948  //   declaration.
4949  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4950  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4951    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4952      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4953  else if (const TemplateSpecializationType *TST =
4954             DeclaratorType->getAs<TemplateSpecializationType>())
4955    if (TST->isTypeAlias())
4956      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4957        << DeclaratorType << 1;
4958
4959  // C++ [class.dtor]p2:
4960  //   A destructor is used to destroy objects of its class type. A
4961  //   destructor takes no parameters, and no return type can be
4962  //   specified for it (not even void). The address of a destructor
4963  //   shall not be taken. A destructor shall not be static. A
4964  //   destructor can be invoked for a const, volatile or const
4965  //   volatile object. A destructor shall not be declared const,
4966  //   volatile or const volatile (9.3.2).
4967  if (SC == SC_Static) {
4968    if (!D.isInvalidType())
4969      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4970        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4971        << SourceRange(D.getIdentifierLoc())
4972        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4973
4974    SC = SC_None;
4975  }
4976  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4977    // Destructors don't have return types, but the parser will
4978    // happily parse something like:
4979    //
4980    //   class X {
4981    //     float ~X();
4982    //   };
4983    //
4984    // The return type will be eliminated later.
4985    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4986      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4987      << SourceRange(D.getIdentifierLoc());
4988  }
4989
4990  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4991  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4992    if (FTI.TypeQuals & Qualifiers::Const)
4993      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4994        << "const" << SourceRange(D.getIdentifierLoc());
4995    if (FTI.TypeQuals & Qualifiers::Volatile)
4996      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4997        << "volatile" << SourceRange(D.getIdentifierLoc());
4998    if (FTI.TypeQuals & Qualifiers::Restrict)
4999      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5000        << "restrict" << SourceRange(D.getIdentifierLoc());
5001    D.setInvalidType();
5002  }
5003
5004  // C++0x [class.dtor]p2:
5005  //   A destructor shall not be declared with a ref-qualifier.
5006  if (FTI.hasRefQualifier()) {
5007    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5008      << FTI.RefQualifierIsLValueRef
5009      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5010    D.setInvalidType();
5011  }
5012
5013  // Make sure we don't have any parameters.
5014  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5015    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5016
5017    // Delete the parameters.
5018    FTI.freeArgs();
5019    D.setInvalidType();
5020  }
5021
5022  // Make sure the destructor isn't variadic.
5023  if (FTI.isVariadic) {
5024    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5025    D.setInvalidType();
5026  }
5027
5028  // Rebuild the function type "R" without any type qualifiers or
5029  // parameters (in case any of the errors above fired) and with
5030  // "void" as the return type, since destructors don't have return
5031  // types.
5032  if (!D.isInvalidType())
5033    return R;
5034
5035  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5036  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5037  EPI.Variadic = false;
5038  EPI.TypeQuals = 0;
5039  EPI.RefQualifier = RQ_None;
5040  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5041}
5042
5043/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5044/// well-formednes of the conversion function declarator @p D with
5045/// type @p R. If there are any errors in the declarator, this routine
5046/// will emit diagnostics and return true. Otherwise, it will return
5047/// false. Either way, the type @p R will be updated to reflect a
5048/// well-formed type for the conversion operator.
5049void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5050                                     StorageClass& SC) {
5051  // C++ [class.conv.fct]p1:
5052  //   Neither parameter types nor return type can be specified. The
5053  //   type of a conversion function (8.3.5) is "function taking no
5054  //   parameter returning conversion-type-id."
5055  if (SC == SC_Static) {
5056    if (!D.isInvalidType())
5057      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5058        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5059        << SourceRange(D.getIdentifierLoc());
5060    D.setInvalidType();
5061    SC = SC_None;
5062  }
5063
5064  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5065
5066  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5067    // Conversion functions don't have return types, but the parser will
5068    // happily parse something like:
5069    //
5070    //   class X {
5071    //     float operator bool();
5072    //   };
5073    //
5074    // The return type will be changed later anyway.
5075    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5076      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5077      << SourceRange(D.getIdentifierLoc());
5078    D.setInvalidType();
5079  }
5080
5081  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5082
5083  // Make sure we don't have any parameters.
5084  if (Proto->getNumArgs() > 0) {
5085    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5086
5087    // Delete the parameters.
5088    D.getFunctionTypeInfo().freeArgs();
5089    D.setInvalidType();
5090  } else if (Proto->isVariadic()) {
5091    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5092    D.setInvalidType();
5093  }
5094
5095  // Diagnose "&operator bool()" and other such nonsense.  This
5096  // is actually a gcc extension which we don't support.
5097  if (Proto->getResultType() != ConvType) {
5098    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5099      << Proto->getResultType();
5100    D.setInvalidType();
5101    ConvType = Proto->getResultType();
5102  }
5103
5104  // C++ [class.conv.fct]p4:
5105  //   The conversion-type-id shall not represent a function type nor
5106  //   an array type.
5107  if (ConvType->isArrayType()) {
5108    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5109    ConvType = Context.getPointerType(ConvType);
5110    D.setInvalidType();
5111  } else if (ConvType->isFunctionType()) {
5112    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5113    ConvType = Context.getPointerType(ConvType);
5114    D.setInvalidType();
5115  }
5116
5117  // Rebuild the function type "R" without any parameters (in case any
5118  // of the errors above fired) and with the conversion type as the
5119  // return type.
5120  if (D.isInvalidType())
5121    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5122
5123  // C++0x explicit conversion operators.
5124  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
5125    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5126         diag::warn_explicit_conversion_functions)
5127      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5128}
5129
5130/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5131/// the declaration of the given C++ conversion function. This routine
5132/// is responsible for recording the conversion function in the C++
5133/// class, if possible.
5134Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5135  assert(Conversion && "Expected to receive a conversion function declaration");
5136
5137  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5138
5139  // Make sure we aren't redeclaring the conversion function.
5140  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5141
5142  // C++ [class.conv.fct]p1:
5143  //   [...] A conversion function is never used to convert a
5144  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5145  //   same object type (or a reference to it), to a (possibly
5146  //   cv-qualified) base class of that type (or a reference to it),
5147  //   or to (possibly cv-qualified) void.
5148  // FIXME: Suppress this warning if the conversion function ends up being a
5149  // virtual function that overrides a virtual function in a base class.
5150  QualType ClassType
5151    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5152  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5153    ConvType = ConvTypeRef->getPointeeType();
5154  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5155      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5156    /* Suppress diagnostics for instantiations. */;
5157  else if (ConvType->isRecordType()) {
5158    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5159    if (ConvType == ClassType)
5160      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5161        << ClassType;
5162    else if (IsDerivedFrom(ClassType, ConvType))
5163      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5164        <<  ClassType << ConvType;
5165  } else if (ConvType->isVoidType()) {
5166    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5167      << ClassType << ConvType;
5168  }
5169
5170  if (FunctionTemplateDecl *ConversionTemplate
5171                                = Conversion->getDescribedFunctionTemplate())
5172    return ConversionTemplate;
5173
5174  return Conversion;
5175}
5176
5177//===----------------------------------------------------------------------===//
5178// Namespace Handling
5179//===----------------------------------------------------------------------===//
5180
5181
5182
5183/// ActOnStartNamespaceDef - This is called at the start of a namespace
5184/// definition.
5185Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5186                                   SourceLocation InlineLoc,
5187                                   SourceLocation NamespaceLoc,
5188                                   SourceLocation IdentLoc,
5189                                   IdentifierInfo *II,
5190                                   SourceLocation LBrace,
5191                                   AttributeList *AttrList) {
5192  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5193  // For anonymous namespace, take the location of the left brace.
5194  SourceLocation Loc = II ? IdentLoc : LBrace;
5195  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
5196                                                 StartLoc, Loc, II);
5197  Namespc->setInline(InlineLoc.isValid());
5198
5199  Scope *DeclRegionScope = NamespcScope->getParent();
5200
5201  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5202
5203  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5204    PushNamespaceVisibilityAttr(Attr);
5205
5206  if (II) {
5207    // C++ [namespace.def]p2:
5208    //   The identifier in an original-namespace-definition shall not
5209    //   have been previously defined in the declarative region in
5210    //   which the original-namespace-definition appears. The
5211    //   identifier in an original-namespace-definition is the name of
5212    //   the namespace. Subsequently in that declarative region, it is
5213    //   treated as an original-namespace-name.
5214    //
5215    // Since namespace names are unique in their scope, and we don't
5216    // look through using directives, just look for any ordinary names.
5217
5218    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5219      Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5220      Decl::IDNS_Namespace;
5221    NamedDecl *PrevDecl = 0;
5222    for (DeclContext::lookup_result R
5223            = CurContext->getRedeclContext()->lookup(II);
5224         R.first != R.second; ++R.first) {
5225      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5226        PrevDecl = *R.first;
5227        break;
5228      }
5229    }
5230
5231    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5232      // This is an extended namespace definition.
5233      if (Namespc->isInline() != OrigNS->isInline()) {
5234        // inline-ness must match
5235        if (OrigNS->isInline()) {
5236          // The user probably just forgot the 'inline', so suggest that it
5237          // be added back.
5238          Diag(Namespc->getLocation(),
5239               diag::warn_inline_namespace_reopened_noninline)
5240            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5241        } else {
5242          Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5243            << Namespc->isInline();
5244        }
5245        Diag(OrigNS->getLocation(), diag::note_previous_definition);
5246
5247        // Recover by ignoring the new namespace's inline status.
5248        Namespc->setInline(OrigNS->isInline());
5249      }
5250
5251      // Attach this namespace decl to the chain of extended namespace
5252      // definitions.
5253      OrigNS->setNextNamespace(Namespc);
5254      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
5255
5256      // Remove the previous declaration from the scope.
5257      if (DeclRegionScope->isDeclScope(OrigNS)) {
5258        IdResolver.RemoveDecl(OrigNS);
5259        DeclRegionScope->RemoveDecl(OrigNS);
5260      }
5261    } else if (PrevDecl) {
5262      // This is an invalid name redefinition.
5263      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5264       << Namespc->getDeclName();
5265      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5266      Namespc->setInvalidDecl();
5267      // Continue on to push Namespc as current DeclContext and return it.
5268    } else if (II->isStr("std") &&
5269               CurContext->getRedeclContext()->isTranslationUnit()) {
5270      // This is the first "real" definition of the namespace "std", so update
5271      // our cache of the "std" namespace to point at this definition.
5272      if (NamespaceDecl *StdNS = getStdNamespace()) {
5273        // We had already defined a dummy namespace "std". Link this new
5274        // namespace definition to the dummy namespace "std".
5275        StdNS->setNextNamespace(Namespc);
5276        StdNS->setLocation(IdentLoc);
5277        Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
5278      }
5279
5280      // Make our StdNamespace cache point at the first real definition of the
5281      // "std" namespace.
5282      StdNamespace = Namespc;
5283
5284      // Add this instance of "std" to the set of known namespaces
5285      KnownNamespaces[Namespc] = false;
5286    } else if (!Namespc->isInline()) {
5287      // Since this is an "original" namespace, add it to the known set of
5288      // namespaces if it is not an inline namespace.
5289      KnownNamespaces[Namespc] = false;
5290    }
5291
5292    PushOnScopeChains(Namespc, DeclRegionScope);
5293  } else {
5294    // Anonymous namespaces.
5295    assert(Namespc->isAnonymousNamespace());
5296
5297    // Link the anonymous namespace into its parent.
5298    NamespaceDecl *PrevDecl;
5299    DeclContext *Parent = CurContext->getRedeclContext();
5300    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5301      PrevDecl = TU->getAnonymousNamespace();
5302      TU->setAnonymousNamespace(Namespc);
5303    } else {
5304      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5305      PrevDecl = ND->getAnonymousNamespace();
5306      ND->setAnonymousNamespace(Namespc);
5307    }
5308
5309    // Link the anonymous namespace with its previous declaration.
5310    if (PrevDecl) {
5311      assert(PrevDecl->isAnonymousNamespace());
5312      assert(!PrevDecl->getNextNamespace());
5313      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5314      PrevDecl->setNextNamespace(Namespc);
5315
5316      if (Namespc->isInline() != PrevDecl->isInline()) {
5317        // inline-ness must match
5318        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5319          << Namespc->isInline();
5320        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5321        Namespc->setInvalidDecl();
5322        // Recover by ignoring the new namespace's inline status.
5323        Namespc->setInline(PrevDecl->isInline());
5324      }
5325    }
5326
5327    CurContext->addDecl(Namespc);
5328
5329    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5330    //   behaves as if it were replaced by
5331    //     namespace unique { /* empty body */ }
5332    //     using namespace unique;
5333    //     namespace unique { namespace-body }
5334    //   where all occurrences of 'unique' in a translation unit are
5335    //   replaced by the same identifier and this identifier differs
5336    //   from all other identifiers in the entire program.
5337
5338    // We just create the namespace with an empty name and then add an
5339    // implicit using declaration, just like the standard suggests.
5340    //
5341    // CodeGen enforces the "universally unique" aspect by giving all
5342    // declarations semantically contained within an anonymous
5343    // namespace internal linkage.
5344
5345    if (!PrevDecl) {
5346      UsingDirectiveDecl* UD
5347        = UsingDirectiveDecl::Create(Context, CurContext,
5348                                     /* 'using' */ LBrace,
5349                                     /* 'namespace' */ SourceLocation(),
5350                                     /* qualifier */ NestedNameSpecifierLoc(),
5351                                     /* identifier */ SourceLocation(),
5352                                     Namespc,
5353                                     /* Ancestor */ CurContext);
5354      UD->setImplicit();
5355      CurContext->addDecl(UD);
5356    }
5357  }
5358
5359  // Although we could have an invalid decl (i.e. the namespace name is a
5360  // redefinition), push it as current DeclContext and try to continue parsing.
5361  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5362  // for the namespace has the declarations that showed up in that particular
5363  // namespace definition.
5364  PushDeclContext(NamespcScope, Namespc);
5365  return Namespc;
5366}
5367
5368/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5369/// is a namespace alias, returns the namespace it points to.
5370static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5371  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5372    return AD->getNamespace();
5373  return dyn_cast_or_null<NamespaceDecl>(D);
5374}
5375
5376/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5377/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5378void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5379  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5380  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5381  Namespc->setRBraceLoc(RBrace);
5382  PopDeclContext();
5383  if (Namespc->hasAttr<VisibilityAttr>())
5384    PopPragmaVisibility();
5385}
5386
5387CXXRecordDecl *Sema::getStdBadAlloc() const {
5388  return cast_or_null<CXXRecordDecl>(
5389                                  StdBadAlloc.get(Context.getExternalSource()));
5390}
5391
5392NamespaceDecl *Sema::getStdNamespace() const {
5393  return cast_or_null<NamespaceDecl>(
5394                                 StdNamespace.get(Context.getExternalSource()));
5395}
5396
5397/// \brief Retrieve the special "std" namespace, which may require us to
5398/// implicitly define the namespace.
5399NamespaceDecl *Sema::getOrCreateStdNamespace() {
5400  if (!StdNamespace) {
5401    // The "std" namespace has not yet been defined, so build one implicitly.
5402    StdNamespace = NamespaceDecl::Create(Context,
5403                                         Context.getTranslationUnitDecl(),
5404                                         SourceLocation(), SourceLocation(),
5405                                         &PP.getIdentifierTable().get("std"));
5406    getStdNamespace()->setImplicit(true);
5407  }
5408
5409  return getStdNamespace();
5410}
5411
5412/// \brief Determine whether a using statement is in a context where it will be
5413/// apply in all contexts.
5414static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5415  switch (CurContext->getDeclKind()) {
5416    case Decl::TranslationUnit:
5417      return true;
5418    case Decl::LinkageSpec:
5419      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5420    default:
5421      return false;
5422  }
5423}
5424
5425static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5426                                       CXXScopeSpec &SS,
5427                                       SourceLocation IdentLoc,
5428                                       IdentifierInfo *Ident) {
5429  R.clear();
5430  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5431                                               R.getLookupKind(), Sc, &SS, NULL,
5432                                               false, S.CTC_NoKeywords, NULL)) {
5433    if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5434        Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5435      std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5436      std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5437      if (DeclContext *DC = S.computeDeclContext(SS, false))
5438        S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5439          << Ident << DC << CorrectedQuotedStr << SS.getRange()
5440          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5441      else
5442        S.Diag(IdentLoc, diag::err_using_directive_suggest)
5443          << Ident << CorrectedQuotedStr
5444          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5445
5446      S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5447           diag::note_namespace_defined_here) << CorrectedQuotedStr;
5448
5449      Ident = Corrected.getCorrectionAsIdentifierInfo();
5450      R.addDecl(Corrected.getCorrectionDecl());
5451      return true;
5452    }
5453    R.setLookupName(Ident);
5454  }
5455  return false;
5456}
5457
5458Decl *Sema::ActOnUsingDirective(Scope *S,
5459                                          SourceLocation UsingLoc,
5460                                          SourceLocation NamespcLoc,
5461                                          CXXScopeSpec &SS,
5462                                          SourceLocation IdentLoc,
5463                                          IdentifierInfo *NamespcName,
5464                                          AttributeList *AttrList) {
5465  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5466  assert(NamespcName && "Invalid NamespcName.");
5467  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5468
5469  // This can only happen along a recovery path.
5470  while (S->getFlags() & Scope::TemplateParamScope)
5471    S = S->getParent();
5472  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5473
5474  UsingDirectiveDecl *UDir = 0;
5475  NestedNameSpecifier *Qualifier = 0;
5476  if (SS.isSet())
5477    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5478
5479  // Lookup namespace name.
5480  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5481  LookupParsedName(R, S, &SS);
5482  if (R.isAmbiguous())
5483    return 0;
5484
5485  if (R.empty()) {
5486    R.clear();
5487    // Allow "using namespace std;" or "using namespace ::std;" even if
5488    // "std" hasn't been defined yet, for GCC compatibility.
5489    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5490        NamespcName->isStr("std")) {
5491      Diag(IdentLoc, diag::ext_using_undefined_std);
5492      R.addDecl(getOrCreateStdNamespace());
5493      R.resolveKind();
5494    }
5495    // Otherwise, attempt typo correction.
5496    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5497  }
5498
5499  if (!R.empty()) {
5500    NamedDecl *Named = R.getFoundDecl();
5501    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5502        && "expected namespace decl");
5503    // C++ [namespace.udir]p1:
5504    //   A using-directive specifies that the names in the nominated
5505    //   namespace can be used in the scope in which the
5506    //   using-directive appears after the using-directive. During
5507    //   unqualified name lookup (3.4.1), the names appear as if they
5508    //   were declared in the nearest enclosing namespace which
5509    //   contains both the using-directive and the nominated
5510    //   namespace. [Note: in this context, "contains" means "contains
5511    //   directly or indirectly". ]
5512
5513    // Find enclosing context containing both using-directive and
5514    // nominated namespace.
5515    NamespaceDecl *NS = getNamespaceDecl(Named);
5516    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5517    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5518      CommonAncestor = CommonAncestor->getParent();
5519
5520    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5521                                      SS.getWithLocInContext(Context),
5522                                      IdentLoc, Named, CommonAncestor);
5523
5524    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5525        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5526      Diag(IdentLoc, diag::warn_using_directive_in_header);
5527    }
5528
5529    PushUsingDirective(S, UDir);
5530  } else {
5531    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5532  }
5533
5534  // FIXME: We ignore attributes for now.
5535  return UDir;
5536}
5537
5538void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5539  // If scope has associated entity, then using directive is at namespace
5540  // or translation unit scope. We add UsingDirectiveDecls, into
5541  // it's lookup structure.
5542  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
5543    Ctx->addDecl(UDir);
5544  else
5545    // Otherwise it is block-sope. using-directives will affect lookup
5546    // only to the end of scope.
5547    S->PushUsingDirective(UDir);
5548}
5549
5550
5551Decl *Sema::ActOnUsingDeclaration(Scope *S,
5552                                  AccessSpecifier AS,
5553                                  bool HasUsingKeyword,
5554                                  SourceLocation UsingLoc,
5555                                  CXXScopeSpec &SS,
5556                                  UnqualifiedId &Name,
5557                                  AttributeList *AttrList,
5558                                  bool IsTypeName,
5559                                  SourceLocation TypenameLoc) {
5560  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5561
5562  switch (Name.getKind()) {
5563  case UnqualifiedId::IK_ImplicitSelfParam:
5564  case UnqualifiedId::IK_Identifier:
5565  case UnqualifiedId::IK_OperatorFunctionId:
5566  case UnqualifiedId::IK_LiteralOperatorId:
5567  case UnqualifiedId::IK_ConversionFunctionId:
5568    break;
5569
5570  case UnqualifiedId::IK_ConstructorName:
5571  case UnqualifiedId::IK_ConstructorTemplateId:
5572    // C++0x inherited constructors.
5573    if (getLangOptions().CPlusPlus0x) break;
5574
5575    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5576      << SS.getRange();
5577    return 0;
5578
5579  case UnqualifiedId::IK_DestructorName:
5580    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5581      << SS.getRange();
5582    return 0;
5583
5584  case UnqualifiedId::IK_TemplateId:
5585    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5586      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5587    return 0;
5588  }
5589
5590  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5591  DeclarationName TargetName = TargetNameInfo.getName();
5592  if (!TargetName)
5593    return 0;
5594
5595  // Warn about using declarations.
5596  // TODO: store that the declaration was written without 'using' and
5597  // talk about access decls instead of using decls in the
5598  // diagnostics.
5599  if (!HasUsingKeyword) {
5600    UsingLoc = Name.getSourceRange().getBegin();
5601
5602    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5603      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5604  }
5605
5606  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5607      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5608    return 0;
5609
5610  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5611                                        TargetNameInfo, AttrList,
5612                                        /* IsInstantiation */ false,
5613                                        IsTypeName, TypenameLoc);
5614  if (UD)
5615    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5616
5617  return UD;
5618}
5619
5620/// \brief Determine whether a using declaration considers the given
5621/// declarations as "equivalent", e.g., if they are redeclarations of
5622/// the same entity or are both typedefs of the same type.
5623static bool
5624IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5625                         bool &SuppressRedeclaration) {
5626  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5627    SuppressRedeclaration = false;
5628    return true;
5629  }
5630
5631  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5632    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5633      SuppressRedeclaration = true;
5634      return Context.hasSameType(TD1->getUnderlyingType(),
5635                                 TD2->getUnderlyingType());
5636    }
5637
5638  return false;
5639}
5640
5641
5642/// Determines whether to create a using shadow decl for a particular
5643/// decl, given the set of decls existing prior to this using lookup.
5644bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5645                                const LookupResult &Previous) {
5646  // Diagnose finding a decl which is not from a base class of the
5647  // current class.  We do this now because there are cases where this
5648  // function will silently decide not to build a shadow decl, which
5649  // will pre-empt further diagnostics.
5650  //
5651  // We don't need to do this in C++0x because we do the check once on
5652  // the qualifier.
5653  //
5654  // FIXME: diagnose the following if we care enough:
5655  //   struct A { int foo; };
5656  //   struct B : A { using A::foo; };
5657  //   template <class T> struct C : A {};
5658  //   template <class T> struct D : C<T> { using B::foo; } // <---
5659  // This is invalid (during instantiation) in C++03 because B::foo
5660  // resolves to the using decl in B, which is not a base class of D<T>.
5661  // We can't diagnose it immediately because C<T> is an unknown
5662  // specialization.  The UsingShadowDecl in D<T> then points directly
5663  // to A::foo, which will look well-formed when we instantiate.
5664  // The right solution is to not collapse the shadow-decl chain.
5665  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5666    DeclContext *OrigDC = Orig->getDeclContext();
5667
5668    // Handle enums and anonymous structs.
5669    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5670    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5671    while (OrigRec->isAnonymousStructOrUnion())
5672      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5673
5674    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5675      if (OrigDC == CurContext) {
5676        Diag(Using->getLocation(),
5677             diag::err_using_decl_nested_name_specifier_is_current_class)
5678          << Using->getQualifierLoc().getSourceRange();
5679        Diag(Orig->getLocation(), diag::note_using_decl_target);
5680        return true;
5681      }
5682
5683      Diag(Using->getQualifierLoc().getBeginLoc(),
5684           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5685        << Using->getQualifier()
5686        << cast<CXXRecordDecl>(CurContext)
5687        << Using->getQualifierLoc().getSourceRange();
5688      Diag(Orig->getLocation(), diag::note_using_decl_target);
5689      return true;
5690    }
5691  }
5692
5693  if (Previous.empty()) return false;
5694
5695  NamedDecl *Target = Orig;
5696  if (isa<UsingShadowDecl>(Target))
5697    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5698
5699  // If the target happens to be one of the previous declarations, we
5700  // don't have a conflict.
5701  //
5702  // FIXME: but we might be increasing its access, in which case we
5703  // should redeclare it.
5704  NamedDecl *NonTag = 0, *Tag = 0;
5705  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5706         I != E; ++I) {
5707    NamedDecl *D = (*I)->getUnderlyingDecl();
5708    bool Result;
5709    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5710      return Result;
5711
5712    (isa<TagDecl>(D) ? Tag : NonTag) = D;
5713  }
5714
5715  if (Target->isFunctionOrFunctionTemplate()) {
5716    FunctionDecl *FD;
5717    if (isa<FunctionTemplateDecl>(Target))
5718      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5719    else
5720      FD = cast<FunctionDecl>(Target);
5721
5722    NamedDecl *OldDecl = 0;
5723    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5724    case Ovl_Overload:
5725      return false;
5726
5727    case Ovl_NonFunction:
5728      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5729      break;
5730
5731    // We found a decl with the exact signature.
5732    case Ovl_Match:
5733      // If we're in a record, we want to hide the target, so we
5734      // return true (without a diagnostic) to tell the caller not to
5735      // build a shadow decl.
5736      if (CurContext->isRecord())
5737        return true;
5738
5739      // If we're not in a record, this is an error.
5740      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5741      break;
5742    }
5743
5744    Diag(Target->getLocation(), diag::note_using_decl_target);
5745    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5746    return true;
5747  }
5748
5749  // Target is not a function.
5750
5751  if (isa<TagDecl>(Target)) {
5752    // No conflict between a tag and a non-tag.
5753    if (!Tag) return false;
5754
5755    Diag(Using->getLocation(), diag::err_using_decl_conflict);
5756    Diag(Target->getLocation(), diag::note_using_decl_target);
5757    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5758    return true;
5759  }
5760
5761  // No conflict between a tag and a non-tag.
5762  if (!NonTag) return false;
5763
5764  Diag(Using->getLocation(), diag::err_using_decl_conflict);
5765  Diag(Target->getLocation(), diag::note_using_decl_target);
5766  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5767  return true;
5768}
5769
5770/// Builds a shadow declaration corresponding to a 'using' declaration.
5771UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5772                                            UsingDecl *UD,
5773                                            NamedDecl *Orig) {
5774
5775  // If we resolved to another shadow declaration, just coalesce them.
5776  NamedDecl *Target = Orig;
5777  if (isa<UsingShadowDecl>(Target)) {
5778    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5779    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5780  }
5781
5782  UsingShadowDecl *Shadow
5783    = UsingShadowDecl::Create(Context, CurContext,
5784                              UD->getLocation(), UD, Target);
5785  UD->addShadowDecl(Shadow);
5786
5787  Shadow->setAccess(UD->getAccess());
5788  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5789    Shadow->setInvalidDecl();
5790
5791  if (S)
5792    PushOnScopeChains(Shadow, S);
5793  else
5794    CurContext->addDecl(Shadow);
5795
5796
5797  return Shadow;
5798}
5799
5800/// Hides a using shadow declaration.  This is required by the current
5801/// using-decl implementation when a resolvable using declaration in a
5802/// class is followed by a declaration which would hide or override
5803/// one or more of the using decl's targets; for example:
5804///
5805///   struct Base { void foo(int); };
5806///   struct Derived : Base {
5807///     using Base::foo;
5808///     void foo(int);
5809///   };
5810///
5811/// The governing language is C++03 [namespace.udecl]p12:
5812///
5813///   When a using-declaration brings names from a base class into a
5814///   derived class scope, member functions in the derived class
5815///   override and/or hide member functions with the same name and
5816///   parameter types in a base class (rather than conflicting).
5817///
5818/// There are two ways to implement this:
5819///   (1) optimistically create shadow decls when they're not hidden
5820///       by existing declarations, or
5821///   (2) don't create any shadow decls (or at least don't make them
5822///       visible) until we've fully parsed/instantiated the class.
5823/// The problem with (1) is that we might have to retroactively remove
5824/// a shadow decl, which requires several O(n) operations because the
5825/// decl structures are (very reasonably) not designed for removal.
5826/// (2) avoids this but is very fiddly and phase-dependent.
5827void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5828  if (Shadow->getDeclName().getNameKind() ==
5829        DeclarationName::CXXConversionFunctionName)
5830    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5831
5832  // Remove it from the DeclContext...
5833  Shadow->getDeclContext()->removeDecl(Shadow);
5834
5835  // ...and the scope, if applicable...
5836  if (S) {
5837    S->RemoveDecl(Shadow);
5838    IdResolver.RemoveDecl(Shadow);
5839  }
5840
5841  // ...and the using decl.
5842  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5843
5844  // TODO: complain somehow if Shadow was used.  It shouldn't
5845  // be possible for this to happen, because...?
5846}
5847
5848/// Builds a using declaration.
5849///
5850/// \param IsInstantiation - Whether this call arises from an
5851///   instantiation of an unresolved using declaration.  We treat
5852///   the lookup differently for these declarations.
5853NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5854                                       SourceLocation UsingLoc,
5855                                       CXXScopeSpec &SS,
5856                                       const DeclarationNameInfo &NameInfo,
5857                                       AttributeList *AttrList,
5858                                       bool IsInstantiation,
5859                                       bool IsTypeName,
5860                                       SourceLocation TypenameLoc) {
5861  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5862  SourceLocation IdentLoc = NameInfo.getLoc();
5863  assert(IdentLoc.isValid() && "Invalid TargetName location.");
5864
5865  // FIXME: We ignore attributes for now.
5866
5867  if (SS.isEmpty()) {
5868    Diag(IdentLoc, diag::err_using_requires_qualname);
5869    return 0;
5870  }
5871
5872  // Do the redeclaration lookup in the current scope.
5873  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5874                        ForRedeclaration);
5875  Previous.setHideTags(false);
5876  if (S) {
5877    LookupName(Previous, S);
5878
5879    // It is really dumb that we have to do this.
5880    LookupResult::Filter F = Previous.makeFilter();
5881    while (F.hasNext()) {
5882      NamedDecl *D = F.next();
5883      if (!isDeclInScope(D, CurContext, S))
5884        F.erase();
5885    }
5886    F.done();
5887  } else {
5888    assert(IsInstantiation && "no scope in non-instantiation");
5889    assert(CurContext->isRecord() && "scope not record in instantiation");
5890    LookupQualifiedName(Previous, CurContext);
5891  }
5892
5893  // Check for invalid redeclarations.
5894  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5895    return 0;
5896
5897  // Check for bad qualifiers.
5898  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5899    return 0;
5900
5901  DeclContext *LookupContext = computeDeclContext(SS);
5902  NamedDecl *D;
5903  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5904  if (!LookupContext) {
5905    if (IsTypeName) {
5906      // FIXME: not all declaration name kinds are legal here
5907      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5908                                              UsingLoc, TypenameLoc,
5909                                              QualifierLoc,
5910                                              IdentLoc, NameInfo.getName());
5911    } else {
5912      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5913                                           QualifierLoc, NameInfo);
5914    }
5915  } else {
5916    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5917                          NameInfo, IsTypeName);
5918  }
5919  D->setAccess(AS);
5920  CurContext->addDecl(D);
5921
5922  if (!LookupContext) return D;
5923  UsingDecl *UD = cast<UsingDecl>(D);
5924
5925  if (RequireCompleteDeclContext(SS, LookupContext)) {
5926    UD->setInvalidDecl();
5927    return UD;
5928  }
5929
5930  // Constructor inheriting using decls get special treatment.
5931  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5932    if (CheckInheritedConstructorUsingDecl(UD))
5933      UD->setInvalidDecl();
5934    return UD;
5935  }
5936
5937  // Otherwise, look up the target name.
5938
5939  LookupResult R(*this, NameInfo, LookupOrdinaryName);
5940  R.setUsingDeclaration(true);
5941
5942  // Unlike most lookups, we don't always want to hide tag
5943  // declarations: tag names are visible through the using declaration
5944  // even if hidden by ordinary names, *except* in a dependent context
5945  // where it's important for the sanity of two-phase lookup.
5946  if (!IsInstantiation)
5947    R.setHideTags(false);
5948
5949  LookupQualifiedName(R, LookupContext);
5950
5951  if (R.empty()) {
5952    Diag(IdentLoc, diag::err_no_member)
5953      << NameInfo.getName() << LookupContext << SS.getRange();
5954    UD->setInvalidDecl();
5955    return UD;
5956  }
5957
5958  if (R.isAmbiguous()) {
5959    UD->setInvalidDecl();
5960    return UD;
5961  }
5962
5963  if (IsTypeName) {
5964    // If we asked for a typename and got a non-type decl, error out.
5965    if (!R.getAsSingle<TypeDecl>()) {
5966      Diag(IdentLoc, diag::err_using_typename_non_type);
5967      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5968        Diag((*I)->getUnderlyingDecl()->getLocation(),
5969             diag::note_using_decl_target);
5970      UD->setInvalidDecl();
5971      return UD;
5972    }
5973  } else {
5974    // If we asked for a non-typename and we got a type, error out,
5975    // but only if this is an instantiation of an unresolved using
5976    // decl.  Otherwise just silently find the type name.
5977    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5978      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5979      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5980      UD->setInvalidDecl();
5981      return UD;
5982    }
5983  }
5984
5985  // C++0x N2914 [namespace.udecl]p6:
5986  // A using-declaration shall not name a namespace.
5987  if (R.getAsSingle<NamespaceDecl>()) {
5988    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5989      << SS.getRange();
5990    UD->setInvalidDecl();
5991    return UD;
5992  }
5993
5994  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5995    if (!CheckUsingShadowDecl(UD, *I, Previous))
5996      BuildUsingShadowDecl(S, UD, *I);
5997  }
5998
5999  return UD;
6000}
6001
6002/// Additional checks for a using declaration referring to a constructor name.
6003bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6004  if (UD->isTypeName()) {
6005    // FIXME: Cannot specify typename when specifying constructor
6006    return true;
6007  }
6008
6009  const Type *SourceType = UD->getQualifier()->getAsType();
6010  assert(SourceType &&
6011         "Using decl naming constructor doesn't have type in scope spec.");
6012  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6013
6014  // Check whether the named type is a direct base class.
6015  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6016  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6017  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6018       BaseIt != BaseE; ++BaseIt) {
6019    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6020    if (CanonicalSourceType == BaseType)
6021      break;
6022  }
6023
6024  if (BaseIt == BaseE) {
6025    // Did not find SourceType in the bases.
6026    Diag(UD->getUsingLocation(),
6027         diag::err_using_decl_constructor_not_in_direct_base)
6028      << UD->getNameInfo().getSourceRange()
6029      << QualType(SourceType, 0) << TargetClass;
6030    return true;
6031  }
6032
6033  BaseIt->setInheritConstructors();
6034
6035  return false;
6036}
6037
6038/// Checks that the given using declaration is not an invalid
6039/// redeclaration.  Note that this is checking only for the using decl
6040/// itself, not for any ill-formedness among the UsingShadowDecls.
6041bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6042                                       bool isTypeName,
6043                                       const CXXScopeSpec &SS,
6044                                       SourceLocation NameLoc,
6045                                       const LookupResult &Prev) {
6046  // C++03 [namespace.udecl]p8:
6047  // C++0x [namespace.udecl]p10:
6048  //   A using-declaration is a declaration and can therefore be used
6049  //   repeatedly where (and only where) multiple declarations are
6050  //   allowed.
6051  //
6052  // That's in non-member contexts.
6053  if (!CurContext->getRedeclContext()->isRecord())
6054    return false;
6055
6056  NestedNameSpecifier *Qual
6057    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6058
6059  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6060    NamedDecl *D = *I;
6061
6062    bool DTypename;
6063    NestedNameSpecifier *DQual;
6064    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6065      DTypename = UD->isTypeName();
6066      DQual = UD->getQualifier();
6067    } else if (UnresolvedUsingValueDecl *UD
6068                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6069      DTypename = false;
6070      DQual = UD->getQualifier();
6071    } else if (UnresolvedUsingTypenameDecl *UD
6072                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6073      DTypename = true;
6074      DQual = UD->getQualifier();
6075    } else continue;
6076
6077    // using decls differ if one says 'typename' and the other doesn't.
6078    // FIXME: non-dependent using decls?
6079    if (isTypeName != DTypename) continue;
6080
6081    // using decls differ if they name different scopes (but note that
6082    // template instantiation can cause this check to trigger when it
6083    // didn't before instantiation).
6084    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6085        Context.getCanonicalNestedNameSpecifier(DQual))
6086      continue;
6087
6088    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6089    Diag(D->getLocation(), diag::note_using_decl) << 1;
6090    return true;
6091  }
6092
6093  return false;
6094}
6095
6096
6097/// Checks that the given nested-name qualifier used in a using decl
6098/// in the current context is appropriately related to the current
6099/// scope.  If an error is found, diagnoses it and returns true.
6100bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6101                                   const CXXScopeSpec &SS,
6102                                   SourceLocation NameLoc) {
6103  DeclContext *NamedContext = computeDeclContext(SS);
6104
6105  if (!CurContext->isRecord()) {
6106    // C++03 [namespace.udecl]p3:
6107    // C++0x [namespace.udecl]p8:
6108    //   A using-declaration for a class member shall be a member-declaration.
6109
6110    // If we weren't able to compute a valid scope, it must be a
6111    // dependent class scope.
6112    if (!NamedContext || NamedContext->isRecord()) {
6113      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6114        << SS.getRange();
6115      return true;
6116    }
6117
6118    // Otherwise, everything is known to be fine.
6119    return false;
6120  }
6121
6122  // The current scope is a record.
6123
6124  // If the named context is dependent, we can't decide much.
6125  if (!NamedContext) {
6126    // FIXME: in C++0x, we can diagnose if we can prove that the
6127    // nested-name-specifier does not refer to a base class, which is
6128    // still possible in some cases.
6129
6130    // Otherwise we have to conservatively report that things might be
6131    // okay.
6132    return false;
6133  }
6134
6135  if (!NamedContext->isRecord()) {
6136    // Ideally this would point at the last name in the specifier,
6137    // but we don't have that level of source info.
6138    Diag(SS.getRange().getBegin(),
6139         diag::err_using_decl_nested_name_specifier_is_not_class)
6140      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6141    return true;
6142  }
6143
6144  if (!NamedContext->isDependentContext() &&
6145      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6146    return true;
6147
6148  if (getLangOptions().CPlusPlus0x) {
6149    // C++0x [namespace.udecl]p3:
6150    //   In a using-declaration used as a member-declaration, the
6151    //   nested-name-specifier shall name a base class of the class
6152    //   being defined.
6153
6154    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6155                                 cast<CXXRecordDecl>(NamedContext))) {
6156      if (CurContext == NamedContext) {
6157        Diag(NameLoc,
6158             diag::err_using_decl_nested_name_specifier_is_current_class)
6159          << SS.getRange();
6160        return true;
6161      }
6162
6163      Diag(SS.getRange().getBegin(),
6164           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6165        << (NestedNameSpecifier*) SS.getScopeRep()
6166        << cast<CXXRecordDecl>(CurContext)
6167        << SS.getRange();
6168      return true;
6169    }
6170
6171    return false;
6172  }
6173
6174  // C++03 [namespace.udecl]p4:
6175  //   A using-declaration used as a member-declaration shall refer
6176  //   to a member of a base class of the class being defined [etc.].
6177
6178  // Salient point: SS doesn't have to name a base class as long as
6179  // lookup only finds members from base classes.  Therefore we can
6180  // diagnose here only if we can prove that that can't happen,
6181  // i.e. if the class hierarchies provably don't intersect.
6182
6183  // TODO: it would be nice if "definitely valid" results were cached
6184  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6185  // need to be repeated.
6186
6187  struct UserData {
6188    llvm::DenseSet<const CXXRecordDecl*> Bases;
6189
6190    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6191      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6192      Data->Bases.insert(Base);
6193      return true;
6194    }
6195
6196    bool hasDependentBases(const CXXRecordDecl *Class) {
6197      return !Class->forallBases(collect, this);
6198    }
6199
6200    /// Returns true if the base is dependent or is one of the
6201    /// accumulated base classes.
6202    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6203      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6204      return !Data->Bases.count(Base);
6205    }
6206
6207    bool mightShareBases(const CXXRecordDecl *Class) {
6208      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6209    }
6210  };
6211
6212  UserData Data;
6213
6214  // Returns false if we find a dependent base.
6215  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6216    return false;
6217
6218  // Returns false if the class has a dependent base or if it or one
6219  // of its bases is present in the base set of the current context.
6220  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6221    return false;
6222
6223  Diag(SS.getRange().getBegin(),
6224       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6225    << (NestedNameSpecifier*) SS.getScopeRep()
6226    << cast<CXXRecordDecl>(CurContext)
6227    << SS.getRange();
6228
6229  return true;
6230}
6231
6232Decl *Sema::ActOnAliasDeclaration(Scope *S,
6233                                  AccessSpecifier AS,
6234                                  MultiTemplateParamsArg TemplateParamLists,
6235                                  SourceLocation UsingLoc,
6236                                  UnqualifiedId &Name,
6237                                  TypeResult Type) {
6238  // Skip up to the relevant declaration scope.
6239  while (S->getFlags() & Scope::TemplateParamScope)
6240    S = S->getParent();
6241  assert((S->getFlags() & Scope::DeclScope) &&
6242         "got alias-declaration outside of declaration scope");
6243
6244  if (Type.isInvalid())
6245    return 0;
6246
6247  bool Invalid = false;
6248  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6249  TypeSourceInfo *TInfo = 0;
6250  GetTypeFromParser(Type.get(), &TInfo);
6251
6252  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6253    return 0;
6254
6255  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6256                                      UPPC_DeclarationType)) {
6257    Invalid = true;
6258    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6259                                             TInfo->getTypeLoc().getBeginLoc());
6260  }
6261
6262  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6263  LookupName(Previous, S);
6264
6265  // Warn about shadowing the name of a template parameter.
6266  if (Previous.isSingleResult() &&
6267      Previous.getFoundDecl()->isTemplateParameter()) {
6268    if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6269                                        Previous.getFoundDecl()))
6270      Invalid = true;
6271    Previous.clear();
6272  }
6273
6274  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6275         "name in alias declaration must be an identifier");
6276  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6277                                               Name.StartLocation,
6278                                               Name.Identifier, TInfo);
6279
6280  NewTD->setAccess(AS);
6281
6282  if (Invalid)
6283    NewTD->setInvalidDecl();
6284
6285  CheckTypedefForVariablyModifiedType(S, NewTD);
6286  Invalid |= NewTD->isInvalidDecl();
6287
6288  bool Redeclaration = false;
6289
6290  NamedDecl *NewND;
6291  if (TemplateParamLists.size()) {
6292    TypeAliasTemplateDecl *OldDecl = 0;
6293    TemplateParameterList *OldTemplateParams = 0;
6294
6295    if (TemplateParamLists.size() != 1) {
6296      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6297        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6298         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6299    }
6300    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6301
6302    // Only consider previous declarations in the same scope.
6303    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6304                         /*ExplicitInstantiationOrSpecialization*/false);
6305    if (!Previous.empty()) {
6306      Redeclaration = true;
6307
6308      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6309      if (!OldDecl && !Invalid) {
6310        Diag(UsingLoc, diag::err_redefinition_different_kind)
6311          << Name.Identifier;
6312
6313        NamedDecl *OldD = Previous.getRepresentativeDecl();
6314        if (OldD->getLocation().isValid())
6315          Diag(OldD->getLocation(), diag::note_previous_definition);
6316
6317        Invalid = true;
6318      }
6319
6320      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6321        if (TemplateParameterListsAreEqual(TemplateParams,
6322                                           OldDecl->getTemplateParameters(),
6323                                           /*Complain=*/true,
6324                                           TPL_TemplateMatch))
6325          OldTemplateParams = OldDecl->getTemplateParameters();
6326        else
6327          Invalid = true;
6328
6329        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6330        if (!Invalid &&
6331            !Context.hasSameType(OldTD->getUnderlyingType(),
6332                                 NewTD->getUnderlyingType())) {
6333          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6334          // but we can't reasonably accept it.
6335          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6336            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6337          if (OldTD->getLocation().isValid())
6338            Diag(OldTD->getLocation(), diag::note_previous_definition);
6339          Invalid = true;
6340        }
6341      }
6342    }
6343
6344    // Merge any previous default template arguments into our parameters,
6345    // and check the parameter list.
6346    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6347                                   TPC_TypeAliasTemplate))
6348      return 0;
6349
6350    TypeAliasTemplateDecl *NewDecl =
6351      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6352                                    Name.Identifier, TemplateParams,
6353                                    NewTD);
6354
6355    NewDecl->setAccess(AS);
6356
6357    if (Invalid)
6358      NewDecl->setInvalidDecl();
6359    else if (OldDecl)
6360      NewDecl->setPreviousDeclaration(OldDecl);
6361
6362    NewND = NewDecl;
6363  } else {
6364    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6365    NewND = NewTD;
6366  }
6367
6368  if (!Redeclaration)
6369    PushOnScopeChains(NewND, S);
6370
6371  return NewND;
6372}
6373
6374Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6375                                             SourceLocation NamespaceLoc,
6376                                             SourceLocation AliasLoc,
6377                                             IdentifierInfo *Alias,
6378                                             CXXScopeSpec &SS,
6379                                             SourceLocation IdentLoc,
6380                                             IdentifierInfo *Ident) {
6381
6382  // Lookup the namespace name.
6383  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6384  LookupParsedName(R, S, &SS);
6385
6386  // Check if we have a previous declaration with the same name.
6387  NamedDecl *PrevDecl
6388    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6389                       ForRedeclaration);
6390  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6391    PrevDecl = 0;
6392
6393  if (PrevDecl) {
6394    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6395      // We already have an alias with the same name that points to the same
6396      // namespace, so don't create a new one.
6397      // FIXME: At some point, we'll want to create the (redundant)
6398      // declaration to maintain better source information.
6399      if (!R.isAmbiguous() && !R.empty() &&
6400          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6401        return 0;
6402    }
6403
6404    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6405      diag::err_redefinition_different_kind;
6406    Diag(AliasLoc, DiagID) << Alias;
6407    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6408    return 0;
6409  }
6410
6411  if (R.isAmbiguous())
6412    return 0;
6413
6414  if (R.empty()) {
6415    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6416      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
6417      return 0;
6418    }
6419  }
6420
6421  NamespaceAliasDecl *AliasDecl =
6422    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6423                               Alias, SS.getWithLocInContext(Context),
6424                               IdentLoc, R.getFoundDecl());
6425
6426  PushOnScopeChains(AliasDecl, S);
6427  return AliasDecl;
6428}
6429
6430namespace {
6431  /// \brief Scoped object used to handle the state changes required in Sema
6432  /// to implicitly define the body of a C++ member function;
6433  class ImplicitlyDefinedFunctionScope {
6434    Sema &S;
6435    Sema::ContextRAII SavedContext;
6436
6437  public:
6438    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6439      : S(S), SavedContext(S, Method)
6440    {
6441      S.PushFunctionScope();
6442      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6443    }
6444
6445    ~ImplicitlyDefinedFunctionScope() {
6446      S.PopExpressionEvaluationContext();
6447      S.PopFunctionOrBlockScope();
6448    }
6449  };
6450}
6451
6452Sema::ImplicitExceptionSpecification
6453Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6454  // C++ [except.spec]p14:
6455  //   An implicitly declared special member function (Clause 12) shall have an
6456  //   exception-specification. [...]
6457  ImplicitExceptionSpecification ExceptSpec(Context);
6458  if (ClassDecl->isInvalidDecl())
6459    return ExceptSpec;
6460
6461  // Direct base-class constructors.
6462  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6463                                       BEnd = ClassDecl->bases_end();
6464       B != BEnd; ++B) {
6465    if (B->isVirtual()) // Handled below.
6466      continue;
6467
6468    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6469      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6470      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6471      // If this is a deleted function, add it anyway. This might be conformant
6472      // with the standard. This might not. I'm not sure. It might not matter.
6473      if (Constructor)
6474        ExceptSpec.CalledDecl(Constructor);
6475    }
6476  }
6477
6478  // Virtual base-class constructors.
6479  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6480                                       BEnd = ClassDecl->vbases_end();
6481       B != BEnd; ++B) {
6482    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6483      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6484      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6485      // If this is a deleted function, add it anyway. This might be conformant
6486      // with the standard. This might not. I'm not sure. It might not matter.
6487      if (Constructor)
6488        ExceptSpec.CalledDecl(Constructor);
6489    }
6490  }
6491
6492  // Field constructors.
6493  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6494                               FEnd = ClassDecl->field_end();
6495       F != FEnd; ++F) {
6496    if (F->hasInClassInitializer()) {
6497      if (Expr *E = F->getInClassInitializer())
6498        ExceptSpec.CalledExpr(E);
6499      else if (!F->isInvalidDecl())
6500        ExceptSpec.SetDelayed();
6501    } else if (const RecordType *RecordTy
6502              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6503      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6504      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6505      // If this is a deleted function, add it anyway. This might be conformant
6506      // with the standard. This might not. I'm not sure. It might not matter.
6507      // In particular, the problem is that this function never gets called. It
6508      // might just be ill-formed because this function attempts to refer to
6509      // a deleted function here.
6510      if (Constructor)
6511        ExceptSpec.CalledDecl(Constructor);
6512    }
6513  }
6514
6515  return ExceptSpec;
6516}
6517
6518CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6519                                                     CXXRecordDecl *ClassDecl) {
6520  // C++ [class.ctor]p5:
6521  //   A default constructor for a class X is a constructor of class X
6522  //   that can be called without an argument. If there is no
6523  //   user-declared constructor for class X, a default constructor is
6524  //   implicitly declared. An implicitly-declared default constructor
6525  //   is an inline public member of its class.
6526  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6527         "Should not build implicit default constructor!");
6528
6529  ImplicitExceptionSpecification Spec =
6530    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6531  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6532
6533  // Create the actual constructor declaration.
6534  CanQualType ClassType
6535    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6536  SourceLocation ClassLoc = ClassDecl->getLocation();
6537  DeclarationName Name
6538    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6539  DeclarationNameInfo NameInfo(Name, ClassLoc);
6540  CXXConstructorDecl *DefaultCon
6541    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6542                                 Context.getFunctionType(Context.VoidTy,
6543                                                         0, 0, EPI),
6544                                 /*TInfo=*/0,
6545                                 /*isExplicit=*/false,
6546                                 /*isInline=*/true,
6547                                 /*isImplicitlyDeclared=*/true,
6548                                 // FIXME: apply the rules for definitions here
6549                                 /*isConstexpr=*/false);
6550  DefaultCon->setAccess(AS_public);
6551  DefaultCon->setDefaulted();
6552  DefaultCon->setImplicit();
6553  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6554
6555  // Note that we have declared this constructor.
6556  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6557
6558  if (Scope *S = getScopeForContext(ClassDecl))
6559    PushOnScopeChains(DefaultCon, S, false);
6560  ClassDecl->addDecl(DefaultCon);
6561
6562  if (ShouldDeleteDefaultConstructor(DefaultCon))
6563    DefaultCon->setDeletedAsWritten();
6564
6565  return DefaultCon;
6566}
6567
6568void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6569                                            CXXConstructorDecl *Constructor) {
6570  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6571          !Constructor->doesThisDeclarationHaveABody() &&
6572          !Constructor->isDeleted()) &&
6573    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6574
6575  CXXRecordDecl *ClassDecl = Constructor->getParent();
6576  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6577
6578  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6579  DiagnosticErrorTrap Trap(Diags);
6580  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6581      Trap.hasErrorOccurred()) {
6582    Diag(CurrentLocation, diag::note_member_synthesized_at)
6583      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6584    Constructor->setInvalidDecl();
6585    return;
6586  }
6587
6588  SourceLocation Loc = Constructor->getLocation();
6589  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6590
6591  Constructor->setUsed();
6592  MarkVTableUsed(CurrentLocation, ClassDecl);
6593
6594  if (ASTMutationListener *L = getASTMutationListener()) {
6595    L->CompletedImplicitDefinition(Constructor);
6596  }
6597}
6598
6599/// Get any existing defaulted default constructor for the given class. Do not
6600/// implicitly define one if it does not exist.
6601static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6602                                                             CXXRecordDecl *D) {
6603  ASTContext &Context = Self.Context;
6604  QualType ClassType = Context.getTypeDeclType(D);
6605  DeclarationName ConstructorName
6606    = Context.DeclarationNames.getCXXConstructorName(
6607                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6608
6609  DeclContext::lookup_const_iterator Con, ConEnd;
6610  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6611       Con != ConEnd; ++Con) {
6612    // A function template cannot be defaulted.
6613    if (isa<FunctionTemplateDecl>(*Con))
6614      continue;
6615
6616    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6617    if (Constructor->isDefaultConstructor())
6618      return Constructor->isDefaulted() ? Constructor : 0;
6619  }
6620  return 0;
6621}
6622
6623void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6624  if (!D) return;
6625  AdjustDeclIfTemplate(D);
6626
6627  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6628  CXXConstructorDecl *CtorDecl
6629    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6630
6631  if (!CtorDecl) return;
6632
6633  // Compute the exception specification for the default constructor.
6634  const FunctionProtoType *CtorTy =
6635    CtorDecl->getType()->castAs<FunctionProtoType>();
6636  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6637    ImplicitExceptionSpecification Spec =
6638      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6639    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6640    assert(EPI.ExceptionSpecType != EST_Delayed);
6641
6642    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6643  }
6644
6645  // If the default constructor is explicitly defaulted, checking the exception
6646  // specification is deferred until now.
6647  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6648      !ClassDecl->isDependentType())
6649    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6650}
6651
6652void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6653  // We start with an initial pass over the base classes to collect those that
6654  // inherit constructors from. If there are none, we can forgo all further
6655  // processing.
6656  typedef SmallVector<const RecordType *, 4> BasesVector;
6657  BasesVector BasesToInheritFrom;
6658  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6659                                          BaseE = ClassDecl->bases_end();
6660         BaseIt != BaseE; ++BaseIt) {
6661    if (BaseIt->getInheritConstructors()) {
6662      QualType Base = BaseIt->getType();
6663      if (Base->isDependentType()) {
6664        // If we inherit constructors from anything that is dependent, just
6665        // abort processing altogether. We'll get another chance for the
6666        // instantiations.
6667        return;
6668      }
6669      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6670    }
6671  }
6672  if (BasesToInheritFrom.empty())
6673    return;
6674
6675  // Now collect the constructors that we already have in the current class.
6676  // Those take precedence over inherited constructors.
6677  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6678  //   unless there is a user-declared constructor with the same signature in
6679  //   the class where the using-declaration appears.
6680  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6681  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6682                                    CtorE = ClassDecl->ctor_end();
6683       CtorIt != CtorE; ++CtorIt) {
6684    ExistingConstructors.insert(
6685        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6686  }
6687
6688  Scope *S = getScopeForContext(ClassDecl);
6689  DeclarationName CreatedCtorName =
6690      Context.DeclarationNames.getCXXConstructorName(
6691          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6692
6693  // Now comes the true work.
6694  // First, we keep a map from constructor types to the base that introduced
6695  // them. Needed for finding conflicting constructors. We also keep the
6696  // actually inserted declarations in there, for pretty diagnostics.
6697  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6698  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6699  ConstructorToSourceMap InheritedConstructors;
6700  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6701                             BaseE = BasesToInheritFrom.end();
6702       BaseIt != BaseE; ++BaseIt) {
6703    const RecordType *Base = *BaseIt;
6704    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6705    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6706    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6707                                      CtorE = BaseDecl->ctor_end();
6708         CtorIt != CtorE; ++CtorIt) {
6709      // Find the using declaration for inheriting this base's constructors.
6710      DeclarationName Name =
6711          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6712      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6713          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6714      SourceLocation UsingLoc = UD ? UD->getLocation() :
6715                                     ClassDecl->getLocation();
6716
6717      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6718      //   from the class X named in the using-declaration consists of actual
6719      //   constructors and notional constructors that result from the
6720      //   transformation of defaulted parameters as follows:
6721      //   - all non-template default constructors of X, and
6722      //   - for each non-template constructor of X that has at least one
6723      //     parameter with a default argument, the set of constructors that
6724      //     results from omitting any ellipsis parameter specification and
6725      //     successively omitting parameters with a default argument from the
6726      //     end of the parameter-type-list.
6727      CXXConstructorDecl *BaseCtor = *CtorIt;
6728      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6729      const FunctionProtoType *BaseCtorType =
6730          BaseCtor->getType()->getAs<FunctionProtoType>();
6731
6732      for (unsigned params = BaseCtor->getMinRequiredArguments(),
6733                    maxParams = BaseCtor->getNumParams();
6734           params <= maxParams; ++params) {
6735        // Skip default constructors. They're never inherited.
6736        if (params == 0)
6737          continue;
6738        // Skip copy and move constructors for the same reason.
6739        if (CanBeCopyOrMove && params == 1)
6740          continue;
6741
6742        // Build up a function type for this particular constructor.
6743        // FIXME: The working paper does not consider that the exception spec
6744        // for the inheriting constructor might be larger than that of the
6745        // source. This code doesn't yet, either. When it does, this code will
6746        // need to be delayed until after exception specifications and in-class
6747        // member initializers are attached.
6748        const Type *NewCtorType;
6749        if (params == maxParams)
6750          NewCtorType = BaseCtorType;
6751        else {
6752          SmallVector<QualType, 16> Args;
6753          for (unsigned i = 0; i < params; ++i) {
6754            Args.push_back(BaseCtorType->getArgType(i));
6755          }
6756          FunctionProtoType::ExtProtoInfo ExtInfo =
6757              BaseCtorType->getExtProtoInfo();
6758          ExtInfo.Variadic = false;
6759          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6760                                                Args.data(), params, ExtInfo)
6761                       .getTypePtr();
6762        }
6763        const Type *CanonicalNewCtorType =
6764            Context.getCanonicalType(NewCtorType);
6765
6766        // Now that we have the type, first check if the class already has a
6767        // constructor with this signature.
6768        if (ExistingConstructors.count(CanonicalNewCtorType))
6769          continue;
6770
6771        // Then we check if we have already declared an inherited constructor
6772        // with this signature.
6773        std::pair<ConstructorToSourceMap::iterator, bool> result =
6774            InheritedConstructors.insert(std::make_pair(
6775                CanonicalNewCtorType,
6776                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6777        if (!result.second) {
6778          // Already in the map. If it came from a different class, that's an
6779          // error. Not if it's from the same.
6780          CanQualType PreviousBase = result.first->second.first;
6781          if (CanonicalBase != PreviousBase) {
6782            const CXXConstructorDecl *PrevCtor = result.first->second.second;
6783            const CXXConstructorDecl *PrevBaseCtor =
6784                PrevCtor->getInheritedConstructor();
6785            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6786
6787            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6788            Diag(BaseCtor->getLocation(),
6789                 diag::note_using_decl_constructor_conflict_current_ctor);
6790            Diag(PrevBaseCtor->getLocation(),
6791                 diag::note_using_decl_constructor_conflict_previous_ctor);
6792            Diag(PrevCtor->getLocation(),
6793                 diag::note_using_decl_constructor_conflict_previous_using);
6794          }
6795          continue;
6796        }
6797
6798        // OK, we're there, now add the constructor.
6799        // C++0x [class.inhctor]p8: [...] that would be performed by a
6800        //   user-written inline constructor [...]
6801        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6802        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6803            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6804            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6805            /*ImplicitlyDeclared=*/true,
6806            // FIXME: Due to a defect in the standard, we treat inherited
6807            // constructors as constexpr even if that makes them ill-formed.
6808            /*Constexpr=*/BaseCtor->isConstexpr());
6809        NewCtor->setAccess(BaseCtor->getAccess());
6810
6811        // Build up the parameter decls and add them.
6812        SmallVector<ParmVarDecl *, 16> ParamDecls;
6813        for (unsigned i = 0; i < params; ++i) {
6814          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6815                                                   UsingLoc, UsingLoc,
6816                                                   /*IdentifierInfo=*/0,
6817                                                   BaseCtorType->getArgType(i),
6818                                                   /*TInfo=*/0, SC_None,
6819                                                   SC_None, /*DefaultArg=*/0));
6820        }
6821        NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6822        NewCtor->setInheritedConstructor(BaseCtor);
6823
6824        PushOnScopeChains(NewCtor, S, false);
6825        ClassDecl->addDecl(NewCtor);
6826        result.first->second.second = NewCtor;
6827      }
6828    }
6829  }
6830}
6831
6832Sema::ImplicitExceptionSpecification
6833Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6834  // C++ [except.spec]p14:
6835  //   An implicitly declared special member function (Clause 12) shall have
6836  //   an exception-specification.
6837  ImplicitExceptionSpecification ExceptSpec(Context);
6838  if (ClassDecl->isInvalidDecl())
6839    return ExceptSpec;
6840
6841  // Direct base-class destructors.
6842  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6843                                       BEnd = ClassDecl->bases_end();
6844       B != BEnd; ++B) {
6845    if (B->isVirtual()) // Handled below.
6846      continue;
6847
6848    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6849      ExceptSpec.CalledDecl(
6850                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6851  }
6852
6853  // Virtual base-class destructors.
6854  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6855                                       BEnd = ClassDecl->vbases_end();
6856       B != BEnd; ++B) {
6857    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6858      ExceptSpec.CalledDecl(
6859                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6860  }
6861
6862  // Field destructors.
6863  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6864                               FEnd = ClassDecl->field_end();
6865       F != FEnd; ++F) {
6866    if (const RecordType *RecordTy
6867        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6868      ExceptSpec.CalledDecl(
6869                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6870  }
6871
6872  return ExceptSpec;
6873}
6874
6875CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6876  // C++ [class.dtor]p2:
6877  //   If a class has no user-declared destructor, a destructor is
6878  //   declared implicitly. An implicitly-declared destructor is an
6879  //   inline public member of its class.
6880
6881  ImplicitExceptionSpecification Spec =
6882      ComputeDefaultedDtorExceptionSpec(ClassDecl);
6883  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6884
6885  // Create the actual destructor declaration.
6886  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6887
6888  CanQualType ClassType
6889    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6890  SourceLocation ClassLoc = ClassDecl->getLocation();
6891  DeclarationName Name
6892    = Context.DeclarationNames.getCXXDestructorName(ClassType);
6893  DeclarationNameInfo NameInfo(Name, ClassLoc);
6894  CXXDestructorDecl *Destructor
6895      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6896                                  /*isInline=*/true,
6897                                  /*isImplicitlyDeclared=*/true);
6898  Destructor->setAccess(AS_public);
6899  Destructor->setDefaulted();
6900  Destructor->setImplicit();
6901  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6902
6903  // Note that we have declared this destructor.
6904  ++ASTContext::NumImplicitDestructorsDeclared;
6905
6906  // Introduce this destructor into its scope.
6907  if (Scope *S = getScopeForContext(ClassDecl))
6908    PushOnScopeChains(Destructor, S, false);
6909  ClassDecl->addDecl(Destructor);
6910
6911  // This could be uniqued if it ever proves significant.
6912  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6913
6914  if (ShouldDeleteDestructor(Destructor))
6915    Destructor->setDeletedAsWritten();
6916
6917  AddOverriddenMethods(ClassDecl, Destructor);
6918
6919  return Destructor;
6920}
6921
6922void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6923                                    CXXDestructorDecl *Destructor) {
6924  assert((Destructor->isDefaulted() &&
6925          !Destructor->doesThisDeclarationHaveABody()) &&
6926         "DefineImplicitDestructor - call it for implicit default dtor");
6927  CXXRecordDecl *ClassDecl = Destructor->getParent();
6928  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6929
6930  if (Destructor->isInvalidDecl())
6931    return;
6932
6933  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6934
6935  DiagnosticErrorTrap Trap(Diags);
6936  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6937                                         Destructor->getParent());
6938
6939  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6940    Diag(CurrentLocation, diag::note_member_synthesized_at)
6941      << CXXDestructor << Context.getTagDeclType(ClassDecl);
6942
6943    Destructor->setInvalidDecl();
6944    return;
6945  }
6946
6947  SourceLocation Loc = Destructor->getLocation();
6948  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6949
6950  Destructor->setUsed();
6951  MarkVTableUsed(CurrentLocation, ClassDecl);
6952
6953  if (ASTMutationListener *L = getASTMutationListener()) {
6954    L->CompletedImplicitDefinition(Destructor);
6955  }
6956}
6957
6958void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6959                                         CXXDestructorDecl *destructor) {
6960  // C++11 [class.dtor]p3:
6961  //   A declaration of a destructor that does not have an exception-
6962  //   specification is implicitly considered to have the same exception-
6963  //   specification as an implicit declaration.
6964  const FunctionProtoType *dtorType = destructor->getType()->
6965                                        getAs<FunctionProtoType>();
6966  if (dtorType->hasExceptionSpec())
6967    return;
6968
6969  ImplicitExceptionSpecification exceptSpec =
6970      ComputeDefaultedDtorExceptionSpec(classDecl);
6971
6972  // Replace the destructor's type.
6973  FunctionProtoType::ExtProtoInfo epi;
6974  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6975  epi.NumExceptions = exceptSpec.size();
6976  epi.Exceptions = exceptSpec.data();
6977  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6978
6979  destructor->setType(ty);
6980
6981  // FIXME: If the destructor has a body that could throw, and the newly created
6982  // spec doesn't allow exceptions, we should emit a warning, because this
6983  // change in behavior can break conforming C++03 programs at runtime.
6984  // However, we don't have a body yet, so it needs to be done somewhere else.
6985}
6986
6987/// \brief Builds a statement that copies/moves the given entity from \p From to
6988/// \c To.
6989///
6990/// This routine is used to copy/move the members of a class with an
6991/// implicitly-declared copy/move assignment operator. When the entities being
6992/// copied are arrays, this routine builds for loops to copy them.
6993///
6994/// \param S The Sema object used for type-checking.
6995///
6996/// \param Loc The location where the implicit copy/move is being generated.
6997///
6998/// \param T The type of the expressions being copied/moved. Both expressions
6999/// must have this type.
7000///
7001/// \param To The expression we are copying/moving to.
7002///
7003/// \param From The expression we are copying/moving from.
7004///
7005/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7006/// Otherwise, it's a non-static member subobject.
7007///
7008/// \param Copying Whether we're copying or moving.
7009///
7010/// \param Depth Internal parameter recording the depth of the recursion.
7011///
7012/// \returns A statement or a loop that copies the expressions.
7013static StmtResult
7014BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7015                      Expr *To, Expr *From,
7016                      bool CopyingBaseSubobject, bool Copying,
7017                      unsigned Depth = 0) {
7018  // C++0x [class.copy]p28:
7019  //   Each subobject is assigned in the manner appropriate to its type:
7020  //
7021  //     - if the subobject is of class type, as if by a call to operator= with
7022  //       the subobject as the object expression and the corresponding
7023  //       subobject of x as a single function argument (as if by explicit
7024  //       qualification; that is, ignoring any possible virtual overriding
7025  //       functions in more derived classes);
7026  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7027    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7028
7029    // Look for operator=.
7030    DeclarationName Name
7031      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7032    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7033    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7034
7035    // Filter out any result that isn't a copy/move-assignment operator.
7036    LookupResult::Filter F = OpLookup.makeFilter();
7037    while (F.hasNext()) {
7038      NamedDecl *D = F.next();
7039      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7040        if (Copying ? Method->isCopyAssignmentOperator() :
7041                      Method->isMoveAssignmentOperator())
7042          continue;
7043
7044      F.erase();
7045    }
7046    F.done();
7047
7048    // Suppress the protected check (C++ [class.protected]) for each of the
7049    // assignment operators we found. This strange dance is required when
7050    // we're assigning via a base classes's copy-assignment operator. To
7051    // ensure that we're getting the right base class subobject (without
7052    // ambiguities), we need to cast "this" to that subobject type; to
7053    // ensure that we don't go through the virtual call mechanism, we need
7054    // to qualify the operator= name with the base class (see below). However,
7055    // this means that if the base class has a protected copy assignment
7056    // operator, the protected member access check will fail. So, we
7057    // rewrite "protected" access to "public" access in this case, since we
7058    // know by construction that we're calling from a derived class.
7059    if (CopyingBaseSubobject) {
7060      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7061           L != LEnd; ++L) {
7062        if (L.getAccess() == AS_protected)
7063          L.setAccess(AS_public);
7064      }
7065    }
7066
7067    // Create the nested-name-specifier that will be used to qualify the
7068    // reference to operator=; this is required to suppress the virtual
7069    // call mechanism.
7070    CXXScopeSpec SS;
7071    SS.MakeTrivial(S.Context,
7072                   NestedNameSpecifier::Create(S.Context, 0, false,
7073                                               T.getTypePtr()),
7074                   Loc);
7075
7076    // Create the reference to operator=.
7077    ExprResult OpEqualRef
7078      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7079                                   /*FirstQualifierInScope=*/0, OpLookup,
7080                                   /*TemplateArgs=*/0,
7081                                   /*SuppressQualifierCheck=*/true);
7082    if (OpEqualRef.isInvalid())
7083      return StmtError();
7084
7085    // Build the call to the assignment operator.
7086
7087    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7088                                                  OpEqualRef.takeAs<Expr>(),
7089                                                  Loc, &From, 1, Loc);
7090    if (Call.isInvalid())
7091      return StmtError();
7092
7093    return S.Owned(Call.takeAs<Stmt>());
7094  }
7095
7096  //     - if the subobject is of scalar type, the built-in assignment
7097  //       operator is used.
7098  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7099  if (!ArrayTy) {
7100    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7101    if (Assignment.isInvalid())
7102      return StmtError();
7103
7104    return S.Owned(Assignment.takeAs<Stmt>());
7105  }
7106
7107  //     - if the subobject is an array, each element is assigned, in the
7108  //       manner appropriate to the element type;
7109
7110  // Construct a loop over the array bounds, e.g.,
7111  //
7112  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7113  //
7114  // that will copy each of the array elements.
7115  QualType SizeType = S.Context.getSizeType();
7116
7117  // Create the iteration variable.
7118  IdentifierInfo *IterationVarName = 0;
7119  {
7120    llvm::SmallString<8> Str;
7121    llvm::raw_svector_ostream OS(Str);
7122    OS << "__i" << Depth;
7123    IterationVarName = &S.Context.Idents.get(OS.str());
7124  }
7125  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7126                                          IterationVarName, SizeType,
7127                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7128                                          SC_None, SC_None);
7129
7130  // Initialize the iteration variable to zero.
7131  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7132  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7133
7134  // Create a reference to the iteration variable; we'll use this several
7135  // times throughout.
7136  Expr *IterationVarRef
7137    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
7138  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7139
7140  // Create the DeclStmt that holds the iteration variable.
7141  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7142
7143  // Create the comparison against the array bound.
7144  llvm::APInt Upper
7145    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7146  Expr *Comparison
7147    = new (S.Context) BinaryOperator(IterationVarRef,
7148                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7149                                     BO_NE, S.Context.BoolTy,
7150                                     VK_RValue, OK_Ordinary, Loc);
7151
7152  // Create the pre-increment of the iteration variable.
7153  Expr *Increment
7154    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7155                                    VK_LValue, OK_Ordinary, Loc);
7156
7157  // Subscript the "from" and "to" expressions with the iteration variable.
7158  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7159                                                         IterationVarRef, Loc));
7160  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7161                                                       IterationVarRef, Loc));
7162  if (!Copying) // Cast to rvalue
7163    From = CastForMoving(S, From);
7164
7165  // Build the copy/move for an individual element of the array.
7166  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7167                                          To, From, CopyingBaseSubobject,
7168                                          Copying, Depth + 1);
7169  if (Copy.isInvalid())
7170    return StmtError();
7171
7172  // Construct the loop that copies all elements of this array.
7173  return S.ActOnForStmt(Loc, Loc, InitStmt,
7174                        S.MakeFullExpr(Comparison),
7175                        0, S.MakeFullExpr(Increment),
7176                        Loc, Copy.take());
7177}
7178
7179std::pair<Sema::ImplicitExceptionSpecification, bool>
7180Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7181                                                   CXXRecordDecl *ClassDecl) {
7182  if (ClassDecl->isInvalidDecl())
7183    return std::make_pair(ImplicitExceptionSpecification(Context), false);
7184
7185  // C++ [class.copy]p10:
7186  //   If the class definition does not explicitly declare a copy
7187  //   assignment operator, one is declared implicitly.
7188  //   The implicitly-defined copy assignment operator for a class X
7189  //   will have the form
7190  //
7191  //       X& X::operator=(const X&)
7192  //
7193  //   if
7194  bool HasConstCopyAssignment = true;
7195
7196  //       -- each direct base class B of X has a copy assignment operator
7197  //          whose parameter is of type const B&, const volatile B& or B,
7198  //          and
7199  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7200                                       BaseEnd = ClassDecl->bases_end();
7201       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7202    // We'll handle this below
7203    if (LangOpts.CPlusPlus0x && Base->isVirtual())
7204      continue;
7205
7206    assert(!Base->getType()->isDependentType() &&
7207           "Cannot generate implicit members for class with dependent bases.");
7208    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7209    LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7210                            &HasConstCopyAssignment);
7211  }
7212
7213  // In C++0x, the above citation has "or virtual added"
7214  if (LangOpts.CPlusPlus0x) {
7215    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7216                                         BaseEnd = ClassDecl->vbases_end();
7217         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7218      assert(!Base->getType()->isDependentType() &&
7219             "Cannot generate implicit members for class with dependent bases.");
7220      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7221      LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7222                              &HasConstCopyAssignment);
7223    }
7224  }
7225
7226  //       -- for all the nonstatic data members of X that are of a class
7227  //          type M (or array thereof), each such class type has a copy
7228  //          assignment operator whose parameter is of type const M&,
7229  //          const volatile M& or M.
7230  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7231                                  FieldEnd = ClassDecl->field_end();
7232       HasConstCopyAssignment && Field != FieldEnd;
7233       ++Field) {
7234    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7235    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7236      LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7237                              &HasConstCopyAssignment);
7238    }
7239  }
7240
7241  //   Otherwise, the implicitly declared copy assignment operator will
7242  //   have the form
7243  //
7244  //       X& X::operator=(X&)
7245
7246  // C++ [except.spec]p14:
7247  //   An implicitly declared special member function (Clause 12) shall have an
7248  //   exception-specification. [...]
7249
7250  // It is unspecified whether or not an implicit copy assignment operator
7251  // attempts to deduplicate calls to assignment operators of virtual bases are
7252  // made. As such, this exception specification is effectively unspecified.
7253  // Based on a similar decision made for constness in C++0x, we're erring on
7254  // the side of assuming such calls to be made regardless of whether they
7255  // actually happen.
7256  ImplicitExceptionSpecification ExceptSpec(Context);
7257  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7258  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7259                                       BaseEnd = ClassDecl->bases_end();
7260       Base != BaseEnd; ++Base) {
7261    if (Base->isVirtual())
7262      continue;
7263
7264    CXXRecordDecl *BaseClassDecl
7265      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7266    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7267                                                            ArgQuals, false, 0))
7268      ExceptSpec.CalledDecl(CopyAssign);
7269  }
7270
7271  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7272                                       BaseEnd = ClassDecl->vbases_end();
7273       Base != BaseEnd; ++Base) {
7274    CXXRecordDecl *BaseClassDecl
7275      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7276    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7277                                                            ArgQuals, false, 0))
7278      ExceptSpec.CalledDecl(CopyAssign);
7279  }
7280
7281  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7282                                  FieldEnd = ClassDecl->field_end();
7283       Field != FieldEnd;
7284       ++Field) {
7285    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7286    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7287      if (CXXMethodDecl *CopyAssign =
7288          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7289        ExceptSpec.CalledDecl(CopyAssign);
7290    }
7291  }
7292
7293  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7294}
7295
7296CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7297  // Note: The following rules are largely analoguous to the copy
7298  // constructor rules. Note that virtual bases are not taken into account
7299  // for determining the argument type of the operator. Note also that
7300  // operators taking an object instead of a reference are allowed.
7301
7302  ImplicitExceptionSpecification Spec(Context);
7303  bool Const;
7304  llvm::tie(Spec, Const) =
7305    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7306
7307  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7308  QualType RetType = Context.getLValueReferenceType(ArgType);
7309  if (Const)
7310    ArgType = ArgType.withConst();
7311  ArgType = Context.getLValueReferenceType(ArgType);
7312
7313  //   An implicitly-declared copy assignment operator is an inline public
7314  //   member of its class.
7315  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7316  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7317  SourceLocation ClassLoc = ClassDecl->getLocation();
7318  DeclarationNameInfo NameInfo(Name, ClassLoc);
7319  CXXMethodDecl *CopyAssignment
7320    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7321                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7322                            /*TInfo=*/0, /*isStatic=*/false,
7323                            /*StorageClassAsWritten=*/SC_None,
7324                            /*isInline=*/true, /*isConstexpr=*/false,
7325                            SourceLocation());
7326  CopyAssignment->setAccess(AS_public);
7327  CopyAssignment->setDefaulted();
7328  CopyAssignment->setImplicit();
7329  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7330
7331  // Add the parameter to the operator.
7332  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7333                                               ClassLoc, ClassLoc, /*Id=*/0,
7334                                               ArgType, /*TInfo=*/0,
7335                                               SC_None,
7336                                               SC_None, 0);
7337  CopyAssignment->setParams(&FromParam, 1);
7338
7339  // Note that we have added this copy-assignment operator.
7340  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7341
7342  if (Scope *S = getScopeForContext(ClassDecl))
7343    PushOnScopeChains(CopyAssignment, S, false);
7344  ClassDecl->addDecl(CopyAssignment);
7345
7346  // C++0x [class.copy]p18:
7347  //   ... If the class definition declares a move constructor or move
7348  //   assignment operator, the implicitly declared copy assignment operator is
7349  //   defined as deleted; ...
7350  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7351      ClassDecl->hasUserDeclaredMoveAssignment() ||
7352      ShouldDeleteCopyAssignmentOperator(CopyAssignment))
7353    CopyAssignment->setDeletedAsWritten();
7354
7355  AddOverriddenMethods(ClassDecl, CopyAssignment);
7356  return CopyAssignment;
7357}
7358
7359void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7360                                        CXXMethodDecl *CopyAssignOperator) {
7361  assert((CopyAssignOperator->isDefaulted() &&
7362          CopyAssignOperator->isOverloadedOperator() &&
7363          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7364          !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
7365         "DefineImplicitCopyAssignment called for wrong function");
7366
7367  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7368
7369  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7370    CopyAssignOperator->setInvalidDecl();
7371    return;
7372  }
7373
7374  CopyAssignOperator->setUsed();
7375
7376  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7377  DiagnosticErrorTrap Trap(Diags);
7378
7379  // C++0x [class.copy]p30:
7380  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7381  //   for a non-union class X performs memberwise copy assignment of its
7382  //   subobjects. The direct base classes of X are assigned first, in the
7383  //   order of their declaration in the base-specifier-list, and then the
7384  //   immediate non-static data members of X are assigned, in the order in
7385  //   which they were declared in the class definition.
7386
7387  // The statements that form the synthesized function body.
7388  ASTOwningVector<Stmt*> Statements(*this);
7389
7390  // The parameter for the "other" object, which we are copying from.
7391  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7392  Qualifiers OtherQuals = Other->getType().getQualifiers();
7393  QualType OtherRefType = Other->getType();
7394  if (const LValueReferenceType *OtherRef
7395                                = OtherRefType->getAs<LValueReferenceType>()) {
7396    OtherRefType = OtherRef->getPointeeType();
7397    OtherQuals = OtherRefType.getQualifiers();
7398  }
7399
7400  // Our location for everything implicitly-generated.
7401  SourceLocation Loc = CopyAssignOperator->getLocation();
7402
7403  // Construct a reference to the "other" object. We'll be using this
7404  // throughout the generated ASTs.
7405  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7406  assert(OtherRef && "Reference to parameter cannot fail!");
7407
7408  // Construct the "this" pointer. We'll be using this throughout the generated
7409  // ASTs.
7410  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7411  assert(This && "Reference to this cannot fail!");
7412
7413  // Assign base classes.
7414  bool Invalid = false;
7415  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7416       E = ClassDecl->bases_end(); Base != E; ++Base) {
7417    // Form the assignment:
7418    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7419    QualType BaseType = Base->getType().getUnqualifiedType();
7420    if (!BaseType->isRecordType()) {
7421      Invalid = true;
7422      continue;
7423    }
7424
7425    CXXCastPath BasePath;
7426    BasePath.push_back(Base);
7427
7428    // Construct the "from" expression, which is an implicit cast to the
7429    // appropriately-qualified base type.
7430    Expr *From = OtherRef;
7431    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7432                             CK_UncheckedDerivedToBase,
7433                             VK_LValue, &BasePath).take();
7434
7435    // Dereference "this".
7436    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7437
7438    // Implicitly cast "this" to the appropriately-qualified base type.
7439    To = ImpCastExprToType(To.take(),
7440                           Context.getCVRQualifiedType(BaseType,
7441                                     CopyAssignOperator->getTypeQualifiers()),
7442                           CK_UncheckedDerivedToBase,
7443                           VK_LValue, &BasePath);
7444
7445    // Build the copy.
7446    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7447                                            To.get(), From,
7448                                            /*CopyingBaseSubobject=*/true,
7449                                            /*Copying=*/true);
7450    if (Copy.isInvalid()) {
7451      Diag(CurrentLocation, diag::note_member_synthesized_at)
7452        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7453      CopyAssignOperator->setInvalidDecl();
7454      return;
7455    }
7456
7457    // Success! Record the copy.
7458    Statements.push_back(Copy.takeAs<Expr>());
7459  }
7460
7461  // \brief Reference to the __builtin_memcpy function.
7462  Expr *BuiltinMemCpyRef = 0;
7463  // \brief Reference to the __builtin_objc_memmove_collectable function.
7464  Expr *CollectableMemCpyRef = 0;
7465
7466  // Assign non-static members.
7467  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7468                                  FieldEnd = ClassDecl->field_end();
7469       Field != FieldEnd; ++Field) {
7470    // Check for members of reference type; we can't copy those.
7471    if (Field->getType()->isReferenceType()) {
7472      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7473        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7474      Diag(Field->getLocation(), diag::note_declared_at);
7475      Diag(CurrentLocation, diag::note_member_synthesized_at)
7476        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7477      Invalid = true;
7478      continue;
7479    }
7480
7481    // Check for members of const-qualified, non-class type.
7482    QualType BaseType = Context.getBaseElementType(Field->getType());
7483    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7484      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7485        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7486      Diag(Field->getLocation(), diag::note_declared_at);
7487      Diag(CurrentLocation, diag::note_member_synthesized_at)
7488        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7489      Invalid = true;
7490      continue;
7491    }
7492
7493    // Suppress assigning zero-width bitfields.
7494    if (const Expr *Width = Field->getBitWidth())
7495      if (Width->EvaluateAsInt(Context) == 0)
7496        continue;
7497
7498    QualType FieldType = Field->getType().getNonReferenceType();
7499    if (FieldType->isIncompleteArrayType()) {
7500      assert(ClassDecl->hasFlexibleArrayMember() &&
7501             "Incomplete array type is not valid");
7502      continue;
7503    }
7504
7505    // Build references to the field in the object we're copying from and to.
7506    CXXScopeSpec SS; // Intentionally empty
7507    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7508                              LookupMemberName);
7509    MemberLookup.addDecl(*Field);
7510    MemberLookup.resolveKind();
7511    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7512                                               Loc, /*IsArrow=*/false,
7513                                               SS, 0, MemberLookup, 0);
7514    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7515                                             Loc, /*IsArrow=*/true,
7516                                             SS, 0, MemberLookup, 0);
7517    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7518    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7519
7520    // If the field should be copied with __builtin_memcpy rather than via
7521    // explicit assignments, do so. This optimization only applies for arrays
7522    // of scalars and arrays of class type with trivial copy-assignment
7523    // operators.
7524    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7525        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7526      // Compute the size of the memory buffer to be copied.
7527      QualType SizeType = Context.getSizeType();
7528      llvm::APInt Size(Context.getTypeSize(SizeType),
7529                       Context.getTypeSizeInChars(BaseType).getQuantity());
7530      for (const ConstantArrayType *Array
7531              = Context.getAsConstantArrayType(FieldType);
7532           Array;
7533           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7534        llvm::APInt ArraySize
7535          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7536        Size *= ArraySize;
7537      }
7538
7539      // Take the address of the field references for "from" and "to".
7540      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7541      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7542
7543      bool NeedsCollectableMemCpy =
7544          (BaseType->isRecordType() &&
7545           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7546
7547      if (NeedsCollectableMemCpy) {
7548        if (!CollectableMemCpyRef) {
7549          // Create a reference to the __builtin_objc_memmove_collectable function.
7550          LookupResult R(*this,
7551                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7552                         Loc, LookupOrdinaryName);
7553          LookupName(R, TUScope, true);
7554
7555          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7556          if (!CollectableMemCpy) {
7557            // Something went horribly wrong earlier, and we will have
7558            // complained about it.
7559            Invalid = true;
7560            continue;
7561          }
7562
7563          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7564                                                  CollectableMemCpy->getType(),
7565                                                  VK_LValue, Loc, 0).take();
7566          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7567        }
7568      }
7569      // Create a reference to the __builtin_memcpy builtin function.
7570      else if (!BuiltinMemCpyRef) {
7571        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7572                       LookupOrdinaryName);
7573        LookupName(R, TUScope, true);
7574
7575        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7576        if (!BuiltinMemCpy) {
7577          // Something went horribly wrong earlier, and we will have complained
7578          // about it.
7579          Invalid = true;
7580          continue;
7581        }
7582
7583        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7584                                            BuiltinMemCpy->getType(),
7585                                            VK_LValue, Loc, 0).take();
7586        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7587      }
7588
7589      ASTOwningVector<Expr*> CallArgs(*this);
7590      CallArgs.push_back(To.takeAs<Expr>());
7591      CallArgs.push_back(From.takeAs<Expr>());
7592      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7593      ExprResult Call = ExprError();
7594      if (NeedsCollectableMemCpy)
7595        Call = ActOnCallExpr(/*Scope=*/0,
7596                             CollectableMemCpyRef,
7597                             Loc, move_arg(CallArgs),
7598                             Loc);
7599      else
7600        Call = ActOnCallExpr(/*Scope=*/0,
7601                             BuiltinMemCpyRef,
7602                             Loc, move_arg(CallArgs),
7603                             Loc);
7604
7605      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7606      Statements.push_back(Call.takeAs<Expr>());
7607      continue;
7608    }
7609
7610    // Build the copy of this field.
7611    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7612                                            To.get(), From.get(),
7613                                            /*CopyingBaseSubobject=*/false,
7614                                            /*Copying=*/true);
7615    if (Copy.isInvalid()) {
7616      Diag(CurrentLocation, diag::note_member_synthesized_at)
7617        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7618      CopyAssignOperator->setInvalidDecl();
7619      return;
7620    }
7621
7622    // Success! Record the copy.
7623    Statements.push_back(Copy.takeAs<Stmt>());
7624  }
7625
7626  if (!Invalid) {
7627    // Add a "return *this;"
7628    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7629
7630    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7631    if (Return.isInvalid())
7632      Invalid = true;
7633    else {
7634      Statements.push_back(Return.takeAs<Stmt>());
7635
7636      if (Trap.hasErrorOccurred()) {
7637        Diag(CurrentLocation, diag::note_member_synthesized_at)
7638          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7639        Invalid = true;
7640      }
7641    }
7642  }
7643
7644  if (Invalid) {
7645    CopyAssignOperator->setInvalidDecl();
7646    return;
7647  }
7648
7649  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7650                                            /*isStmtExpr=*/false);
7651  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7652  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7653
7654  if (ASTMutationListener *L = getASTMutationListener()) {
7655    L->CompletedImplicitDefinition(CopyAssignOperator);
7656  }
7657}
7658
7659Sema::ImplicitExceptionSpecification
7660Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7661  ImplicitExceptionSpecification ExceptSpec(Context);
7662
7663  if (ClassDecl->isInvalidDecl())
7664    return ExceptSpec;
7665
7666  // C++0x [except.spec]p14:
7667  //   An implicitly declared special member function (Clause 12) shall have an
7668  //   exception-specification. [...]
7669
7670  // It is unspecified whether or not an implicit move assignment operator
7671  // attempts to deduplicate calls to assignment operators of virtual bases are
7672  // made. As such, this exception specification is effectively unspecified.
7673  // Based on a similar decision made for constness in C++0x, we're erring on
7674  // the side of assuming such calls to be made regardless of whether they
7675  // actually happen.
7676  // Note that a move constructor is not implicitly declared when there are
7677  // virtual bases, but it can still be user-declared and explicitly defaulted.
7678  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7679                                       BaseEnd = ClassDecl->bases_end();
7680       Base != BaseEnd; ++Base) {
7681    if (Base->isVirtual())
7682      continue;
7683
7684    CXXRecordDecl *BaseClassDecl
7685      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7686    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7687                                                           false, 0))
7688      ExceptSpec.CalledDecl(MoveAssign);
7689  }
7690
7691  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7692                                       BaseEnd = ClassDecl->vbases_end();
7693       Base != BaseEnd; ++Base) {
7694    CXXRecordDecl *BaseClassDecl
7695      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7696    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7697                                                           false, 0))
7698      ExceptSpec.CalledDecl(MoveAssign);
7699  }
7700
7701  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7702                                  FieldEnd = ClassDecl->field_end();
7703       Field != FieldEnd;
7704       ++Field) {
7705    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7706    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7707      if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7708                                                             false, 0))
7709        ExceptSpec.CalledDecl(MoveAssign);
7710    }
7711  }
7712
7713  return ExceptSpec;
7714}
7715
7716CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7717  // Note: The following rules are largely analoguous to the move
7718  // constructor rules.
7719
7720  ImplicitExceptionSpecification Spec(
7721      ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7722
7723  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7724  QualType RetType = Context.getLValueReferenceType(ArgType);
7725  ArgType = Context.getRValueReferenceType(ArgType);
7726
7727  //   An implicitly-declared move assignment operator is an inline public
7728  //   member of its class.
7729  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7730  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7731  SourceLocation ClassLoc = ClassDecl->getLocation();
7732  DeclarationNameInfo NameInfo(Name, ClassLoc);
7733  CXXMethodDecl *MoveAssignment
7734    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7735                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7736                            /*TInfo=*/0, /*isStatic=*/false,
7737                            /*StorageClassAsWritten=*/SC_None,
7738                            /*isInline=*/true,
7739                            /*isConstexpr=*/false,
7740                            SourceLocation());
7741  MoveAssignment->setAccess(AS_public);
7742  MoveAssignment->setDefaulted();
7743  MoveAssignment->setImplicit();
7744  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7745
7746  // Add the parameter to the operator.
7747  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7748                                               ClassLoc, ClassLoc, /*Id=*/0,
7749                                               ArgType, /*TInfo=*/0,
7750                                               SC_None,
7751                                               SC_None, 0);
7752  MoveAssignment->setParams(&FromParam, 1);
7753
7754  // Note that we have added this copy-assignment operator.
7755  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7756
7757  // C++0x [class.copy]p9:
7758  //   If the definition of a class X does not explicitly declare a move
7759  //   assignment operator, one will be implicitly declared as defaulted if and
7760  //   only if:
7761  //   [...]
7762  //   - the move assignment operator would not be implicitly defined as
7763  //     deleted.
7764  if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7765    // Cache this result so that we don't try to generate this over and over
7766    // on every lookup, leaking memory and wasting time.
7767    ClassDecl->setFailedImplicitMoveAssignment();
7768    return 0;
7769  }
7770
7771  if (Scope *S = getScopeForContext(ClassDecl))
7772    PushOnScopeChains(MoveAssignment, S, false);
7773  ClassDecl->addDecl(MoveAssignment);
7774
7775  AddOverriddenMethods(ClassDecl, MoveAssignment);
7776  return MoveAssignment;
7777}
7778
7779void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
7780                                        CXXMethodDecl *MoveAssignOperator) {
7781  assert((MoveAssignOperator->isDefaulted() &&
7782          MoveAssignOperator->isOverloadedOperator() &&
7783          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
7784          !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
7785         "DefineImplicitMoveAssignment called for wrong function");
7786
7787  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
7788
7789  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
7790    MoveAssignOperator->setInvalidDecl();
7791    return;
7792  }
7793
7794  MoveAssignOperator->setUsed();
7795
7796  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
7797  DiagnosticErrorTrap Trap(Diags);
7798
7799  // C++0x [class.copy]p28:
7800  //   The implicitly-defined or move assignment operator for a non-union class
7801  //   X performs memberwise move assignment of its subobjects. The direct base
7802  //   classes of X are assigned first, in the order of their declaration in the
7803  //   base-specifier-list, and then the immediate non-static data members of X
7804  //   are assigned, in the order in which they were declared in the class
7805  //   definition.
7806
7807  // The statements that form the synthesized function body.
7808  ASTOwningVector<Stmt*> Statements(*this);
7809
7810  // The parameter for the "other" object, which we are move from.
7811  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
7812  QualType OtherRefType = Other->getType()->
7813      getAs<RValueReferenceType>()->getPointeeType();
7814  assert(OtherRefType.getQualifiers() == 0 &&
7815         "Bad argument type of defaulted move assignment");
7816
7817  // Our location for everything implicitly-generated.
7818  SourceLocation Loc = MoveAssignOperator->getLocation();
7819
7820  // Construct a reference to the "other" object. We'll be using this
7821  // throughout the generated ASTs.
7822  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7823  assert(OtherRef && "Reference to parameter cannot fail!");
7824  // Cast to rvalue.
7825  OtherRef = CastForMoving(*this, OtherRef);
7826
7827  // Construct the "this" pointer. We'll be using this throughout the generated
7828  // ASTs.
7829  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7830  assert(This && "Reference to this cannot fail!");
7831
7832  // Assign base classes.
7833  bool Invalid = false;
7834  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7835       E = ClassDecl->bases_end(); Base != E; ++Base) {
7836    // Form the assignment:
7837    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
7838    QualType BaseType = Base->getType().getUnqualifiedType();
7839    if (!BaseType->isRecordType()) {
7840      Invalid = true;
7841      continue;
7842    }
7843
7844    CXXCastPath BasePath;
7845    BasePath.push_back(Base);
7846
7847    // Construct the "from" expression, which is an implicit cast to the
7848    // appropriately-qualified base type.
7849    Expr *From = OtherRef;
7850    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
7851                             VK_XValue, &BasePath).take();
7852
7853    // Dereference "this".
7854    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7855
7856    // Implicitly cast "this" to the appropriately-qualified base type.
7857    To = ImpCastExprToType(To.take(),
7858                           Context.getCVRQualifiedType(BaseType,
7859                                     MoveAssignOperator->getTypeQualifiers()),
7860                           CK_UncheckedDerivedToBase,
7861                           VK_LValue, &BasePath);
7862
7863    // Build the move.
7864    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
7865                                            To.get(), From,
7866                                            /*CopyingBaseSubobject=*/true,
7867                                            /*Copying=*/false);
7868    if (Move.isInvalid()) {
7869      Diag(CurrentLocation, diag::note_member_synthesized_at)
7870        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7871      MoveAssignOperator->setInvalidDecl();
7872      return;
7873    }
7874
7875    // Success! Record the move.
7876    Statements.push_back(Move.takeAs<Expr>());
7877  }
7878
7879  // \brief Reference to the __builtin_memcpy function.
7880  Expr *BuiltinMemCpyRef = 0;
7881  // \brief Reference to the __builtin_objc_memmove_collectable function.
7882  Expr *CollectableMemCpyRef = 0;
7883
7884  // Assign non-static members.
7885  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7886                                  FieldEnd = ClassDecl->field_end();
7887       Field != FieldEnd; ++Field) {
7888    // Check for members of reference type; we can't move those.
7889    if (Field->getType()->isReferenceType()) {
7890      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7891        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7892      Diag(Field->getLocation(), diag::note_declared_at);
7893      Diag(CurrentLocation, diag::note_member_synthesized_at)
7894        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7895      Invalid = true;
7896      continue;
7897    }
7898
7899    // Check for members of const-qualified, non-class type.
7900    QualType BaseType = Context.getBaseElementType(Field->getType());
7901    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7902      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7903        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7904      Diag(Field->getLocation(), diag::note_declared_at);
7905      Diag(CurrentLocation, diag::note_member_synthesized_at)
7906        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
7907      Invalid = true;
7908      continue;
7909    }
7910
7911    // Suppress assigning zero-width bitfields.
7912    if (const Expr *Width = Field->getBitWidth())
7913      if (Width->EvaluateAsInt(Context) == 0)
7914        continue;
7915
7916    QualType FieldType = Field->getType().getNonReferenceType();
7917    if (FieldType->isIncompleteArrayType()) {
7918      assert(ClassDecl->hasFlexibleArrayMember() &&
7919             "Incomplete array type is not valid");
7920      continue;
7921    }
7922
7923    // Build references to the field in the object we're copying from and to.
7924    CXXScopeSpec SS; // Intentionally empty
7925    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7926                              LookupMemberName);
7927    MemberLookup.addDecl(*Field);
7928    MemberLookup.resolveKind();
7929    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7930                                               Loc, /*IsArrow=*/false,
7931                                               SS, 0, MemberLookup, 0);
7932    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7933                                             Loc, /*IsArrow=*/true,
7934                                             SS, 0, MemberLookup, 0);
7935    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7936    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7937
7938    assert(!From.get()->isLValue() && // could be xvalue or prvalue
7939        "Member reference with rvalue base must be rvalue except for reference "
7940        "members, which aren't allowed for move assignment.");
7941
7942    // If the field should be copied with __builtin_memcpy rather than via
7943    // explicit assignments, do so. This optimization only applies for arrays
7944    // of scalars and arrays of class type with trivial move-assignment
7945    // operators.
7946    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7947        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
7948      // Compute the size of the memory buffer to be copied.
7949      QualType SizeType = Context.getSizeType();
7950      llvm::APInt Size(Context.getTypeSize(SizeType),
7951                       Context.getTypeSizeInChars(BaseType).getQuantity());
7952      for (const ConstantArrayType *Array
7953              = Context.getAsConstantArrayType(FieldType);
7954           Array;
7955           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7956        llvm::APInt ArraySize
7957          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7958        Size *= ArraySize;
7959      }
7960
7961      // Take the address of the field references for "from" and "to". We
7962      // directly construct UnaryOperators here because semantic analysis
7963      // does not permit us to take the address of an xvalue.
7964      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
7965                             Context.getPointerType(From.get()->getType()),
7966                             VK_RValue, OK_Ordinary, Loc);
7967      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
7968                           Context.getPointerType(To.get()->getType()),
7969                           VK_RValue, OK_Ordinary, Loc);
7970
7971      bool NeedsCollectableMemCpy =
7972          (BaseType->isRecordType() &&
7973           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7974
7975      if (NeedsCollectableMemCpy) {
7976        if (!CollectableMemCpyRef) {
7977          // Create a reference to the __builtin_objc_memmove_collectable function.
7978          LookupResult R(*this,
7979                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7980                         Loc, LookupOrdinaryName);
7981          LookupName(R, TUScope, true);
7982
7983          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7984          if (!CollectableMemCpy) {
7985            // Something went horribly wrong earlier, and we will have
7986            // complained about it.
7987            Invalid = true;
7988            continue;
7989          }
7990
7991          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7992                                                  CollectableMemCpy->getType(),
7993                                                  VK_LValue, Loc, 0).take();
7994          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7995        }
7996      }
7997      // Create a reference to the __builtin_memcpy builtin function.
7998      else if (!BuiltinMemCpyRef) {
7999        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8000                       LookupOrdinaryName);
8001        LookupName(R, TUScope, true);
8002
8003        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8004        if (!BuiltinMemCpy) {
8005          // Something went horribly wrong earlier, and we will have complained
8006          // about it.
8007          Invalid = true;
8008          continue;
8009        }
8010
8011        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8012                                            BuiltinMemCpy->getType(),
8013                                            VK_LValue, Loc, 0).take();
8014        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8015      }
8016
8017      ASTOwningVector<Expr*> CallArgs(*this);
8018      CallArgs.push_back(To.takeAs<Expr>());
8019      CallArgs.push_back(From.takeAs<Expr>());
8020      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8021      ExprResult Call = ExprError();
8022      if (NeedsCollectableMemCpy)
8023        Call = ActOnCallExpr(/*Scope=*/0,
8024                             CollectableMemCpyRef,
8025                             Loc, move_arg(CallArgs),
8026                             Loc);
8027      else
8028        Call = ActOnCallExpr(/*Scope=*/0,
8029                             BuiltinMemCpyRef,
8030                             Loc, move_arg(CallArgs),
8031                             Loc);
8032
8033      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8034      Statements.push_back(Call.takeAs<Expr>());
8035      continue;
8036    }
8037
8038    // Build the move of this field.
8039    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8040                                            To.get(), From.get(),
8041                                            /*CopyingBaseSubobject=*/false,
8042                                            /*Copying=*/false);
8043    if (Move.isInvalid()) {
8044      Diag(CurrentLocation, diag::note_member_synthesized_at)
8045        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8046      MoveAssignOperator->setInvalidDecl();
8047      return;
8048    }
8049
8050    // Success! Record the copy.
8051    Statements.push_back(Move.takeAs<Stmt>());
8052  }
8053
8054  if (!Invalid) {
8055    // Add a "return *this;"
8056    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8057
8058    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8059    if (Return.isInvalid())
8060      Invalid = true;
8061    else {
8062      Statements.push_back(Return.takeAs<Stmt>());
8063
8064      if (Trap.hasErrorOccurred()) {
8065        Diag(CurrentLocation, diag::note_member_synthesized_at)
8066          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8067        Invalid = true;
8068      }
8069    }
8070  }
8071
8072  if (Invalid) {
8073    MoveAssignOperator->setInvalidDecl();
8074    return;
8075  }
8076
8077  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8078                                            /*isStmtExpr=*/false);
8079  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8080  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8081
8082  if (ASTMutationListener *L = getASTMutationListener()) {
8083    L->CompletedImplicitDefinition(MoveAssignOperator);
8084  }
8085}
8086
8087std::pair<Sema::ImplicitExceptionSpecification, bool>
8088Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8089  if (ClassDecl->isInvalidDecl())
8090    return std::make_pair(ImplicitExceptionSpecification(Context), false);
8091
8092  // C++ [class.copy]p5:
8093  //   The implicitly-declared copy constructor for a class X will
8094  //   have the form
8095  //
8096  //       X::X(const X&)
8097  //
8098  //   if
8099  // FIXME: It ought to be possible to store this on the record.
8100  bool HasConstCopyConstructor = true;
8101
8102  //     -- each direct or virtual base class B of X has a copy
8103  //        constructor whose first parameter is of type const B& or
8104  //        const volatile B&, and
8105  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8106                                       BaseEnd = ClassDecl->bases_end();
8107       HasConstCopyConstructor && Base != BaseEnd;
8108       ++Base) {
8109    // Virtual bases are handled below.
8110    if (Base->isVirtual())
8111      continue;
8112
8113    CXXRecordDecl *BaseClassDecl
8114      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8115    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8116                             &HasConstCopyConstructor);
8117  }
8118
8119  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8120                                       BaseEnd = ClassDecl->vbases_end();
8121       HasConstCopyConstructor && Base != BaseEnd;
8122       ++Base) {
8123    CXXRecordDecl *BaseClassDecl
8124      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8125    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8126                             &HasConstCopyConstructor);
8127  }
8128
8129  //     -- for all the nonstatic data members of X that are of a
8130  //        class type M (or array thereof), each such class type
8131  //        has a copy constructor whose first parameter is of type
8132  //        const M& or const volatile M&.
8133  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8134                                  FieldEnd = ClassDecl->field_end();
8135       HasConstCopyConstructor && Field != FieldEnd;
8136       ++Field) {
8137    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8138    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8139      LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8140                               &HasConstCopyConstructor);
8141    }
8142  }
8143  //   Otherwise, the implicitly declared copy constructor will have
8144  //   the form
8145  //
8146  //       X::X(X&)
8147
8148  // C++ [except.spec]p14:
8149  //   An implicitly declared special member function (Clause 12) shall have an
8150  //   exception-specification. [...]
8151  ImplicitExceptionSpecification ExceptSpec(Context);
8152  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8153  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8154                                       BaseEnd = ClassDecl->bases_end();
8155       Base != BaseEnd;
8156       ++Base) {
8157    // Virtual bases are handled below.
8158    if (Base->isVirtual())
8159      continue;
8160
8161    CXXRecordDecl *BaseClassDecl
8162      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8163    if (CXXConstructorDecl *CopyConstructor =
8164          LookupCopyingConstructor(BaseClassDecl, Quals))
8165      ExceptSpec.CalledDecl(CopyConstructor);
8166  }
8167  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8168                                       BaseEnd = ClassDecl->vbases_end();
8169       Base != BaseEnd;
8170       ++Base) {
8171    CXXRecordDecl *BaseClassDecl
8172      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8173    if (CXXConstructorDecl *CopyConstructor =
8174          LookupCopyingConstructor(BaseClassDecl, Quals))
8175      ExceptSpec.CalledDecl(CopyConstructor);
8176  }
8177  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8178                                  FieldEnd = ClassDecl->field_end();
8179       Field != FieldEnd;
8180       ++Field) {
8181    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8182    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8183      if (CXXConstructorDecl *CopyConstructor =
8184        LookupCopyingConstructor(FieldClassDecl, Quals))
8185      ExceptSpec.CalledDecl(CopyConstructor);
8186    }
8187  }
8188
8189  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8190}
8191
8192CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8193                                                    CXXRecordDecl *ClassDecl) {
8194  // C++ [class.copy]p4:
8195  //   If the class definition does not explicitly declare a copy
8196  //   constructor, one is declared implicitly.
8197
8198  ImplicitExceptionSpecification Spec(Context);
8199  bool Const;
8200  llvm::tie(Spec, Const) =
8201    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8202
8203  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8204  QualType ArgType = ClassType;
8205  if (Const)
8206    ArgType = ArgType.withConst();
8207  ArgType = Context.getLValueReferenceType(ArgType);
8208
8209  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8210
8211  DeclarationName Name
8212    = Context.DeclarationNames.getCXXConstructorName(
8213                                           Context.getCanonicalType(ClassType));
8214  SourceLocation ClassLoc = ClassDecl->getLocation();
8215  DeclarationNameInfo NameInfo(Name, ClassLoc);
8216
8217  //   An implicitly-declared copy constructor is an inline public
8218  //   member of its class.
8219  CXXConstructorDecl *CopyConstructor
8220    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8221                                 Context.getFunctionType(Context.VoidTy,
8222                                                         &ArgType, 1, EPI),
8223                                 /*TInfo=*/0,
8224                                 /*isExplicit=*/false,
8225                                 /*isInline=*/true,
8226                                 /*isImplicitlyDeclared=*/true,
8227                                 // FIXME: apply the rules for definitions here
8228                                 /*isConstexpr=*/false);
8229  CopyConstructor->setAccess(AS_public);
8230  CopyConstructor->setDefaulted();
8231  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8232
8233  // Note that we have declared this constructor.
8234  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8235
8236  // Add the parameter to the constructor.
8237  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8238                                               ClassLoc, ClassLoc,
8239                                               /*IdentifierInfo=*/0,
8240                                               ArgType, /*TInfo=*/0,
8241                                               SC_None,
8242                                               SC_None, 0);
8243  CopyConstructor->setParams(&FromParam, 1);
8244
8245  if (Scope *S = getScopeForContext(ClassDecl))
8246    PushOnScopeChains(CopyConstructor, S, false);
8247  ClassDecl->addDecl(CopyConstructor);
8248
8249  // C++0x [class.copy]p7:
8250  //   ... If the class definition declares a move constructor or move
8251  //   assignment operator, the implicitly declared constructor is defined as
8252  //   deleted; ...
8253  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8254      ClassDecl->hasUserDeclaredMoveAssignment() ||
8255      ShouldDeleteCopyConstructor(CopyConstructor))
8256    CopyConstructor->setDeletedAsWritten();
8257
8258  return CopyConstructor;
8259}
8260
8261void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8262                                   CXXConstructorDecl *CopyConstructor) {
8263  assert((CopyConstructor->isDefaulted() &&
8264          CopyConstructor->isCopyConstructor() &&
8265          !CopyConstructor->doesThisDeclarationHaveABody()) &&
8266         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8267
8268  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8269  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8270
8271  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8272  DiagnosticErrorTrap Trap(Diags);
8273
8274  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8275      Trap.hasErrorOccurred()) {
8276    Diag(CurrentLocation, diag::note_member_synthesized_at)
8277      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8278    CopyConstructor->setInvalidDecl();
8279  }  else {
8280    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8281                                               CopyConstructor->getLocation(),
8282                                               MultiStmtArg(*this, 0, 0),
8283                                               /*isStmtExpr=*/false)
8284                                                              .takeAs<Stmt>());
8285  }
8286
8287  CopyConstructor->setUsed();
8288
8289  if (ASTMutationListener *L = getASTMutationListener()) {
8290    L->CompletedImplicitDefinition(CopyConstructor);
8291  }
8292}
8293
8294Sema::ImplicitExceptionSpecification
8295Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8296  // C++ [except.spec]p14:
8297  //   An implicitly declared special member function (Clause 12) shall have an
8298  //   exception-specification. [...]
8299  ImplicitExceptionSpecification ExceptSpec(Context);
8300  if (ClassDecl->isInvalidDecl())
8301    return ExceptSpec;
8302
8303  // Direct base-class constructors.
8304  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8305                                       BEnd = ClassDecl->bases_end();
8306       B != BEnd; ++B) {
8307    if (B->isVirtual()) // Handled below.
8308      continue;
8309
8310    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8311      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8312      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8313      // If this is a deleted function, add it anyway. This might be conformant
8314      // with the standard. This might not. I'm not sure. It might not matter.
8315      if (Constructor)
8316        ExceptSpec.CalledDecl(Constructor);
8317    }
8318  }
8319
8320  // Virtual base-class constructors.
8321  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8322                                       BEnd = ClassDecl->vbases_end();
8323       B != BEnd; ++B) {
8324    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8325      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8326      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8327      // If this is a deleted function, add it anyway. This might be conformant
8328      // with the standard. This might not. I'm not sure. It might not matter.
8329      if (Constructor)
8330        ExceptSpec.CalledDecl(Constructor);
8331    }
8332  }
8333
8334  // Field constructors.
8335  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8336                               FEnd = ClassDecl->field_end();
8337       F != FEnd; ++F) {
8338    if (F->hasInClassInitializer()) {
8339      if (Expr *E = F->getInClassInitializer())
8340        ExceptSpec.CalledExpr(E);
8341      else if (!F->isInvalidDecl())
8342        ExceptSpec.SetDelayed();
8343    } else if (const RecordType *RecordTy
8344              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8345      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8346      CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8347      // If this is a deleted function, add it anyway. This might be conformant
8348      // with the standard. This might not. I'm not sure. It might not matter.
8349      // In particular, the problem is that this function never gets called. It
8350      // might just be ill-formed because this function attempts to refer to
8351      // a deleted function here.
8352      if (Constructor)
8353        ExceptSpec.CalledDecl(Constructor);
8354    }
8355  }
8356
8357  return ExceptSpec;
8358}
8359
8360CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8361                                                    CXXRecordDecl *ClassDecl) {
8362  ImplicitExceptionSpecification Spec(
8363      ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8364
8365  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8366  QualType ArgType = Context.getRValueReferenceType(ClassType);
8367
8368  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8369
8370  DeclarationName Name
8371    = Context.DeclarationNames.getCXXConstructorName(
8372                                           Context.getCanonicalType(ClassType));
8373  SourceLocation ClassLoc = ClassDecl->getLocation();
8374  DeclarationNameInfo NameInfo(Name, ClassLoc);
8375
8376  // C++0x [class.copy]p11:
8377  //   An implicitly-declared copy/move constructor is an inline public
8378  //   member of its class.
8379  CXXConstructorDecl *MoveConstructor
8380    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8381                                 Context.getFunctionType(Context.VoidTy,
8382                                                         &ArgType, 1, EPI),
8383                                 /*TInfo=*/0,
8384                                 /*isExplicit=*/false,
8385                                 /*isInline=*/true,
8386                                 /*isImplicitlyDeclared=*/true,
8387                                 // FIXME: apply the rules for definitions here
8388                                 /*isConstexpr=*/false);
8389  MoveConstructor->setAccess(AS_public);
8390  MoveConstructor->setDefaulted();
8391  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8392
8393  // Add the parameter to the constructor.
8394  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8395                                               ClassLoc, ClassLoc,
8396                                               /*IdentifierInfo=*/0,
8397                                               ArgType, /*TInfo=*/0,
8398                                               SC_None,
8399                                               SC_None, 0);
8400  MoveConstructor->setParams(&FromParam, 1);
8401
8402  // C++0x [class.copy]p9:
8403  //   If the definition of a class X does not explicitly declare a move
8404  //   constructor, one will be implicitly declared as defaulted if and only if:
8405  //   [...]
8406  //   - the move constructor would not be implicitly defined as deleted.
8407  if (ShouldDeleteMoveConstructor(MoveConstructor)) {
8408    // Cache this result so that we don't try to generate this over and over
8409    // on every lookup, leaking memory and wasting time.
8410    ClassDecl->setFailedImplicitMoveConstructor();
8411    return 0;
8412  }
8413
8414  // Note that we have declared this constructor.
8415  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8416
8417  if (Scope *S = getScopeForContext(ClassDecl))
8418    PushOnScopeChains(MoveConstructor, S, false);
8419  ClassDecl->addDecl(MoveConstructor);
8420
8421  return MoveConstructor;
8422}
8423
8424void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8425                                   CXXConstructorDecl *MoveConstructor) {
8426  assert((MoveConstructor->isDefaulted() &&
8427          MoveConstructor->isMoveConstructor() &&
8428          !MoveConstructor->doesThisDeclarationHaveABody()) &&
8429         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8430
8431  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8432  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8433
8434  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8435  DiagnosticErrorTrap Trap(Diags);
8436
8437  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8438      Trap.hasErrorOccurred()) {
8439    Diag(CurrentLocation, diag::note_member_synthesized_at)
8440      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8441    MoveConstructor->setInvalidDecl();
8442  }  else {
8443    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8444                                               MoveConstructor->getLocation(),
8445                                               MultiStmtArg(*this, 0, 0),
8446                                               /*isStmtExpr=*/false)
8447                                                              .takeAs<Stmt>());
8448  }
8449
8450  MoveConstructor->setUsed();
8451
8452  if (ASTMutationListener *L = getASTMutationListener()) {
8453    L->CompletedImplicitDefinition(MoveConstructor);
8454  }
8455}
8456
8457ExprResult
8458Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8459                            CXXConstructorDecl *Constructor,
8460                            MultiExprArg ExprArgs,
8461                            bool RequiresZeroInit,
8462                            unsigned ConstructKind,
8463                            SourceRange ParenRange) {
8464  bool Elidable = false;
8465
8466  // C++0x [class.copy]p34:
8467  //   When certain criteria are met, an implementation is allowed to
8468  //   omit the copy/move construction of a class object, even if the
8469  //   copy/move constructor and/or destructor for the object have
8470  //   side effects. [...]
8471  //     - when a temporary class object that has not been bound to a
8472  //       reference (12.2) would be copied/moved to a class object
8473  //       with the same cv-unqualified type, the copy/move operation
8474  //       can be omitted by constructing the temporary object
8475  //       directly into the target of the omitted copy/move
8476  if (ConstructKind == CXXConstructExpr::CK_Complete &&
8477      Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
8478    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
8479    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
8480  }
8481
8482  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
8483                               Elidable, move(ExprArgs), RequiresZeroInit,
8484                               ConstructKind, ParenRange);
8485}
8486
8487/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8488/// including handling of its default argument expressions.
8489ExprResult
8490Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8491                            CXXConstructorDecl *Constructor, bool Elidable,
8492                            MultiExprArg ExprArgs,
8493                            bool RequiresZeroInit,
8494                            unsigned ConstructKind,
8495                            SourceRange ParenRange) {
8496  unsigned NumExprs = ExprArgs.size();
8497  Expr **Exprs = (Expr **)ExprArgs.release();
8498
8499  for (specific_attr_iterator<NonNullAttr>
8500           i = Constructor->specific_attr_begin<NonNullAttr>(),
8501           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8502    const NonNullAttr *NonNull = *i;
8503    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8504  }
8505
8506  MarkDeclarationReferenced(ConstructLoc, Constructor);
8507  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
8508                                        Constructor, Elidable, Exprs, NumExprs,
8509                                        RequiresZeroInit,
8510              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8511                                        ParenRange));
8512}
8513
8514bool Sema::InitializeVarWithConstructor(VarDecl *VD,
8515                                        CXXConstructorDecl *Constructor,
8516                                        MultiExprArg Exprs) {
8517  // FIXME: Provide the correct paren SourceRange when available.
8518  ExprResult TempResult =
8519    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
8520                          move(Exprs), false, CXXConstructExpr::CK_Complete,
8521                          SourceRange());
8522  if (TempResult.isInvalid())
8523    return true;
8524
8525  Expr *Temp = TempResult.takeAs<Expr>();
8526  CheckImplicitConversions(Temp, VD->getLocation());
8527  MarkDeclarationReferenced(VD->getLocation(), Constructor);
8528  Temp = MaybeCreateExprWithCleanups(Temp);
8529  VD->setInit(Temp);
8530
8531  return false;
8532}
8533
8534void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
8535  if (VD->isInvalidDecl()) return;
8536
8537  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
8538  if (ClassDecl->isInvalidDecl()) return;
8539  if (ClassDecl->hasTrivialDestructor()) return;
8540  if (ClassDecl->isDependentContext()) return;
8541
8542  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8543  MarkDeclarationReferenced(VD->getLocation(), Destructor);
8544  CheckDestructorAccess(VD->getLocation(), Destructor,
8545                        PDiag(diag::err_access_dtor_var)
8546                        << VD->getDeclName()
8547                        << VD->getType());
8548
8549  if (!VD->hasGlobalStorage()) return;
8550
8551  // Emit warning for non-trivial dtor in global scope (a real global,
8552  // class-static, function-static).
8553  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8554
8555  // TODO: this should be re-enabled for static locals by !CXAAtExit
8556  if (!VD->isStaticLocal())
8557    Diag(VD->getLocation(), diag::warn_global_destructor);
8558}
8559
8560/// AddCXXDirectInitializerToDecl - This action is called immediately after
8561/// ActOnDeclarator, when a C++ direct initializer is present.
8562/// e.g: "int x(1);"
8563void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
8564                                         SourceLocation LParenLoc,
8565                                         MultiExprArg Exprs,
8566                                         SourceLocation RParenLoc,
8567                                         bool TypeMayContainAuto) {
8568  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
8569
8570  // If there is no declaration, there was an error parsing it.  Just ignore
8571  // the initializer.
8572  if (RealDecl == 0)
8573    return;
8574
8575  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8576  if (!VDecl) {
8577    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8578    RealDecl->setInvalidDecl();
8579    return;
8580  }
8581
8582  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8583  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
8584    // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8585    if (Exprs.size() > 1) {
8586      Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8587           diag::err_auto_var_init_multiple_expressions)
8588        << VDecl->getDeclName() << VDecl->getType()
8589        << VDecl->getSourceRange();
8590      RealDecl->setInvalidDecl();
8591      return;
8592    }
8593
8594    Expr *Init = Exprs.get()[0];
8595    TypeSourceInfo *DeducedType = 0;
8596    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
8597      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8598        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8599        << Init->getSourceRange();
8600    if (!DeducedType) {
8601      RealDecl->setInvalidDecl();
8602      return;
8603    }
8604    VDecl->setTypeSourceInfo(DeducedType);
8605    VDecl->setType(DeducedType->getType());
8606
8607    // In ARC, infer lifetime.
8608    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8609      VDecl->setInvalidDecl();
8610
8611    // If this is a redeclaration, check that the type we just deduced matches
8612    // the previously declared type.
8613    if (VarDecl *Old = VDecl->getPreviousDeclaration())
8614      MergeVarDeclTypes(VDecl, Old);
8615  }
8616
8617  // We will represent direct-initialization similarly to copy-initialization:
8618  //    int x(1);  -as-> int x = 1;
8619  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8620  //
8621  // Clients that want to distinguish between the two forms, can check for
8622  // direct initializer using VarDecl::hasCXXDirectInitializer().
8623  // A major benefit is that clients that don't particularly care about which
8624  // exactly form was it (like the CodeGen) can handle both cases without
8625  // special case code.
8626
8627  // C++ 8.5p11:
8628  // The form of initialization (using parentheses or '=') is generally
8629  // insignificant, but does matter when the entity being initialized has a
8630  // class type.
8631
8632  if (!VDecl->getType()->isDependentType() &&
8633      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
8634                          diag::err_typecheck_decl_incomplete_type)) {
8635    VDecl->setInvalidDecl();
8636    return;
8637  }
8638
8639  // The variable can not have an abstract class type.
8640  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8641                             diag::err_abstract_type_in_decl,
8642                             AbstractVariableType))
8643    VDecl->setInvalidDecl();
8644
8645  const VarDecl *Def;
8646  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8647    Diag(VDecl->getLocation(), diag::err_redefinition)
8648    << VDecl->getDeclName();
8649    Diag(Def->getLocation(), diag::note_previous_definition);
8650    VDecl->setInvalidDecl();
8651    return;
8652  }
8653
8654  // C++ [class.static.data]p4
8655  //   If a static data member is of const integral or const
8656  //   enumeration type, its declaration in the class definition can
8657  //   specify a constant-initializer which shall be an integral
8658  //   constant expression (5.19). In that case, the member can appear
8659  //   in integral constant expressions. The member shall still be
8660  //   defined in a namespace scope if it is used in the program and the
8661  //   namespace scope definition shall not contain an initializer.
8662  //
8663  // We already performed a redefinition check above, but for static
8664  // data members we also need to check whether there was an in-class
8665  // declaration with an initializer.
8666  const VarDecl* PrevInit = 0;
8667  if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8668    Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8669    Diag(PrevInit->getLocation(), diag::note_previous_definition);
8670    return;
8671  }
8672
8673  bool IsDependent = false;
8674  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8675    if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8676      VDecl->setInvalidDecl();
8677      return;
8678    }
8679
8680    if (Exprs.get()[I]->isTypeDependent())
8681      IsDependent = true;
8682  }
8683
8684  // If either the declaration has a dependent type or if any of the
8685  // expressions is type-dependent, we represent the initialization
8686  // via a ParenListExpr for later use during template instantiation.
8687  if (VDecl->getType()->isDependentType() || IsDependent) {
8688    // Let clients know that initialization was done with a direct initializer.
8689    VDecl->setCXXDirectInitializer(true);
8690
8691    // Store the initialization expressions as a ParenListExpr.
8692    unsigned NumExprs = Exprs.size();
8693    VDecl->setInit(new (Context) ParenListExpr(
8694        Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8695        VDecl->getType().getNonReferenceType()));
8696    return;
8697  }
8698
8699  // Capture the variable that is being initialized and the style of
8700  // initialization.
8701  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8702
8703  // FIXME: Poor source location information.
8704  InitializationKind Kind
8705    = InitializationKind::CreateDirect(VDecl->getLocation(),
8706                                       LParenLoc, RParenLoc);
8707
8708  InitializationSequence InitSeq(*this, Entity, Kind,
8709                                 Exprs.get(), Exprs.size());
8710  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
8711  if (Result.isInvalid()) {
8712    VDecl->setInvalidDecl();
8713    return;
8714  }
8715
8716  CheckImplicitConversions(Result.get(), LParenLoc);
8717
8718  Result = MaybeCreateExprWithCleanups(Result);
8719  VDecl->setInit(Result.takeAs<Expr>());
8720  VDecl->setCXXDirectInitializer(true);
8721
8722  CheckCompleteVariableDeclaration(VDecl);
8723}
8724
8725/// \brief Given a constructor and the set of arguments provided for the
8726/// constructor, convert the arguments and add any required default arguments
8727/// to form a proper call to this constructor.
8728///
8729/// \returns true if an error occurred, false otherwise.
8730bool
8731Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8732                              MultiExprArg ArgsPtr,
8733                              SourceLocation Loc,
8734                              ASTOwningVector<Expr*> &ConvertedArgs) {
8735  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8736  unsigned NumArgs = ArgsPtr.size();
8737  Expr **Args = (Expr **)ArgsPtr.get();
8738
8739  const FunctionProtoType *Proto
8740    = Constructor->getType()->getAs<FunctionProtoType>();
8741  assert(Proto && "Constructor without a prototype?");
8742  unsigned NumArgsInProto = Proto->getNumArgs();
8743
8744  // If too few arguments are available, we'll fill in the rest with defaults.
8745  if (NumArgs < NumArgsInProto)
8746    ConvertedArgs.reserve(NumArgsInProto);
8747  else
8748    ConvertedArgs.reserve(NumArgs);
8749
8750  VariadicCallType CallType =
8751    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
8752  SmallVector<Expr *, 8> AllArgs;
8753  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
8754                                        Proto, 0, Args, NumArgs, AllArgs,
8755                                        CallType);
8756  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
8757    ConvertedArgs.push_back(AllArgs[i]);
8758  return Invalid;
8759}
8760
8761static inline bool
8762CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
8763                                       const FunctionDecl *FnDecl) {
8764  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
8765  if (isa<NamespaceDecl>(DC)) {
8766    return SemaRef.Diag(FnDecl->getLocation(),
8767                        diag::err_operator_new_delete_declared_in_namespace)
8768      << FnDecl->getDeclName();
8769  }
8770
8771  if (isa<TranslationUnitDecl>(DC) &&
8772      FnDecl->getStorageClass() == SC_Static) {
8773    return SemaRef.Diag(FnDecl->getLocation(),
8774                        diag::err_operator_new_delete_declared_static)
8775      << FnDecl->getDeclName();
8776  }
8777
8778  return false;
8779}
8780
8781static inline bool
8782CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
8783                            CanQualType ExpectedResultType,
8784                            CanQualType ExpectedFirstParamType,
8785                            unsigned DependentParamTypeDiag,
8786                            unsigned InvalidParamTypeDiag) {
8787  QualType ResultType =
8788    FnDecl->getType()->getAs<FunctionType>()->getResultType();
8789
8790  // Check that the result type is not dependent.
8791  if (ResultType->isDependentType())
8792    return SemaRef.Diag(FnDecl->getLocation(),
8793                        diag::err_operator_new_delete_dependent_result_type)
8794    << FnDecl->getDeclName() << ExpectedResultType;
8795
8796  // Check that the result type is what we expect.
8797  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
8798    return SemaRef.Diag(FnDecl->getLocation(),
8799                        diag::err_operator_new_delete_invalid_result_type)
8800    << FnDecl->getDeclName() << ExpectedResultType;
8801
8802  // A function template must have at least 2 parameters.
8803  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
8804    return SemaRef.Diag(FnDecl->getLocation(),
8805                      diag::err_operator_new_delete_template_too_few_parameters)
8806        << FnDecl->getDeclName();
8807
8808  // The function decl must have at least 1 parameter.
8809  if (FnDecl->getNumParams() == 0)
8810    return SemaRef.Diag(FnDecl->getLocation(),
8811                        diag::err_operator_new_delete_too_few_parameters)
8812      << FnDecl->getDeclName();
8813
8814  // Check the the first parameter type is not dependent.
8815  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
8816  if (FirstParamType->isDependentType())
8817    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
8818      << FnDecl->getDeclName() << ExpectedFirstParamType;
8819
8820  // Check that the first parameter type is what we expect.
8821  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
8822      ExpectedFirstParamType)
8823    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
8824    << FnDecl->getDeclName() << ExpectedFirstParamType;
8825
8826  return false;
8827}
8828
8829static bool
8830CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8831  // C++ [basic.stc.dynamic.allocation]p1:
8832  //   A program is ill-formed if an allocation function is declared in a
8833  //   namespace scope other than global scope or declared static in global
8834  //   scope.
8835  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8836    return true;
8837
8838  CanQualType SizeTy =
8839    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
8840
8841  // C++ [basic.stc.dynamic.allocation]p1:
8842  //  The return type shall be void*. The first parameter shall have type
8843  //  std::size_t.
8844  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
8845                                  SizeTy,
8846                                  diag::err_operator_new_dependent_param_type,
8847                                  diag::err_operator_new_param_type))
8848    return true;
8849
8850  // C++ [basic.stc.dynamic.allocation]p1:
8851  //  The first parameter shall not have an associated default argument.
8852  if (FnDecl->getParamDecl(0)->hasDefaultArg())
8853    return SemaRef.Diag(FnDecl->getLocation(),
8854                        diag::err_operator_new_default_arg)
8855      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
8856
8857  return false;
8858}
8859
8860static bool
8861CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
8862  // C++ [basic.stc.dynamic.deallocation]p1:
8863  //   A program is ill-formed if deallocation functions are declared in a
8864  //   namespace scope other than global scope or declared static in global
8865  //   scope.
8866  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
8867    return true;
8868
8869  // C++ [basic.stc.dynamic.deallocation]p2:
8870  //   Each deallocation function shall return void and its first parameter
8871  //   shall be void*.
8872  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
8873                                  SemaRef.Context.VoidPtrTy,
8874                                 diag::err_operator_delete_dependent_param_type,
8875                                 diag::err_operator_delete_param_type))
8876    return true;
8877
8878  return false;
8879}
8880
8881/// CheckOverloadedOperatorDeclaration - Check whether the declaration
8882/// of this overloaded operator is well-formed. If so, returns false;
8883/// otherwise, emits appropriate diagnostics and returns true.
8884bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
8885  assert(FnDecl && FnDecl->isOverloadedOperator() &&
8886         "Expected an overloaded operator declaration");
8887
8888  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
8889
8890  // C++ [over.oper]p5:
8891  //   The allocation and deallocation functions, operator new,
8892  //   operator new[], operator delete and operator delete[], are
8893  //   described completely in 3.7.3. The attributes and restrictions
8894  //   found in the rest of this subclause do not apply to them unless
8895  //   explicitly stated in 3.7.3.
8896  if (Op == OO_Delete || Op == OO_Array_Delete)
8897    return CheckOperatorDeleteDeclaration(*this, FnDecl);
8898
8899  if (Op == OO_New || Op == OO_Array_New)
8900    return CheckOperatorNewDeclaration(*this, FnDecl);
8901
8902  // C++ [over.oper]p6:
8903  //   An operator function shall either be a non-static member
8904  //   function or be a non-member function and have at least one
8905  //   parameter whose type is a class, a reference to a class, an
8906  //   enumeration, or a reference to an enumeration.
8907  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
8908    if (MethodDecl->isStatic())
8909      return Diag(FnDecl->getLocation(),
8910                  diag::err_operator_overload_static) << FnDecl->getDeclName();
8911  } else {
8912    bool ClassOrEnumParam = false;
8913    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
8914                                   ParamEnd = FnDecl->param_end();
8915         Param != ParamEnd; ++Param) {
8916      QualType ParamType = (*Param)->getType().getNonReferenceType();
8917      if (ParamType->isDependentType() || ParamType->isRecordType() ||
8918          ParamType->isEnumeralType()) {
8919        ClassOrEnumParam = true;
8920        break;
8921      }
8922    }
8923
8924    if (!ClassOrEnumParam)
8925      return Diag(FnDecl->getLocation(),
8926                  diag::err_operator_overload_needs_class_or_enum)
8927        << FnDecl->getDeclName();
8928  }
8929
8930  // C++ [over.oper]p8:
8931  //   An operator function cannot have default arguments (8.3.6),
8932  //   except where explicitly stated below.
8933  //
8934  // Only the function-call operator allows default arguments
8935  // (C++ [over.call]p1).
8936  if (Op != OO_Call) {
8937    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
8938         Param != FnDecl->param_end(); ++Param) {
8939      if ((*Param)->hasDefaultArg())
8940        return Diag((*Param)->getLocation(),
8941                    diag::err_operator_overload_default_arg)
8942          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
8943    }
8944  }
8945
8946  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
8947    { false, false, false }
8948#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
8949    , { Unary, Binary, MemberOnly }
8950#include "clang/Basic/OperatorKinds.def"
8951  };
8952
8953  bool CanBeUnaryOperator = OperatorUses[Op][0];
8954  bool CanBeBinaryOperator = OperatorUses[Op][1];
8955  bool MustBeMemberOperator = OperatorUses[Op][2];
8956
8957  // C++ [over.oper]p8:
8958  //   [...] Operator functions cannot have more or fewer parameters
8959  //   than the number required for the corresponding operator, as
8960  //   described in the rest of this subclause.
8961  unsigned NumParams = FnDecl->getNumParams()
8962                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
8963  if (Op != OO_Call &&
8964      ((NumParams == 1 && !CanBeUnaryOperator) ||
8965       (NumParams == 2 && !CanBeBinaryOperator) ||
8966       (NumParams < 1) || (NumParams > 2))) {
8967    // We have the wrong number of parameters.
8968    unsigned ErrorKind;
8969    if (CanBeUnaryOperator && CanBeBinaryOperator) {
8970      ErrorKind = 2;  // 2 -> unary or binary.
8971    } else if (CanBeUnaryOperator) {
8972      ErrorKind = 0;  // 0 -> unary
8973    } else {
8974      assert(CanBeBinaryOperator &&
8975             "All non-call overloaded operators are unary or binary!");
8976      ErrorKind = 1;  // 1 -> binary
8977    }
8978
8979    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
8980      << FnDecl->getDeclName() << NumParams << ErrorKind;
8981  }
8982
8983  // Overloaded operators other than operator() cannot be variadic.
8984  if (Op != OO_Call &&
8985      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
8986    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
8987      << FnDecl->getDeclName();
8988  }
8989
8990  // Some operators must be non-static member functions.
8991  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
8992    return Diag(FnDecl->getLocation(),
8993                diag::err_operator_overload_must_be_member)
8994      << FnDecl->getDeclName();
8995  }
8996
8997  // C++ [over.inc]p1:
8998  //   The user-defined function called operator++ implements the
8999  //   prefix and postfix ++ operator. If this function is a member
9000  //   function with no parameters, or a non-member function with one
9001  //   parameter of class or enumeration type, it defines the prefix
9002  //   increment operator ++ for objects of that type. If the function
9003  //   is a member function with one parameter (which shall be of type
9004  //   int) or a non-member function with two parameters (the second
9005  //   of which shall be of type int), it defines the postfix
9006  //   increment operator ++ for objects of that type.
9007  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9008    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9009    bool ParamIsInt = false;
9010    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9011      ParamIsInt = BT->getKind() == BuiltinType::Int;
9012
9013    if (!ParamIsInt)
9014      return Diag(LastParam->getLocation(),
9015                  diag::err_operator_overload_post_incdec_must_be_int)
9016        << LastParam->getType() << (Op == OO_MinusMinus);
9017  }
9018
9019  return false;
9020}
9021
9022/// CheckLiteralOperatorDeclaration - Check whether the declaration
9023/// of this literal operator function is well-formed. If so, returns
9024/// false; otherwise, emits appropriate diagnostics and returns true.
9025bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9026  DeclContext *DC = FnDecl->getDeclContext();
9027  Decl::Kind Kind = DC->getDeclKind();
9028  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9029      Kind != Decl::LinkageSpec) {
9030    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9031      << FnDecl->getDeclName();
9032    return true;
9033  }
9034
9035  bool Valid = false;
9036
9037  // template <char...> type operator "" name() is the only valid template
9038  // signature, and the only valid signature with no parameters.
9039  if (FnDecl->param_size() == 0) {
9040    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9041      // Must have only one template parameter
9042      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9043      if (Params->size() == 1) {
9044        NonTypeTemplateParmDecl *PmDecl =
9045          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9046
9047        // The template parameter must be a char parameter pack.
9048        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9049            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9050          Valid = true;
9051      }
9052    }
9053  } else {
9054    // Check the first parameter
9055    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9056
9057    QualType T = (*Param)->getType();
9058
9059    // unsigned long long int, long double, and any character type are allowed
9060    // as the only parameters.
9061    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9062        Context.hasSameType(T, Context.LongDoubleTy) ||
9063        Context.hasSameType(T, Context.CharTy) ||
9064        Context.hasSameType(T, Context.WCharTy) ||
9065        Context.hasSameType(T, Context.Char16Ty) ||
9066        Context.hasSameType(T, Context.Char32Ty)) {
9067      if (++Param == FnDecl->param_end())
9068        Valid = true;
9069      goto FinishedParams;
9070    }
9071
9072    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9073    const PointerType *PT = T->getAs<PointerType>();
9074    if (!PT)
9075      goto FinishedParams;
9076    T = PT->getPointeeType();
9077    if (!T.isConstQualified())
9078      goto FinishedParams;
9079    T = T.getUnqualifiedType();
9080
9081    // Move on to the second parameter;
9082    ++Param;
9083
9084    // If there is no second parameter, the first must be a const char *
9085    if (Param == FnDecl->param_end()) {
9086      if (Context.hasSameType(T, Context.CharTy))
9087        Valid = true;
9088      goto FinishedParams;
9089    }
9090
9091    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9092    // are allowed as the first parameter to a two-parameter function
9093    if (!(Context.hasSameType(T, Context.CharTy) ||
9094          Context.hasSameType(T, Context.WCharTy) ||
9095          Context.hasSameType(T, Context.Char16Ty) ||
9096          Context.hasSameType(T, Context.Char32Ty)))
9097      goto FinishedParams;
9098
9099    // The second and final parameter must be an std::size_t
9100    T = (*Param)->getType().getUnqualifiedType();
9101    if (Context.hasSameType(T, Context.getSizeType()) &&
9102        ++Param == FnDecl->param_end())
9103      Valid = true;
9104  }
9105
9106  // FIXME: This diagnostic is absolutely terrible.
9107FinishedParams:
9108  if (!Valid) {
9109    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9110      << FnDecl->getDeclName();
9111    return true;
9112  }
9113
9114  StringRef LiteralName
9115    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9116  if (LiteralName[0] != '_') {
9117    // C++0x [usrlit.suffix]p1:
9118    //   Literal suffix identifiers that do not start with an underscore are
9119    //   reserved for future standardization.
9120    bool IsHexFloat = true;
9121    if (LiteralName.size() > 1 &&
9122        (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9123      for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9124        if (!isdigit(LiteralName[I])) {
9125          IsHexFloat = false;
9126          break;
9127        }
9128      }
9129    }
9130
9131    if (IsHexFloat)
9132      Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9133        << LiteralName;
9134    else
9135      Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9136  }
9137
9138  return false;
9139}
9140
9141/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9142/// linkage specification, including the language and (if present)
9143/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9144/// the location of the language string literal, which is provided
9145/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9146/// the '{' brace. Otherwise, this linkage specification does not
9147/// have any braces.
9148Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9149                                           SourceLocation LangLoc,
9150                                           StringRef Lang,
9151                                           SourceLocation LBraceLoc) {
9152  LinkageSpecDecl::LanguageIDs Language;
9153  if (Lang == "\"C\"")
9154    Language = LinkageSpecDecl::lang_c;
9155  else if (Lang == "\"C++\"")
9156    Language = LinkageSpecDecl::lang_cxx;
9157  else {
9158    Diag(LangLoc, diag::err_bad_language);
9159    return 0;
9160  }
9161
9162  // FIXME: Add all the various semantics of linkage specifications
9163
9164  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9165                                               ExternLoc, LangLoc, Language);
9166  CurContext->addDecl(D);
9167  PushDeclContext(S, D);
9168  return D;
9169}
9170
9171/// ActOnFinishLinkageSpecification - Complete the definition of
9172/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9173/// valid, it's the position of the closing '}' brace in a linkage
9174/// specification that uses braces.
9175Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9176                                            Decl *LinkageSpec,
9177                                            SourceLocation RBraceLoc) {
9178  if (LinkageSpec) {
9179    if (RBraceLoc.isValid()) {
9180      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9181      LSDecl->setRBraceLoc(RBraceLoc);
9182    }
9183    PopDeclContext();
9184  }
9185  return LinkageSpec;
9186}
9187
9188/// \brief Perform semantic analysis for the variable declaration that
9189/// occurs within a C++ catch clause, returning the newly-created
9190/// variable.
9191VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9192                                         TypeSourceInfo *TInfo,
9193                                         SourceLocation StartLoc,
9194                                         SourceLocation Loc,
9195                                         IdentifierInfo *Name) {
9196  bool Invalid = false;
9197  QualType ExDeclType = TInfo->getType();
9198
9199  // Arrays and functions decay.
9200  if (ExDeclType->isArrayType())
9201    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9202  else if (ExDeclType->isFunctionType())
9203    ExDeclType = Context.getPointerType(ExDeclType);
9204
9205  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9206  // The exception-declaration shall not denote a pointer or reference to an
9207  // incomplete type, other than [cv] void*.
9208  // N2844 forbids rvalue references.
9209  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9210    Diag(Loc, diag::err_catch_rvalue_ref);
9211    Invalid = true;
9212  }
9213
9214  // GCC allows catching pointers and references to incomplete types
9215  // as an extension; so do we, but we warn by default.
9216
9217  QualType BaseType = ExDeclType;
9218  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9219  unsigned DK = diag::err_catch_incomplete;
9220  bool IncompleteCatchIsInvalid = true;
9221  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9222    BaseType = Ptr->getPointeeType();
9223    Mode = 1;
9224    DK = diag::ext_catch_incomplete_ptr;
9225    IncompleteCatchIsInvalid = false;
9226  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9227    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9228    BaseType = Ref->getPointeeType();
9229    Mode = 2;
9230    DK = diag::ext_catch_incomplete_ref;
9231    IncompleteCatchIsInvalid = false;
9232  }
9233  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9234      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9235      IncompleteCatchIsInvalid)
9236    Invalid = true;
9237
9238  if (!Invalid && !ExDeclType->isDependentType() &&
9239      RequireNonAbstractType(Loc, ExDeclType,
9240                             diag::err_abstract_type_in_decl,
9241                             AbstractVariableType))
9242    Invalid = true;
9243
9244  // Only the non-fragile NeXT runtime currently supports C++ catches
9245  // of ObjC types, and no runtime supports catching ObjC types by value.
9246  if (!Invalid && getLangOptions().ObjC1) {
9247    QualType T = ExDeclType;
9248    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9249      T = RT->getPointeeType();
9250
9251    if (T->isObjCObjectType()) {
9252      Diag(Loc, diag::err_objc_object_catch);
9253      Invalid = true;
9254    } else if (T->isObjCObjectPointerType()) {
9255      if (!getLangOptions().ObjCNonFragileABI)
9256        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9257    }
9258  }
9259
9260  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9261                                    ExDeclType, TInfo, SC_None, SC_None);
9262  ExDecl->setExceptionVariable(true);
9263
9264  if (!Invalid && !ExDeclType->isDependentType()) {
9265    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9266      // C++ [except.handle]p16:
9267      //   The object declared in an exception-declaration or, if the
9268      //   exception-declaration does not specify a name, a temporary (12.2) is
9269      //   copy-initialized (8.5) from the exception object. [...]
9270      //   The object is destroyed when the handler exits, after the destruction
9271      //   of any automatic objects initialized within the handler.
9272      //
9273      // We just pretend to initialize the object with itself, then make sure
9274      // it can be destroyed later.
9275      QualType initType = ExDeclType;
9276
9277      InitializedEntity entity =
9278        InitializedEntity::InitializeVariable(ExDecl);
9279      InitializationKind initKind =
9280        InitializationKind::CreateCopy(Loc, SourceLocation());
9281
9282      Expr *opaqueValue =
9283        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9284      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9285      ExprResult result = sequence.Perform(*this, entity, initKind,
9286                                           MultiExprArg(&opaqueValue, 1));
9287      if (result.isInvalid())
9288        Invalid = true;
9289      else {
9290        // If the constructor used was non-trivial, set this as the
9291        // "initializer".
9292        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9293        if (!construct->getConstructor()->isTrivial()) {
9294          Expr *init = MaybeCreateExprWithCleanups(construct);
9295          ExDecl->setInit(init);
9296        }
9297
9298        // And make sure it's destructable.
9299        FinalizeVarWithDestructor(ExDecl, recordType);
9300      }
9301    }
9302  }
9303
9304  if (Invalid)
9305    ExDecl->setInvalidDecl();
9306
9307  return ExDecl;
9308}
9309
9310/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9311/// handler.
9312Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9313  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9314  bool Invalid = D.isInvalidType();
9315
9316  // Check for unexpanded parameter packs.
9317  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9318                                               UPPC_ExceptionType)) {
9319    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9320                                             D.getIdentifierLoc());
9321    Invalid = true;
9322  }
9323
9324  IdentifierInfo *II = D.getIdentifier();
9325  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9326                                             LookupOrdinaryName,
9327                                             ForRedeclaration)) {
9328    // The scope should be freshly made just for us. There is just no way
9329    // it contains any previous declaration.
9330    assert(!S->isDeclScope(PrevDecl));
9331    if (PrevDecl->isTemplateParameter()) {
9332      // Maybe we will complain about the shadowed template parameter.
9333      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9334    }
9335  }
9336
9337  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9338    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9339      << D.getCXXScopeSpec().getRange();
9340    Invalid = true;
9341  }
9342
9343  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9344                                              D.getSourceRange().getBegin(),
9345                                              D.getIdentifierLoc(),
9346                                              D.getIdentifier());
9347  if (Invalid)
9348    ExDecl->setInvalidDecl();
9349
9350  // Add the exception declaration into this scope.
9351  if (II)
9352    PushOnScopeChains(ExDecl, S);
9353  else
9354    CurContext->addDecl(ExDecl);
9355
9356  ProcessDeclAttributes(S, ExDecl, D);
9357  return ExDecl;
9358}
9359
9360Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9361                                         Expr *AssertExpr,
9362                                         Expr *AssertMessageExpr_,
9363                                         SourceLocation RParenLoc) {
9364  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9365
9366  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9367    llvm::APSInt Value(32);
9368    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
9369      Diag(StaticAssertLoc,
9370           diag::err_static_assert_expression_is_not_constant) <<
9371        AssertExpr->getSourceRange();
9372      return 0;
9373    }
9374
9375    if (Value == 0) {
9376      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9377        << AssertMessage->getString() << AssertExpr->getSourceRange();
9378    }
9379  }
9380
9381  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9382    return 0;
9383
9384  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9385                                        AssertExpr, AssertMessage, RParenLoc);
9386
9387  CurContext->addDecl(Decl);
9388  return Decl;
9389}
9390
9391/// \brief Perform semantic analysis of the given friend type declaration.
9392///
9393/// \returns A friend declaration that.
9394FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9395                                      TypeSourceInfo *TSInfo) {
9396  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9397
9398  QualType T = TSInfo->getType();
9399  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9400
9401  if (!getLangOptions().CPlusPlus0x) {
9402    // C++03 [class.friend]p2:
9403    //   An elaborated-type-specifier shall be used in a friend declaration
9404    //   for a class.*
9405    //
9406    //   * The class-key of the elaborated-type-specifier is required.
9407    if (!ActiveTemplateInstantiations.empty()) {
9408      // Do not complain about the form of friend template types during
9409      // template instantiation; we will already have complained when the
9410      // template was declared.
9411    } else if (!T->isElaboratedTypeSpecifier()) {
9412      // If we evaluated the type to a record type, suggest putting
9413      // a tag in front.
9414      if (const RecordType *RT = T->getAs<RecordType>()) {
9415        RecordDecl *RD = RT->getDecl();
9416
9417        std::string InsertionText = std::string(" ") + RD->getKindName();
9418
9419        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9420          << (unsigned) RD->getTagKind()
9421          << T
9422          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9423                                        InsertionText);
9424      } else {
9425        Diag(FriendLoc, diag::ext_nonclass_type_friend)
9426          << T
9427          << SourceRange(FriendLoc, TypeRange.getEnd());
9428      }
9429    } else if (T->getAs<EnumType>()) {
9430      Diag(FriendLoc, diag::ext_enum_friend)
9431        << T
9432        << SourceRange(FriendLoc, TypeRange.getEnd());
9433    }
9434  }
9435
9436  // C++0x [class.friend]p3:
9437  //   If the type specifier in a friend declaration designates a (possibly
9438  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9439  //   the friend declaration is ignored.
9440
9441  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9442  // in [class.friend]p3 that we do not implement.
9443
9444  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9445}
9446
9447/// Handle a friend tag declaration where the scope specifier was
9448/// templated.
9449Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9450                                    unsigned TagSpec, SourceLocation TagLoc,
9451                                    CXXScopeSpec &SS,
9452                                    IdentifierInfo *Name, SourceLocation NameLoc,
9453                                    AttributeList *Attr,
9454                                    MultiTemplateParamsArg TempParamLists) {
9455  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9456
9457  bool isExplicitSpecialization = false;
9458  bool Invalid = false;
9459
9460  if (TemplateParameterList *TemplateParams
9461        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9462                                                  TempParamLists.get(),
9463                                                  TempParamLists.size(),
9464                                                  /*friend*/ true,
9465                                                  isExplicitSpecialization,
9466                                                  Invalid)) {
9467    if (TemplateParams->size() > 0) {
9468      // This is a declaration of a class template.
9469      if (Invalid)
9470        return 0;
9471
9472      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9473                                SS, Name, NameLoc, Attr,
9474                                TemplateParams, AS_public,
9475                                /*ModulePrivateLoc=*/SourceLocation(),
9476                                TempParamLists.size() - 1,
9477                   (TemplateParameterList**) TempParamLists.release()).take();
9478    } else {
9479      // The "template<>" header is extraneous.
9480      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9481        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9482      isExplicitSpecialization = true;
9483    }
9484  }
9485
9486  if (Invalid) return 0;
9487
9488  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9489
9490  bool isAllExplicitSpecializations = true;
9491  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9492    if (TempParamLists.get()[I]->size()) {
9493      isAllExplicitSpecializations = false;
9494      break;
9495    }
9496  }
9497
9498  // FIXME: don't ignore attributes.
9499
9500  // If it's explicit specializations all the way down, just forget
9501  // about the template header and build an appropriate non-templated
9502  // friend.  TODO: for source fidelity, remember the headers.
9503  if (isAllExplicitSpecializations) {
9504    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9505    ElaboratedTypeKeyword Keyword
9506      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9507    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9508                                   *Name, NameLoc);
9509    if (T.isNull())
9510      return 0;
9511
9512    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9513    if (isa<DependentNameType>(T)) {
9514      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9515      TL.setKeywordLoc(TagLoc);
9516      TL.setQualifierLoc(QualifierLoc);
9517      TL.setNameLoc(NameLoc);
9518    } else {
9519      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9520      TL.setKeywordLoc(TagLoc);
9521      TL.setQualifierLoc(QualifierLoc);
9522      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9523    }
9524
9525    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9526                                            TSI, FriendLoc);
9527    Friend->setAccess(AS_public);
9528    CurContext->addDecl(Friend);
9529    return Friend;
9530  }
9531
9532  // Handle the case of a templated-scope friend class.  e.g.
9533  //   template <class T> class A<T>::B;
9534  // FIXME: we don't support these right now.
9535  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9536  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9537  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9538  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9539  TL.setKeywordLoc(TagLoc);
9540  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9541  TL.setNameLoc(NameLoc);
9542
9543  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9544                                          TSI, FriendLoc);
9545  Friend->setAccess(AS_public);
9546  Friend->setUnsupportedFriend(true);
9547  CurContext->addDecl(Friend);
9548  return Friend;
9549}
9550
9551
9552/// Handle a friend type declaration.  This works in tandem with
9553/// ActOnTag.
9554///
9555/// Notes on friend class templates:
9556///
9557/// We generally treat friend class declarations as if they were
9558/// declaring a class.  So, for example, the elaborated type specifier
9559/// in a friend declaration is required to obey the restrictions of a
9560/// class-head (i.e. no typedefs in the scope chain), template
9561/// parameters are required to match up with simple template-ids, &c.
9562/// However, unlike when declaring a template specialization, it's
9563/// okay to refer to a template specialization without an empty
9564/// template parameter declaration, e.g.
9565///   friend class A<T>::B<unsigned>;
9566/// We permit this as a special case; if there are any template
9567/// parameters present at all, require proper matching, i.e.
9568///   template <> template <class T> friend class A<int>::B;
9569Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
9570                                MultiTemplateParamsArg TempParams) {
9571  SourceLocation Loc = DS.getSourceRange().getBegin();
9572
9573  assert(DS.isFriendSpecified());
9574  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9575
9576  // Try to convert the decl specifier to a type.  This works for
9577  // friend templates because ActOnTag never produces a ClassTemplateDecl
9578  // for a TUK_Friend.
9579  Declarator TheDeclarator(DS, Declarator::MemberContext);
9580  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9581  QualType T = TSI->getType();
9582  if (TheDeclarator.isInvalidType())
9583    return 0;
9584
9585  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9586    return 0;
9587
9588  // This is definitely an error in C++98.  It's probably meant to
9589  // be forbidden in C++0x, too, but the specification is just
9590  // poorly written.
9591  //
9592  // The problem is with declarations like the following:
9593  //   template <T> friend A<T>::foo;
9594  // where deciding whether a class C is a friend or not now hinges
9595  // on whether there exists an instantiation of A that causes
9596  // 'foo' to equal C.  There are restrictions on class-heads
9597  // (which we declare (by fiat) elaborated friend declarations to
9598  // be) that makes this tractable.
9599  //
9600  // FIXME: handle "template <> friend class A<T>;", which
9601  // is possibly well-formed?  Who even knows?
9602  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
9603    Diag(Loc, diag::err_tagless_friend_type_template)
9604      << DS.getSourceRange();
9605    return 0;
9606  }
9607
9608  // C++98 [class.friend]p1: A friend of a class is a function
9609  //   or class that is not a member of the class . . .
9610  // This is fixed in DR77, which just barely didn't make the C++03
9611  // deadline.  It's also a very silly restriction that seriously
9612  // affects inner classes and which nobody else seems to implement;
9613  // thus we never diagnose it, not even in -pedantic.
9614  //
9615  // But note that we could warn about it: it's always useless to
9616  // friend one of your own members (it's not, however, worthless to
9617  // friend a member of an arbitrary specialization of your template).
9618
9619  Decl *D;
9620  if (unsigned NumTempParamLists = TempParams.size())
9621    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
9622                                   NumTempParamLists,
9623                                   TempParams.release(),
9624                                   TSI,
9625                                   DS.getFriendSpecLoc());
9626  else
9627    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9628
9629  if (!D)
9630    return 0;
9631
9632  D->setAccess(AS_public);
9633  CurContext->addDecl(D);
9634
9635  return D;
9636}
9637
9638Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
9639                                    MultiTemplateParamsArg TemplateParams) {
9640  const DeclSpec &DS = D.getDeclSpec();
9641
9642  assert(DS.isFriendSpecified());
9643  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9644
9645  SourceLocation Loc = D.getIdentifierLoc();
9646  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9647  QualType T = TInfo->getType();
9648
9649  // C++ [class.friend]p1
9650  //   A friend of a class is a function or class....
9651  // Note that this sees through typedefs, which is intended.
9652  // It *doesn't* see through dependent types, which is correct
9653  // according to [temp.arg.type]p3:
9654  //   If a declaration acquires a function type through a
9655  //   type dependent on a template-parameter and this causes
9656  //   a declaration that does not use the syntactic form of a
9657  //   function declarator to have a function type, the program
9658  //   is ill-formed.
9659  if (!T->isFunctionType()) {
9660    Diag(Loc, diag::err_unexpected_friend);
9661
9662    // It might be worthwhile to try to recover by creating an
9663    // appropriate declaration.
9664    return 0;
9665  }
9666
9667  // C++ [namespace.memdef]p3
9668  //  - If a friend declaration in a non-local class first declares a
9669  //    class or function, the friend class or function is a member
9670  //    of the innermost enclosing namespace.
9671  //  - The name of the friend is not found by simple name lookup
9672  //    until a matching declaration is provided in that namespace
9673  //    scope (either before or after the class declaration granting
9674  //    friendship).
9675  //  - If a friend function is called, its name may be found by the
9676  //    name lookup that considers functions from namespaces and
9677  //    classes associated with the types of the function arguments.
9678  //  - When looking for a prior declaration of a class or a function
9679  //    declared as a friend, scopes outside the innermost enclosing
9680  //    namespace scope are not considered.
9681
9682  CXXScopeSpec &SS = D.getCXXScopeSpec();
9683  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9684  DeclarationName Name = NameInfo.getName();
9685  assert(Name);
9686
9687  // Check for unexpanded parameter packs.
9688  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9689      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9690      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9691    return 0;
9692
9693  // The context we found the declaration in, or in which we should
9694  // create the declaration.
9695  DeclContext *DC;
9696  Scope *DCScope = S;
9697  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9698                        ForRedeclaration);
9699
9700  // FIXME: there are different rules in local classes
9701
9702  // There are four cases here.
9703  //   - There's no scope specifier, in which case we just go to the
9704  //     appropriate scope and look for a function or function template
9705  //     there as appropriate.
9706  // Recover from invalid scope qualifiers as if they just weren't there.
9707  if (SS.isInvalid() || !SS.isSet()) {
9708    // C++0x [namespace.memdef]p3:
9709    //   If the name in a friend declaration is neither qualified nor
9710    //   a template-id and the declaration is a function or an
9711    //   elaborated-type-specifier, the lookup to determine whether
9712    //   the entity has been previously declared shall not consider
9713    //   any scopes outside the innermost enclosing namespace.
9714    // C++0x [class.friend]p11:
9715    //   If a friend declaration appears in a local class and the name
9716    //   specified is an unqualified name, a prior declaration is
9717    //   looked up without considering scopes that are outside the
9718    //   innermost enclosing non-class scope. For a friend function
9719    //   declaration, if there is no prior declaration, the program is
9720    //   ill-formed.
9721    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
9722    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
9723
9724    // Find the appropriate context according to the above.
9725    DC = CurContext;
9726    while (true) {
9727      // Skip class contexts.  If someone can cite chapter and verse
9728      // for this behavior, that would be nice --- it's what GCC and
9729      // EDG do, and it seems like a reasonable intent, but the spec
9730      // really only says that checks for unqualified existing
9731      // declarations should stop at the nearest enclosing namespace,
9732      // not that they should only consider the nearest enclosing
9733      // namespace.
9734      while (DC->isRecord())
9735        DC = DC->getParent();
9736
9737      LookupQualifiedName(Previous, DC);
9738
9739      // TODO: decide what we think about using declarations.
9740      if (isLocal || !Previous.empty())
9741        break;
9742
9743      if (isTemplateId) {
9744        if (isa<TranslationUnitDecl>(DC)) break;
9745      } else {
9746        if (DC->isFileContext()) break;
9747      }
9748      DC = DC->getParent();
9749    }
9750
9751    // C++ [class.friend]p1: A friend of a class is a function or
9752    //   class that is not a member of the class . . .
9753    // C++0x changes this for both friend types and functions.
9754    // Most C++ 98 compilers do seem to give an error here, so
9755    // we do, too.
9756    if (!Previous.empty() && DC->Equals(CurContext)
9757        && !getLangOptions().CPlusPlus0x)
9758      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9759
9760    DCScope = getScopeForDeclContext(S, DC);
9761
9762  //   - There's a non-dependent scope specifier, in which case we
9763  //     compute it and do a previous lookup there for a function
9764  //     or function template.
9765  } else if (!SS.getScopeRep()->isDependent()) {
9766    DC = computeDeclContext(SS);
9767    if (!DC) return 0;
9768
9769    if (RequireCompleteDeclContext(SS, DC)) return 0;
9770
9771    LookupQualifiedName(Previous, DC);
9772
9773    // Ignore things found implicitly in the wrong scope.
9774    // TODO: better diagnostics for this case.  Suggesting the right
9775    // qualified scope would be nice...
9776    LookupResult::Filter F = Previous.makeFilter();
9777    while (F.hasNext()) {
9778      NamedDecl *D = F.next();
9779      if (!DC->InEnclosingNamespaceSetOf(
9780              D->getDeclContext()->getRedeclContext()))
9781        F.erase();
9782    }
9783    F.done();
9784
9785    if (Previous.empty()) {
9786      D.setInvalidType();
9787      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
9788      return 0;
9789    }
9790
9791    // C++ [class.friend]p1: A friend of a class is a function or
9792    //   class that is not a member of the class . . .
9793    if (DC->Equals(CurContext))
9794      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
9795
9796  //   - There's a scope specifier that does not match any template
9797  //     parameter lists, in which case we use some arbitrary context,
9798  //     create a method or method template, and wait for instantiation.
9799  //   - There's a scope specifier that does match some template
9800  //     parameter lists, which we don't handle right now.
9801  } else {
9802    DC = CurContext;
9803    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
9804  }
9805
9806  if (!DC->isRecord()) {
9807    // This implies that it has to be an operator or function.
9808    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
9809        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
9810        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
9811      Diag(Loc, diag::err_introducing_special_friend) <<
9812        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
9813         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
9814      return 0;
9815    }
9816  }
9817
9818  bool Redeclaration = false;
9819  bool AddToScope = true;
9820  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
9821                                          move(TemplateParams),
9822                                          IsDefinition,
9823                                          Redeclaration, AddToScope);
9824  if (!ND) return 0;
9825
9826  assert(ND->getDeclContext() == DC);
9827  assert(ND->getLexicalDeclContext() == CurContext);
9828
9829  // Add the function declaration to the appropriate lookup tables,
9830  // adjusting the redeclarations list as necessary.  We don't
9831  // want to do this yet if the friending class is dependent.
9832  //
9833  // Also update the scope-based lookup if the target context's
9834  // lookup context is in lexical scope.
9835  if (!CurContext->isDependentContext()) {
9836    DC = DC->getRedeclContext();
9837    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
9838    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
9839      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
9840  }
9841
9842  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
9843                                       D.getIdentifierLoc(), ND,
9844                                       DS.getFriendSpecLoc());
9845  FrD->setAccess(AS_public);
9846  CurContext->addDecl(FrD);
9847
9848  if (ND->isInvalidDecl())
9849    FrD->setInvalidDecl();
9850  else {
9851    FunctionDecl *FD;
9852    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9853      FD = FTD->getTemplatedDecl();
9854    else
9855      FD = cast<FunctionDecl>(ND);
9856
9857    // Mark templated-scope function declarations as unsupported.
9858    if (FD->getNumTemplateParameterLists())
9859      FrD->setUnsupportedFriend(true);
9860  }
9861
9862  return ND;
9863}
9864
9865void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
9866  AdjustDeclIfTemplate(Dcl);
9867
9868  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
9869  if (!Fn) {
9870    Diag(DelLoc, diag::err_deleted_non_function);
9871    return;
9872  }
9873  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
9874    Diag(DelLoc, diag::err_deleted_decl_not_first);
9875    Diag(Prev->getLocation(), diag::note_previous_declaration);
9876    // If the declaration wasn't the first, we delete the function anyway for
9877    // recovery.
9878  }
9879  Fn->setDeletedAsWritten();
9880}
9881
9882void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
9883  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
9884
9885  if (MD) {
9886    if (MD->getParent()->isDependentType()) {
9887      MD->setDefaulted();
9888      MD->setExplicitlyDefaulted();
9889      return;
9890    }
9891
9892    CXXSpecialMember Member = getSpecialMember(MD);
9893    if (Member == CXXInvalid) {
9894      Diag(DefaultLoc, diag::err_default_special_members);
9895      return;
9896    }
9897
9898    MD->setDefaulted();
9899    MD->setExplicitlyDefaulted();
9900
9901    // If this definition appears within the record, do the checking when
9902    // the record is complete.
9903    const FunctionDecl *Primary = MD;
9904    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
9905      // Find the uninstantiated declaration that actually had the '= default'
9906      // on it.
9907      MD->getTemplateInstantiationPattern()->isDefined(Primary);
9908
9909    if (Primary == Primary->getCanonicalDecl())
9910      return;
9911
9912    switch (Member) {
9913    case CXXDefaultConstructor: {
9914      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9915      CheckExplicitlyDefaultedDefaultConstructor(CD);
9916      if (!CD->isInvalidDecl())
9917        DefineImplicitDefaultConstructor(DefaultLoc, CD);
9918      break;
9919    }
9920
9921    case CXXCopyConstructor: {
9922      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9923      CheckExplicitlyDefaultedCopyConstructor(CD);
9924      if (!CD->isInvalidDecl())
9925        DefineImplicitCopyConstructor(DefaultLoc, CD);
9926      break;
9927    }
9928
9929    case CXXCopyAssignment: {
9930      CheckExplicitlyDefaultedCopyAssignment(MD);
9931      if (!MD->isInvalidDecl())
9932        DefineImplicitCopyAssignment(DefaultLoc, MD);
9933      break;
9934    }
9935
9936    case CXXDestructor: {
9937      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
9938      CheckExplicitlyDefaultedDestructor(DD);
9939      if (!DD->isInvalidDecl())
9940        DefineImplicitDestructor(DefaultLoc, DD);
9941      break;
9942    }
9943
9944    case CXXMoveConstructor: {
9945      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
9946      CheckExplicitlyDefaultedMoveConstructor(CD);
9947      if (!CD->isInvalidDecl())
9948        DefineImplicitMoveConstructor(DefaultLoc, CD);
9949      break;
9950    }
9951
9952    case CXXMoveAssignment: {
9953      CheckExplicitlyDefaultedMoveAssignment(MD);
9954      if (!MD->isInvalidDecl())
9955        DefineImplicitMoveAssignment(DefaultLoc, MD);
9956      break;
9957    }
9958
9959    case CXXInvalid:
9960      assert(false && "Invalid special member.");
9961      break;
9962    }
9963  } else {
9964    Diag(DefaultLoc, diag::err_default_special_members);
9965  }
9966}
9967
9968static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
9969  for (Stmt::child_range CI = S->children(); CI; ++CI) {
9970    Stmt *SubStmt = *CI;
9971    if (!SubStmt)
9972      continue;
9973    if (isa<ReturnStmt>(SubStmt))
9974      Self.Diag(SubStmt->getSourceRange().getBegin(),
9975           diag::err_return_in_constructor_handler);
9976    if (!isa<Expr>(SubStmt))
9977      SearchForReturnInStmt(Self, SubStmt);
9978  }
9979}
9980
9981void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
9982  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
9983    CXXCatchStmt *Handler = TryBlock->getHandler(I);
9984    SearchForReturnInStmt(*this, Handler);
9985  }
9986}
9987
9988bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
9989                                             const CXXMethodDecl *Old) {
9990  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
9991  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
9992
9993  if (Context.hasSameType(NewTy, OldTy) ||
9994      NewTy->isDependentType() || OldTy->isDependentType())
9995    return false;
9996
9997  // Check if the return types are covariant
9998  QualType NewClassTy, OldClassTy;
9999
10000  /// Both types must be pointers or references to classes.
10001  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10002    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10003      NewClassTy = NewPT->getPointeeType();
10004      OldClassTy = OldPT->getPointeeType();
10005    }
10006  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10007    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10008      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10009        NewClassTy = NewRT->getPointeeType();
10010        OldClassTy = OldRT->getPointeeType();
10011      }
10012    }
10013  }
10014
10015  // The return types aren't either both pointers or references to a class type.
10016  if (NewClassTy.isNull()) {
10017    Diag(New->getLocation(),
10018         diag::err_different_return_type_for_overriding_virtual_function)
10019      << New->getDeclName() << NewTy << OldTy;
10020    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10021
10022    return true;
10023  }
10024
10025  // C++ [class.virtual]p6:
10026  //   If the return type of D::f differs from the return type of B::f, the
10027  //   class type in the return type of D::f shall be complete at the point of
10028  //   declaration of D::f or shall be the class type D.
10029  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10030    if (!RT->isBeingDefined() &&
10031        RequireCompleteType(New->getLocation(), NewClassTy,
10032                            PDiag(diag::err_covariant_return_incomplete)
10033                              << New->getDeclName()))
10034    return true;
10035  }
10036
10037  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10038    // Check if the new class derives from the old class.
10039    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10040      Diag(New->getLocation(),
10041           diag::err_covariant_return_not_derived)
10042      << New->getDeclName() << NewTy << OldTy;
10043      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10044      return true;
10045    }
10046
10047    // Check if we the conversion from derived to base is valid.
10048    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10049                    diag::err_covariant_return_inaccessible_base,
10050                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10051                    // FIXME: Should this point to the return type?
10052                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10053      // FIXME: this note won't trigger for delayed access control
10054      // diagnostics, and it's impossible to get an undelayed error
10055      // here from access control during the original parse because
10056      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10057      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10058      return true;
10059    }
10060  }
10061
10062  // The qualifiers of the return types must be the same.
10063  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10064    Diag(New->getLocation(),
10065         diag::err_covariant_return_type_different_qualifications)
10066    << New->getDeclName() << NewTy << OldTy;
10067    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10068    return true;
10069  };
10070
10071
10072  // The new class type must have the same or less qualifiers as the old type.
10073  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10074    Diag(New->getLocation(),
10075         diag::err_covariant_return_type_class_type_more_qualified)
10076    << New->getDeclName() << NewTy << OldTy;
10077    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10078    return true;
10079  };
10080
10081  return false;
10082}
10083
10084/// \brief Mark the given method pure.
10085///
10086/// \param Method the method to be marked pure.
10087///
10088/// \param InitRange the source range that covers the "0" initializer.
10089bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10090  SourceLocation EndLoc = InitRange.getEnd();
10091  if (EndLoc.isValid())
10092    Method->setRangeEnd(EndLoc);
10093
10094  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10095    Method->setPure();
10096    return false;
10097  }
10098
10099  if (!Method->isInvalidDecl())
10100    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10101      << Method->getDeclName() << InitRange;
10102  return true;
10103}
10104
10105/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10106/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10107/// is a fresh scope pushed for just this purpose.
10108///
10109/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10110/// static data member of class X, names should be looked up in the scope of
10111/// class X.
10112void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10113  // If there is no declaration, there was an error parsing it.
10114  if (D == 0 || D->isInvalidDecl()) return;
10115
10116  // We should only get called for declarations with scope specifiers, like:
10117  //   int foo::bar;
10118  assert(D->isOutOfLine());
10119  EnterDeclaratorContext(S, D->getDeclContext());
10120}
10121
10122/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10123/// initializer for the out-of-line declaration 'D'.
10124void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10125  // If there is no declaration, there was an error parsing it.
10126  if (D == 0 || D->isInvalidDecl()) return;
10127
10128  assert(D->isOutOfLine());
10129  ExitDeclaratorContext(S);
10130}
10131
10132/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10133/// C++ if/switch/while/for statement.
10134/// e.g: "if (int x = f()) {...}"
10135DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10136  // C++ 6.4p2:
10137  // The declarator shall not specify a function or an array.
10138  // The type-specifier-seq shall not contain typedef and shall not declare a
10139  // new class or enumeration.
10140  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10141         "Parser allowed 'typedef' as storage class of condition decl.");
10142
10143  Decl *Dcl = ActOnDeclarator(S, D);
10144  if (!Dcl)
10145    return true;
10146
10147  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10148    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10149      << D.getSourceRange();
10150    return true;
10151  }
10152
10153  return Dcl;
10154}
10155
10156void Sema::LoadExternalVTableUses() {
10157  if (!ExternalSource)
10158    return;
10159
10160  SmallVector<ExternalVTableUse, 4> VTables;
10161  ExternalSource->ReadUsedVTables(VTables);
10162  SmallVector<VTableUse, 4> NewUses;
10163  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10164    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10165      = VTablesUsed.find(VTables[I].Record);
10166    // Even if a definition wasn't required before, it may be required now.
10167    if (Pos != VTablesUsed.end()) {
10168      if (!Pos->second && VTables[I].DefinitionRequired)
10169        Pos->second = true;
10170      continue;
10171    }
10172
10173    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10174    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10175  }
10176
10177  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10178}
10179
10180void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10181                          bool DefinitionRequired) {
10182  // Ignore any vtable uses in unevaluated operands or for classes that do
10183  // not have a vtable.
10184  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10185      CurContext->isDependentContext() ||
10186      ExprEvalContexts.back().Context == Unevaluated)
10187    return;
10188
10189  // Try to insert this class into the map.
10190  LoadExternalVTableUses();
10191  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10192  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10193    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10194  if (!Pos.second) {
10195    // If we already had an entry, check to see if we are promoting this vtable
10196    // to required a definition. If so, we need to reappend to the VTableUses
10197    // list, since we may have already processed the first entry.
10198    if (DefinitionRequired && !Pos.first->second) {
10199      Pos.first->second = true;
10200    } else {
10201      // Otherwise, we can early exit.
10202      return;
10203    }
10204  }
10205
10206  // Local classes need to have their virtual members marked
10207  // immediately. For all other classes, we mark their virtual members
10208  // at the end of the translation unit.
10209  if (Class->isLocalClass())
10210    MarkVirtualMembersReferenced(Loc, Class);
10211  else
10212    VTableUses.push_back(std::make_pair(Class, Loc));
10213}
10214
10215bool Sema::DefineUsedVTables() {
10216  LoadExternalVTableUses();
10217  if (VTableUses.empty())
10218    return false;
10219
10220  // Note: The VTableUses vector could grow as a result of marking
10221  // the members of a class as "used", so we check the size each
10222  // time through the loop and prefer indices (with are stable) to
10223  // iterators (which are not).
10224  bool DefinedAnything = false;
10225  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10226    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10227    if (!Class)
10228      continue;
10229
10230    SourceLocation Loc = VTableUses[I].second;
10231
10232    // If this class has a key function, but that key function is
10233    // defined in another translation unit, we don't need to emit the
10234    // vtable even though we're using it.
10235    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10236    if (KeyFunction && !KeyFunction->hasBody()) {
10237      switch (KeyFunction->getTemplateSpecializationKind()) {
10238      case TSK_Undeclared:
10239      case TSK_ExplicitSpecialization:
10240      case TSK_ExplicitInstantiationDeclaration:
10241        // The key function is in another translation unit.
10242        continue;
10243
10244      case TSK_ExplicitInstantiationDefinition:
10245      case TSK_ImplicitInstantiation:
10246        // We will be instantiating the key function.
10247        break;
10248      }
10249    } else if (!KeyFunction) {
10250      // If we have a class with no key function that is the subject
10251      // of an explicit instantiation declaration, suppress the
10252      // vtable; it will live with the explicit instantiation
10253      // definition.
10254      bool IsExplicitInstantiationDeclaration
10255        = Class->getTemplateSpecializationKind()
10256                                      == TSK_ExplicitInstantiationDeclaration;
10257      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10258                                 REnd = Class->redecls_end();
10259           R != REnd; ++R) {
10260        TemplateSpecializationKind TSK
10261          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10262        if (TSK == TSK_ExplicitInstantiationDeclaration)
10263          IsExplicitInstantiationDeclaration = true;
10264        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10265          IsExplicitInstantiationDeclaration = false;
10266          break;
10267        }
10268      }
10269
10270      if (IsExplicitInstantiationDeclaration)
10271        continue;
10272    }
10273
10274    // Mark all of the virtual members of this class as referenced, so
10275    // that we can build a vtable. Then, tell the AST consumer that a
10276    // vtable for this class is required.
10277    DefinedAnything = true;
10278    MarkVirtualMembersReferenced(Loc, Class);
10279    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10280    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10281
10282    // Optionally warn if we're emitting a weak vtable.
10283    if (Class->getLinkage() == ExternalLinkage &&
10284        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10285      if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
10286        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10287    }
10288  }
10289  VTableUses.clear();
10290
10291  return DefinedAnything;
10292}
10293
10294void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10295                                        const CXXRecordDecl *RD) {
10296  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10297       e = RD->method_end(); i != e; ++i) {
10298    CXXMethodDecl *MD = *i;
10299
10300    // C++ [basic.def.odr]p2:
10301    //   [...] A virtual member function is used if it is not pure. [...]
10302    if (MD->isVirtual() && !MD->isPure())
10303      MarkDeclarationReferenced(Loc, MD);
10304  }
10305
10306  // Only classes that have virtual bases need a VTT.
10307  if (RD->getNumVBases() == 0)
10308    return;
10309
10310  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10311           e = RD->bases_end(); i != e; ++i) {
10312    const CXXRecordDecl *Base =
10313        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10314    if (Base->getNumVBases() == 0)
10315      continue;
10316    MarkVirtualMembersReferenced(Loc, Base);
10317  }
10318}
10319
10320/// SetIvarInitializers - This routine builds initialization ASTs for the
10321/// Objective-C implementation whose ivars need be initialized.
10322void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10323  if (!getLangOptions().CPlusPlus)
10324    return;
10325  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10326    SmallVector<ObjCIvarDecl*, 8> ivars;
10327    CollectIvarsToConstructOrDestruct(OID, ivars);
10328    if (ivars.empty())
10329      return;
10330    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10331    for (unsigned i = 0; i < ivars.size(); i++) {
10332      FieldDecl *Field = ivars[i];
10333      if (Field->isInvalidDecl())
10334        continue;
10335
10336      CXXCtorInitializer *Member;
10337      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10338      InitializationKind InitKind =
10339        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10340
10341      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10342      ExprResult MemberInit =
10343        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10344      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10345      // Note, MemberInit could actually come back empty if no initialization
10346      // is required (e.g., because it would call a trivial default constructor)
10347      if (!MemberInit.get() || MemberInit.isInvalid())
10348        continue;
10349
10350      Member =
10351        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10352                                         SourceLocation(),
10353                                         MemberInit.takeAs<Expr>(),
10354                                         SourceLocation());
10355      AllToInit.push_back(Member);
10356
10357      // Be sure that the destructor is accessible and is marked as referenced.
10358      if (const RecordType *RecordTy
10359                  = Context.getBaseElementType(Field->getType())
10360                                                        ->getAs<RecordType>()) {
10361                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10362        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10363          MarkDeclarationReferenced(Field->getLocation(), Destructor);
10364          CheckDestructorAccess(Field->getLocation(), Destructor,
10365                            PDiag(diag::err_access_dtor_ivar)
10366                              << Context.getBaseElementType(Field->getType()));
10367        }
10368      }
10369    }
10370    ObjCImplementation->setIvarInitializers(Context,
10371                                            AllToInit.data(), AllToInit.size());
10372  }
10373}
10374
10375static
10376void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10377                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10378                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10379                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10380                           Sema &S) {
10381  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10382                                                   CE = Current.end();
10383  if (Ctor->isInvalidDecl())
10384    return;
10385
10386  const FunctionDecl *FNTarget = 0;
10387  CXXConstructorDecl *Target;
10388
10389  // We ignore the result here since if we don't have a body, Target will be
10390  // null below.
10391  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10392  Target
10393= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10394
10395  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10396                     // Avoid dereferencing a null pointer here.
10397                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10398
10399  if (!Current.insert(Canonical))
10400    return;
10401
10402  // We know that beyond here, we aren't chaining into a cycle.
10403  if (!Target || !Target->isDelegatingConstructor() ||
10404      Target->isInvalidDecl() || Valid.count(TCanonical)) {
10405    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10406      Valid.insert(*CI);
10407    Current.clear();
10408  // We've hit a cycle.
10409  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10410             Current.count(TCanonical)) {
10411    // If we haven't diagnosed this cycle yet, do so now.
10412    if (!Invalid.count(TCanonical)) {
10413      S.Diag((*Ctor->init_begin())->getSourceLocation(),
10414             diag::warn_delegating_ctor_cycle)
10415        << Ctor;
10416
10417      // Don't add a note for a function delegating directo to itself.
10418      if (TCanonical != Canonical)
10419        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10420
10421      CXXConstructorDecl *C = Target;
10422      while (C->getCanonicalDecl() != Canonical) {
10423        (void)C->getTargetConstructor()->hasBody(FNTarget);
10424        assert(FNTarget && "Ctor cycle through bodiless function");
10425
10426        C
10427       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10428        S.Diag(C->getLocation(), diag::note_which_delegates_to);
10429      }
10430    }
10431
10432    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10433      Invalid.insert(*CI);
10434    Current.clear();
10435  } else {
10436    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10437  }
10438}
10439
10440
10441void Sema::CheckDelegatingCtorCycles() {
10442  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10443
10444  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10445                                                   CE = Current.end();
10446
10447  for (DelegatingCtorDeclsType::iterator
10448         I = DelegatingCtorDecls.begin(ExternalSource),
10449         E = DelegatingCtorDecls.end();
10450       I != E; ++I) {
10451   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10452  }
10453
10454  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10455    (*CI)->setInvalidDecl();
10456}
10457