SemaDeclCXX.cpp revision 98a5403ecf1d2b60ae8cbf43e54194bd762cacaa
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, BaseTy **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 = llvm::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                               ExprTy *BW, const VirtSpecifiers &VS,
1064                               ExprTy *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. Such parsing
1238/// is deferred until the class is complete.
1239void
1240Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1241                                       Expr *InitExpr) {
1242  FieldDecl *FD = cast<FieldDecl>(D);
1243
1244  if (!InitExpr) {
1245    FD->setInvalidDecl();
1246    FD->removeInClassInitializer();
1247    return;
1248  }
1249
1250  ExprResult Init = InitExpr;
1251  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1252    // FIXME: if there is no EqualLoc, this is list-initialization.
1253    Init = PerformCopyInitialization(
1254      InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1255    if (Init.isInvalid()) {
1256      FD->setInvalidDecl();
1257      return;
1258    }
1259
1260    CheckImplicitConversions(Init.get(), EqualLoc);
1261  }
1262
1263  // C++0x [class.base.init]p7:
1264  //   The initialization of each base and member constitutes a
1265  //   full-expression.
1266  Init = MaybeCreateExprWithCleanups(Init);
1267  if (Init.isInvalid()) {
1268    FD->setInvalidDecl();
1269    return;
1270  }
1271
1272  InitExpr = Init.release();
1273
1274  FD->setInClassInitializer(InitExpr);
1275}
1276
1277/// \brief Find the direct and/or virtual base specifiers that
1278/// correspond to the given base type, for use in base initialization
1279/// within a constructor.
1280static bool FindBaseInitializer(Sema &SemaRef,
1281                                CXXRecordDecl *ClassDecl,
1282                                QualType BaseType,
1283                                const CXXBaseSpecifier *&DirectBaseSpec,
1284                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1285  // First, check for a direct base class.
1286  DirectBaseSpec = 0;
1287  for (CXXRecordDecl::base_class_const_iterator Base
1288         = ClassDecl->bases_begin();
1289       Base != ClassDecl->bases_end(); ++Base) {
1290    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1291      // We found a direct base of this type. That's what we're
1292      // initializing.
1293      DirectBaseSpec = &*Base;
1294      break;
1295    }
1296  }
1297
1298  // Check for a virtual base class.
1299  // FIXME: We might be able to short-circuit this if we know in advance that
1300  // there are no virtual bases.
1301  VirtualBaseSpec = 0;
1302  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1303    // We haven't found a base yet; search the class hierarchy for a
1304    // virtual base class.
1305    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1306                       /*DetectVirtual=*/false);
1307    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1308                              BaseType, Paths)) {
1309      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1310           Path != Paths.end(); ++Path) {
1311        if (Path->back().Base->isVirtual()) {
1312          VirtualBaseSpec = Path->back().Base;
1313          break;
1314        }
1315      }
1316    }
1317  }
1318
1319  return DirectBaseSpec || VirtualBaseSpec;
1320}
1321
1322/// ActOnMemInitializer - Handle a C++ member initializer.
1323MemInitResult
1324Sema::ActOnMemInitializer(Decl *ConstructorD,
1325                          Scope *S,
1326                          CXXScopeSpec &SS,
1327                          IdentifierInfo *MemberOrBase,
1328                          ParsedType TemplateTypeTy,
1329                          SourceLocation IdLoc,
1330                          SourceLocation LParenLoc,
1331                          ExprTy **Args, unsigned NumArgs,
1332                          SourceLocation RParenLoc,
1333                          SourceLocation EllipsisLoc) {
1334  if (!ConstructorD)
1335    return true;
1336
1337  AdjustDeclIfTemplate(ConstructorD);
1338
1339  CXXConstructorDecl *Constructor
1340    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1341  if (!Constructor) {
1342    // The user wrote a constructor initializer on a function that is
1343    // not a C++ constructor. Ignore the error for now, because we may
1344    // have more member initializers coming; we'll diagnose it just
1345    // once in ActOnMemInitializers.
1346    return true;
1347  }
1348
1349  CXXRecordDecl *ClassDecl = Constructor->getParent();
1350
1351  // C++ [class.base.init]p2:
1352  //   Names in a mem-initializer-id are looked up in the scope of the
1353  //   constructor's class and, if not found in that scope, are looked
1354  //   up in the scope containing the constructor's definition.
1355  //   [Note: if the constructor's class contains a member with the
1356  //   same name as a direct or virtual base class of the class, a
1357  //   mem-initializer-id naming the member or base class and composed
1358  //   of a single identifier refers to the class member. A
1359  //   mem-initializer-id for the hidden base class may be specified
1360  //   using a qualified name. ]
1361  if (!SS.getScopeRep() && !TemplateTypeTy) {
1362    // Look for a member, first.
1363    FieldDecl *Member = 0;
1364    DeclContext::lookup_result Result
1365      = ClassDecl->lookup(MemberOrBase);
1366    if (Result.first != Result.second) {
1367      Member = dyn_cast<FieldDecl>(*Result.first);
1368
1369      if (Member) {
1370        if (EllipsisLoc.isValid())
1371          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1372            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1373
1374        return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1375                                    LParenLoc, RParenLoc);
1376      }
1377
1378      // Handle anonymous union case.
1379      if (IndirectFieldDecl* IndirectField
1380            = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1381        if (EllipsisLoc.isValid())
1382          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1383            << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1384
1385         return BuildMemberInitializer(IndirectField, (Expr**)Args,
1386                                       NumArgs, IdLoc,
1387                                       LParenLoc, RParenLoc);
1388      }
1389    }
1390  }
1391  // It didn't name a member, so see if it names a class.
1392  QualType BaseType;
1393  TypeSourceInfo *TInfo = 0;
1394
1395  if (TemplateTypeTy) {
1396    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1397  } else {
1398    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1399    LookupParsedName(R, S, &SS);
1400
1401    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1402    if (!TyD) {
1403      if (R.isAmbiguous()) return true;
1404
1405      // We don't want access-control diagnostics here.
1406      R.suppressDiagnostics();
1407
1408      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1409        bool NotUnknownSpecialization = false;
1410        DeclContext *DC = computeDeclContext(SS, false);
1411        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1412          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1413
1414        if (!NotUnknownSpecialization) {
1415          // When the scope specifier can refer to a member of an unknown
1416          // specialization, we take it as a type name.
1417          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1418                                       SS.getWithLocInContext(Context),
1419                                       *MemberOrBase, IdLoc);
1420          if (BaseType.isNull())
1421            return true;
1422
1423          R.clear();
1424          R.setLookupName(MemberOrBase);
1425        }
1426      }
1427
1428      // If no results were found, try to correct typos.
1429      TypoCorrection Corr;
1430      if (R.empty() && BaseType.isNull() &&
1431          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1432                              ClassDecl, false, CTC_NoKeywords))) {
1433        std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1434        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1435        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1436          if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1437            // We have found a non-static data member with a similar
1438            // name to what was typed; complain and initialize that
1439            // member.
1440            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1441              << MemberOrBase << true << CorrectedQuotedStr
1442              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1443            Diag(Member->getLocation(), diag::note_previous_decl)
1444              << CorrectedQuotedStr;
1445
1446            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1447                                          LParenLoc, RParenLoc);
1448          }
1449        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1450          const CXXBaseSpecifier *DirectBaseSpec;
1451          const CXXBaseSpecifier *VirtualBaseSpec;
1452          if (FindBaseInitializer(*this, ClassDecl,
1453                                  Context.getTypeDeclType(Type),
1454                                  DirectBaseSpec, VirtualBaseSpec)) {
1455            // We have found a direct or virtual base class with a
1456            // similar name to what was typed; complain and initialize
1457            // that base class.
1458            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1459              << MemberOrBase << false << CorrectedQuotedStr
1460              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1461
1462            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1463                                                             : VirtualBaseSpec;
1464            Diag(BaseSpec->getSourceRange().getBegin(),
1465                 diag::note_base_class_specified_here)
1466              << BaseSpec->getType()
1467              << BaseSpec->getSourceRange();
1468
1469            TyD = Type;
1470          }
1471        }
1472      }
1473
1474      if (!TyD && BaseType.isNull()) {
1475        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1476          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1477        return true;
1478      }
1479    }
1480
1481    if (BaseType.isNull()) {
1482      BaseType = Context.getTypeDeclType(TyD);
1483      if (SS.isSet()) {
1484        NestedNameSpecifier *Qualifier =
1485          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1486
1487        // FIXME: preserve source range information
1488        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1489      }
1490    }
1491  }
1492
1493  if (!TInfo)
1494    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1495
1496  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1497                              LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1498}
1499
1500/// Checks an initializer expression for use of uninitialized fields, such as
1501/// containing the field that is being initialized. Returns true if there is an
1502/// uninitialized field was used an updates the SourceLocation parameter; false
1503/// otherwise.
1504static bool InitExprContainsUninitializedFields(const Stmt *S,
1505                                                const ValueDecl *LhsField,
1506                                                SourceLocation *L) {
1507  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1508
1509  if (isa<CallExpr>(S)) {
1510    // Do not descend into function calls or constructors, as the use
1511    // of an uninitialized field may be valid. One would have to inspect
1512    // the contents of the function/ctor to determine if it is safe or not.
1513    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1514    // may be safe, depending on what the function/ctor does.
1515    return false;
1516  }
1517  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1518    const NamedDecl *RhsField = ME->getMemberDecl();
1519
1520    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1521      // The member expression points to a static data member.
1522      assert(VD->isStaticDataMember() &&
1523             "Member points to non-static data member!");
1524      (void)VD;
1525      return false;
1526    }
1527
1528    if (isa<EnumConstantDecl>(RhsField)) {
1529      // The member expression points to an enum.
1530      return false;
1531    }
1532
1533    if (RhsField == LhsField) {
1534      // Initializing a field with itself. Throw a warning.
1535      // But wait; there are exceptions!
1536      // Exception #1:  The field may not belong to this record.
1537      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1538      const Expr *base = ME->getBase();
1539      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1540        // Even though the field matches, it does not belong to this record.
1541        return false;
1542      }
1543      // None of the exceptions triggered; return true to indicate an
1544      // uninitialized field was used.
1545      *L = ME->getMemberLoc();
1546      return true;
1547    }
1548  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1549    // sizeof/alignof doesn't reference contents, do not warn.
1550    return false;
1551  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1552    // address-of doesn't reference contents (the pointer may be dereferenced
1553    // in the same expression but it would be rare; and weird).
1554    if (UOE->getOpcode() == UO_AddrOf)
1555      return false;
1556  }
1557  for (Stmt::const_child_range it = S->children(); it; ++it) {
1558    if (!*it) {
1559      // An expression such as 'member(arg ?: "")' may trigger this.
1560      continue;
1561    }
1562    if (InitExprContainsUninitializedFields(*it, LhsField, L))
1563      return true;
1564  }
1565  return false;
1566}
1567
1568MemInitResult
1569Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1570                             unsigned NumArgs, SourceLocation IdLoc,
1571                             SourceLocation LParenLoc,
1572                             SourceLocation RParenLoc) {
1573  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1574  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1575  assert((DirectMember || IndirectMember) &&
1576         "Member must be a FieldDecl or IndirectFieldDecl");
1577
1578  if (Member->isInvalidDecl())
1579    return true;
1580
1581  // Diagnose value-uses of fields to initialize themselves, e.g.
1582  //   foo(foo)
1583  // where foo is not also a parameter to the constructor.
1584  // TODO: implement -Wuninitialized and fold this into that framework.
1585  for (unsigned i = 0; i < NumArgs; ++i) {
1586    SourceLocation L;
1587    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1588      // FIXME: Return true in the case when other fields are used before being
1589      // uninitialized. For example, let this field be the i'th field. When
1590      // initializing the i'th field, throw a warning if any of the >= i'th
1591      // fields are used, as they are not yet initialized.
1592      // Right now we are only handling the case where the i'th field uses
1593      // itself in its initializer.
1594      Diag(L, diag::warn_field_is_uninit);
1595    }
1596  }
1597
1598  bool HasDependentArg = false;
1599  for (unsigned i = 0; i < NumArgs; i++)
1600    HasDependentArg |= Args[i]->isTypeDependent();
1601
1602  Expr *Init;
1603  if (Member->getType()->isDependentType() || HasDependentArg) {
1604    // Can't check initialization for a member of dependent type or when
1605    // any of the arguments are type-dependent expressions.
1606    Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1607                                       RParenLoc,
1608                                       Member->getType().getNonReferenceType());
1609
1610    DiscardCleanupsInEvaluationContext();
1611  } else {
1612    // Initialize the member.
1613    InitializedEntity MemberEntity =
1614      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1615                   : InitializedEntity::InitializeMember(IndirectMember, 0);
1616    InitializationKind Kind =
1617      InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1618
1619    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1620
1621    ExprResult MemberInit =
1622      InitSeq.Perform(*this, MemberEntity, Kind,
1623                      MultiExprArg(*this, Args, NumArgs), 0);
1624    if (MemberInit.isInvalid())
1625      return true;
1626
1627    CheckImplicitConversions(MemberInit.get(), LParenLoc);
1628
1629    // C++0x [class.base.init]p7:
1630    //   The initialization of each base and member constitutes a
1631    //   full-expression.
1632    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1633    if (MemberInit.isInvalid())
1634      return true;
1635
1636    // If we are in a dependent context, template instantiation will
1637    // perform this type-checking again. Just save the arguments that we
1638    // received in a ParenListExpr.
1639    // FIXME: This isn't quite ideal, since our ASTs don't capture all
1640    // of the information that we have about the member
1641    // initializer. However, deconstructing the ASTs is a dicey process,
1642    // and this approach is far more likely to get the corner cases right.
1643    if (CurContext->isDependentContext())
1644      Init = new (Context) ParenListExpr(
1645          Context, LParenLoc, Args, NumArgs, RParenLoc,
1646          Member->getType().getNonReferenceType());
1647    else
1648      Init = MemberInit.get();
1649  }
1650
1651  if (DirectMember) {
1652    return new (Context) CXXCtorInitializer(Context, DirectMember,
1653                                                    IdLoc, LParenLoc, Init,
1654                                                    RParenLoc);
1655  } else {
1656    return new (Context) CXXCtorInitializer(Context, IndirectMember,
1657                                                    IdLoc, LParenLoc, Init,
1658                                                    RParenLoc);
1659  }
1660}
1661
1662MemInitResult
1663Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1664                                 Expr **Args, unsigned NumArgs,
1665                                 SourceLocation NameLoc,
1666                                 SourceLocation LParenLoc,
1667                                 SourceLocation RParenLoc,
1668                                 CXXRecordDecl *ClassDecl) {
1669  SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1670  if (!LangOpts.CPlusPlus0x)
1671    return Diag(Loc, diag::err_delegation_0x_only)
1672      << TInfo->getTypeLoc().getLocalSourceRange();
1673
1674  // Initialize the object.
1675  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1676                                     QualType(ClassDecl->getTypeForDecl(), 0));
1677  InitializationKind Kind =
1678    InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1679
1680  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1681
1682  ExprResult DelegationInit =
1683    InitSeq.Perform(*this, DelegationEntity, Kind,
1684                    MultiExprArg(*this, Args, NumArgs), 0);
1685  if (DelegationInit.isInvalid())
1686    return true;
1687
1688  CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1689  CXXConstructorDecl *Constructor
1690    = ConExpr->getConstructor();
1691  assert(Constructor && "Delegating constructor with no target?");
1692
1693  CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1694
1695  // C++0x [class.base.init]p7:
1696  //   The initialization of each base and member constitutes a
1697  //   full-expression.
1698  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1699  if (DelegationInit.isInvalid())
1700    return true;
1701
1702  assert(!CurContext->isDependentContext());
1703  return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1704                                          DelegationInit.takeAs<Expr>(),
1705                                          RParenLoc);
1706}
1707
1708MemInitResult
1709Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1710                           Expr **Args, unsigned NumArgs,
1711                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1712                           CXXRecordDecl *ClassDecl,
1713                           SourceLocation EllipsisLoc) {
1714  bool HasDependentArg = false;
1715  for (unsigned i = 0; i < NumArgs; i++)
1716    HasDependentArg |= Args[i]->isTypeDependent();
1717
1718  SourceLocation BaseLoc
1719    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1720
1721  if (!BaseType->isDependentType() && !BaseType->isRecordType())
1722    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1723             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1724
1725  // C++ [class.base.init]p2:
1726  //   [...] Unless the mem-initializer-id names a nonstatic data
1727  //   member of the constructor's class or a direct or virtual base
1728  //   of that class, the mem-initializer is ill-formed. A
1729  //   mem-initializer-list can initialize a base class using any
1730  //   name that denotes that base class type.
1731  bool Dependent = BaseType->isDependentType() || HasDependentArg;
1732
1733  if (EllipsisLoc.isValid()) {
1734    // This is a pack expansion.
1735    if (!BaseType->containsUnexpandedParameterPack())  {
1736      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1737        << SourceRange(BaseLoc, RParenLoc);
1738
1739      EllipsisLoc = SourceLocation();
1740    }
1741  } else {
1742    // Check for any unexpanded parameter packs.
1743    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1744      return true;
1745
1746    for (unsigned I = 0; I != NumArgs; ++I)
1747      if (DiagnoseUnexpandedParameterPack(Args[I]))
1748        return true;
1749  }
1750
1751  // Check for direct and virtual base classes.
1752  const CXXBaseSpecifier *DirectBaseSpec = 0;
1753  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1754  if (!Dependent) {
1755    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1756                                       BaseType))
1757      return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1758                                        LParenLoc, RParenLoc, ClassDecl);
1759
1760    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1761                        VirtualBaseSpec);
1762
1763    // C++ [base.class.init]p2:
1764    // Unless the mem-initializer-id names a nonstatic data member of the
1765    // constructor's class or a direct or virtual base of that class, the
1766    // mem-initializer is ill-formed.
1767    if (!DirectBaseSpec && !VirtualBaseSpec) {
1768      // If the class has any dependent bases, then it's possible that
1769      // one of those types will resolve to the same type as
1770      // BaseType. Therefore, just treat this as a dependent base
1771      // class initialization.  FIXME: Should we try to check the
1772      // initialization anyway? It seems odd.
1773      if (ClassDecl->hasAnyDependentBases())
1774        Dependent = true;
1775      else
1776        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1777          << BaseType << Context.getTypeDeclType(ClassDecl)
1778          << BaseTInfo->getTypeLoc().getLocalSourceRange();
1779    }
1780  }
1781
1782  if (Dependent) {
1783    // Can't check initialization for a base of dependent type or when
1784    // any of the arguments are type-dependent expressions.
1785    ExprResult BaseInit
1786      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1787                                          RParenLoc, BaseType));
1788
1789    DiscardCleanupsInEvaluationContext();
1790
1791    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1792                                                    /*IsVirtual=*/false,
1793                                                    LParenLoc,
1794                                                    BaseInit.takeAs<Expr>(),
1795                                                    RParenLoc,
1796                                                    EllipsisLoc);
1797  }
1798
1799  // C++ [base.class.init]p2:
1800  //   If a mem-initializer-id is ambiguous because it designates both
1801  //   a direct non-virtual base class and an inherited virtual base
1802  //   class, the mem-initializer is ill-formed.
1803  if (DirectBaseSpec && VirtualBaseSpec)
1804    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1805      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1806
1807  CXXBaseSpecifier *BaseSpec
1808    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1809  if (!BaseSpec)
1810    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1811
1812  // Initialize the base.
1813  InitializedEntity BaseEntity =
1814    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1815  InitializationKind Kind =
1816    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1817
1818  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1819
1820  ExprResult BaseInit =
1821    InitSeq.Perform(*this, BaseEntity, Kind,
1822                    MultiExprArg(*this, Args, NumArgs), 0);
1823  if (BaseInit.isInvalid())
1824    return true;
1825
1826  CheckImplicitConversions(BaseInit.get(), LParenLoc);
1827
1828  // C++0x [class.base.init]p7:
1829  //   The initialization of each base and member constitutes a
1830  //   full-expression.
1831  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1832  if (BaseInit.isInvalid())
1833    return true;
1834
1835  // If we are in a dependent context, template instantiation will
1836  // perform this type-checking again. Just save the arguments that we
1837  // received in a ParenListExpr.
1838  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1839  // of the information that we have about the base
1840  // initializer. However, deconstructing the ASTs is a dicey process,
1841  // and this approach is far more likely to get the corner cases right.
1842  if (CurContext->isDependentContext()) {
1843    ExprResult Init
1844      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1845                                          RParenLoc, BaseType));
1846    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1847                                                    BaseSpec->isVirtual(),
1848                                                    LParenLoc,
1849                                                    Init.takeAs<Expr>(),
1850                                                    RParenLoc,
1851                                                    EllipsisLoc);
1852  }
1853
1854  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1855                                                  BaseSpec->isVirtual(),
1856                                                  LParenLoc,
1857                                                  BaseInit.takeAs<Expr>(),
1858                                                  RParenLoc,
1859                                                  EllipsisLoc);
1860}
1861
1862/// ImplicitInitializerKind - How an implicit base or member initializer should
1863/// initialize its base or member.
1864enum ImplicitInitializerKind {
1865  IIK_Default,
1866  IIK_Copy,
1867  IIK_Move
1868};
1869
1870static bool
1871BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1872                             ImplicitInitializerKind ImplicitInitKind,
1873                             CXXBaseSpecifier *BaseSpec,
1874                             bool IsInheritedVirtualBase,
1875                             CXXCtorInitializer *&CXXBaseInit) {
1876  InitializedEntity InitEntity
1877    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1878                                        IsInheritedVirtualBase);
1879
1880  ExprResult BaseInit;
1881
1882  switch (ImplicitInitKind) {
1883  case IIK_Default: {
1884    InitializationKind InitKind
1885      = InitializationKind::CreateDefault(Constructor->getLocation());
1886    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1887    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1888                               MultiExprArg(SemaRef, 0, 0));
1889    break;
1890  }
1891
1892  case IIK_Copy: {
1893    ParmVarDecl *Param = Constructor->getParamDecl(0);
1894    QualType ParamType = Param->getType().getNonReferenceType();
1895
1896    Expr *CopyCtorArg =
1897      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1898                          Constructor->getLocation(), ParamType,
1899                          VK_LValue, 0);
1900
1901    // Cast to the base class to avoid ambiguities.
1902    QualType ArgTy =
1903      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1904                                       ParamType.getQualifiers());
1905
1906    CXXCastPath BasePath;
1907    BasePath.push_back(BaseSpec);
1908    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1909                                            CK_UncheckedDerivedToBase,
1910                                            VK_LValue, &BasePath).take();
1911
1912    InitializationKind InitKind
1913      = InitializationKind::CreateDirect(Constructor->getLocation(),
1914                                         SourceLocation(), SourceLocation());
1915    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1916                                   &CopyCtorArg, 1);
1917    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1918                               MultiExprArg(&CopyCtorArg, 1));
1919    break;
1920  }
1921
1922  case IIK_Move:
1923    assert(false && "Unhandled initializer kind!");
1924  }
1925
1926  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
1927  if (BaseInit.isInvalid())
1928    return true;
1929
1930  CXXBaseInit =
1931    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
1932               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1933                                                        SourceLocation()),
1934                                             BaseSpec->isVirtual(),
1935                                             SourceLocation(),
1936                                             BaseInit.takeAs<Expr>(),
1937                                             SourceLocation(),
1938                                             SourceLocation());
1939
1940  return false;
1941}
1942
1943static bool
1944BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1945                               ImplicitInitializerKind ImplicitInitKind,
1946                               FieldDecl *Field,
1947                               CXXCtorInitializer *&CXXMemberInit) {
1948  if (Field->isInvalidDecl())
1949    return true;
1950
1951  SourceLocation Loc = Constructor->getLocation();
1952
1953  if (ImplicitInitKind == IIK_Copy) {
1954    ParmVarDecl *Param = Constructor->getParamDecl(0);
1955    QualType ParamType = Param->getType().getNonReferenceType();
1956
1957    // Suppress copying zero-width bitfields.
1958    if (const Expr *Width = Field->getBitWidth())
1959      if (Width->EvaluateAsInt(SemaRef.Context) == 0)
1960        return false;
1961
1962    Expr *MemberExprBase =
1963      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1964                          Loc, ParamType, VK_LValue, 0);
1965
1966    // Build a reference to this field within the parameter.
1967    CXXScopeSpec SS;
1968    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1969                              Sema::LookupMemberName);
1970    MemberLookup.addDecl(Field, AS_public);
1971    MemberLookup.resolveKind();
1972    ExprResult CopyCtorArg
1973      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
1974                                         ParamType, Loc,
1975                                         /*IsArrow=*/false,
1976                                         SS,
1977                                         /*FirstQualifierInScope=*/0,
1978                                         MemberLookup,
1979                                         /*TemplateArgs=*/0);
1980    if (CopyCtorArg.isInvalid())
1981      return true;
1982
1983    // When the field we are copying is an array, create index variables for
1984    // each dimension of the array. We use these index variables to subscript
1985    // the source array, and other clients (e.g., CodeGen) will perform the
1986    // necessary iteration with these index variables.
1987    llvm::SmallVector<VarDecl *, 4> IndexVariables;
1988    QualType BaseType = Field->getType();
1989    QualType SizeType = SemaRef.Context.getSizeType();
1990    while (const ConstantArrayType *Array
1991                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1992      // Create the iteration variable for this array index.
1993      IdentifierInfo *IterationVarName = 0;
1994      {
1995        llvm::SmallString<8> Str;
1996        llvm::raw_svector_ostream OS(Str);
1997        OS << "__i" << IndexVariables.size();
1998        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1999      }
2000      VarDecl *IterationVar
2001        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2002                          IterationVarName, SizeType,
2003                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2004                          SC_None, SC_None);
2005      IndexVariables.push_back(IterationVar);
2006
2007      // Create a reference to the iteration variable.
2008      ExprResult IterationVarRef
2009        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2010      assert(!IterationVarRef.isInvalid() &&
2011             "Reference to invented variable cannot fail!");
2012
2013      // Subscript the array with this iteration variable.
2014      CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
2015                                                            Loc,
2016                                                        IterationVarRef.take(),
2017                                                            Loc);
2018      if (CopyCtorArg.isInvalid())
2019        return true;
2020
2021      BaseType = Array->getElementType();
2022    }
2023
2024    // Construct the entity that we will be initializing. For an array, this
2025    // will be first element in the array, which may require several levels
2026    // of array-subscript entities.
2027    llvm::SmallVector<InitializedEntity, 4> Entities;
2028    Entities.reserve(1 + IndexVariables.size());
2029    Entities.push_back(InitializedEntity::InitializeMember(Field));
2030    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2031      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2032                                                              0,
2033                                                              Entities.back()));
2034
2035    // Direct-initialize to use the copy constructor.
2036    InitializationKind InitKind =
2037      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2038
2039    Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2040    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2041                                   &CopyCtorArgE, 1);
2042
2043    ExprResult MemberInit
2044      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2045                        MultiExprArg(&CopyCtorArgE, 1));
2046    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2047    if (MemberInit.isInvalid())
2048      return true;
2049
2050    CXXMemberInit
2051      = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
2052                                           MemberInit.takeAs<Expr>(), Loc,
2053                                           IndexVariables.data(),
2054                                           IndexVariables.size());
2055    return false;
2056  }
2057
2058  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2059
2060  QualType FieldBaseElementType =
2061    SemaRef.Context.getBaseElementType(Field->getType());
2062
2063  if (FieldBaseElementType->isRecordType()) {
2064    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
2065    InitializationKind InitKind =
2066      InitializationKind::CreateDefault(Loc);
2067
2068    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2069    ExprResult MemberInit =
2070      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2071
2072    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2073    if (MemberInit.isInvalid())
2074      return true;
2075
2076    CXXMemberInit =
2077      new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2078                                                       Field, Loc, Loc,
2079                                                       MemberInit.get(),
2080                                                       Loc);
2081    return false;
2082  }
2083
2084  if (!Field->getParent()->isUnion()) {
2085    if (FieldBaseElementType->isReferenceType()) {
2086      SemaRef.Diag(Constructor->getLocation(),
2087                   diag::err_uninitialized_member_in_ctor)
2088      << (int)Constructor->isImplicit()
2089      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2090      << 0 << Field->getDeclName();
2091      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2092      return true;
2093    }
2094
2095    if (FieldBaseElementType.isConstQualified()) {
2096      SemaRef.Diag(Constructor->getLocation(),
2097                   diag::err_uninitialized_member_in_ctor)
2098      << (int)Constructor->isImplicit()
2099      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2100      << 1 << Field->getDeclName();
2101      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2102      return true;
2103    }
2104  }
2105
2106  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2107      FieldBaseElementType->isObjCRetainableType() &&
2108      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2109      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2110    // Instant objects:
2111    //   Default-initialize Objective-C pointers to NULL.
2112    CXXMemberInit
2113      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2114                                                 Loc, Loc,
2115                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2116                                                 Loc);
2117    return false;
2118  }
2119
2120  // Nothing to initialize.
2121  CXXMemberInit = 0;
2122  return false;
2123}
2124
2125namespace {
2126struct BaseAndFieldInfo {
2127  Sema &S;
2128  CXXConstructorDecl *Ctor;
2129  bool AnyErrorsInInits;
2130  ImplicitInitializerKind IIK;
2131  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2132  llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
2133
2134  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2135    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2136    // FIXME: Handle implicit move constructors.
2137    if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2138      IIK = IIK_Copy;
2139    else
2140      IIK = IIK_Default;
2141  }
2142};
2143}
2144
2145static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2146                                    FieldDecl *Top, FieldDecl *Field) {
2147
2148  // Overwhelmingly common case: we have a direct initializer for this field.
2149  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2150    Info.AllToInit.push_back(Init);
2151    return false;
2152  }
2153
2154  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2155  // has a brace-or-equal-initializer, the entity is initialized as specified
2156  // in [dcl.init].
2157  if (Field->hasInClassInitializer()) {
2158    Info.AllToInit.push_back(
2159      new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2160                                               SourceLocation(),
2161                                               SourceLocation(), 0,
2162                                               SourceLocation()));
2163    return false;
2164  }
2165
2166  if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2167    const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2168    assert(FieldClassType && "anonymous struct/union without record type");
2169    CXXRecordDecl *FieldClassDecl
2170      = cast<CXXRecordDecl>(FieldClassType->getDecl());
2171
2172    // Even though union members never have non-trivial default
2173    // constructions in C++03, we still build member initializers for aggregate
2174    // record types which can be union members, and C++0x allows non-trivial
2175    // default constructors for union members, so we ensure that only one
2176    // member is initialized for these.
2177    if (FieldClassDecl->isUnion()) {
2178      // First check for an explicit initializer for one field.
2179      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2180           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2181        if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
2182          Info.AllToInit.push_back(Init);
2183
2184          // Once we've initialized a field of an anonymous union, the union
2185          // field in the class is also initialized, so exit immediately.
2186          return false;
2187        } else if ((*FA)->isAnonymousStructOrUnion()) {
2188          if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2189            return true;
2190        }
2191      }
2192
2193      // Fallthrough and construct a default initializer for the union as
2194      // a whole, which can call its default constructor if such a thing exists
2195      // (C++0x perhaps). FIXME: It's not clear that this is the correct
2196      // behavior going forward with C++0x, when anonymous unions there are
2197      // finalized, we should revisit this.
2198    } else {
2199      // For structs, we simply descend through to initialize all members where
2200      // necessary.
2201      for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2202           EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2203        if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2204          return true;
2205      }
2206    }
2207  }
2208
2209  // Don't try to build an implicit initializer if there were semantic
2210  // errors in any of the initializers (and therefore we might be
2211  // missing some that the user actually wrote).
2212  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2213    return false;
2214
2215  CXXCtorInitializer *Init = 0;
2216  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2217    return true;
2218
2219  if (Init)
2220    Info.AllToInit.push_back(Init);
2221
2222  return false;
2223}
2224
2225bool
2226Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2227                               CXXCtorInitializer *Initializer) {
2228  assert(Initializer->isDelegatingInitializer());
2229  Constructor->setNumCtorInitializers(1);
2230  CXXCtorInitializer **initializer =
2231    new (Context) CXXCtorInitializer*[1];
2232  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2233  Constructor->setCtorInitializers(initializer);
2234
2235  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2236    MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2237    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2238  }
2239
2240  DelegatingCtorDecls.push_back(Constructor);
2241
2242  return false;
2243}
2244
2245bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2246                               CXXCtorInitializer **Initializers,
2247                               unsigned NumInitializers,
2248                               bool AnyErrors) {
2249  if (Constructor->getDeclContext()->isDependentContext()) {
2250    // Just store the initializers as written, they will be checked during
2251    // instantiation.
2252    if (NumInitializers > 0) {
2253      Constructor->setNumCtorInitializers(NumInitializers);
2254      CXXCtorInitializer **baseOrMemberInitializers =
2255        new (Context) CXXCtorInitializer*[NumInitializers];
2256      memcpy(baseOrMemberInitializers, Initializers,
2257             NumInitializers * sizeof(CXXCtorInitializer*));
2258      Constructor->setCtorInitializers(baseOrMemberInitializers);
2259    }
2260
2261    return false;
2262  }
2263
2264  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2265
2266  // We need to build the initializer AST according to order of construction
2267  // and not what user specified in the Initializers list.
2268  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2269  if (!ClassDecl)
2270    return true;
2271
2272  bool HadError = false;
2273
2274  for (unsigned i = 0; i < NumInitializers; i++) {
2275    CXXCtorInitializer *Member = Initializers[i];
2276
2277    if (Member->isBaseInitializer())
2278      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2279    else
2280      Info.AllBaseFields[Member->getAnyMember()] = Member;
2281  }
2282
2283  // Keep track of the direct virtual bases.
2284  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2285  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2286       E = ClassDecl->bases_end(); I != E; ++I) {
2287    if (I->isVirtual())
2288      DirectVBases.insert(I);
2289  }
2290
2291  // Push virtual bases before others.
2292  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2293       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2294
2295    if (CXXCtorInitializer *Value
2296        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2297      Info.AllToInit.push_back(Value);
2298    } else if (!AnyErrors) {
2299      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2300      CXXCtorInitializer *CXXBaseInit;
2301      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2302                                       VBase, IsInheritedVirtualBase,
2303                                       CXXBaseInit)) {
2304        HadError = true;
2305        continue;
2306      }
2307
2308      Info.AllToInit.push_back(CXXBaseInit);
2309    }
2310  }
2311
2312  // Non-virtual bases.
2313  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2314       E = ClassDecl->bases_end(); Base != E; ++Base) {
2315    // Virtuals are in the virtual base list and already constructed.
2316    if (Base->isVirtual())
2317      continue;
2318
2319    if (CXXCtorInitializer *Value
2320          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2321      Info.AllToInit.push_back(Value);
2322    } else if (!AnyErrors) {
2323      CXXCtorInitializer *CXXBaseInit;
2324      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2325                                       Base, /*IsInheritedVirtualBase=*/false,
2326                                       CXXBaseInit)) {
2327        HadError = true;
2328        continue;
2329      }
2330
2331      Info.AllToInit.push_back(CXXBaseInit);
2332    }
2333  }
2334
2335  // Fields.
2336  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2337       E = ClassDecl->field_end(); Field != E; ++Field) {
2338    if ((*Field)->getType()->isIncompleteArrayType()) {
2339      assert(ClassDecl->hasFlexibleArrayMember() &&
2340             "Incomplete array type is not valid");
2341      continue;
2342    }
2343    if (CollectFieldInitializer(*this, Info, *Field, *Field))
2344      HadError = true;
2345  }
2346
2347  NumInitializers = Info.AllToInit.size();
2348  if (NumInitializers > 0) {
2349    Constructor->setNumCtorInitializers(NumInitializers);
2350    CXXCtorInitializer **baseOrMemberInitializers =
2351      new (Context) CXXCtorInitializer*[NumInitializers];
2352    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2353           NumInitializers * sizeof(CXXCtorInitializer*));
2354    Constructor->setCtorInitializers(baseOrMemberInitializers);
2355
2356    // Constructors implicitly reference the base and member
2357    // destructors.
2358    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2359                                           Constructor->getParent());
2360  }
2361
2362  return HadError;
2363}
2364
2365static void *GetKeyForTopLevelField(FieldDecl *Field) {
2366  // For anonymous unions, use the class declaration as the key.
2367  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2368    if (RT->getDecl()->isAnonymousStructOrUnion())
2369      return static_cast<void *>(RT->getDecl());
2370  }
2371  return static_cast<void *>(Field);
2372}
2373
2374static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2375  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2376}
2377
2378static void *GetKeyForMember(ASTContext &Context,
2379                             CXXCtorInitializer *Member) {
2380  if (!Member->isAnyMemberInitializer())
2381    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2382
2383  // For fields injected into the class via declaration of an anonymous union,
2384  // use its anonymous union class declaration as the unique key.
2385  FieldDecl *Field = Member->getAnyMember();
2386
2387  // If the field is a member of an anonymous struct or union, our key
2388  // is the anonymous record decl that's a direct child of the class.
2389  RecordDecl *RD = Field->getParent();
2390  if (RD->isAnonymousStructOrUnion()) {
2391    while (true) {
2392      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2393      if (Parent->isAnonymousStructOrUnion())
2394        RD = Parent;
2395      else
2396        break;
2397    }
2398
2399    return static_cast<void *>(RD);
2400  }
2401
2402  return static_cast<void *>(Field);
2403}
2404
2405static void
2406DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2407                                  const CXXConstructorDecl *Constructor,
2408                                  CXXCtorInitializer **Inits,
2409                                  unsigned NumInits) {
2410  if (Constructor->getDeclContext()->isDependentContext())
2411    return;
2412
2413  // Don't check initializers order unless the warning is enabled at the
2414  // location of at least one initializer.
2415  bool ShouldCheckOrder = false;
2416  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2417    CXXCtorInitializer *Init = Inits[InitIndex];
2418    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2419                                         Init->getSourceLocation())
2420          != Diagnostic::Ignored) {
2421      ShouldCheckOrder = true;
2422      break;
2423    }
2424  }
2425  if (!ShouldCheckOrder)
2426    return;
2427
2428  // Build the list of bases and members in the order that they'll
2429  // actually be initialized.  The explicit initializers should be in
2430  // this same order but may be missing things.
2431  llvm::SmallVector<const void*, 32> IdealInitKeys;
2432
2433  const CXXRecordDecl *ClassDecl = Constructor->getParent();
2434
2435  // 1. Virtual bases.
2436  for (CXXRecordDecl::base_class_const_iterator VBase =
2437       ClassDecl->vbases_begin(),
2438       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2439    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2440
2441  // 2. Non-virtual bases.
2442  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2443       E = ClassDecl->bases_end(); Base != E; ++Base) {
2444    if (Base->isVirtual())
2445      continue;
2446    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2447  }
2448
2449  // 3. Direct fields.
2450  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2451       E = ClassDecl->field_end(); Field != E; ++Field)
2452    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2453
2454  unsigned NumIdealInits = IdealInitKeys.size();
2455  unsigned IdealIndex = 0;
2456
2457  CXXCtorInitializer *PrevInit = 0;
2458  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2459    CXXCtorInitializer *Init = Inits[InitIndex];
2460    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2461
2462    // Scan forward to try to find this initializer in the idealized
2463    // initializers list.
2464    for (; IdealIndex != NumIdealInits; ++IdealIndex)
2465      if (InitKey == IdealInitKeys[IdealIndex])
2466        break;
2467
2468    // If we didn't find this initializer, it must be because we
2469    // scanned past it on a previous iteration.  That can only
2470    // happen if we're out of order;  emit a warning.
2471    if (IdealIndex == NumIdealInits && PrevInit) {
2472      Sema::SemaDiagnosticBuilder D =
2473        SemaRef.Diag(PrevInit->getSourceLocation(),
2474                     diag::warn_initializer_out_of_order);
2475
2476      if (PrevInit->isAnyMemberInitializer())
2477        D << 0 << PrevInit->getAnyMember()->getDeclName();
2478      else
2479        D << 1 << PrevInit->getBaseClassInfo()->getType();
2480
2481      if (Init->isAnyMemberInitializer())
2482        D << 0 << Init->getAnyMember()->getDeclName();
2483      else
2484        D << 1 << Init->getBaseClassInfo()->getType();
2485
2486      // Move back to the initializer's location in the ideal list.
2487      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2488        if (InitKey == IdealInitKeys[IdealIndex])
2489          break;
2490
2491      assert(IdealIndex != NumIdealInits &&
2492             "initializer not found in initializer list");
2493    }
2494
2495    PrevInit = Init;
2496  }
2497}
2498
2499namespace {
2500bool CheckRedundantInit(Sema &S,
2501                        CXXCtorInitializer *Init,
2502                        CXXCtorInitializer *&PrevInit) {
2503  if (!PrevInit) {
2504    PrevInit = Init;
2505    return false;
2506  }
2507
2508  if (FieldDecl *Field = Init->getMember())
2509    S.Diag(Init->getSourceLocation(),
2510           diag::err_multiple_mem_initialization)
2511      << Field->getDeclName()
2512      << Init->getSourceRange();
2513  else {
2514    const Type *BaseClass = Init->getBaseClass();
2515    assert(BaseClass && "neither field nor base");
2516    S.Diag(Init->getSourceLocation(),
2517           diag::err_multiple_base_initialization)
2518      << QualType(BaseClass, 0)
2519      << Init->getSourceRange();
2520  }
2521  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2522    << 0 << PrevInit->getSourceRange();
2523
2524  return true;
2525}
2526
2527typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2528typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2529
2530bool CheckRedundantUnionInit(Sema &S,
2531                             CXXCtorInitializer *Init,
2532                             RedundantUnionMap &Unions) {
2533  FieldDecl *Field = Init->getAnyMember();
2534  RecordDecl *Parent = Field->getParent();
2535  if (!Parent->isAnonymousStructOrUnion())
2536    return false;
2537
2538  NamedDecl *Child = Field;
2539  do {
2540    if (Parent->isUnion()) {
2541      UnionEntry &En = Unions[Parent];
2542      if (En.first && En.first != Child) {
2543        S.Diag(Init->getSourceLocation(),
2544               diag::err_multiple_mem_union_initialization)
2545          << Field->getDeclName()
2546          << Init->getSourceRange();
2547        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2548          << 0 << En.second->getSourceRange();
2549        return true;
2550      } else if (!En.first) {
2551        En.first = Child;
2552        En.second = Init;
2553      }
2554    }
2555
2556    Child = Parent;
2557    Parent = cast<RecordDecl>(Parent->getDeclContext());
2558  } while (Parent->isAnonymousStructOrUnion());
2559
2560  return false;
2561}
2562}
2563
2564/// ActOnMemInitializers - Handle the member initializers for a constructor.
2565void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2566                                SourceLocation ColonLoc,
2567                                MemInitTy **meminits, unsigned NumMemInits,
2568                                bool AnyErrors) {
2569  if (!ConstructorDecl)
2570    return;
2571
2572  AdjustDeclIfTemplate(ConstructorDecl);
2573
2574  CXXConstructorDecl *Constructor
2575    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2576
2577  if (!Constructor) {
2578    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2579    return;
2580  }
2581
2582  CXXCtorInitializer **MemInits =
2583    reinterpret_cast<CXXCtorInitializer **>(meminits);
2584
2585  // Mapping for the duplicate initializers check.
2586  // For member initializers, this is keyed with a FieldDecl*.
2587  // For base initializers, this is keyed with a Type*.
2588  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2589
2590  // Mapping for the inconsistent anonymous-union initializers check.
2591  RedundantUnionMap MemberUnions;
2592
2593  bool HadError = false;
2594  for (unsigned i = 0; i < NumMemInits; i++) {
2595    CXXCtorInitializer *Init = MemInits[i];
2596
2597    // Set the source order index.
2598    Init->setSourceOrder(i);
2599
2600    if (Init->isAnyMemberInitializer()) {
2601      FieldDecl *Field = Init->getAnyMember();
2602      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2603          CheckRedundantUnionInit(*this, Init, MemberUnions))
2604        HadError = true;
2605    } else if (Init->isBaseInitializer()) {
2606      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2607      if (CheckRedundantInit(*this, Init, Members[Key]))
2608        HadError = true;
2609    } else {
2610      assert(Init->isDelegatingInitializer());
2611      // This must be the only initializer
2612      if (i != 0 || NumMemInits > 1) {
2613        Diag(MemInits[0]->getSourceLocation(),
2614             diag::err_delegating_initializer_alone)
2615          << MemInits[0]->getSourceRange();
2616        HadError = true;
2617        // We will treat this as being the only initializer.
2618      }
2619      SetDelegatingInitializer(Constructor, MemInits[i]);
2620      // Return immediately as the initializer is set.
2621      return;
2622    }
2623  }
2624
2625  if (HadError)
2626    return;
2627
2628  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2629
2630  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2631}
2632
2633void
2634Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2635                                             CXXRecordDecl *ClassDecl) {
2636  // Ignore dependent contexts.
2637  if (ClassDecl->isDependentContext())
2638    return;
2639
2640  // FIXME: all the access-control diagnostics are positioned on the
2641  // field/base declaration.  That's probably good; that said, the
2642  // user might reasonably want to know why the destructor is being
2643  // emitted, and we currently don't say.
2644
2645  // Non-static data members.
2646  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2647       E = ClassDecl->field_end(); I != E; ++I) {
2648    FieldDecl *Field = *I;
2649    if (Field->isInvalidDecl())
2650      continue;
2651    QualType FieldType = Context.getBaseElementType(Field->getType());
2652
2653    const RecordType* RT = FieldType->getAs<RecordType>();
2654    if (!RT)
2655      continue;
2656
2657    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2658    if (FieldClassDecl->isInvalidDecl())
2659      continue;
2660    if (FieldClassDecl->hasTrivialDestructor())
2661      continue;
2662
2663    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2664    assert(Dtor && "No dtor found for FieldClassDecl!");
2665    CheckDestructorAccess(Field->getLocation(), Dtor,
2666                          PDiag(diag::err_access_dtor_field)
2667                            << Field->getDeclName()
2668                            << FieldType);
2669
2670    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2671  }
2672
2673  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2674
2675  // Bases.
2676  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2677       E = ClassDecl->bases_end(); Base != E; ++Base) {
2678    // Bases are always records in a well-formed non-dependent class.
2679    const RecordType *RT = Base->getType()->getAs<RecordType>();
2680
2681    // Remember direct virtual bases.
2682    if (Base->isVirtual())
2683      DirectVirtualBases.insert(RT);
2684
2685    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2686    // If our base class is invalid, we probably can't get its dtor anyway.
2687    if (BaseClassDecl->isInvalidDecl())
2688      continue;
2689    // Ignore trivial destructors.
2690    if (BaseClassDecl->hasTrivialDestructor())
2691      continue;
2692
2693    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2694    assert(Dtor && "No dtor found for BaseClassDecl!");
2695
2696    // FIXME: caret should be on the start of the class name
2697    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2698                          PDiag(diag::err_access_dtor_base)
2699                            << Base->getType()
2700                            << Base->getSourceRange());
2701
2702    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2703  }
2704
2705  // Virtual bases.
2706  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2707       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2708
2709    // Bases are always records in a well-formed non-dependent class.
2710    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2711
2712    // Ignore direct virtual bases.
2713    if (DirectVirtualBases.count(RT))
2714      continue;
2715
2716    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2717    // If our base class is invalid, we probably can't get its dtor anyway.
2718    if (BaseClassDecl->isInvalidDecl())
2719      continue;
2720    // Ignore trivial destructors.
2721    if (BaseClassDecl->hasTrivialDestructor())
2722      continue;
2723
2724    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2725    assert(Dtor && "No dtor found for BaseClassDecl!");
2726    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2727                          PDiag(diag::err_access_dtor_vbase)
2728                            << VBase->getType());
2729
2730    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2731  }
2732}
2733
2734void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2735  if (!CDtorDecl)
2736    return;
2737
2738  if (CXXConstructorDecl *Constructor
2739      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2740    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2741}
2742
2743bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2744                                  unsigned DiagID, AbstractDiagSelID SelID) {
2745  if (SelID == -1)
2746    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2747  else
2748    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2749}
2750
2751bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2752                                  const PartialDiagnostic &PD) {
2753  if (!getLangOptions().CPlusPlus)
2754    return false;
2755
2756  if (const ArrayType *AT = Context.getAsArrayType(T))
2757    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2758
2759  if (const PointerType *PT = T->getAs<PointerType>()) {
2760    // Find the innermost pointer type.
2761    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2762      PT = T;
2763
2764    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2765      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2766  }
2767
2768  const RecordType *RT = T->getAs<RecordType>();
2769  if (!RT)
2770    return false;
2771
2772  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2773
2774  // We can't answer whether something is abstract until it has a
2775  // definition.  If it's currently being defined, we'll walk back
2776  // over all the declarations when we have a full definition.
2777  const CXXRecordDecl *Def = RD->getDefinition();
2778  if (!Def || Def->isBeingDefined())
2779    return false;
2780
2781  if (!RD->isAbstract())
2782    return false;
2783
2784  Diag(Loc, PD) << RD->getDeclName();
2785  DiagnoseAbstractType(RD);
2786
2787  return true;
2788}
2789
2790void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2791  // Check if we've already emitted the list of pure virtual functions
2792  // for this class.
2793  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2794    return;
2795
2796  CXXFinalOverriderMap FinalOverriders;
2797  RD->getFinalOverriders(FinalOverriders);
2798
2799  // Keep a set of seen pure methods so we won't diagnose the same method
2800  // more than once.
2801  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2802
2803  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2804                                   MEnd = FinalOverriders.end();
2805       M != MEnd;
2806       ++M) {
2807    for (OverridingMethods::iterator SO = M->second.begin(),
2808                                  SOEnd = M->second.end();
2809         SO != SOEnd; ++SO) {
2810      // C++ [class.abstract]p4:
2811      //   A class is abstract if it contains or inherits at least one
2812      //   pure virtual function for which the final overrider is pure
2813      //   virtual.
2814
2815      //
2816      if (SO->second.size() != 1)
2817        continue;
2818
2819      if (!SO->second.front().Method->isPure())
2820        continue;
2821
2822      if (!SeenPureMethods.insert(SO->second.front().Method))
2823        continue;
2824
2825      Diag(SO->second.front().Method->getLocation(),
2826           diag::note_pure_virtual_function)
2827        << SO->second.front().Method->getDeclName() << RD->getDeclName();
2828    }
2829  }
2830
2831  if (!PureVirtualClassDiagSet)
2832    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2833  PureVirtualClassDiagSet->insert(RD);
2834}
2835
2836namespace {
2837struct AbstractUsageInfo {
2838  Sema &S;
2839  CXXRecordDecl *Record;
2840  CanQualType AbstractType;
2841  bool Invalid;
2842
2843  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2844    : S(S), Record(Record),
2845      AbstractType(S.Context.getCanonicalType(
2846                   S.Context.getTypeDeclType(Record))),
2847      Invalid(false) {}
2848
2849  void DiagnoseAbstractType() {
2850    if (Invalid) return;
2851    S.DiagnoseAbstractType(Record);
2852    Invalid = true;
2853  }
2854
2855  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2856};
2857
2858struct CheckAbstractUsage {
2859  AbstractUsageInfo &Info;
2860  const NamedDecl *Ctx;
2861
2862  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2863    : Info(Info), Ctx(Ctx) {}
2864
2865  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2866    switch (TL.getTypeLocClass()) {
2867#define ABSTRACT_TYPELOC(CLASS, PARENT)
2868#define TYPELOC(CLASS, PARENT) \
2869    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2870#include "clang/AST/TypeLocNodes.def"
2871    }
2872  }
2873
2874  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2875    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2876    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2877      if (!TL.getArg(I))
2878        continue;
2879
2880      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2881      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
2882    }
2883  }
2884
2885  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2886    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2887  }
2888
2889  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2890    // Visit the type parameters from a permissive context.
2891    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2892      TemplateArgumentLoc TAL = TL.getArgLoc(I);
2893      if (TAL.getArgument().getKind() == TemplateArgument::Type)
2894        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2895          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2896      // TODO: other template argument types?
2897    }
2898  }
2899
2900  // Visit pointee types from a permissive context.
2901#define CheckPolymorphic(Type) \
2902  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2903    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2904  }
2905  CheckPolymorphic(PointerTypeLoc)
2906  CheckPolymorphic(ReferenceTypeLoc)
2907  CheckPolymorphic(MemberPointerTypeLoc)
2908  CheckPolymorphic(BlockPointerTypeLoc)
2909
2910  /// Handle all the types we haven't given a more specific
2911  /// implementation for above.
2912  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2913    // Every other kind of type that we haven't called out already
2914    // that has an inner type is either (1) sugar or (2) contains that
2915    // inner type in some way as a subobject.
2916    if (TypeLoc Next = TL.getNextTypeLoc())
2917      return Visit(Next, Sel);
2918
2919    // If there's no inner type and we're in a permissive context,
2920    // don't diagnose.
2921    if (Sel == Sema::AbstractNone) return;
2922
2923    // Check whether the type matches the abstract type.
2924    QualType T = TL.getType();
2925    if (T->isArrayType()) {
2926      Sel = Sema::AbstractArrayType;
2927      T = Info.S.Context.getBaseElementType(T);
2928    }
2929    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2930    if (CT != Info.AbstractType) return;
2931
2932    // It matched; do some magic.
2933    if (Sel == Sema::AbstractArrayType) {
2934      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2935        << T << TL.getSourceRange();
2936    } else {
2937      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2938        << Sel << T << TL.getSourceRange();
2939    }
2940    Info.DiagnoseAbstractType();
2941  }
2942};
2943
2944void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2945                                  Sema::AbstractDiagSelID Sel) {
2946  CheckAbstractUsage(*this, D).Visit(TL, Sel);
2947}
2948
2949}
2950
2951/// Check for invalid uses of an abstract type in a method declaration.
2952static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2953                                    CXXMethodDecl *MD) {
2954  // No need to do the check on definitions, which require that
2955  // the return/param types be complete.
2956  if (MD->doesThisDeclarationHaveABody())
2957    return;
2958
2959  // For safety's sake, just ignore it if we don't have type source
2960  // information.  This should never happen for non-implicit methods,
2961  // but...
2962  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2963    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2964}
2965
2966/// Check for invalid uses of an abstract type within a class definition.
2967static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2968                                    CXXRecordDecl *RD) {
2969  for (CXXRecordDecl::decl_iterator
2970         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2971    Decl *D = *I;
2972    if (D->isImplicit()) continue;
2973
2974    // Methods and method templates.
2975    if (isa<CXXMethodDecl>(D)) {
2976      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2977    } else if (isa<FunctionTemplateDecl>(D)) {
2978      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2979      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2980
2981    // Fields and static variables.
2982    } else if (isa<FieldDecl>(D)) {
2983      FieldDecl *FD = cast<FieldDecl>(D);
2984      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2985        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2986    } else if (isa<VarDecl>(D)) {
2987      VarDecl *VD = cast<VarDecl>(D);
2988      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2989        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2990
2991    // Nested classes and class templates.
2992    } else if (isa<CXXRecordDecl>(D)) {
2993      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2994    } else if (isa<ClassTemplateDecl>(D)) {
2995      CheckAbstractClassUsage(Info,
2996                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2997    }
2998  }
2999}
3000
3001/// \brief Perform semantic checks on a class definition that has been
3002/// completing, introducing implicitly-declared members, checking for
3003/// abstract types, etc.
3004void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3005  if (!Record)
3006    return;
3007
3008  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3009    AbstractUsageInfo Info(*this, Record);
3010    CheckAbstractClassUsage(Info, Record);
3011  }
3012
3013  // If this is not an aggregate type and has no user-declared constructor,
3014  // complain about any non-static data members of reference or const scalar
3015  // type, since they will never get initializers.
3016  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3017      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3018    bool Complained = false;
3019    for (RecordDecl::field_iterator F = Record->field_begin(),
3020                                 FEnd = Record->field_end();
3021         F != FEnd; ++F) {
3022      if (F->hasInClassInitializer())
3023        continue;
3024
3025      if (F->getType()->isReferenceType() ||
3026          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3027        if (!Complained) {
3028          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3029            << Record->getTagKind() << Record;
3030          Complained = true;
3031        }
3032
3033        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3034          << F->getType()->isReferenceType()
3035          << F->getDeclName();
3036      }
3037    }
3038  }
3039
3040  if (Record->isDynamicClass() && !Record->isDependentType())
3041    DynamicClasses.push_back(Record);
3042
3043  if (Record->getIdentifier()) {
3044    // C++ [class.mem]p13:
3045    //   If T is the name of a class, then each of the following shall have a
3046    //   name different from T:
3047    //     - every member of every anonymous union that is a member of class T.
3048    //
3049    // C++ [class.mem]p14:
3050    //   In addition, if class T has a user-declared constructor (12.1), every
3051    //   non-static data member of class T shall have a name different from T.
3052    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3053         R.first != R.second; ++R.first) {
3054      NamedDecl *D = *R.first;
3055      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3056          isa<IndirectFieldDecl>(D)) {
3057        Diag(D->getLocation(), diag::err_member_name_of_class)
3058          << D->getDeclName();
3059        break;
3060      }
3061    }
3062  }
3063
3064  // Warn if the class has virtual methods but non-virtual public destructor.
3065  if (Record->isPolymorphic() && !Record->isDependentType()) {
3066    CXXDestructorDecl *dtor = Record->getDestructor();
3067    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3068      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3069           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3070  }
3071
3072  // See if a method overloads virtual methods in a base
3073  /// class without overriding any.
3074  if (!Record->isDependentType()) {
3075    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3076                                     MEnd = Record->method_end();
3077         M != MEnd; ++M) {
3078      if (!(*M)->isStatic())
3079        DiagnoseHiddenVirtualMethods(Record, *M);
3080    }
3081  }
3082
3083  // Declare inherited constructors. We do this eagerly here because:
3084  // - The standard requires an eager diagnostic for conflicting inherited
3085  //   constructors from different classes.
3086  // - The lazy declaration of the other implicit constructors is so as to not
3087  //   waste space and performance on classes that are not meant to be
3088  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3089  //   have inherited constructors.
3090  DeclareInheritedConstructors(Record);
3091
3092  if (!Record->isDependentType())
3093    CheckExplicitlyDefaultedMethods(Record);
3094}
3095
3096void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3097  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3098                                      ME = Record->method_end();
3099       MI != ME; ++MI) {
3100    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3101      switch (getSpecialMember(*MI)) {
3102      case CXXDefaultConstructor:
3103        CheckExplicitlyDefaultedDefaultConstructor(
3104                                                  cast<CXXConstructorDecl>(*MI));
3105        break;
3106
3107      case CXXDestructor:
3108        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3109        break;
3110
3111      case CXXCopyConstructor:
3112        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3113        break;
3114
3115      case CXXCopyAssignment:
3116        CheckExplicitlyDefaultedCopyAssignment(*MI);
3117        break;
3118
3119      case CXXMoveConstructor:
3120      case CXXMoveAssignment:
3121        Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3122        break;
3123
3124      default:
3125        // FIXME: Do moves once they exist
3126        llvm_unreachable("non-special member explicitly defaulted!");
3127      }
3128    }
3129  }
3130
3131}
3132
3133void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3134  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3135
3136  // Whether this was the first-declared instance of the constructor.
3137  // This affects whether we implicitly add an exception spec (and, eventually,
3138  // constexpr). It is also ill-formed to explicitly default a constructor such
3139  // that it would be deleted. (C++0x [decl.fct.def.default])
3140  bool First = CD == CD->getCanonicalDecl();
3141
3142  bool HadError = false;
3143  if (CD->getNumParams() != 0) {
3144    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3145      << CD->getSourceRange();
3146    HadError = true;
3147  }
3148
3149  ImplicitExceptionSpecification Spec
3150    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3151  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3152  if (EPI.ExceptionSpecType == EST_Delayed) {
3153    // Exception specification depends on some deferred part of the class. We'll
3154    // try again when the class's definition has been fully processed.
3155    return;
3156  }
3157  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3158                          *ExceptionType = Context.getFunctionType(
3159                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3160
3161  if (CtorType->hasExceptionSpec()) {
3162    if (CheckEquivalentExceptionSpec(
3163          PDiag(diag::err_incorrect_defaulted_exception_spec)
3164            << CXXDefaultConstructor,
3165          PDiag(),
3166          ExceptionType, SourceLocation(),
3167          CtorType, CD->getLocation())) {
3168      HadError = true;
3169    }
3170  } else if (First) {
3171    // We set the declaration to have the computed exception spec here.
3172    // We know there are no parameters.
3173    EPI.ExtInfo = CtorType->getExtInfo();
3174    CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3175  }
3176
3177  if (HadError) {
3178    CD->setInvalidDecl();
3179    return;
3180  }
3181
3182  if (ShouldDeleteDefaultConstructor(CD)) {
3183    if (First) {
3184      CD->setDeletedAsWritten();
3185    } else {
3186      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3187        << CXXDefaultConstructor;
3188      CD->setInvalidDecl();
3189    }
3190  }
3191}
3192
3193void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3194  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3195
3196  // Whether this was the first-declared instance of the constructor.
3197  bool First = CD == CD->getCanonicalDecl();
3198
3199  bool HadError = false;
3200  if (CD->getNumParams() != 1) {
3201    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3202      << CD->getSourceRange();
3203    HadError = true;
3204  }
3205
3206  ImplicitExceptionSpecification Spec(Context);
3207  bool Const;
3208  llvm::tie(Spec, Const) =
3209    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3210
3211  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3212  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3213                          *ExceptionType = Context.getFunctionType(
3214                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3215
3216  // Check for parameter type matching.
3217  // This is a copy ctor so we know it's a cv-qualified reference to T.
3218  QualType ArgType = CtorType->getArgType(0);
3219  if (ArgType->getPointeeType().isVolatileQualified()) {
3220    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3221    HadError = true;
3222  }
3223  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3224    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3225    HadError = true;
3226  }
3227
3228  if (CtorType->hasExceptionSpec()) {
3229    if (CheckEquivalentExceptionSpec(
3230          PDiag(diag::err_incorrect_defaulted_exception_spec)
3231            << CXXCopyConstructor,
3232          PDiag(),
3233          ExceptionType, SourceLocation(),
3234          CtorType, CD->getLocation())) {
3235      HadError = true;
3236    }
3237  } else if (First) {
3238    // We set the declaration to have the computed exception spec here.
3239    // We duplicate the one parameter type.
3240    EPI.ExtInfo = CtorType->getExtInfo();
3241    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3242  }
3243
3244  if (HadError) {
3245    CD->setInvalidDecl();
3246    return;
3247  }
3248
3249  if (ShouldDeleteCopyConstructor(CD)) {
3250    if (First) {
3251      CD->setDeletedAsWritten();
3252    } else {
3253      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3254        << CXXCopyConstructor;
3255      CD->setInvalidDecl();
3256    }
3257  }
3258}
3259
3260void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3261  assert(MD->isExplicitlyDefaulted());
3262
3263  // Whether this was the first-declared instance of the operator
3264  bool First = MD == MD->getCanonicalDecl();
3265
3266  bool HadError = false;
3267  if (MD->getNumParams() != 1) {
3268    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3269      << MD->getSourceRange();
3270    HadError = true;
3271  }
3272
3273  QualType ReturnType =
3274    MD->getType()->getAs<FunctionType>()->getResultType();
3275  if (!ReturnType->isLValueReferenceType() ||
3276      !Context.hasSameType(
3277        Context.getCanonicalType(ReturnType->getPointeeType()),
3278        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3279    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3280    HadError = true;
3281  }
3282
3283  ImplicitExceptionSpecification Spec(Context);
3284  bool Const;
3285  llvm::tie(Spec, Const) =
3286    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3287
3288  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3289  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3290                          *ExceptionType = Context.getFunctionType(
3291                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3292
3293  QualType ArgType = OperType->getArgType(0);
3294  if (!ArgType->isReferenceType()) {
3295    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3296    HadError = true;
3297  } else {
3298    if (ArgType->getPointeeType().isVolatileQualified()) {
3299      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3300      HadError = true;
3301    }
3302    if (ArgType->getPointeeType().isConstQualified() && !Const) {
3303      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3304      HadError = true;
3305    }
3306  }
3307
3308  if (OperType->getTypeQuals()) {
3309    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3310    HadError = true;
3311  }
3312
3313  if (OperType->hasExceptionSpec()) {
3314    if (CheckEquivalentExceptionSpec(
3315          PDiag(diag::err_incorrect_defaulted_exception_spec)
3316            << CXXCopyAssignment,
3317          PDiag(),
3318          ExceptionType, SourceLocation(),
3319          OperType, MD->getLocation())) {
3320      HadError = true;
3321    }
3322  } else if (First) {
3323    // We set the declaration to have the computed exception spec here.
3324    // We duplicate the one parameter type.
3325    EPI.RefQualifier = OperType->getRefQualifier();
3326    EPI.ExtInfo = OperType->getExtInfo();
3327    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3328  }
3329
3330  if (HadError) {
3331    MD->setInvalidDecl();
3332    return;
3333  }
3334
3335  if (ShouldDeleteCopyAssignmentOperator(MD)) {
3336    if (First) {
3337      MD->setDeletedAsWritten();
3338    } else {
3339      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3340        << CXXCopyAssignment;
3341      MD->setInvalidDecl();
3342    }
3343  }
3344}
3345
3346void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3347  assert(DD->isExplicitlyDefaulted());
3348
3349  // Whether this was the first-declared instance of the destructor.
3350  bool First = DD == DD->getCanonicalDecl();
3351
3352  ImplicitExceptionSpecification Spec
3353    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3354  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3355  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3356                          *ExceptionType = Context.getFunctionType(
3357                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3358
3359  if (DtorType->hasExceptionSpec()) {
3360    if (CheckEquivalentExceptionSpec(
3361          PDiag(diag::err_incorrect_defaulted_exception_spec)
3362            << CXXDestructor,
3363          PDiag(),
3364          ExceptionType, SourceLocation(),
3365          DtorType, DD->getLocation())) {
3366      DD->setInvalidDecl();
3367      return;
3368    }
3369  } else if (First) {
3370    // We set the declaration to have the computed exception spec here.
3371    // There are no parameters.
3372    EPI.ExtInfo = DtorType->getExtInfo();
3373    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3374  }
3375
3376  if (ShouldDeleteDestructor(DD)) {
3377    if (First) {
3378      DD->setDeletedAsWritten();
3379    } else {
3380      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3381        << CXXDestructor;
3382      DD->setInvalidDecl();
3383    }
3384  }
3385}
3386
3387bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3388  CXXRecordDecl *RD = CD->getParent();
3389  assert(!RD->isDependentType() && "do deletion after instantiation");
3390  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3391    return false;
3392
3393  SourceLocation Loc = CD->getLocation();
3394
3395  // Do access control from the constructor
3396  ContextRAII CtorContext(*this, CD);
3397
3398  bool Union = RD->isUnion();
3399  bool AllConst = true;
3400
3401  // We do this because we should never actually use an anonymous
3402  // union's constructor.
3403  if (Union && RD->isAnonymousStructOrUnion())
3404    return false;
3405
3406  // FIXME: We should put some diagnostic logic right into this function.
3407
3408  // C++0x [class.ctor]/5
3409  //    A defaulted default constructor for class X is defined as deleted if:
3410
3411  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3412                                          BE = RD->bases_end();
3413       BI != BE; ++BI) {
3414    // We'll handle this one later
3415    if (BI->isVirtual())
3416      continue;
3417
3418    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3419    assert(BaseDecl && "base isn't a CXXRecordDecl");
3420
3421    // -- any [direct base class] has a type with a destructor that is
3422    //    deleted or inaccessible from the defaulted default constructor
3423    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3424    if (BaseDtor->isDeleted())
3425      return true;
3426    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3427        AR_accessible)
3428      return true;
3429
3430    // -- any [direct base class either] has no default constructor or
3431    //    overload resolution as applied to [its] default constructor
3432    //    results in an ambiguity or in a function that is deleted or
3433    //    inaccessible from the defaulted default constructor
3434    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3435    if (!BaseDefault || BaseDefault->isDeleted())
3436      return true;
3437
3438    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3439                               PDiag()) != AR_accessible)
3440      return true;
3441  }
3442
3443  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3444                                          BE = RD->vbases_end();
3445       BI != BE; ++BI) {
3446    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3447    assert(BaseDecl && "base isn't a CXXRecordDecl");
3448
3449    // -- any [virtual base class] has a type with a destructor that is
3450    //    delete or inaccessible from the defaulted default constructor
3451    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3452    if (BaseDtor->isDeleted())
3453      return true;
3454    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3455        AR_accessible)
3456      return true;
3457
3458    // -- any [virtual base class either] has no default constructor or
3459    //    overload resolution as applied to [its] default constructor
3460    //    results in an ambiguity or in a function that is deleted or
3461    //    inaccessible from the defaulted default constructor
3462    CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3463    if (!BaseDefault || BaseDefault->isDeleted())
3464      return true;
3465
3466    if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3467                               PDiag()) != AR_accessible)
3468      return true;
3469  }
3470
3471  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3472                                     FE = RD->field_end();
3473       FI != FE; ++FI) {
3474    if (FI->isInvalidDecl())
3475      continue;
3476
3477    QualType FieldType = Context.getBaseElementType(FI->getType());
3478    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3479
3480    // -- any non-static data member with no brace-or-equal-initializer is of
3481    //    reference type
3482    if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3483      return true;
3484
3485    // -- X is a union and all its variant members are of const-qualified type
3486    //    (or array thereof)
3487    if (Union && !FieldType.isConstQualified())
3488      AllConst = false;
3489
3490    if (FieldRecord) {
3491      // -- X is a union-like class that has a variant member with a non-trivial
3492      //    default constructor
3493      if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3494        return true;
3495
3496      CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3497      if (FieldDtor->isDeleted())
3498        return true;
3499      if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3500          AR_accessible)
3501        return true;
3502
3503      // -- any non-variant non-static data member of const-qualified type (or
3504      //    array thereof) with no brace-or-equal-initializer does not have a
3505      //    user-provided default constructor
3506      if (FieldType.isConstQualified() &&
3507          !FI->hasInClassInitializer() &&
3508          !FieldRecord->hasUserProvidedDefaultConstructor())
3509        return true;
3510
3511      if (!Union && FieldRecord->isUnion() &&
3512          FieldRecord->isAnonymousStructOrUnion()) {
3513        // We're okay to reuse AllConst here since we only care about the
3514        // value otherwise if we're in a union.
3515        AllConst = true;
3516
3517        for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3518                                           UE = FieldRecord->field_end();
3519             UI != UE; ++UI) {
3520          QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3521          CXXRecordDecl *UnionFieldRecord =
3522            UnionFieldType->getAsCXXRecordDecl();
3523
3524          if (!UnionFieldType.isConstQualified())
3525            AllConst = false;
3526
3527          if (UnionFieldRecord &&
3528              !UnionFieldRecord->hasTrivialDefaultConstructor())
3529            return true;
3530        }
3531
3532        if (AllConst)
3533          return true;
3534
3535        // Don't try to initialize the anonymous union
3536        // This is technically non-conformant, but sanity demands it.
3537        continue;
3538      }
3539
3540      // -- any non-static data member with no brace-or-equal-initializer has
3541      //    class type M (or array thereof) and either M has no default
3542      //    constructor or overload resolution as applied to M's default
3543      //    constructor results in an ambiguity or in a function that is deleted
3544      //    or inaccessible from the defaulted default constructor.
3545      if (!FI->hasInClassInitializer()) {
3546        CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3547        if (!FieldDefault || FieldDefault->isDeleted())
3548          return true;
3549        if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3550                                   PDiag()) != AR_accessible)
3551          return true;
3552      }
3553    } else if (!Union && FieldType.isConstQualified() &&
3554               !FI->hasInClassInitializer()) {
3555      // -- any non-variant non-static data member of const-qualified type (or
3556      //    array thereof) with no brace-or-equal-initializer does not have a
3557      //    user-provided default constructor
3558      return true;
3559    }
3560  }
3561
3562  if (Union && AllConst)
3563    return true;
3564
3565  return false;
3566}
3567
3568bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3569  CXXRecordDecl *RD = CD->getParent();
3570  assert(!RD->isDependentType() && "do deletion after instantiation");
3571  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3572    return false;
3573
3574  SourceLocation Loc = CD->getLocation();
3575
3576  // Do access control from the constructor
3577  ContextRAII CtorContext(*this, CD);
3578
3579  bool Union = RD->isUnion();
3580
3581  assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3582         "copy assignment arg has no pointee type");
3583  unsigned ArgQuals =
3584    CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3585      Qualifiers::Const : 0;
3586
3587  // We do this because we should never actually use an anonymous
3588  // union's constructor.
3589  if (Union && RD->isAnonymousStructOrUnion())
3590    return false;
3591
3592  // FIXME: We should put some diagnostic logic right into this function.
3593
3594  // C++0x [class.copy]/11
3595  //    A defaulted [copy] constructor for class X is defined as delete if X has:
3596
3597  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3598                                          BE = RD->bases_end();
3599       BI != BE; ++BI) {
3600    // We'll handle this one later
3601    if (BI->isVirtual())
3602      continue;
3603
3604    QualType BaseType = BI->getType();
3605    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3606    assert(BaseDecl && "base isn't a CXXRecordDecl");
3607
3608    // -- any [direct base class] of a type with a destructor that is deleted or
3609    //    inaccessible from the defaulted constructor
3610    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3611    if (BaseDtor->isDeleted())
3612      return true;
3613    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3614        AR_accessible)
3615      return true;
3616
3617    // -- a [direct base class] B that cannot be [copied] because overload
3618    //    resolution, as applied to B's [copy] constructor, results in an
3619    //    ambiguity or a function that is deleted or inaccessible from the
3620    //    defaulted constructor
3621    CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3622    if (!BaseCtor || BaseCtor->isDeleted())
3623      return true;
3624    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3625        AR_accessible)
3626      return true;
3627  }
3628
3629  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3630                                          BE = RD->vbases_end();
3631       BI != BE; ++BI) {
3632    QualType BaseType = BI->getType();
3633    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3634    assert(BaseDecl && "base isn't a CXXRecordDecl");
3635
3636    // -- any [virtual base class] of a type with a destructor that is deleted or
3637    //    inaccessible from the defaulted constructor
3638    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3639    if (BaseDtor->isDeleted())
3640      return true;
3641    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3642        AR_accessible)
3643      return true;
3644
3645    // -- a [virtual base class] B that cannot be [copied] because overload
3646    //    resolution, as applied to B's [copy] constructor, results in an
3647    //    ambiguity or a function that is deleted or inaccessible from the
3648    //    defaulted constructor
3649    CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals);
3650    if (!BaseCtor || BaseCtor->isDeleted())
3651      return true;
3652    if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3653        AR_accessible)
3654      return true;
3655  }
3656
3657  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3658                                     FE = RD->field_end();
3659       FI != FE; ++FI) {
3660    QualType FieldType = Context.getBaseElementType(FI->getType());
3661
3662    // -- for a copy constructor, a non-static data member of rvalue reference
3663    //    type
3664    if (FieldType->isRValueReferenceType())
3665      return true;
3666
3667    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3668
3669    if (FieldRecord) {
3670      // This is an anonymous union
3671      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3672        // Anonymous unions inside unions do not variant members create
3673        if (!Union) {
3674          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3675                                             UE = FieldRecord->field_end();
3676               UI != UE; ++UI) {
3677            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3678            CXXRecordDecl *UnionFieldRecord =
3679              UnionFieldType->getAsCXXRecordDecl();
3680
3681            // -- a variant member with a non-trivial [copy] constructor and X
3682            //    is a union-like class
3683            if (UnionFieldRecord &&
3684                !UnionFieldRecord->hasTrivialCopyConstructor())
3685              return true;
3686          }
3687        }
3688
3689        // Don't try to initalize an anonymous union
3690        continue;
3691      } else {
3692         // -- a variant member with a non-trivial [copy] constructor and X is a
3693         //    union-like class
3694        if (Union && !FieldRecord->hasTrivialCopyConstructor())
3695          return true;
3696
3697        // -- any [non-static data member] of a type with a destructor that is
3698        //    deleted or inaccessible from the defaulted constructor
3699        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3700        if (FieldDtor->isDeleted())
3701          return true;
3702        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3703            AR_accessible)
3704          return true;
3705      }
3706
3707    // -- a [non-static data member of class type (or array thereof)] B that
3708    //    cannot be [copied] because overload resolution, as applied to B's
3709    //    [copy] constructor, results in an ambiguity or a function that is
3710    //    deleted or inaccessible from the defaulted constructor
3711      CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord,
3712                                                               ArgQuals);
3713      if (!FieldCtor || FieldCtor->isDeleted())
3714        return true;
3715      if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3716                                 PDiag()) != AR_accessible)
3717        return true;
3718    }
3719  }
3720
3721  return false;
3722}
3723
3724bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3725  CXXRecordDecl *RD = MD->getParent();
3726  assert(!RD->isDependentType() && "do deletion after instantiation");
3727  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3728    return false;
3729
3730  SourceLocation Loc = MD->getLocation();
3731
3732  // Do access control from the constructor
3733  ContextRAII MethodContext(*this, MD);
3734
3735  bool Union = RD->isUnion();
3736
3737  unsigned ArgQuals =
3738    MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3739      Qualifiers::Const : 0;
3740
3741  // We do this because we should never actually use an anonymous
3742  // union's constructor.
3743  if (Union && RD->isAnonymousStructOrUnion())
3744    return false;
3745
3746  // FIXME: We should put some diagnostic logic right into this function.
3747
3748  // C++0x [class.copy]/11
3749  //    A defaulted [copy] assignment operator for class X is defined as deleted
3750  //    if X has:
3751
3752  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3753                                          BE = RD->bases_end();
3754       BI != BE; ++BI) {
3755    // We'll handle this one later
3756    if (BI->isVirtual())
3757      continue;
3758
3759    QualType BaseType = BI->getType();
3760    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3761    assert(BaseDecl && "base isn't a CXXRecordDecl");
3762
3763    // -- a [direct base class] B that cannot be [copied] because overload
3764    //    resolution, as applied to B's [copy] assignment operator, results in
3765    //    an ambiguity or a function that is deleted or inaccessible from the
3766    //    assignment operator
3767    CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3768                                                      0);
3769    if (!CopyOper || CopyOper->isDeleted())
3770      return true;
3771    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3772      return true;
3773  }
3774
3775  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3776                                          BE = RD->vbases_end();
3777       BI != BE; ++BI) {
3778    QualType BaseType = BI->getType();
3779    CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3780    assert(BaseDecl && "base isn't a CXXRecordDecl");
3781
3782    // -- a [virtual base class] B that cannot be [copied] because overload
3783    //    resolution, as applied to B's [copy] assignment operator, results in
3784    //    an ambiguity or a function that is deleted or inaccessible from the
3785    //    assignment operator
3786    CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
3787                                                      0);
3788    if (!CopyOper || CopyOper->isDeleted())
3789      return true;
3790    if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3791      return true;
3792  }
3793
3794  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3795                                     FE = RD->field_end();
3796       FI != FE; ++FI) {
3797    QualType FieldType = Context.getBaseElementType(FI->getType());
3798
3799    // -- a non-static data member of reference type
3800    if (FieldType->isReferenceType())
3801      return true;
3802
3803    // -- a non-static data member of const non-class type (or array thereof)
3804    if (FieldType.isConstQualified() && !FieldType->isRecordType())
3805      return true;
3806
3807    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3808
3809    if (FieldRecord) {
3810      // This is an anonymous union
3811      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3812        // Anonymous unions inside unions do not variant members create
3813        if (!Union) {
3814          for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3815                                             UE = FieldRecord->field_end();
3816               UI != UE; ++UI) {
3817            QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3818            CXXRecordDecl *UnionFieldRecord =
3819              UnionFieldType->getAsCXXRecordDecl();
3820
3821            // -- a variant member with a non-trivial [copy] assignment operator
3822            //    and X is a union-like class
3823            if (UnionFieldRecord &&
3824                !UnionFieldRecord->hasTrivialCopyAssignment())
3825              return true;
3826          }
3827        }
3828
3829        // Don't try to initalize an anonymous union
3830        continue;
3831      // -- a variant member with a non-trivial [copy] assignment operator
3832      //    and X is a union-like class
3833      } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3834          return true;
3835      }
3836
3837      CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
3838                                                        false, 0);
3839      if (!CopyOper || CopyOper->isDeleted())
3840        return false;
3841      if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
3842        return false;
3843    }
3844  }
3845
3846  return false;
3847}
3848
3849bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3850  CXXRecordDecl *RD = DD->getParent();
3851  assert(!RD->isDependentType() && "do deletion after instantiation");
3852  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
3853    return false;
3854
3855  SourceLocation Loc = DD->getLocation();
3856
3857  // Do access control from the destructor
3858  ContextRAII CtorContext(*this, DD);
3859
3860  bool Union = RD->isUnion();
3861
3862  // We do this because we should never actually use an anonymous
3863  // union's destructor.
3864  if (Union && RD->isAnonymousStructOrUnion())
3865    return false;
3866
3867  // C++0x [class.dtor]p5
3868  //    A defaulted destructor for a class X is defined as deleted if:
3869  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3870                                          BE = RD->bases_end();
3871       BI != BE; ++BI) {
3872    // We'll handle this one later
3873    if (BI->isVirtual())
3874      continue;
3875
3876    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3877    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3878    assert(BaseDtor && "base has no destructor");
3879
3880    // -- any direct or virtual base class has a deleted destructor or
3881    //    a destructor that is inaccessible from the defaulted destructor
3882    if (BaseDtor->isDeleted())
3883      return true;
3884    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3885        AR_accessible)
3886      return true;
3887  }
3888
3889  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3890                                          BE = RD->vbases_end();
3891       BI != BE; ++BI) {
3892    CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3893    CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3894    assert(BaseDtor && "base has no destructor");
3895
3896    // -- any direct or virtual base class has a deleted destructor or
3897    //    a destructor that is inaccessible from the defaulted destructor
3898    if (BaseDtor->isDeleted())
3899      return true;
3900    if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3901        AR_accessible)
3902      return true;
3903  }
3904
3905  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3906                                     FE = RD->field_end();
3907       FI != FE; ++FI) {
3908    QualType FieldType = Context.getBaseElementType(FI->getType());
3909    CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3910    if (FieldRecord) {
3911      if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3912         for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3913                                            UE = FieldRecord->field_end();
3914              UI != UE; ++UI) {
3915           QualType UnionFieldType = Context.getBaseElementType(FI->getType());
3916           CXXRecordDecl *UnionFieldRecord =
3917             UnionFieldType->getAsCXXRecordDecl();
3918
3919           // -- X is a union-like class that has a variant member with a non-
3920           //    trivial destructor.
3921           if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
3922             return true;
3923         }
3924      // Technically we are supposed to do this next check unconditionally.
3925      // But that makes absolutely no sense.
3926      } else {
3927        CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3928
3929        // -- any of the non-static data members has class type M (or array
3930        //    thereof) and M has a deleted destructor or a destructor that is
3931        //    inaccessible from the defaulted destructor
3932        if (FieldDtor->isDeleted())
3933          return true;
3934        if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3935          AR_accessible)
3936        return true;
3937
3938        // -- X is a union-like class that has a variant member with a non-
3939        //    trivial destructor.
3940        if (Union && !FieldDtor->isTrivial())
3941          return true;
3942      }
3943    }
3944  }
3945
3946  if (DD->isVirtual()) {
3947    FunctionDecl *OperatorDelete = 0;
3948    DeclarationName Name =
3949      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3950    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
3951          false))
3952      return true;
3953  }
3954
3955
3956  return false;
3957}
3958
3959/// \brief Data used with FindHiddenVirtualMethod
3960namespace {
3961  struct FindHiddenVirtualMethodData {
3962    Sema *S;
3963    CXXMethodDecl *Method;
3964    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
3965    llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3966  };
3967}
3968
3969/// \brief Member lookup function that determines whether a given C++
3970/// method overloads virtual methods in a base class without overriding any,
3971/// to be used with CXXRecordDecl::lookupInBases().
3972static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
3973                                    CXXBasePath &Path,
3974                                    void *UserData) {
3975  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
3976
3977  FindHiddenVirtualMethodData &Data
3978    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
3979
3980  DeclarationName Name = Data.Method->getDeclName();
3981  assert(Name.getNameKind() == DeclarationName::Identifier);
3982
3983  bool foundSameNameMethod = false;
3984  llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
3985  for (Path.Decls = BaseRecord->lookup(Name);
3986       Path.Decls.first != Path.Decls.second;
3987       ++Path.Decls.first) {
3988    NamedDecl *D = *Path.Decls.first;
3989    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
3990      MD = MD->getCanonicalDecl();
3991      foundSameNameMethod = true;
3992      // Interested only in hidden virtual methods.
3993      if (!MD->isVirtual())
3994        continue;
3995      // If the method we are checking overrides a method from its base
3996      // don't warn about the other overloaded methods.
3997      if (!Data.S->IsOverload(Data.Method, MD, false))
3998        return true;
3999      // Collect the overload only if its hidden.
4000      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4001        overloadedMethods.push_back(MD);
4002    }
4003  }
4004
4005  if (foundSameNameMethod)
4006    Data.OverloadedMethods.append(overloadedMethods.begin(),
4007                                   overloadedMethods.end());
4008  return foundSameNameMethod;
4009}
4010
4011/// \brief See if a method overloads virtual methods in a base class without
4012/// overriding any.
4013void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4014  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4015                               MD->getLocation()) == Diagnostic::Ignored)
4016    return;
4017  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4018    return;
4019
4020  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4021                     /*bool RecordPaths=*/false,
4022                     /*bool DetectVirtual=*/false);
4023  FindHiddenVirtualMethodData Data;
4024  Data.Method = MD;
4025  Data.S = this;
4026
4027  // Keep the base methods that were overriden or introduced in the subclass
4028  // by 'using' in a set. A base method not in this set is hidden.
4029  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4030       res.first != res.second; ++res.first) {
4031    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4032      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4033                                          E = MD->end_overridden_methods();
4034           I != E; ++I)
4035        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4036    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4037      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4038        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4039  }
4040
4041  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4042      !Data.OverloadedMethods.empty()) {
4043    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4044      << MD << (Data.OverloadedMethods.size() > 1);
4045
4046    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4047      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4048      Diag(overloadedMD->getLocation(),
4049           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4050    }
4051  }
4052}
4053
4054void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4055                                             Decl *TagDecl,
4056                                             SourceLocation LBrac,
4057                                             SourceLocation RBrac,
4058                                             AttributeList *AttrList) {
4059  if (!TagDecl)
4060    return;
4061
4062  AdjustDeclIfTemplate(TagDecl);
4063
4064  ActOnFields(S, RLoc, TagDecl,
4065              // strict aliasing violation!
4066              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4067              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4068
4069  CheckCompletedCXXClass(
4070                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4071}
4072
4073/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4074/// special functions, such as the default constructor, copy
4075/// constructor, or destructor, to the given C++ class (C++
4076/// [special]p1).  This routine can only be executed just before the
4077/// definition of the class is complete.
4078void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4079  if (!ClassDecl->hasUserDeclaredConstructor())
4080    ++ASTContext::NumImplicitDefaultConstructors;
4081
4082  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4083    ++ASTContext::NumImplicitCopyConstructors;
4084
4085  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4086    ++ASTContext::NumImplicitCopyAssignmentOperators;
4087
4088    // If we have a dynamic class, then the copy assignment operator may be
4089    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4090    // it shows up in the right place in the vtable and that we diagnose
4091    // problems with the implicit exception specification.
4092    if (ClassDecl->isDynamicClass())
4093      DeclareImplicitCopyAssignment(ClassDecl);
4094  }
4095
4096  if (!ClassDecl->hasUserDeclaredDestructor()) {
4097    ++ASTContext::NumImplicitDestructors;
4098
4099    // If we have a dynamic class, then the destructor may be virtual, so we
4100    // have to declare the destructor immediately. This ensures that, e.g., it
4101    // shows up in the right place in the vtable and that we diagnose problems
4102    // with the implicit exception specification.
4103    if (ClassDecl->isDynamicClass())
4104      DeclareImplicitDestructor(ClassDecl);
4105  }
4106}
4107
4108void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4109  if (!D)
4110    return;
4111
4112  int NumParamList = D->getNumTemplateParameterLists();
4113  for (int i = 0; i < NumParamList; i++) {
4114    TemplateParameterList* Params = D->getTemplateParameterList(i);
4115    for (TemplateParameterList::iterator Param = Params->begin(),
4116                                      ParamEnd = Params->end();
4117          Param != ParamEnd; ++Param) {
4118      NamedDecl *Named = cast<NamedDecl>(*Param);
4119      if (Named->getDeclName()) {
4120        S->AddDecl(Named);
4121        IdResolver.AddDecl(Named);
4122      }
4123    }
4124  }
4125}
4126
4127void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4128  if (!D)
4129    return;
4130
4131  TemplateParameterList *Params = 0;
4132  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4133    Params = Template->getTemplateParameters();
4134  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4135           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4136    Params = PartialSpec->getTemplateParameters();
4137  else
4138    return;
4139
4140  for (TemplateParameterList::iterator Param = Params->begin(),
4141                                    ParamEnd = Params->end();
4142       Param != ParamEnd; ++Param) {
4143    NamedDecl *Named = cast<NamedDecl>(*Param);
4144    if (Named->getDeclName()) {
4145      S->AddDecl(Named);
4146      IdResolver.AddDecl(Named);
4147    }
4148  }
4149}
4150
4151void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4152  if (!RecordD) return;
4153  AdjustDeclIfTemplate(RecordD);
4154  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4155  PushDeclContext(S, Record);
4156}
4157
4158void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4159  if (!RecordD) return;
4160  PopDeclContext();
4161}
4162
4163/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4164/// parsing a top-level (non-nested) C++ class, and we are now
4165/// parsing those parts of the given Method declaration that could
4166/// not be parsed earlier (C++ [class.mem]p2), such as default
4167/// arguments. This action should enter the scope of the given
4168/// Method declaration as if we had just parsed the qualified method
4169/// name. However, it should not bring the parameters into scope;
4170/// that will be performed by ActOnDelayedCXXMethodParameter.
4171void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4172}
4173
4174/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4175/// C++ method declaration. We're (re-)introducing the given
4176/// function parameter into scope for use in parsing later parts of
4177/// the method declaration. For example, we could see an
4178/// ActOnParamDefaultArgument event for this parameter.
4179void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4180  if (!ParamD)
4181    return;
4182
4183  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4184
4185  // If this parameter has an unparsed default argument, clear it out
4186  // to make way for the parsed default argument.
4187  if (Param->hasUnparsedDefaultArg())
4188    Param->setDefaultArg(0);
4189
4190  S->AddDecl(Param);
4191  if (Param->getDeclName())
4192    IdResolver.AddDecl(Param);
4193}
4194
4195/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4196/// processing the delayed method declaration for Method. The method
4197/// declaration is now considered finished. There may be a separate
4198/// ActOnStartOfFunctionDef action later (not necessarily
4199/// immediately!) for this method, if it was also defined inside the
4200/// class body.
4201void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4202  if (!MethodD)
4203    return;
4204
4205  AdjustDeclIfTemplate(MethodD);
4206
4207  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4208
4209  // Now that we have our default arguments, check the constructor
4210  // again. It could produce additional diagnostics or affect whether
4211  // the class has implicitly-declared destructors, among other
4212  // things.
4213  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4214    CheckConstructor(Constructor);
4215
4216  // Check the default arguments, which we may have added.
4217  if (!Method->isInvalidDecl())
4218    CheckCXXDefaultArguments(Method);
4219}
4220
4221/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4222/// the well-formedness of the constructor declarator @p D with type @p
4223/// R. If there are any errors in the declarator, this routine will
4224/// emit diagnostics and set the invalid bit to true.  In any case, the type
4225/// will be updated to reflect a well-formed type for the constructor and
4226/// returned.
4227QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4228                                          StorageClass &SC) {
4229  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4230
4231  // C++ [class.ctor]p3:
4232  //   A constructor shall not be virtual (10.3) or static (9.4). A
4233  //   constructor can be invoked for a const, volatile or const
4234  //   volatile object. A constructor shall not be declared const,
4235  //   volatile, or const volatile (9.3.2).
4236  if (isVirtual) {
4237    if (!D.isInvalidType())
4238      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4239        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4240        << SourceRange(D.getIdentifierLoc());
4241    D.setInvalidType();
4242  }
4243  if (SC == SC_Static) {
4244    if (!D.isInvalidType())
4245      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4246        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4247        << SourceRange(D.getIdentifierLoc());
4248    D.setInvalidType();
4249    SC = SC_None;
4250  }
4251
4252  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4253  if (FTI.TypeQuals != 0) {
4254    if (FTI.TypeQuals & Qualifiers::Const)
4255      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4256        << "const" << SourceRange(D.getIdentifierLoc());
4257    if (FTI.TypeQuals & Qualifiers::Volatile)
4258      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4259        << "volatile" << SourceRange(D.getIdentifierLoc());
4260    if (FTI.TypeQuals & Qualifiers::Restrict)
4261      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4262        << "restrict" << SourceRange(D.getIdentifierLoc());
4263    D.setInvalidType();
4264  }
4265
4266  // C++0x [class.ctor]p4:
4267  //   A constructor shall not be declared with a ref-qualifier.
4268  if (FTI.hasRefQualifier()) {
4269    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4270      << FTI.RefQualifierIsLValueRef
4271      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4272    D.setInvalidType();
4273  }
4274
4275  // Rebuild the function type "R" without any type qualifiers (in
4276  // case any of the errors above fired) and with "void" as the
4277  // return type, since constructors don't have return types.
4278  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4279  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4280    return R;
4281
4282  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4283  EPI.TypeQuals = 0;
4284  EPI.RefQualifier = RQ_None;
4285
4286  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4287                                 Proto->getNumArgs(), EPI);
4288}
4289
4290/// CheckConstructor - Checks a fully-formed constructor for
4291/// well-formedness, issuing any diagnostics required. Returns true if
4292/// the constructor declarator is invalid.
4293void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4294  CXXRecordDecl *ClassDecl
4295    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4296  if (!ClassDecl)
4297    return Constructor->setInvalidDecl();
4298
4299  // C++ [class.copy]p3:
4300  //   A declaration of a constructor for a class X is ill-formed if
4301  //   its first parameter is of type (optionally cv-qualified) X and
4302  //   either there are no other parameters or else all other
4303  //   parameters have default arguments.
4304  if (!Constructor->isInvalidDecl() &&
4305      ((Constructor->getNumParams() == 1) ||
4306       (Constructor->getNumParams() > 1 &&
4307        Constructor->getParamDecl(1)->hasDefaultArg())) &&
4308      Constructor->getTemplateSpecializationKind()
4309                                              != TSK_ImplicitInstantiation) {
4310    QualType ParamType = Constructor->getParamDecl(0)->getType();
4311    QualType ClassTy = Context.getTagDeclType(ClassDecl);
4312    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4313      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4314      const char *ConstRef
4315        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4316                                                        : " const &";
4317      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4318        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4319
4320      // FIXME: Rather that making the constructor invalid, we should endeavor
4321      // to fix the type.
4322      Constructor->setInvalidDecl();
4323    }
4324  }
4325}
4326
4327/// CheckDestructor - Checks a fully-formed destructor definition for
4328/// well-formedness, issuing any diagnostics required.  Returns true
4329/// on error.
4330bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4331  CXXRecordDecl *RD = Destructor->getParent();
4332
4333  if (Destructor->isVirtual()) {
4334    SourceLocation Loc;
4335
4336    if (!Destructor->isImplicit())
4337      Loc = Destructor->getLocation();
4338    else
4339      Loc = RD->getLocation();
4340
4341    // If we have a virtual destructor, look up the deallocation function
4342    FunctionDecl *OperatorDelete = 0;
4343    DeclarationName Name =
4344    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4345    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4346      return true;
4347
4348    MarkDeclarationReferenced(Loc, OperatorDelete);
4349
4350    Destructor->setOperatorDelete(OperatorDelete);
4351  }
4352
4353  return false;
4354}
4355
4356static inline bool
4357FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4358  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4359          FTI.ArgInfo[0].Param &&
4360          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4361}
4362
4363/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4364/// the well-formednes of the destructor declarator @p D with type @p
4365/// R. If there are any errors in the declarator, this routine will
4366/// emit diagnostics and set the declarator to invalid.  Even if this happens,
4367/// will be updated to reflect a well-formed type for the destructor and
4368/// returned.
4369QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4370                                         StorageClass& SC) {
4371  // C++ [class.dtor]p1:
4372  //   [...] A typedef-name that names a class is a class-name
4373  //   (7.1.3); however, a typedef-name that names a class shall not
4374  //   be used as the identifier in the declarator for a destructor
4375  //   declaration.
4376  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4377  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4378    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4379      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4380  else if (const TemplateSpecializationType *TST =
4381             DeclaratorType->getAs<TemplateSpecializationType>())
4382    if (TST->isTypeAlias())
4383      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4384        << DeclaratorType << 1;
4385
4386  // C++ [class.dtor]p2:
4387  //   A destructor is used to destroy objects of its class type. A
4388  //   destructor takes no parameters, and no return type can be
4389  //   specified for it (not even void). The address of a destructor
4390  //   shall not be taken. A destructor shall not be static. A
4391  //   destructor can be invoked for a const, volatile or const
4392  //   volatile object. A destructor shall not be declared const,
4393  //   volatile or const volatile (9.3.2).
4394  if (SC == SC_Static) {
4395    if (!D.isInvalidType())
4396      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4397        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4398        << SourceRange(D.getIdentifierLoc())
4399        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4400
4401    SC = SC_None;
4402  }
4403  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4404    // Destructors don't have return types, but the parser will
4405    // happily parse something like:
4406    //
4407    //   class X {
4408    //     float ~X();
4409    //   };
4410    //
4411    // The return type will be eliminated later.
4412    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4413      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4414      << SourceRange(D.getIdentifierLoc());
4415  }
4416
4417  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4418  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4419    if (FTI.TypeQuals & Qualifiers::Const)
4420      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4421        << "const" << SourceRange(D.getIdentifierLoc());
4422    if (FTI.TypeQuals & Qualifiers::Volatile)
4423      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4424        << "volatile" << SourceRange(D.getIdentifierLoc());
4425    if (FTI.TypeQuals & Qualifiers::Restrict)
4426      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4427        << "restrict" << SourceRange(D.getIdentifierLoc());
4428    D.setInvalidType();
4429  }
4430
4431  // C++0x [class.dtor]p2:
4432  //   A destructor shall not be declared with a ref-qualifier.
4433  if (FTI.hasRefQualifier()) {
4434    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4435      << FTI.RefQualifierIsLValueRef
4436      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4437    D.setInvalidType();
4438  }
4439
4440  // Make sure we don't have any parameters.
4441  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
4442    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4443
4444    // Delete the parameters.
4445    FTI.freeArgs();
4446    D.setInvalidType();
4447  }
4448
4449  // Make sure the destructor isn't variadic.
4450  if (FTI.isVariadic) {
4451    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
4452    D.setInvalidType();
4453  }
4454
4455  // Rebuild the function type "R" without any type qualifiers or
4456  // parameters (in case any of the errors above fired) and with
4457  // "void" as the return type, since destructors don't have return
4458  // types.
4459  if (!D.isInvalidType())
4460    return R;
4461
4462  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4463  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4464  EPI.Variadic = false;
4465  EPI.TypeQuals = 0;
4466  EPI.RefQualifier = RQ_None;
4467  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
4468}
4469
4470/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4471/// well-formednes of the conversion function declarator @p D with
4472/// type @p R. If there are any errors in the declarator, this routine
4473/// will emit diagnostics and return true. Otherwise, it will return
4474/// false. Either way, the type @p R will be updated to reflect a
4475/// well-formed type for the conversion operator.
4476void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
4477                                     StorageClass& SC) {
4478  // C++ [class.conv.fct]p1:
4479  //   Neither parameter types nor return type can be specified. The
4480  //   type of a conversion function (8.3.5) is "function taking no
4481  //   parameter returning conversion-type-id."
4482  if (SC == SC_Static) {
4483    if (!D.isInvalidType())
4484      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4485        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4486        << SourceRange(D.getIdentifierLoc());
4487    D.setInvalidType();
4488    SC = SC_None;
4489  }
4490
4491  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4492
4493  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4494    // Conversion functions don't have return types, but the parser will
4495    // happily parse something like:
4496    //
4497    //   class X {
4498    //     float operator bool();
4499    //   };
4500    //
4501    // The return type will be changed later anyway.
4502    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4503      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4504      << SourceRange(D.getIdentifierLoc());
4505    D.setInvalidType();
4506  }
4507
4508  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4509
4510  // Make sure we don't have any parameters.
4511  if (Proto->getNumArgs() > 0) {
4512    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4513
4514    // Delete the parameters.
4515    D.getFunctionTypeInfo().freeArgs();
4516    D.setInvalidType();
4517  } else if (Proto->isVariadic()) {
4518    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
4519    D.setInvalidType();
4520  }
4521
4522  // Diagnose "&operator bool()" and other such nonsense.  This
4523  // is actually a gcc extension which we don't support.
4524  if (Proto->getResultType() != ConvType) {
4525    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4526      << Proto->getResultType();
4527    D.setInvalidType();
4528    ConvType = Proto->getResultType();
4529  }
4530
4531  // C++ [class.conv.fct]p4:
4532  //   The conversion-type-id shall not represent a function type nor
4533  //   an array type.
4534  if (ConvType->isArrayType()) {
4535    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4536    ConvType = Context.getPointerType(ConvType);
4537    D.setInvalidType();
4538  } else if (ConvType->isFunctionType()) {
4539    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4540    ConvType = Context.getPointerType(ConvType);
4541    D.setInvalidType();
4542  }
4543
4544  // Rebuild the function type "R" without any parameters (in case any
4545  // of the errors above fired) and with the conversion type as the
4546  // return type.
4547  if (D.isInvalidType())
4548    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
4549
4550  // C++0x explicit conversion operators.
4551  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
4552    Diag(D.getDeclSpec().getExplicitSpecLoc(),
4553         diag::warn_explicit_conversion_functions)
4554      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
4555}
4556
4557/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4558/// the declaration of the given C++ conversion function. This routine
4559/// is responsible for recording the conversion function in the C++
4560/// class, if possible.
4561Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
4562  assert(Conversion && "Expected to receive a conversion function declaration");
4563
4564  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
4565
4566  // Make sure we aren't redeclaring the conversion function.
4567  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
4568
4569  // C++ [class.conv.fct]p1:
4570  //   [...] A conversion function is never used to convert a
4571  //   (possibly cv-qualified) object to the (possibly cv-qualified)
4572  //   same object type (or a reference to it), to a (possibly
4573  //   cv-qualified) base class of that type (or a reference to it),
4574  //   or to (possibly cv-qualified) void.
4575  // FIXME: Suppress this warning if the conversion function ends up being a
4576  // virtual function that overrides a virtual function in a base class.
4577  QualType ClassType
4578    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4579  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
4580    ConvType = ConvTypeRef->getPointeeType();
4581  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4582      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4583    /* Suppress diagnostics for instantiations. */;
4584  else if (ConvType->isRecordType()) {
4585    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4586    if (ConvType == ClassType)
4587      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
4588        << ClassType;
4589    else if (IsDerivedFrom(ClassType, ConvType))
4590      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
4591        <<  ClassType << ConvType;
4592  } else if (ConvType->isVoidType()) {
4593    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
4594      << ClassType << ConvType;
4595  }
4596
4597  if (FunctionTemplateDecl *ConversionTemplate
4598                                = Conversion->getDescribedFunctionTemplate())
4599    return ConversionTemplate;
4600
4601  return Conversion;
4602}
4603
4604//===----------------------------------------------------------------------===//
4605// Namespace Handling
4606//===----------------------------------------------------------------------===//
4607
4608
4609
4610/// ActOnStartNamespaceDef - This is called at the start of a namespace
4611/// definition.
4612Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
4613                                   SourceLocation InlineLoc,
4614                                   SourceLocation NamespaceLoc,
4615                                   SourceLocation IdentLoc,
4616                                   IdentifierInfo *II,
4617                                   SourceLocation LBrace,
4618                                   AttributeList *AttrList) {
4619  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4620  // For anonymous namespace, take the location of the left brace.
4621  SourceLocation Loc = II ? IdentLoc : LBrace;
4622  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
4623                                                 StartLoc, Loc, II);
4624  Namespc->setInline(InlineLoc.isValid());
4625
4626  Scope *DeclRegionScope = NamespcScope->getParent();
4627
4628  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4629
4630  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4631    PushNamespaceVisibilityAttr(Attr);
4632
4633  if (II) {
4634    // C++ [namespace.def]p2:
4635    //   The identifier in an original-namespace-definition shall not
4636    //   have been previously defined in the declarative region in
4637    //   which the original-namespace-definition appears. The
4638    //   identifier in an original-namespace-definition is the name of
4639    //   the namespace. Subsequently in that declarative region, it is
4640    //   treated as an original-namespace-name.
4641    //
4642    // Since namespace names are unique in their scope, and we don't
4643    // look through using directives, just look for any ordinary names.
4644
4645    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4646      Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4647      Decl::IDNS_Namespace;
4648    NamedDecl *PrevDecl = 0;
4649    for (DeclContext::lookup_result R
4650            = CurContext->getRedeclContext()->lookup(II);
4651         R.first != R.second; ++R.first) {
4652      if ((*R.first)->getIdentifierNamespace() & IDNS) {
4653        PrevDecl = *R.first;
4654        break;
4655      }
4656    }
4657
4658    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4659      // This is an extended namespace definition.
4660      if (Namespc->isInline() != OrigNS->isInline()) {
4661        // inline-ness must match
4662        if (OrigNS->isInline()) {
4663          // The user probably just forgot the 'inline', so suggest that it
4664          // be added back.
4665          Diag(Namespc->getLocation(),
4666               diag::warn_inline_namespace_reopened_noninline)
4667            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4668        } else {
4669          Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4670            << Namespc->isInline();
4671        }
4672        Diag(OrigNS->getLocation(), diag::note_previous_definition);
4673
4674        // Recover by ignoring the new namespace's inline status.
4675        Namespc->setInline(OrigNS->isInline());
4676      }
4677
4678      // Attach this namespace decl to the chain of extended namespace
4679      // definitions.
4680      OrigNS->setNextNamespace(Namespc);
4681      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
4682
4683      // Remove the previous declaration from the scope.
4684      if (DeclRegionScope->isDeclScope(OrigNS)) {
4685        IdResolver.RemoveDecl(OrigNS);
4686        DeclRegionScope->RemoveDecl(OrigNS);
4687      }
4688    } else if (PrevDecl) {
4689      // This is an invalid name redefinition.
4690      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4691       << Namespc->getDeclName();
4692      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4693      Namespc->setInvalidDecl();
4694      // Continue on to push Namespc as current DeclContext and return it.
4695    } else if (II->isStr("std") &&
4696               CurContext->getRedeclContext()->isTranslationUnit()) {
4697      // This is the first "real" definition of the namespace "std", so update
4698      // our cache of the "std" namespace to point at this definition.
4699      if (NamespaceDecl *StdNS = getStdNamespace()) {
4700        // We had already defined a dummy namespace "std". Link this new
4701        // namespace definition to the dummy namespace "std".
4702        StdNS->setNextNamespace(Namespc);
4703        StdNS->setLocation(IdentLoc);
4704        Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
4705      }
4706
4707      // Make our StdNamespace cache point at the first real definition of the
4708      // "std" namespace.
4709      StdNamespace = Namespc;
4710
4711      // Add this instance of "std" to the set of known namespaces
4712      KnownNamespaces[Namespc] = false;
4713    } else if (!Namespc->isInline()) {
4714      // Since this is an "original" namespace, add it to the known set of
4715      // namespaces if it is not an inline namespace.
4716      KnownNamespaces[Namespc] = false;
4717    }
4718
4719    PushOnScopeChains(Namespc, DeclRegionScope);
4720  } else {
4721    // Anonymous namespaces.
4722    assert(Namespc->isAnonymousNamespace());
4723
4724    // Link the anonymous namespace into its parent.
4725    NamespaceDecl *PrevDecl;
4726    DeclContext *Parent = CurContext->getRedeclContext();
4727    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4728      PrevDecl = TU->getAnonymousNamespace();
4729      TU->setAnonymousNamespace(Namespc);
4730    } else {
4731      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4732      PrevDecl = ND->getAnonymousNamespace();
4733      ND->setAnonymousNamespace(Namespc);
4734    }
4735
4736    // Link the anonymous namespace with its previous declaration.
4737    if (PrevDecl) {
4738      assert(PrevDecl->isAnonymousNamespace());
4739      assert(!PrevDecl->getNextNamespace());
4740      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4741      PrevDecl->setNextNamespace(Namespc);
4742
4743      if (Namespc->isInline() != PrevDecl->isInline()) {
4744        // inline-ness must match
4745        Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4746          << Namespc->isInline();
4747        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4748        Namespc->setInvalidDecl();
4749        // Recover by ignoring the new namespace's inline status.
4750        Namespc->setInline(PrevDecl->isInline());
4751      }
4752    }
4753
4754    CurContext->addDecl(Namespc);
4755
4756    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
4757    //   behaves as if it were replaced by
4758    //     namespace unique { /* empty body */ }
4759    //     using namespace unique;
4760    //     namespace unique { namespace-body }
4761    //   where all occurrences of 'unique' in a translation unit are
4762    //   replaced by the same identifier and this identifier differs
4763    //   from all other identifiers in the entire program.
4764
4765    // We just create the namespace with an empty name and then add an
4766    // implicit using declaration, just like the standard suggests.
4767    //
4768    // CodeGen enforces the "universally unique" aspect by giving all
4769    // declarations semantically contained within an anonymous
4770    // namespace internal linkage.
4771
4772    if (!PrevDecl) {
4773      UsingDirectiveDecl* UD
4774        = UsingDirectiveDecl::Create(Context, CurContext,
4775                                     /* 'using' */ LBrace,
4776                                     /* 'namespace' */ SourceLocation(),
4777                                     /* qualifier */ NestedNameSpecifierLoc(),
4778                                     /* identifier */ SourceLocation(),
4779                                     Namespc,
4780                                     /* Ancestor */ CurContext);
4781      UD->setImplicit();
4782      CurContext->addDecl(UD);
4783    }
4784  }
4785
4786  // Although we could have an invalid decl (i.e. the namespace name is a
4787  // redefinition), push it as current DeclContext and try to continue parsing.
4788  // FIXME: We should be able to push Namespc here, so that the each DeclContext
4789  // for the namespace has the declarations that showed up in that particular
4790  // namespace definition.
4791  PushDeclContext(NamespcScope, Namespc);
4792  return Namespc;
4793}
4794
4795/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4796/// is a namespace alias, returns the namespace it points to.
4797static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4798  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4799    return AD->getNamespace();
4800  return dyn_cast_or_null<NamespaceDecl>(D);
4801}
4802
4803/// ActOnFinishNamespaceDef - This callback is called after a namespace is
4804/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
4805void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
4806  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4807  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
4808  Namespc->setRBraceLoc(RBrace);
4809  PopDeclContext();
4810  if (Namespc->hasAttr<VisibilityAttr>())
4811    PopPragmaVisibility();
4812}
4813
4814CXXRecordDecl *Sema::getStdBadAlloc() const {
4815  return cast_or_null<CXXRecordDecl>(
4816                                  StdBadAlloc.get(Context.getExternalSource()));
4817}
4818
4819NamespaceDecl *Sema::getStdNamespace() const {
4820  return cast_or_null<NamespaceDecl>(
4821                                 StdNamespace.get(Context.getExternalSource()));
4822}
4823
4824/// \brief Retrieve the special "std" namespace, which may require us to
4825/// implicitly define the namespace.
4826NamespaceDecl *Sema::getOrCreateStdNamespace() {
4827  if (!StdNamespace) {
4828    // The "std" namespace has not yet been defined, so build one implicitly.
4829    StdNamespace = NamespaceDecl::Create(Context,
4830                                         Context.getTranslationUnitDecl(),
4831                                         SourceLocation(), SourceLocation(),
4832                                         &PP.getIdentifierTable().get("std"));
4833    getStdNamespace()->setImplicit(true);
4834  }
4835
4836  return getStdNamespace();
4837}
4838
4839/// \brief Determine whether a using statement is in a context where it will be
4840/// apply in all contexts.
4841static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4842  switch (CurContext->getDeclKind()) {
4843    case Decl::TranslationUnit:
4844      return true;
4845    case Decl::LinkageSpec:
4846      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4847    default:
4848      return false;
4849  }
4850}
4851
4852static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
4853                                       CXXScopeSpec &SS,
4854                                       SourceLocation IdentLoc,
4855                                       IdentifierInfo *Ident) {
4856  R.clear();
4857  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
4858                                               R.getLookupKind(), Sc, &SS, NULL,
4859                                               false, S.CTC_NoKeywords, NULL)) {
4860    if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
4861        Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
4862      std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
4863      std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
4864      if (DeclContext *DC = S.computeDeclContext(SS, false))
4865        S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
4866          << Ident << DC << CorrectedQuotedStr << SS.getRange()
4867          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4868      else
4869        S.Diag(IdentLoc, diag::err_using_directive_suggest)
4870          << Ident << CorrectedQuotedStr
4871          << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
4872
4873      S.Diag(Corrected.getCorrectionDecl()->getLocation(),
4874           diag::note_namespace_defined_here) << CorrectedQuotedStr;
4875
4876      Ident = Corrected.getCorrectionAsIdentifierInfo();
4877      R.addDecl(Corrected.getCorrectionDecl());
4878      return true;
4879    }
4880    R.setLookupName(Ident);
4881  }
4882  return false;
4883}
4884
4885Decl *Sema::ActOnUsingDirective(Scope *S,
4886                                          SourceLocation UsingLoc,
4887                                          SourceLocation NamespcLoc,
4888                                          CXXScopeSpec &SS,
4889                                          SourceLocation IdentLoc,
4890                                          IdentifierInfo *NamespcName,
4891                                          AttributeList *AttrList) {
4892  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4893  assert(NamespcName && "Invalid NamespcName.");
4894  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
4895
4896  // This can only happen along a recovery path.
4897  while (S->getFlags() & Scope::TemplateParamScope)
4898    S = S->getParent();
4899  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4900
4901  UsingDirectiveDecl *UDir = 0;
4902  NestedNameSpecifier *Qualifier = 0;
4903  if (SS.isSet())
4904    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4905
4906  // Lookup namespace name.
4907  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4908  LookupParsedName(R, S, &SS);
4909  if (R.isAmbiguous())
4910    return 0;
4911
4912  if (R.empty()) {
4913    R.clear();
4914    // Allow "using namespace std;" or "using namespace ::std;" even if
4915    // "std" hasn't been defined yet, for GCC compatibility.
4916    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4917        NamespcName->isStr("std")) {
4918      Diag(IdentLoc, diag::ext_using_undefined_std);
4919      R.addDecl(getOrCreateStdNamespace());
4920      R.resolveKind();
4921    }
4922    // Otherwise, attempt typo correction.
4923    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
4924  }
4925
4926  if (!R.empty()) {
4927    NamedDecl *Named = R.getFoundDecl();
4928    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
4929        && "expected namespace decl");
4930    // C++ [namespace.udir]p1:
4931    //   A using-directive specifies that the names in the nominated
4932    //   namespace can be used in the scope in which the
4933    //   using-directive appears after the using-directive. During
4934    //   unqualified name lookup (3.4.1), the names appear as if they
4935    //   were declared in the nearest enclosing namespace which
4936    //   contains both the using-directive and the nominated
4937    //   namespace. [Note: in this context, "contains" means "contains
4938    //   directly or indirectly". ]
4939
4940    // Find enclosing context containing both using-directive and
4941    // nominated namespace.
4942    NamespaceDecl *NS = getNamespaceDecl(Named);
4943    DeclContext *CommonAncestor = cast<DeclContext>(NS);
4944    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
4945      CommonAncestor = CommonAncestor->getParent();
4946
4947    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
4948                                      SS.getWithLocInContext(Context),
4949                                      IdentLoc, Named, CommonAncestor);
4950
4951    if (IsUsingDirectiveInToplevelContext(CurContext) &&
4952        !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
4953      Diag(IdentLoc, diag::warn_using_directive_in_header);
4954    }
4955
4956    PushUsingDirective(S, UDir);
4957  } else {
4958    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
4959  }
4960
4961  // FIXME: We ignore attributes for now.
4962  return UDir;
4963}
4964
4965void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
4966  // If scope has associated entity, then using directive is at namespace
4967  // or translation unit scope. We add UsingDirectiveDecls, into
4968  // it's lookup structure.
4969  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
4970    Ctx->addDecl(UDir);
4971  else
4972    // Otherwise it is block-sope. using-directives will affect lookup
4973    // only to the end of scope.
4974    S->PushUsingDirective(UDir);
4975}
4976
4977
4978Decl *Sema::ActOnUsingDeclaration(Scope *S,
4979                                  AccessSpecifier AS,
4980                                  bool HasUsingKeyword,
4981                                  SourceLocation UsingLoc,
4982                                  CXXScopeSpec &SS,
4983                                  UnqualifiedId &Name,
4984                                  AttributeList *AttrList,
4985                                  bool IsTypeName,
4986                                  SourceLocation TypenameLoc) {
4987  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4988
4989  switch (Name.getKind()) {
4990  case UnqualifiedId::IK_ImplicitSelfParam:
4991  case UnqualifiedId::IK_Identifier:
4992  case UnqualifiedId::IK_OperatorFunctionId:
4993  case UnqualifiedId::IK_LiteralOperatorId:
4994  case UnqualifiedId::IK_ConversionFunctionId:
4995    break;
4996
4997  case UnqualifiedId::IK_ConstructorName:
4998  case UnqualifiedId::IK_ConstructorTemplateId:
4999    // C++0x inherited constructors.
5000    if (getLangOptions().CPlusPlus0x) break;
5001
5002    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5003      << SS.getRange();
5004    return 0;
5005
5006  case UnqualifiedId::IK_DestructorName:
5007    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5008      << SS.getRange();
5009    return 0;
5010
5011  case UnqualifiedId::IK_TemplateId:
5012    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5013      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5014    return 0;
5015  }
5016
5017  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5018  DeclarationName TargetName = TargetNameInfo.getName();
5019  if (!TargetName)
5020    return 0;
5021
5022  // Warn about using declarations.
5023  // TODO: store that the declaration was written without 'using' and
5024  // talk about access decls instead of using decls in the
5025  // diagnostics.
5026  if (!HasUsingKeyword) {
5027    UsingLoc = Name.getSourceRange().getBegin();
5028
5029    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5030      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5031  }
5032
5033  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5034      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5035    return 0;
5036
5037  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5038                                        TargetNameInfo, AttrList,
5039                                        /* IsInstantiation */ false,
5040                                        IsTypeName, TypenameLoc);
5041  if (UD)
5042    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5043
5044  return UD;
5045}
5046
5047/// \brief Determine whether a using declaration considers the given
5048/// declarations as "equivalent", e.g., if they are redeclarations of
5049/// the same entity or are both typedefs of the same type.
5050static bool
5051IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5052                         bool &SuppressRedeclaration) {
5053  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5054    SuppressRedeclaration = false;
5055    return true;
5056  }
5057
5058  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5059    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5060      SuppressRedeclaration = true;
5061      return Context.hasSameType(TD1->getUnderlyingType(),
5062                                 TD2->getUnderlyingType());
5063    }
5064
5065  return false;
5066}
5067
5068
5069/// Determines whether to create a using shadow decl for a particular
5070/// decl, given the set of decls existing prior to this using lookup.
5071bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5072                                const LookupResult &Previous) {
5073  // Diagnose finding a decl which is not from a base class of the
5074  // current class.  We do this now because there are cases where this
5075  // function will silently decide not to build a shadow decl, which
5076  // will pre-empt further diagnostics.
5077  //
5078  // We don't need to do this in C++0x because we do the check once on
5079  // the qualifier.
5080  //
5081  // FIXME: diagnose the following if we care enough:
5082  //   struct A { int foo; };
5083  //   struct B : A { using A::foo; };
5084  //   template <class T> struct C : A {};
5085  //   template <class T> struct D : C<T> { using B::foo; } // <---
5086  // This is invalid (during instantiation) in C++03 because B::foo
5087  // resolves to the using decl in B, which is not a base class of D<T>.
5088  // We can't diagnose it immediately because C<T> is an unknown
5089  // specialization.  The UsingShadowDecl in D<T> then points directly
5090  // to A::foo, which will look well-formed when we instantiate.
5091  // The right solution is to not collapse the shadow-decl chain.
5092  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5093    DeclContext *OrigDC = Orig->getDeclContext();
5094
5095    // Handle enums and anonymous structs.
5096    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5097    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5098    while (OrigRec->isAnonymousStructOrUnion())
5099      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5100
5101    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5102      if (OrigDC == CurContext) {
5103        Diag(Using->getLocation(),
5104             diag::err_using_decl_nested_name_specifier_is_current_class)
5105          << Using->getQualifierLoc().getSourceRange();
5106        Diag(Orig->getLocation(), diag::note_using_decl_target);
5107        return true;
5108      }
5109
5110      Diag(Using->getQualifierLoc().getBeginLoc(),
5111           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5112        << Using->getQualifier()
5113        << cast<CXXRecordDecl>(CurContext)
5114        << Using->getQualifierLoc().getSourceRange();
5115      Diag(Orig->getLocation(), diag::note_using_decl_target);
5116      return true;
5117    }
5118  }
5119
5120  if (Previous.empty()) return false;
5121
5122  NamedDecl *Target = Orig;
5123  if (isa<UsingShadowDecl>(Target))
5124    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5125
5126  // If the target happens to be one of the previous declarations, we
5127  // don't have a conflict.
5128  //
5129  // FIXME: but we might be increasing its access, in which case we
5130  // should redeclare it.
5131  NamedDecl *NonTag = 0, *Tag = 0;
5132  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5133         I != E; ++I) {
5134    NamedDecl *D = (*I)->getUnderlyingDecl();
5135    bool Result;
5136    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5137      return Result;
5138
5139    (isa<TagDecl>(D) ? Tag : NonTag) = D;
5140  }
5141
5142  if (Target->isFunctionOrFunctionTemplate()) {
5143    FunctionDecl *FD;
5144    if (isa<FunctionTemplateDecl>(Target))
5145      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5146    else
5147      FD = cast<FunctionDecl>(Target);
5148
5149    NamedDecl *OldDecl = 0;
5150    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5151    case Ovl_Overload:
5152      return false;
5153
5154    case Ovl_NonFunction:
5155      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5156      break;
5157
5158    // We found a decl with the exact signature.
5159    case Ovl_Match:
5160      // If we're in a record, we want to hide the target, so we
5161      // return true (without a diagnostic) to tell the caller not to
5162      // build a shadow decl.
5163      if (CurContext->isRecord())
5164        return true;
5165
5166      // If we're not in a record, this is an error.
5167      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5168      break;
5169    }
5170
5171    Diag(Target->getLocation(), diag::note_using_decl_target);
5172    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5173    return true;
5174  }
5175
5176  // Target is not a function.
5177
5178  if (isa<TagDecl>(Target)) {
5179    // No conflict between a tag and a non-tag.
5180    if (!Tag) return false;
5181
5182    Diag(Using->getLocation(), diag::err_using_decl_conflict);
5183    Diag(Target->getLocation(), diag::note_using_decl_target);
5184    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5185    return true;
5186  }
5187
5188  // No conflict between a tag and a non-tag.
5189  if (!NonTag) return false;
5190
5191  Diag(Using->getLocation(), diag::err_using_decl_conflict);
5192  Diag(Target->getLocation(), diag::note_using_decl_target);
5193  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5194  return true;
5195}
5196
5197/// Builds a shadow declaration corresponding to a 'using' declaration.
5198UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5199                                            UsingDecl *UD,
5200                                            NamedDecl *Orig) {
5201
5202  // If we resolved to another shadow declaration, just coalesce them.
5203  NamedDecl *Target = Orig;
5204  if (isa<UsingShadowDecl>(Target)) {
5205    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5206    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5207  }
5208
5209  UsingShadowDecl *Shadow
5210    = UsingShadowDecl::Create(Context, CurContext,
5211                              UD->getLocation(), UD, Target);
5212  UD->addShadowDecl(Shadow);
5213
5214  Shadow->setAccess(UD->getAccess());
5215  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5216    Shadow->setInvalidDecl();
5217
5218  if (S)
5219    PushOnScopeChains(Shadow, S);
5220  else
5221    CurContext->addDecl(Shadow);
5222
5223
5224  return Shadow;
5225}
5226
5227/// Hides a using shadow declaration.  This is required by the current
5228/// using-decl implementation when a resolvable using declaration in a
5229/// class is followed by a declaration which would hide or override
5230/// one or more of the using decl's targets; for example:
5231///
5232///   struct Base { void foo(int); };
5233///   struct Derived : Base {
5234///     using Base::foo;
5235///     void foo(int);
5236///   };
5237///
5238/// The governing language is C++03 [namespace.udecl]p12:
5239///
5240///   When a using-declaration brings names from a base class into a
5241///   derived class scope, member functions in the derived class
5242///   override and/or hide member functions with the same name and
5243///   parameter types in a base class (rather than conflicting).
5244///
5245/// There are two ways to implement this:
5246///   (1) optimistically create shadow decls when they're not hidden
5247///       by existing declarations, or
5248///   (2) don't create any shadow decls (or at least don't make them
5249///       visible) until we've fully parsed/instantiated the class.
5250/// The problem with (1) is that we might have to retroactively remove
5251/// a shadow decl, which requires several O(n) operations because the
5252/// decl structures are (very reasonably) not designed for removal.
5253/// (2) avoids this but is very fiddly and phase-dependent.
5254void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5255  if (Shadow->getDeclName().getNameKind() ==
5256        DeclarationName::CXXConversionFunctionName)
5257    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5258
5259  // Remove it from the DeclContext...
5260  Shadow->getDeclContext()->removeDecl(Shadow);
5261
5262  // ...and the scope, if applicable...
5263  if (S) {
5264    S->RemoveDecl(Shadow);
5265    IdResolver.RemoveDecl(Shadow);
5266  }
5267
5268  // ...and the using decl.
5269  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5270
5271  // TODO: complain somehow if Shadow was used.  It shouldn't
5272  // be possible for this to happen, because...?
5273}
5274
5275/// Builds a using declaration.
5276///
5277/// \param IsInstantiation - Whether this call arises from an
5278///   instantiation of an unresolved using declaration.  We treat
5279///   the lookup differently for these declarations.
5280NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5281                                       SourceLocation UsingLoc,
5282                                       CXXScopeSpec &SS,
5283                                       const DeclarationNameInfo &NameInfo,
5284                                       AttributeList *AttrList,
5285                                       bool IsInstantiation,
5286                                       bool IsTypeName,
5287                                       SourceLocation TypenameLoc) {
5288  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5289  SourceLocation IdentLoc = NameInfo.getLoc();
5290  assert(IdentLoc.isValid() && "Invalid TargetName location.");
5291
5292  // FIXME: We ignore attributes for now.
5293
5294  if (SS.isEmpty()) {
5295    Diag(IdentLoc, diag::err_using_requires_qualname);
5296    return 0;
5297  }
5298
5299  // Do the redeclaration lookup in the current scope.
5300  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5301                        ForRedeclaration);
5302  Previous.setHideTags(false);
5303  if (S) {
5304    LookupName(Previous, S);
5305
5306    // It is really dumb that we have to do this.
5307    LookupResult::Filter F = Previous.makeFilter();
5308    while (F.hasNext()) {
5309      NamedDecl *D = F.next();
5310      if (!isDeclInScope(D, CurContext, S))
5311        F.erase();
5312    }
5313    F.done();
5314  } else {
5315    assert(IsInstantiation && "no scope in non-instantiation");
5316    assert(CurContext->isRecord() && "scope not record in instantiation");
5317    LookupQualifiedName(Previous, CurContext);
5318  }
5319
5320  // Check for invalid redeclarations.
5321  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5322    return 0;
5323
5324  // Check for bad qualifiers.
5325  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5326    return 0;
5327
5328  DeclContext *LookupContext = computeDeclContext(SS);
5329  NamedDecl *D;
5330  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5331  if (!LookupContext) {
5332    if (IsTypeName) {
5333      // FIXME: not all declaration name kinds are legal here
5334      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5335                                              UsingLoc, TypenameLoc,
5336                                              QualifierLoc,
5337                                              IdentLoc, NameInfo.getName());
5338    } else {
5339      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5340                                           QualifierLoc, NameInfo);
5341    }
5342  } else {
5343    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5344                          NameInfo, IsTypeName);
5345  }
5346  D->setAccess(AS);
5347  CurContext->addDecl(D);
5348
5349  if (!LookupContext) return D;
5350  UsingDecl *UD = cast<UsingDecl>(D);
5351
5352  if (RequireCompleteDeclContext(SS, LookupContext)) {
5353    UD->setInvalidDecl();
5354    return UD;
5355  }
5356
5357  // Constructor inheriting using decls get special treatment.
5358  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5359    if (CheckInheritedConstructorUsingDecl(UD))
5360      UD->setInvalidDecl();
5361    return UD;
5362  }
5363
5364  // Otherwise, look up the target name.
5365
5366  LookupResult R(*this, NameInfo, LookupOrdinaryName);
5367  R.setUsingDeclaration(true);
5368
5369  // Unlike most lookups, we don't always want to hide tag
5370  // declarations: tag names are visible through the using declaration
5371  // even if hidden by ordinary names, *except* in a dependent context
5372  // where it's important for the sanity of two-phase lookup.
5373  if (!IsInstantiation)
5374    R.setHideTags(false);
5375
5376  LookupQualifiedName(R, LookupContext);
5377
5378  if (R.empty()) {
5379    Diag(IdentLoc, diag::err_no_member)
5380      << NameInfo.getName() << LookupContext << SS.getRange();
5381    UD->setInvalidDecl();
5382    return UD;
5383  }
5384
5385  if (R.isAmbiguous()) {
5386    UD->setInvalidDecl();
5387    return UD;
5388  }
5389
5390  if (IsTypeName) {
5391    // If we asked for a typename and got a non-type decl, error out.
5392    if (!R.getAsSingle<TypeDecl>()) {
5393      Diag(IdentLoc, diag::err_using_typename_non_type);
5394      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5395        Diag((*I)->getUnderlyingDecl()->getLocation(),
5396             diag::note_using_decl_target);
5397      UD->setInvalidDecl();
5398      return UD;
5399    }
5400  } else {
5401    // If we asked for a non-typename and we got a type, error out,
5402    // but only if this is an instantiation of an unresolved using
5403    // decl.  Otherwise just silently find the type name.
5404    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5405      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5406      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5407      UD->setInvalidDecl();
5408      return UD;
5409    }
5410  }
5411
5412  // C++0x N2914 [namespace.udecl]p6:
5413  // A using-declaration shall not name a namespace.
5414  if (R.getAsSingle<NamespaceDecl>()) {
5415    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5416      << SS.getRange();
5417    UD->setInvalidDecl();
5418    return UD;
5419  }
5420
5421  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5422    if (!CheckUsingShadowDecl(UD, *I, Previous))
5423      BuildUsingShadowDecl(S, UD, *I);
5424  }
5425
5426  return UD;
5427}
5428
5429/// Additional checks for a using declaration referring to a constructor name.
5430bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5431  if (UD->isTypeName()) {
5432    // FIXME: Cannot specify typename when specifying constructor
5433    return true;
5434  }
5435
5436  const Type *SourceType = UD->getQualifier()->getAsType();
5437  assert(SourceType &&
5438         "Using decl naming constructor doesn't have type in scope spec.");
5439  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5440
5441  // Check whether the named type is a direct base class.
5442  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5443  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5444  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5445       BaseIt != BaseE; ++BaseIt) {
5446    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5447    if (CanonicalSourceType == BaseType)
5448      break;
5449  }
5450
5451  if (BaseIt == BaseE) {
5452    // Did not find SourceType in the bases.
5453    Diag(UD->getUsingLocation(),
5454         diag::err_using_decl_constructor_not_in_direct_base)
5455      << UD->getNameInfo().getSourceRange()
5456      << QualType(SourceType, 0) << TargetClass;
5457    return true;
5458  }
5459
5460  BaseIt->setInheritConstructors();
5461
5462  return false;
5463}
5464
5465/// Checks that the given using declaration is not an invalid
5466/// redeclaration.  Note that this is checking only for the using decl
5467/// itself, not for any ill-formedness among the UsingShadowDecls.
5468bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5469                                       bool isTypeName,
5470                                       const CXXScopeSpec &SS,
5471                                       SourceLocation NameLoc,
5472                                       const LookupResult &Prev) {
5473  // C++03 [namespace.udecl]p8:
5474  // C++0x [namespace.udecl]p10:
5475  //   A using-declaration is a declaration and can therefore be used
5476  //   repeatedly where (and only where) multiple declarations are
5477  //   allowed.
5478  //
5479  // That's in non-member contexts.
5480  if (!CurContext->getRedeclContext()->isRecord())
5481    return false;
5482
5483  NestedNameSpecifier *Qual
5484    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5485
5486  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5487    NamedDecl *D = *I;
5488
5489    bool DTypename;
5490    NestedNameSpecifier *DQual;
5491    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5492      DTypename = UD->isTypeName();
5493      DQual = UD->getQualifier();
5494    } else if (UnresolvedUsingValueDecl *UD
5495                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5496      DTypename = false;
5497      DQual = UD->getQualifier();
5498    } else if (UnresolvedUsingTypenameDecl *UD
5499                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5500      DTypename = true;
5501      DQual = UD->getQualifier();
5502    } else continue;
5503
5504    // using decls differ if one says 'typename' and the other doesn't.
5505    // FIXME: non-dependent using decls?
5506    if (isTypeName != DTypename) continue;
5507
5508    // using decls differ if they name different scopes (but note that
5509    // template instantiation can cause this check to trigger when it
5510    // didn't before instantiation).
5511    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5512        Context.getCanonicalNestedNameSpecifier(DQual))
5513      continue;
5514
5515    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
5516    Diag(D->getLocation(), diag::note_using_decl) << 1;
5517    return true;
5518  }
5519
5520  return false;
5521}
5522
5523
5524/// Checks that the given nested-name qualifier used in a using decl
5525/// in the current context is appropriately related to the current
5526/// scope.  If an error is found, diagnoses it and returns true.
5527bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5528                                   const CXXScopeSpec &SS,
5529                                   SourceLocation NameLoc) {
5530  DeclContext *NamedContext = computeDeclContext(SS);
5531
5532  if (!CurContext->isRecord()) {
5533    // C++03 [namespace.udecl]p3:
5534    // C++0x [namespace.udecl]p8:
5535    //   A using-declaration for a class member shall be a member-declaration.
5536
5537    // If we weren't able to compute a valid scope, it must be a
5538    // dependent class scope.
5539    if (!NamedContext || NamedContext->isRecord()) {
5540      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5541        << SS.getRange();
5542      return true;
5543    }
5544
5545    // Otherwise, everything is known to be fine.
5546    return false;
5547  }
5548
5549  // The current scope is a record.
5550
5551  // If the named context is dependent, we can't decide much.
5552  if (!NamedContext) {
5553    // FIXME: in C++0x, we can diagnose if we can prove that the
5554    // nested-name-specifier does not refer to a base class, which is
5555    // still possible in some cases.
5556
5557    // Otherwise we have to conservatively report that things might be
5558    // okay.
5559    return false;
5560  }
5561
5562  if (!NamedContext->isRecord()) {
5563    // Ideally this would point at the last name in the specifier,
5564    // but we don't have that level of source info.
5565    Diag(SS.getRange().getBegin(),
5566         diag::err_using_decl_nested_name_specifier_is_not_class)
5567      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5568    return true;
5569  }
5570
5571  if (!NamedContext->isDependentContext() &&
5572      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5573    return true;
5574
5575  if (getLangOptions().CPlusPlus0x) {
5576    // C++0x [namespace.udecl]p3:
5577    //   In a using-declaration used as a member-declaration, the
5578    //   nested-name-specifier shall name a base class of the class
5579    //   being defined.
5580
5581    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5582                                 cast<CXXRecordDecl>(NamedContext))) {
5583      if (CurContext == NamedContext) {
5584        Diag(NameLoc,
5585             diag::err_using_decl_nested_name_specifier_is_current_class)
5586          << SS.getRange();
5587        return true;
5588      }
5589
5590      Diag(SS.getRange().getBegin(),
5591           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5592        << (NestedNameSpecifier*) SS.getScopeRep()
5593        << cast<CXXRecordDecl>(CurContext)
5594        << SS.getRange();
5595      return true;
5596    }
5597
5598    return false;
5599  }
5600
5601  // C++03 [namespace.udecl]p4:
5602  //   A using-declaration used as a member-declaration shall refer
5603  //   to a member of a base class of the class being defined [etc.].
5604
5605  // Salient point: SS doesn't have to name a base class as long as
5606  // lookup only finds members from base classes.  Therefore we can
5607  // diagnose here only if we can prove that that can't happen,
5608  // i.e. if the class hierarchies provably don't intersect.
5609
5610  // TODO: it would be nice if "definitely valid" results were cached
5611  // in the UsingDecl and UsingShadowDecl so that these checks didn't
5612  // need to be repeated.
5613
5614  struct UserData {
5615    llvm::DenseSet<const CXXRecordDecl*> Bases;
5616
5617    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5618      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5619      Data->Bases.insert(Base);
5620      return true;
5621    }
5622
5623    bool hasDependentBases(const CXXRecordDecl *Class) {
5624      return !Class->forallBases(collect, this);
5625    }
5626
5627    /// Returns true if the base is dependent or is one of the
5628    /// accumulated base classes.
5629    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5630      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5631      return !Data->Bases.count(Base);
5632    }
5633
5634    bool mightShareBases(const CXXRecordDecl *Class) {
5635      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5636    }
5637  };
5638
5639  UserData Data;
5640
5641  // Returns false if we find a dependent base.
5642  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5643    return false;
5644
5645  // Returns false if the class has a dependent base or if it or one
5646  // of its bases is present in the base set of the current context.
5647  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5648    return false;
5649
5650  Diag(SS.getRange().getBegin(),
5651       diag::err_using_decl_nested_name_specifier_is_not_base_class)
5652    << (NestedNameSpecifier*) SS.getScopeRep()
5653    << cast<CXXRecordDecl>(CurContext)
5654    << SS.getRange();
5655
5656  return true;
5657}
5658
5659Decl *Sema::ActOnAliasDeclaration(Scope *S,
5660                                  AccessSpecifier AS,
5661                                  MultiTemplateParamsArg TemplateParamLists,
5662                                  SourceLocation UsingLoc,
5663                                  UnqualifiedId &Name,
5664                                  TypeResult Type) {
5665  // Skip up to the relevant declaration scope.
5666  while (S->getFlags() & Scope::TemplateParamScope)
5667    S = S->getParent();
5668  assert((S->getFlags() & Scope::DeclScope) &&
5669         "got alias-declaration outside of declaration scope");
5670
5671  if (Type.isInvalid())
5672    return 0;
5673
5674  bool Invalid = false;
5675  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5676  TypeSourceInfo *TInfo = 0;
5677  GetTypeFromParser(Type.get(), &TInfo);
5678
5679  if (DiagnoseClassNameShadow(CurContext, NameInfo))
5680    return 0;
5681
5682  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
5683                                      UPPC_DeclarationType)) {
5684    Invalid = true;
5685    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5686                                             TInfo->getTypeLoc().getBeginLoc());
5687  }
5688
5689  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5690  LookupName(Previous, S);
5691
5692  // Warn about shadowing the name of a template parameter.
5693  if (Previous.isSingleResult() &&
5694      Previous.getFoundDecl()->isTemplateParameter()) {
5695    if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5696                                        Previous.getFoundDecl()))
5697      Invalid = true;
5698    Previous.clear();
5699  }
5700
5701  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5702         "name in alias declaration must be an identifier");
5703  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5704                                               Name.StartLocation,
5705                                               Name.Identifier, TInfo);
5706
5707  NewTD->setAccess(AS);
5708
5709  if (Invalid)
5710    NewTD->setInvalidDecl();
5711
5712  CheckTypedefForVariablyModifiedType(S, NewTD);
5713  Invalid |= NewTD->isInvalidDecl();
5714
5715  bool Redeclaration = false;
5716
5717  NamedDecl *NewND;
5718  if (TemplateParamLists.size()) {
5719    TypeAliasTemplateDecl *OldDecl = 0;
5720    TemplateParameterList *OldTemplateParams = 0;
5721
5722    if (TemplateParamLists.size() != 1) {
5723      Diag(UsingLoc, diag::err_alias_template_extra_headers)
5724        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5725         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5726    }
5727    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5728
5729    // Only consider previous declarations in the same scope.
5730    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5731                         /*ExplicitInstantiationOrSpecialization*/false);
5732    if (!Previous.empty()) {
5733      Redeclaration = true;
5734
5735      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5736      if (!OldDecl && !Invalid) {
5737        Diag(UsingLoc, diag::err_redefinition_different_kind)
5738          << Name.Identifier;
5739
5740        NamedDecl *OldD = Previous.getRepresentativeDecl();
5741        if (OldD->getLocation().isValid())
5742          Diag(OldD->getLocation(), diag::note_previous_definition);
5743
5744        Invalid = true;
5745      }
5746
5747      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5748        if (TemplateParameterListsAreEqual(TemplateParams,
5749                                           OldDecl->getTemplateParameters(),
5750                                           /*Complain=*/true,
5751                                           TPL_TemplateMatch))
5752          OldTemplateParams = OldDecl->getTemplateParameters();
5753        else
5754          Invalid = true;
5755
5756        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5757        if (!Invalid &&
5758            !Context.hasSameType(OldTD->getUnderlyingType(),
5759                                 NewTD->getUnderlyingType())) {
5760          // FIXME: The C++0x standard does not clearly say this is ill-formed,
5761          // but we can't reasonably accept it.
5762          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5763            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5764          if (OldTD->getLocation().isValid())
5765            Diag(OldTD->getLocation(), diag::note_previous_definition);
5766          Invalid = true;
5767        }
5768      }
5769    }
5770
5771    // Merge any previous default template arguments into our parameters,
5772    // and check the parameter list.
5773    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5774                                   TPC_TypeAliasTemplate))
5775      return 0;
5776
5777    TypeAliasTemplateDecl *NewDecl =
5778      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5779                                    Name.Identifier, TemplateParams,
5780                                    NewTD);
5781
5782    NewDecl->setAccess(AS);
5783
5784    if (Invalid)
5785      NewDecl->setInvalidDecl();
5786    else if (OldDecl)
5787      NewDecl->setPreviousDeclaration(OldDecl);
5788
5789    NewND = NewDecl;
5790  } else {
5791    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5792    NewND = NewTD;
5793  }
5794
5795  if (!Redeclaration)
5796    PushOnScopeChains(NewND, S);
5797
5798  return NewND;
5799}
5800
5801Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
5802                                             SourceLocation NamespaceLoc,
5803                                             SourceLocation AliasLoc,
5804                                             IdentifierInfo *Alias,
5805                                             CXXScopeSpec &SS,
5806                                             SourceLocation IdentLoc,
5807                                             IdentifierInfo *Ident) {
5808
5809  // Lookup the namespace name.
5810  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5811  LookupParsedName(R, S, &SS);
5812
5813  // Check if we have a previous declaration with the same name.
5814  NamedDecl *PrevDecl
5815    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5816                       ForRedeclaration);
5817  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5818    PrevDecl = 0;
5819
5820  if (PrevDecl) {
5821    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
5822      // We already have an alias with the same name that points to the same
5823      // namespace, so don't create a new one.
5824      // FIXME: At some point, we'll want to create the (redundant)
5825      // declaration to maintain better source information.
5826      if (!R.isAmbiguous() && !R.empty() &&
5827          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
5828        return 0;
5829    }
5830
5831    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5832      diag::err_redefinition_different_kind;
5833    Diag(AliasLoc, DiagID) << Alias;
5834    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5835    return 0;
5836  }
5837
5838  if (R.isAmbiguous())
5839    return 0;
5840
5841  if (R.empty()) {
5842    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
5843      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
5844      return 0;
5845    }
5846  }
5847
5848  NamespaceAliasDecl *AliasDecl =
5849    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
5850                               Alias, SS.getWithLocInContext(Context),
5851                               IdentLoc, R.getFoundDecl());
5852
5853  PushOnScopeChains(AliasDecl, S);
5854  return AliasDecl;
5855}
5856
5857namespace {
5858  /// \brief Scoped object used to handle the state changes required in Sema
5859  /// to implicitly define the body of a C++ member function;
5860  class ImplicitlyDefinedFunctionScope {
5861    Sema &S;
5862    Sema::ContextRAII SavedContext;
5863
5864  public:
5865    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
5866      : S(S), SavedContext(S, Method)
5867    {
5868      S.PushFunctionScope();
5869      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5870    }
5871
5872    ~ImplicitlyDefinedFunctionScope() {
5873      S.PopExpressionEvaluationContext();
5874      S.PopFunctionOrBlockScope();
5875    }
5876  };
5877}
5878
5879Sema::ImplicitExceptionSpecification
5880Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
5881  // C++ [except.spec]p14:
5882  //   An implicitly declared special member function (Clause 12) shall have an
5883  //   exception-specification. [...]
5884  ImplicitExceptionSpecification ExceptSpec(Context);
5885  if (ClassDecl->isInvalidDecl())
5886    return ExceptSpec;
5887
5888  // Direct base-class constructors.
5889  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5890                                       BEnd = ClassDecl->bases_end();
5891       B != BEnd; ++B) {
5892    if (B->isVirtual()) // Handled below.
5893      continue;
5894
5895    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5896      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5897      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5898      // If this is a deleted function, add it anyway. This might be conformant
5899      // with the standard. This might not. I'm not sure. It might not matter.
5900      if (Constructor)
5901        ExceptSpec.CalledDecl(Constructor);
5902    }
5903  }
5904
5905  // Virtual base-class constructors.
5906  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5907                                       BEnd = ClassDecl->vbases_end();
5908       B != BEnd; ++B) {
5909    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5910      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5911      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5912      // If this is a deleted function, add it anyway. This might be conformant
5913      // with the standard. This might not. I'm not sure. It might not matter.
5914      if (Constructor)
5915        ExceptSpec.CalledDecl(Constructor);
5916    }
5917  }
5918
5919  // Field constructors.
5920  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5921                               FEnd = ClassDecl->field_end();
5922       F != FEnd; ++F) {
5923    if (F->hasInClassInitializer()) {
5924      if (Expr *E = F->getInClassInitializer())
5925        ExceptSpec.CalledExpr(E);
5926      else if (!F->isInvalidDecl())
5927        ExceptSpec.SetDelayed();
5928    } else if (const RecordType *RecordTy
5929              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
5930      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5931      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
5932      // If this is a deleted function, add it anyway. This might be conformant
5933      // with the standard. This might not. I'm not sure. It might not matter.
5934      // In particular, the problem is that this function never gets called. It
5935      // might just be ill-formed because this function attempts to refer to
5936      // a deleted function here.
5937      if (Constructor)
5938        ExceptSpec.CalledDecl(Constructor);
5939    }
5940  }
5941
5942  return ExceptSpec;
5943}
5944
5945CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
5946                                                     CXXRecordDecl *ClassDecl) {
5947  // C++ [class.ctor]p5:
5948  //   A default constructor for a class X is a constructor of class X
5949  //   that can be called without an argument. If there is no
5950  //   user-declared constructor for class X, a default constructor is
5951  //   implicitly declared. An implicitly-declared default constructor
5952  //   is an inline public member of its class.
5953  assert(!ClassDecl->hasUserDeclaredConstructor() &&
5954         "Should not build implicit default constructor!");
5955
5956  ImplicitExceptionSpecification Spec =
5957    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
5958  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
5959
5960  // Create the actual constructor declaration.
5961  CanQualType ClassType
5962    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5963  SourceLocation ClassLoc = ClassDecl->getLocation();
5964  DeclarationName Name
5965    = Context.DeclarationNames.getCXXConstructorName(ClassType);
5966  DeclarationNameInfo NameInfo(Name, ClassLoc);
5967  CXXConstructorDecl *DefaultCon
5968    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
5969                                 Context.getFunctionType(Context.VoidTy,
5970                                                         0, 0, EPI),
5971                                 /*TInfo=*/0,
5972                                 /*isExplicit=*/false,
5973                                 /*isInline=*/true,
5974                                 /*isImplicitlyDeclared=*/true);
5975  DefaultCon->setAccess(AS_public);
5976  DefaultCon->setDefaulted();
5977  DefaultCon->setImplicit();
5978  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
5979
5980  // Note that we have declared this constructor.
5981  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
5982
5983  if (Scope *S = getScopeForContext(ClassDecl))
5984    PushOnScopeChains(DefaultCon, S, false);
5985  ClassDecl->addDecl(DefaultCon);
5986
5987  if (ShouldDeleteDefaultConstructor(DefaultCon))
5988    DefaultCon->setDeletedAsWritten();
5989
5990  return DefaultCon;
5991}
5992
5993void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5994                                            CXXConstructorDecl *Constructor) {
5995  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5996          !Constructor->doesThisDeclarationHaveABody() &&
5997          !Constructor->isDeleted()) &&
5998    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
5999
6000  CXXRecordDecl *ClassDecl = Constructor->getParent();
6001  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6002
6003  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6004  DiagnosticErrorTrap Trap(Diags);
6005  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6006      Trap.hasErrorOccurred()) {
6007    Diag(CurrentLocation, diag::note_member_synthesized_at)
6008      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6009    Constructor->setInvalidDecl();
6010    return;
6011  }
6012
6013  SourceLocation Loc = Constructor->getLocation();
6014  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6015
6016  Constructor->setUsed();
6017  MarkVTableUsed(CurrentLocation, ClassDecl);
6018
6019  if (ASTMutationListener *L = getASTMutationListener()) {
6020    L->CompletedImplicitDefinition(Constructor);
6021  }
6022}
6023
6024/// Get any existing defaulted default constructor for the given class. Do not
6025/// implicitly define one if it does not exist.
6026static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6027                                                             CXXRecordDecl *D) {
6028  ASTContext &Context = Self.Context;
6029  QualType ClassType = Context.getTypeDeclType(D);
6030  DeclarationName ConstructorName
6031    = Context.DeclarationNames.getCXXConstructorName(
6032                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6033
6034  DeclContext::lookup_const_iterator Con, ConEnd;
6035  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6036       Con != ConEnd; ++Con) {
6037    // A function template cannot be defaulted.
6038    if (isa<FunctionTemplateDecl>(*Con))
6039      continue;
6040
6041    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6042    if (Constructor->isDefaultConstructor())
6043      return Constructor->isDefaulted() ? Constructor : 0;
6044  }
6045  return 0;
6046}
6047
6048void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6049  if (!D) return;
6050  AdjustDeclIfTemplate(D);
6051
6052  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6053  CXXConstructorDecl *CtorDecl
6054    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6055
6056  if (!CtorDecl) return;
6057
6058  // Compute the exception specification for the default constructor.
6059  const FunctionProtoType *CtorTy =
6060    CtorDecl->getType()->castAs<FunctionProtoType>();
6061  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6062    ImplicitExceptionSpecification Spec =
6063      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6064    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6065    assert(EPI.ExceptionSpecType != EST_Delayed);
6066
6067    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6068  }
6069
6070  // If the default constructor is explicitly defaulted, checking the exception
6071  // specification is deferred until now.
6072  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6073      !ClassDecl->isDependentType())
6074    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6075}
6076
6077void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6078  // We start with an initial pass over the base classes to collect those that
6079  // inherit constructors from. If there are none, we can forgo all further
6080  // processing.
6081  typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6082  BasesVector BasesToInheritFrom;
6083  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6084                                          BaseE = ClassDecl->bases_end();
6085         BaseIt != BaseE; ++BaseIt) {
6086    if (BaseIt->getInheritConstructors()) {
6087      QualType Base = BaseIt->getType();
6088      if (Base->isDependentType()) {
6089        // If we inherit constructors from anything that is dependent, just
6090        // abort processing altogether. We'll get another chance for the
6091        // instantiations.
6092        return;
6093      }
6094      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6095    }
6096  }
6097  if (BasesToInheritFrom.empty())
6098    return;
6099
6100  // Now collect the constructors that we already have in the current class.
6101  // Those take precedence over inherited constructors.
6102  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6103  //   unless there is a user-declared constructor with the same signature in
6104  //   the class where the using-declaration appears.
6105  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6106  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6107                                    CtorE = ClassDecl->ctor_end();
6108       CtorIt != CtorE; ++CtorIt) {
6109    ExistingConstructors.insert(
6110        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6111  }
6112
6113  Scope *S = getScopeForContext(ClassDecl);
6114  DeclarationName CreatedCtorName =
6115      Context.DeclarationNames.getCXXConstructorName(
6116          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6117
6118  // Now comes the true work.
6119  // First, we keep a map from constructor types to the base that introduced
6120  // them. Needed for finding conflicting constructors. We also keep the
6121  // actually inserted declarations in there, for pretty diagnostics.
6122  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6123  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6124  ConstructorToSourceMap InheritedConstructors;
6125  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6126                             BaseE = BasesToInheritFrom.end();
6127       BaseIt != BaseE; ++BaseIt) {
6128    const RecordType *Base = *BaseIt;
6129    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6130    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6131    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6132                                      CtorE = BaseDecl->ctor_end();
6133         CtorIt != CtorE; ++CtorIt) {
6134      // Find the using declaration for inheriting this base's constructors.
6135      DeclarationName Name =
6136          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6137      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6138          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6139      SourceLocation UsingLoc = UD ? UD->getLocation() :
6140                                     ClassDecl->getLocation();
6141
6142      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6143      //   from the class X named in the using-declaration consists of actual
6144      //   constructors and notional constructors that result from the
6145      //   transformation of defaulted parameters as follows:
6146      //   - all non-template default constructors of X, and
6147      //   - for each non-template constructor of X that has at least one
6148      //     parameter with a default argument, the set of constructors that
6149      //     results from omitting any ellipsis parameter specification and
6150      //     successively omitting parameters with a default argument from the
6151      //     end of the parameter-type-list.
6152      CXXConstructorDecl *BaseCtor = *CtorIt;
6153      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6154      const FunctionProtoType *BaseCtorType =
6155          BaseCtor->getType()->getAs<FunctionProtoType>();
6156
6157      for (unsigned params = BaseCtor->getMinRequiredArguments(),
6158                    maxParams = BaseCtor->getNumParams();
6159           params <= maxParams; ++params) {
6160        // Skip default constructors. They're never inherited.
6161        if (params == 0)
6162          continue;
6163        // Skip copy and move constructors for the same reason.
6164        if (CanBeCopyOrMove && params == 1)
6165          continue;
6166
6167        // Build up a function type for this particular constructor.
6168        // FIXME: The working paper does not consider that the exception spec
6169        // for the inheriting constructor might be larger than that of the
6170        // source. This code doesn't yet, either. When it does, this code will
6171        // need to be delayed until after exception specifications and in-class
6172        // member initializers are attached.
6173        const Type *NewCtorType;
6174        if (params == maxParams)
6175          NewCtorType = BaseCtorType;
6176        else {
6177          llvm::SmallVector<QualType, 16> Args;
6178          for (unsigned i = 0; i < params; ++i) {
6179            Args.push_back(BaseCtorType->getArgType(i));
6180          }
6181          FunctionProtoType::ExtProtoInfo ExtInfo =
6182              BaseCtorType->getExtProtoInfo();
6183          ExtInfo.Variadic = false;
6184          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6185                                                Args.data(), params, ExtInfo)
6186                       .getTypePtr();
6187        }
6188        const Type *CanonicalNewCtorType =
6189            Context.getCanonicalType(NewCtorType);
6190
6191        // Now that we have the type, first check if the class already has a
6192        // constructor with this signature.
6193        if (ExistingConstructors.count(CanonicalNewCtorType))
6194          continue;
6195
6196        // Then we check if we have already declared an inherited constructor
6197        // with this signature.
6198        std::pair<ConstructorToSourceMap::iterator, bool> result =
6199            InheritedConstructors.insert(std::make_pair(
6200                CanonicalNewCtorType,
6201                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6202        if (!result.second) {
6203          // Already in the map. If it came from a different class, that's an
6204          // error. Not if it's from the same.
6205          CanQualType PreviousBase = result.first->second.first;
6206          if (CanonicalBase != PreviousBase) {
6207            const CXXConstructorDecl *PrevCtor = result.first->second.second;
6208            const CXXConstructorDecl *PrevBaseCtor =
6209                PrevCtor->getInheritedConstructor();
6210            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6211
6212            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6213            Diag(BaseCtor->getLocation(),
6214                 diag::note_using_decl_constructor_conflict_current_ctor);
6215            Diag(PrevBaseCtor->getLocation(),
6216                 diag::note_using_decl_constructor_conflict_previous_ctor);
6217            Diag(PrevCtor->getLocation(),
6218                 diag::note_using_decl_constructor_conflict_previous_using);
6219          }
6220          continue;
6221        }
6222
6223        // OK, we're there, now add the constructor.
6224        // C++0x [class.inhctor]p8: [...] that would be performed by a
6225        //   user-writtern inline constructor [...]
6226        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6227        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6228            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6229            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6230            /*ImplicitlyDeclared=*/true);
6231        NewCtor->setAccess(BaseCtor->getAccess());
6232
6233        // Build up the parameter decls and add them.
6234        llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6235        for (unsigned i = 0; i < params; ++i) {
6236          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6237                                                   UsingLoc, UsingLoc,
6238                                                   /*IdentifierInfo=*/0,
6239                                                   BaseCtorType->getArgType(i),
6240                                                   /*TInfo=*/0, SC_None,
6241                                                   SC_None, /*DefaultArg=*/0));
6242        }
6243        NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6244        NewCtor->setInheritedConstructor(BaseCtor);
6245
6246        PushOnScopeChains(NewCtor, S, false);
6247        ClassDecl->addDecl(NewCtor);
6248        result.first->second.second = NewCtor;
6249      }
6250    }
6251  }
6252}
6253
6254Sema::ImplicitExceptionSpecification
6255Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6256  // C++ [except.spec]p14:
6257  //   An implicitly declared special member function (Clause 12) shall have
6258  //   an exception-specification.
6259  ImplicitExceptionSpecification ExceptSpec(Context);
6260  if (ClassDecl->isInvalidDecl())
6261    return ExceptSpec;
6262
6263  // Direct base-class destructors.
6264  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6265                                       BEnd = ClassDecl->bases_end();
6266       B != BEnd; ++B) {
6267    if (B->isVirtual()) // Handled below.
6268      continue;
6269
6270    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6271      ExceptSpec.CalledDecl(
6272                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6273  }
6274
6275  // Virtual base-class destructors.
6276  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6277                                       BEnd = ClassDecl->vbases_end();
6278       B != BEnd; ++B) {
6279    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6280      ExceptSpec.CalledDecl(
6281                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6282  }
6283
6284  // Field destructors.
6285  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6286                               FEnd = ClassDecl->field_end();
6287       F != FEnd; ++F) {
6288    if (const RecordType *RecordTy
6289        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6290      ExceptSpec.CalledDecl(
6291                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6292  }
6293
6294  return ExceptSpec;
6295}
6296
6297CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6298  // C++ [class.dtor]p2:
6299  //   If a class has no user-declared destructor, a destructor is
6300  //   declared implicitly. An implicitly-declared destructor is an
6301  //   inline public member of its class.
6302
6303  ImplicitExceptionSpecification Spec =
6304      ComputeDefaultedDtorExceptionSpec(ClassDecl);
6305  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6306
6307  // Create the actual destructor declaration.
6308  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6309
6310  CanQualType ClassType
6311    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6312  SourceLocation ClassLoc = ClassDecl->getLocation();
6313  DeclarationName Name
6314    = Context.DeclarationNames.getCXXDestructorName(ClassType);
6315  DeclarationNameInfo NameInfo(Name, ClassLoc);
6316  CXXDestructorDecl *Destructor
6317      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6318                                  /*isInline=*/true,
6319                                  /*isImplicitlyDeclared=*/true);
6320  Destructor->setAccess(AS_public);
6321  Destructor->setDefaulted();
6322  Destructor->setImplicit();
6323  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6324
6325  // Note that we have declared this destructor.
6326  ++ASTContext::NumImplicitDestructorsDeclared;
6327
6328  // Introduce this destructor into its scope.
6329  if (Scope *S = getScopeForContext(ClassDecl))
6330    PushOnScopeChains(Destructor, S, false);
6331  ClassDecl->addDecl(Destructor);
6332
6333  // This could be uniqued if it ever proves significant.
6334  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6335
6336  if (ShouldDeleteDestructor(Destructor))
6337    Destructor->setDeletedAsWritten();
6338
6339  AddOverriddenMethods(ClassDecl, Destructor);
6340
6341  return Destructor;
6342}
6343
6344void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6345                                    CXXDestructorDecl *Destructor) {
6346  assert((Destructor->isDefaulted() &&
6347          !Destructor->doesThisDeclarationHaveABody()) &&
6348         "DefineImplicitDestructor - call it for implicit default dtor");
6349  CXXRecordDecl *ClassDecl = Destructor->getParent();
6350  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6351
6352  if (Destructor->isInvalidDecl())
6353    return;
6354
6355  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6356
6357  DiagnosticErrorTrap Trap(Diags);
6358  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6359                                         Destructor->getParent());
6360
6361  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6362    Diag(CurrentLocation, diag::note_member_synthesized_at)
6363      << CXXDestructor << Context.getTagDeclType(ClassDecl);
6364
6365    Destructor->setInvalidDecl();
6366    return;
6367  }
6368
6369  SourceLocation Loc = Destructor->getLocation();
6370  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6371
6372  Destructor->setUsed();
6373  MarkVTableUsed(CurrentLocation, ClassDecl);
6374
6375  if (ASTMutationListener *L = getASTMutationListener()) {
6376    L->CompletedImplicitDefinition(Destructor);
6377  }
6378}
6379
6380void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6381                                         CXXDestructorDecl *destructor) {
6382  // C++11 [class.dtor]p3:
6383  //   A declaration of a destructor that does not have an exception-
6384  //   specification is implicitly considered to have the same exception-
6385  //   specification as an implicit declaration.
6386  const FunctionProtoType *dtorType = destructor->getType()->
6387                                        getAs<FunctionProtoType>();
6388  if (dtorType->hasExceptionSpec())
6389    return;
6390
6391  ImplicitExceptionSpecification exceptSpec =
6392      ComputeDefaultedDtorExceptionSpec(classDecl);
6393
6394  // Replace the destructor's type.
6395  FunctionProtoType::ExtProtoInfo epi;
6396  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6397  epi.NumExceptions = exceptSpec.size();
6398  epi.Exceptions = exceptSpec.data();
6399  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6400
6401  destructor->setType(ty);
6402
6403  // FIXME: If the destructor has a body that could throw, and the newly created
6404  // spec doesn't allow exceptions, we should emit a warning, because this
6405  // change in behavior can break conforming C++03 programs at runtime.
6406  // However, we don't have a body yet, so it needs to be done somewhere else.
6407}
6408
6409/// \brief Builds a statement that copies the given entity from \p From to
6410/// \c To.
6411///
6412/// This routine is used to copy the members of a class with an
6413/// implicitly-declared copy assignment operator. When the entities being
6414/// copied are arrays, this routine builds for loops to copy them.
6415///
6416/// \param S The Sema object used for type-checking.
6417///
6418/// \param Loc The location where the implicit copy is being generated.
6419///
6420/// \param T The type of the expressions being copied. Both expressions must
6421/// have this type.
6422///
6423/// \param To The expression we are copying to.
6424///
6425/// \param From The expression we are copying from.
6426///
6427/// \param CopyingBaseSubobject Whether we're copying a base subobject.
6428/// Otherwise, it's a non-static member subobject.
6429///
6430/// \param Depth Internal parameter recording the depth of the recursion.
6431///
6432/// \returns A statement or a loop that copies the expressions.
6433static StmtResult
6434BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
6435                      Expr *To, Expr *From,
6436                      bool CopyingBaseSubobject, unsigned Depth = 0) {
6437  // C++0x [class.copy]p30:
6438  //   Each subobject is assigned in the manner appropriate to its type:
6439  //
6440  //     - if the subobject is of class type, the copy assignment operator
6441  //       for the class is used (as if by explicit qualification; that is,
6442  //       ignoring any possible virtual overriding functions in more derived
6443  //       classes);
6444  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6445    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6446
6447    // Look for operator=.
6448    DeclarationName Name
6449      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6450    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6451    S.LookupQualifiedName(OpLookup, ClassDecl, false);
6452
6453    // Filter out any result that isn't a copy-assignment operator.
6454    LookupResult::Filter F = OpLookup.makeFilter();
6455    while (F.hasNext()) {
6456      NamedDecl *D = F.next();
6457      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6458        if (Method->isCopyAssignmentOperator())
6459          continue;
6460
6461      F.erase();
6462    }
6463    F.done();
6464
6465    // Suppress the protected check (C++ [class.protected]) for each of the
6466    // assignment operators we found. This strange dance is required when
6467    // we're assigning via a base classes's copy-assignment operator. To
6468    // ensure that we're getting the right base class subobject (without
6469    // ambiguities), we need to cast "this" to that subobject type; to
6470    // ensure that we don't go through the virtual call mechanism, we need
6471    // to qualify the operator= name with the base class (see below). However,
6472    // this means that if the base class has a protected copy assignment
6473    // operator, the protected member access check will fail. So, we
6474    // rewrite "protected" access to "public" access in this case, since we
6475    // know by construction that we're calling from a derived class.
6476    if (CopyingBaseSubobject) {
6477      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6478           L != LEnd; ++L) {
6479        if (L.getAccess() == AS_protected)
6480          L.setAccess(AS_public);
6481      }
6482    }
6483
6484    // Create the nested-name-specifier that will be used to qualify the
6485    // reference to operator=; this is required to suppress the virtual
6486    // call mechanism.
6487    CXXScopeSpec SS;
6488    SS.MakeTrivial(S.Context,
6489                   NestedNameSpecifier::Create(S.Context, 0, false,
6490                                               T.getTypePtr()),
6491                   Loc);
6492
6493    // Create the reference to operator=.
6494    ExprResult OpEqualRef
6495      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
6496                                   /*FirstQualifierInScope=*/0, OpLookup,
6497                                   /*TemplateArgs=*/0,
6498                                   /*SuppressQualifierCheck=*/true);
6499    if (OpEqualRef.isInvalid())
6500      return StmtError();
6501
6502    // Build the call to the assignment operator.
6503
6504    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
6505                                                  OpEqualRef.takeAs<Expr>(),
6506                                                  Loc, &From, 1, Loc);
6507    if (Call.isInvalid())
6508      return StmtError();
6509
6510    return S.Owned(Call.takeAs<Stmt>());
6511  }
6512
6513  //     - if the subobject is of scalar type, the built-in assignment
6514  //       operator is used.
6515  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6516  if (!ArrayTy) {
6517    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
6518    if (Assignment.isInvalid())
6519      return StmtError();
6520
6521    return S.Owned(Assignment.takeAs<Stmt>());
6522  }
6523
6524  //     - if the subobject is an array, each element is assigned, in the
6525  //       manner appropriate to the element type;
6526
6527  // Construct a loop over the array bounds, e.g.,
6528  //
6529  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6530  //
6531  // that will copy each of the array elements.
6532  QualType SizeType = S.Context.getSizeType();
6533
6534  // Create the iteration variable.
6535  IdentifierInfo *IterationVarName = 0;
6536  {
6537    llvm::SmallString<8> Str;
6538    llvm::raw_svector_ostream OS(Str);
6539    OS << "__i" << Depth;
6540    IterationVarName = &S.Context.Idents.get(OS.str());
6541  }
6542  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
6543                                          IterationVarName, SizeType,
6544                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
6545                                          SC_None, SC_None);
6546
6547  // Initialize the iteration variable to zero.
6548  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
6549  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
6550
6551  // Create a reference to the iteration variable; we'll use this several
6552  // times throughout.
6553  Expr *IterationVarRef
6554    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
6555  assert(IterationVarRef && "Reference to invented variable cannot fail!");
6556
6557  // Create the DeclStmt that holds the iteration variable.
6558  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6559
6560  // Create the comparison against the array bound.
6561  llvm::APInt Upper
6562    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
6563  Expr *Comparison
6564    = new (S.Context) BinaryOperator(IterationVarRef,
6565                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6566                                     BO_NE, S.Context.BoolTy,
6567                                     VK_RValue, OK_Ordinary, Loc);
6568
6569  // Create the pre-increment of the iteration variable.
6570  Expr *Increment
6571    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6572                                    VK_LValue, OK_Ordinary, Loc);
6573
6574  // Subscript the "from" and "to" expressions with the iteration variable.
6575  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6576                                                         IterationVarRef, Loc));
6577  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6578                                                       IterationVarRef, Loc));
6579
6580  // Build the copy for an individual element of the array.
6581  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6582                                          To, From, CopyingBaseSubobject,
6583                                          Depth + 1);
6584  if (Copy.isInvalid())
6585    return StmtError();
6586
6587  // Construct the loop that copies all elements of this array.
6588  return S.ActOnForStmt(Loc, Loc, InitStmt,
6589                        S.MakeFullExpr(Comparison),
6590                        0, S.MakeFullExpr(Increment),
6591                        Loc, Copy.take());
6592}
6593
6594std::pair<Sema::ImplicitExceptionSpecification, bool>
6595Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6596                                                   CXXRecordDecl *ClassDecl) {
6597  if (ClassDecl->isInvalidDecl())
6598    return std::make_pair(ImplicitExceptionSpecification(Context), false);
6599
6600  // C++ [class.copy]p10:
6601  //   If the class definition does not explicitly declare a copy
6602  //   assignment operator, one is declared implicitly.
6603  //   The implicitly-defined copy assignment operator for a class X
6604  //   will have the form
6605  //
6606  //       X& X::operator=(const X&)
6607  //
6608  //   if
6609  bool HasConstCopyAssignment = true;
6610
6611  //       -- each direct base class B of X has a copy assignment operator
6612  //          whose parameter is of type const B&, const volatile B& or B,
6613  //          and
6614  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6615                                       BaseEnd = ClassDecl->bases_end();
6616       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6617    // We'll handle this below
6618    if (LangOpts.CPlusPlus0x && Base->isVirtual())
6619      continue;
6620
6621    assert(!Base->getType()->isDependentType() &&
6622           "Cannot generate implicit members for class with dependent bases.");
6623    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6624    LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6625                            &HasConstCopyAssignment);
6626  }
6627
6628  // In C++0x, the above citation has "or virtual added"
6629  if (LangOpts.CPlusPlus0x) {
6630    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6631                                         BaseEnd = ClassDecl->vbases_end();
6632         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6633      assert(!Base->getType()->isDependentType() &&
6634             "Cannot generate implicit members for class with dependent bases.");
6635      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
6636      LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
6637                              &HasConstCopyAssignment);
6638    }
6639  }
6640
6641  //       -- for all the nonstatic data members of X that are of a class
6642  //          type M (or array thereof), each such class type has a copy
6643  //          assignment operator whose parameter is of type const M&,
6644  //          const volatile M& or M.
6645  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6646                                  FieldEnd = ClassDecl->field_end();
6647       HasConstCopyAssignment && Field != FieldEnd;
6648       ++Field) {
6649    QualType FieldType = Context.getBaseElementType((*Field)->getType());
6650    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6651      LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
6652                              &HasConstCopyAssignment);
6653    }
6654  }
6655
6656  //   Otherwise, the implicitly declared copy assignment operator will
6657  //   have the form
6658  //
6659  //       X& X::operator=(X&)
6660
6661  // C++ [except.spec]p14:
6662  //   An implicitly declared special member function (Clause 12) shall have an
6663  //   exception-specification. [...]
6664
6665  // It is unspecified whether or not an implicit copy assignment operator
6666  // attempts to deduplicate calls to assignment operators of virtual bases are
6667  // made. As such, this exception specification is effectively unspecified.
6668  // Based on a similar decision made for constness in C++0x, we're erring on
6669  // the side of assuming such calls to be made regardless of whether they
6670  // actually happen.
6671  ImplicitExceptionSpecification ExceptSpec(Context);
6672  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
6673  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6674                                       BaseEnd = ClassDecl->bases_end();
6675       Base != BaseEnd; ++Base) {
6676    if (Base->isVirtual())
6677      continue;
6678
6679    CXXRecordDecl *BaseClassDecl
6680      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6681    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6682                                                            ArgQuals, false, 0))
6683      ExceptSpec.CalledDecl(CopyAssign);
6684  }
6685
6686  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
6687                                       BaseEnd = ClassDecl->vbases_end();
6688       Base != BaseEnd; ++Base) {
6689    CXXRecordDecl *BaseClassDecl
6690      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6691    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
6692                                                            ArgQuals, false, 0))
6693      ExceptSpec.CalledDecl(CopyAssign);
6694  }
6695
6696  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6697                                  FieldEnd = ClassDecl->field_end();
6698       Field != FieldEnd;
6699       ++Field) {
6700    QualType FieldType = Context.getBaseElementType((*Field)->getType());
6701    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
6702      if (CXXMethodDecl *CopyAssign =
6703          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
6704        ExceptSpec.CalledDecl(CopyAssign);
6705    }
6706  }
6707
6708  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6709}
6710
6711CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6712  // Note: The following rules are largely analoguous to the copy
6713  // constructor rules. Note that virtual bases are not taken into account
6714  // for determining the argument type of the operator. Note also that
6715  // operators taking an object instead of a reference are allowed.
6716
6717  ImplicitExceptionSpecification Spec(Context);
6718  bool Const;
6719  llvm::tie(Spec, Const) =
6720    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6721
6722  QualType ArgType = Context.getTypeDeclType(ClassDecl);
6723  QualType RetType = Context.getLValueReferenceType(ArgType);
6724  if (Const)
6725    ArgType = ArgType.withConst();
6726  ArgType = Context.getLValueReferenceType(ArgType);
6727
6728  //   An implicitly-declared copy assignment operator is an inline public
6729  //   member of its class.
6730  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6731  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6732  SourceLocation ClassLoc = ClassDecl->getLocation();
6733  DeclarationNameInfo NameInfo(Name, ClassLoc);
6734  CXXMethodDecl *CopyAssignment
6735    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6736                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
6737                            /*TInfo=*/0, /*isStatic=*/false,
6738                            /*StorageClassAsWritten=*/SC_None,
6739                            /*isInline=*/true,
6740                            SourceLocation());
6741  CopyAssignment->setAccess(AS_public);
6742  CopyAssignment->setDefaulted();
6743  CopyAssignment->setImplicit();
6744  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
6745
6746  // Add the parameter to the operator.
6747  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
6748                                               ClassLoc, ClassLoc, /*Id=*/0,
6749                                               ArgType, /*TInfo=*/0,
6750                                               SC_None,
6751                                               SC_None, 0);
6752  CopyAssignment->setParams(&FromParam, 1);
6753
6754  // Note that we have added this copy-assignment operator.
6755  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
6756
6757  if (Scope *S = getScopeForContext(ClassDecl))
6758    PushOnScopeChains(CopyAssignment, S, false);
6759  ClassDecl->addDecl(CopyAssignment);
6760
6761  // C++0x [class.copy]p18:
6762  //   ... If the class definition declares a move constructor or move
6763  //   assignment operator, the implicitly declared copy assignment operator is
6764  //   defined as deleted; ...
6765  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
6766      ClassDecl->hasUserDeclaredMoveAssignment() ||
6767      ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6768    CopyAssignment->setDeletedAsWritten();
6769
6770  AddOverriddenMethods(ClassDecl, CopyAssignment);
6771  return CopyAssignment;
6772}
6773
6774void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6775                                        CXXMethodDecl *CopyAssignOperator) {
6776  assert((CopyAssignOperator->isDefaulted() &&
6777          CopyAssignOperator->isOverloadedOperator() &&
6778          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
6779          !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
6780         "DefineImplicitCopyAssignment called for wrong function");
6781
6782  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6783
6784  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6785    CopyAssignOperator->setInvalidDecl();
6786    return;
6787  }
6788
6789  CopyAssignOperator->setUsed();
6790
6791  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
6792  DiagnosticErrorTrap Trap(Diags);
6793
6794  // C++0x [class.copy]p30:
6795  //   The implicitly-defined or explicitly-defaulted copy assignment operator
6796  //   for a non-union class X performs memberwise copy assignment of its
6797  //   subobjects. The direct base classes of X are assigned first, in the
6798  //   order of their declaration in the base-specifier-list, and then the
6799  //   immediate non-static data members of X are assigned, in the order in
6800  //   which they were declared in the class definition.
6801
6802  // The statements that form the synthesized function body.
6803  ASTOwningVector<Stmt*> Statements(*this);
6804
6805  // The parameter for the "other" object, which we are copying from.
6806  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6807  Qualifiers OtherQuals = Other->getType().getQualifiers();
6808  QualType OtherRefType = Other->getType();
6809  if (const LValueReferenceType *OtherRef
6810                                = OtherRefType->getAs<LValueReferenceType>()) {
6811    OtherRefType = OtherRef->getPointeeType();
6812    OtherQuals = OtherRefType.getQualifiers();
6813  }
6814
6815  // Our location for everything implicitly-generated.
6816  SourceLocation Loc = CopyAssignOperator->getLocation();
6817
6818  // Construct a reference to the "other" object. We'll be using this
6819  // throughout the generated ASTs.
6820  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
6821  assert(OtherRef && "Reference to parameter cannot fail!");
6822
6823  // Construct the "this" pointer. We'll be using this throughout the generated
6824  // ASTs.
6825  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6826  assert(This && "Reference to this cannot fail!");
6827
6828  // Assign base classes.
6829  bool Invalid = false;
6830  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6831       E = ClassDecl->bases_end(); Base != E; ++Base) {
6832    // Form the assignment:
6833    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6834    QualType BaseType = Base->getType().getUnqualifiedType();
6835    if (!BaseType->isRecordType()) {
6836      Invalid = true;
6837      continue;
6838    }
6839
6840    CXXCastPath BasePath;
6841    BasePath.push_back(Base);
6842
6843    // Construct the "from" expression, which is an implicit cast to the
6844    // appropriately-qualified base type.
6845    Expr *From = OtherRef;
6846    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6847                             CK_UncheckedDerivedToBase,
6848                             VK_LValue, &BasePath).take();
6849
6850    // Dereference "this".
6851    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
6852
6853    // Implicitly cast "this" to the appropriately-qualified base type.
6854    To = ImpCastExprToType(To.take(),
6855                           Context.getCVRQualifiedType(BaseType,
6856                                     CopyAssignOperator->getTypeQualifiers()),
6857                           CK_UncheckedDerivedToBase,
6858                           VK_LValue, &BasePath);
6859
6860    // Build the copy.
6861    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
6862                                            To.get(), From,
6863                                            /*CopyingBaseSubobject=*/true);
6864    if (Copy.isInvalid()) {
6865      Diag(CurrentLocation, diag::note_member_synthesized_at)
6866        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6867      CopyAssignOperator->setInvalidDecl();
6868      return;
6869    }
6870
6871    // Success! Record the copy.
6872    Statements.push_back(Copy.takeAs<Expr>());
6873  }
6874
6875  // \brief Reference to the __builtin_memcpy function.
6876  Expr *BuiltinMemCpyRef = 0;
6877  // \brief Reference to the __builtin_objc_memmove_collectable function.
6878  Expr *CollectableMemCpyRef = 0;
6879
6880  // Assign non-static members.
6881  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6882                                  FieldEnd = ClassDecl->field_end();
6883       Field != FieldEnd; ++Field) {
6884    // Check for members of reference type; we can't copy those.
6885    if (Field->getType()->isReferenceType()) {
6886      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6887        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6888      Diag(Field->getLocation(), diag::note_declared_at);
6889      Diag(CurrentLocation, diag::note_member_synthesized_at)
6890        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6891      Invalid = true;
6892      continue;
6893    }
6894
6895    // Check for members of const-qualified, non-class type.
6896    QualType BaseType = Context.getBaseElementType(Field->getType());
6897    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
6898      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6899        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
6900      Diag(Field->getLocation(), diag::note_declared_at);
6901      Diag(CurrentLocation, diag::note_member_synthesized_at)
6902        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6903      Invalid = true;
6904      continue;
6905    }
6906
6907    // Suppress assigning zero-width bitfields.
6908    if (const Expr *Width = Field->getBitWidth())
6909      if (Width->EvaluateAsInt(Context) == 0)
6910        continue;
6911
6912    QualType FieldType = Field->getType().getNonReferenceType();
6913    if (FieldType->isIncompleteArrayType()) {
6914      assert(ClassDecl->hasFlexibleArrayMember() &&
6915             "Incomplete array type is not valid");
6916      continue;
6917    }
6918
6919    // Build references to the field in the object we're copying from and to.
6920    CXXScopeSpec SS; // Intentionally empty
6921    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
6922                              LookupMemberName);
6923    MemberLookup.addDecl(*Field);
6924    MemberLookup.resolveKind();
6925    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
6926                                               Loc, /*IsArrow=*/false,
6927                                               SS, 0, MemberLookup, 0);
6928    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
6929                                             Loc, /*IsArrow=*/true,
6930                                             SS, 0, MemberLookup, 0);
6931    assert(!From.isInvalid() && "Implicit field reference cannot fail");
6932    assert(!To.isInvalid() && "Implicit field reference cannot fail");
6933
6934    // If the field should be copied with __builtin_memcpy rather than via
6935    // explicit assignments, do so. This optimization only applies for arrays
6936    // of scalars and arrays of class type with trivial copy-assignment
6937    // operators.
6938    if (FieldType->isArrayType() &&
6939        BaseType.hasTrivialCopyAssignment(Context)) {
6940      // Compute the size of the memory buffer to be copied.
6941      QualType SizeType = Context.getSizeType();
6942      llvm::APInt Size(Context.getTypeSize(SizeType),
6943                       Context.getTypeSizeInChars(BaseType).getQuantity());
6944      for (const ConstantArrayType *Array
6945              = Context.getAsConstantArrayType(FieldType);
6946           Array;
6947           Array = Context.getAsConstantArrayType(Array->getElementType())) {
6948        llvm::APInt ArraySize
6949          = Array->getSize().zextOrTrunc(Size.getBitWidth());
6950        Size *= ArraySize;
6951      }
6952
6953      // Take the address of the field references for "from" and "to".
6954      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
6955      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
6956
6957      bool NeedsCollectableMemCpy =
6958          (BaseType->isRecordType() &&
6959           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
6960
6961      if (NeedsCollectableMemCpy) {
6962        if (!CollectableMemCpyRef) {
6963          // Create a reference to the __builtin_objc_memmove_collectable function.
6964          LookupResult R(*this,
6965                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
6966                         Loc, LookupOrdinaryName);
6967          LookupName(R, TUScope, true);
6968
6969          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
6970          if (!CollectableMemCpy) {
6971            // Something went horribly wrong earlier, and we will have
6972            // complained about it.
6973            Invalid = true;
6974            continue;
6975          }
6976
6977          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
6978                                                  CollectableMemCpy->getType(),
6979                                                  VK_LValue, Loc, 0).take();
6980          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
6981        }
6982      }
6983      // Create a reference to the __builtin_memcpy builtin function.
6984      else if (!BuiltinMemCpyRef) {
6985        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
6986                       LookupOrdinaryName);
6987        LookupName(R, TUScope, true);
6988
6989        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
6990        if (!BuiltinMemCpy) {
6991          // Something went horribly wrong earlier, and we will have complained
6992          // about it.
6993          Invalid = true;
6994          continue;
6995        }
6996
6997        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
6998                                            BuiltinMemCpy->getType(),
6999                                            VK_LValue, Loc, 0).take();
7000        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7001      }
7002
7003      ASTOwningVector<Expr*> CallArgs(*this);
7004      CallArgs.push_back(To.takeAs<Expr>());
7005      CallArgs.push_back(From.takeAs<Expr>());
7006      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7007      ExprResult Call = ExprError();
7008      if (NeedsCollectableMemCpy)
7009        Call = ActOnCallExpr(/*Scope=*/0,
7010                             CollectableMemCpyRef,
7011                             Loc, move_arg(CallArgs),
7012                             Loc);
7013      else
7014        Call = ActOnCallExpr(/*Scope=*/0,
7015                             BuiltinMemCpyRef,
7016                             Loc, move_arg(CallArgs),
7017                             Loc);
7018
7019      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7020      Statements.push_back(Call.takeAs<Expr>());
7021      continue;
7022    }
7023
7024    // Build the copy of this field.
7025    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7026                                                  To.get(), From.get(),
7027                                              /*CopyingBaseSubobject=*/false);
7028    if (Copy.isInvalid()) {
7029      Diag(CurrentLocation, diag::note_member_synthesized_at)
7030        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7031      CopyAssignOperator->setInvalidDecl();
7032      return;
7033    }
7034
7035    // Success! Record the copy.
7036    Statements.push_back(Copy.takeAs<Stmt>());
7037  }
7038
7039  if (!Invalid) {
7040    // Add a "return *this;"
7041    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7042
7043    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7044    if (Return.isInvalid())
7045      Invalid = true;
7046    else {
7047      Statements.push_back(Return.takeAs<Stmt>());
7048
7049      if (Trap.hasErrorOccurred()) {
7050        Diag(CurrentLocation, diag::note_member_synthesized_at)
7051          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7052        Invalid = true;
7053      }
7054    }
7055  }
7056
7057  if (Invalid) {
7058    CopyAssignOperator->setInvalidDecl();
7059    return;
7060  }
7061
7062  StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7063                                            /*isStmtExpr=*/false);
7064  assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7065  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7066
7067  if (ASTMutationListener *L = getASTMutationListener()) {
7068    L->CompletedImplicitDefinition(CopyAssignOperator);
7069  }
7070}
7071
7072std::pair<Sema::ImplicitExceptionSpecification, bool>
7073Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
7074  if (ClassDecl->isInvalidDecl())
7075    return std::make_pair(ImplicitExceptionSpecification(Context), false);
7076
7077  // C++ [class.copy]p5:
7078  //   The implicitly-declared copy constructor for a class X will
7079  //   have the form
7080  //
7081  //       X::X(const X&)
7082  //
7083  //   if
7084  // FIXME: It ought to be possible to store this on the record.
7085  bool HasConstCopyConstructor = true;
7086
7087  //     -- each direct or virtual base class B of X has a copy
7088  //        constructor whose first parameter is of type const B& or
7089  //        const volatile B&, and
7090  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7091                                       BaseEnd = ClassDecl->bases_end();
7092       HasConstCopyConstructor && Base != BaseEnd;
7093       ++Base) {
7094    // Virtual bases are handled below.
7095    if (Base->isVirtual())
7096      continue;
7097
7098    CXXRecordDecl *BaseClassDecl
7099      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7100    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7101                             &HasConstCopyConstructor);
7102  }
7103
7104  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7105                                       BaseEnd = ClassDecl->vbases_end();
7106       HasConstCopyConstructor && Base != BaseEnd;
7107       ++Base) {
7108    CXXRecordDecl *BaseClassDecl
7109      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7110    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
7111                             &HasConstCopyConstructor);
7112  }
7113
7114  //     -- for all the nonstatic data members of X that are of a
7115  //        class type M (or array thereof), each such class type
7116  //        has a copy constructor whose first parameter is of type
7117  //        const M& or const volatile M&.
7118  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7119                                  FieldEnd = ClassDecl->field_end();
7120       HasConstCopyConstructor && Field != FieldEnd;
7121       ++Field) {
7122    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7123    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7124      LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
7125                               &HasConstCopyConstructor);
7126    }
7127  }
7128  //   Otherwise, the implicitly declared copy constructor will have
7129  //   the form
7130  //
7131  //       X::X(X&)
7132
7133  // C++ [except.spec]p14:
7134  //   An implicitly declared special member function (Clause 12) shall have an
7135  //   exception-specification. [...]
7136  ImplicitExceptionSpecification ExceptSpec(Context);
7137  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7138  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7139                                       BaseEnd = ClassDecl->bases_end();
7140       Base != BaseEnd;
7141       ++Base) {
7142    // Virtual bases are handled below.
7143    if (Base->isVirtual())
7144      continue;
7145
7146    CXXRecordDecl *BaseClassDecl
7147      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7148    if (CXXConstructorDecl *CopyConstructor =
7149          LookupCopyingConstructor(BaseClassDecl, Quals))
7150      ExceptSpec.CalledDecl(CopyConstructor);
7151  }
7152  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7153                                       BaseEnd = ClassDecl->vbases_end();
7154       Base != BaseEnd;
7155       ++Base) {
7156    CXXRecordDecl *BaseClassDecl
7157      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7158    if (CXXConstructorDecl *CopyConstructor =
7159          LookupCopyingConstructor(BaseClassDecl, Quals))
7160      ExceptSpec.CalledDecl(CopyConstructor);
7161  }
7162  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7163                                  FieldEnd = ClassDecl->field_end();
7164       Field != FieldEnd;
7165       ++Field) {
7166    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7167    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7168      if (CXXConstructorDecl *CopyConstructor =
7169        LookupCopyingConstructor(FieldClassDecl, Quals))
7170      ExceptSpec.CalledDecl(CopyConstructor);
7171    }
7172  }
7173
7174  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7175}
7176
7177CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7178                                                    CXXRecordDecl *ClassDecl) {
7179  // C++ [class.copy]p4:
7180  //   If the class definition does not explicitly declare a copy
7181  //   constructor, one is declared implicitly.
7182
7183  ImplicitExceptionSpecification Spec(Context);
7184  bool Const;
7185  llvm::tie(Spec, Const) =
7186    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7187
7188  QualType ClassType = Context.getTypeDeclType(ClassDecl);
7189  QualType ArgType = ClassType;
7190  if (Const)
7191    ArgType = ArgType.withConst();
7192  ArgType = Context.getLValueReferenceType(ArgType);
7193
7194  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7195
7196  DeclarationName Name
7197    = Context.DeclarationNames.getCXXConstructorName(
7198                                           Context.getCanonicalType(ClassType));
7199  SourceLocation ClassLoc = ClassDecl->getLocation();
7200  DeclarationNameInfo NameInfo(Name, ClassLoc);
7201
7202  //   An implicitly-declared copy constructor is an inline public
7203  //   member of its class.
7204  CXXConstructorDecl *CopyConstructor
7205    = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7206                                 Context.getFunctionType(Context.VoidTy,
7207                                                         &ArgType, 1, EPI),
7208                                 /*TInfo=*/0,
7209                                 /*isExplicit=*/false,
7210                                 /*isInline=*/true,
7211                                 /*isImplicitlyDeclared=*/true);
7212  CopyConstructor->setAccess(AS_public);
7213  CopyConstructor->setDefaulted();
7214  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7215
7216  // Note that we have declared this constructor.
7217  ++ASTContext::NumImplicitCopyConstructorsDeclared;
7218
7219  // Add the parameter to the constructor.
7220  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
7221                                               ClassLoc, ClassLoc,
7222                                               /*IdentifierInfo=*/0,
7223                                               ArgType, /*TInfo=*/0,
7224                                               SC_None,
7225                                               SC_None, 0);
7226  CopyConstructor->setParams(&FromParam, 1);
7227
7228  if (Scope *S = getScopeForContext(ClassDecl))
7229    PushOnScopeChains(CopyConstructor, S, false);
7230  ClassDecl->addDecl(CopyConstructor);
7231
7232  // C++0x [class.copy]p7:
7233  //   ... If the class definition declares a move constructor or move
7234  //   assignment operator, the implicitly declared constructor is defined as
7235  //   deleted; ...
7236  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7237      ClassDecl->hasUserDeclaredMoveAssignment() ||
7238      ShouldDeleteCopyConstructor(CopyConstructor))
7239    CopyConstructor->setDeletedAsWritten();
7240
7241  return CopyConstructor;
7242}
7243
7244void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
7245                                   CXXConstructorDecl *CopyConstructor) {
7246  assert((CopyConstructor->isDefaulted() &&
7247          CopyConstructor->isCopyConstructor() &&
7248          !CopyConstructor->doesThisDeclarationHaveABody()) &&
7249         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
7250
7251  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
7252  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
7253
7254  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
7255  DiagnosticErrorTrap Trap(Diags);
7256
7257  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
7258      Trap.hasErrorOccurred()) {
7259    Diag(CurrentLocation, diag::note_member_synthesized_at)
7260      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
7261    CopyConstructor->setInvalidDecl();
7262  }  else {
7263    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7264                                               CopyConstructor->getLocation(),
7265                                               MultiStmtArg(*this, 0, 0),
7266                                               /*isStmtExpr=*/false)
7267                                                              .takeAs<Stmt>());
7268  }
7269
7270  CopyConstructor->setUsed();
7271
7272  if (ASTMutationListener *L = getASTMutationListener()) {
7273    L->CompletedImplicitDefinition(CopyConstructor);
7274  }
7275}
7276
7277ExprResult
7278Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7279                            CXXConstructorDecl *Constructor,
7280                            MultiExprArg ExprArgs,
7281                            bool RequiresZeroInit,
7282                            unsigned ConstructKind,
7283                            SourceRange ParenRange) {
7284  bool Elidable = false;
7285
7286  // C++0x [class.copy]p34:
7287  //   When certain criteria are met, an implementation is allowed to
7288  //   omit the copy/move construction of a class object, even if the
7289  //   copy/move constructor and/or destructor for the object have
7290  //   side effects. [...]
7291  //     - when a temporary class object that has not been bound to a
7292  //       reference (12.2) would be copied/moved to a class object
7293  //       with the same cv-unqualified type, the copy/move operation
7294  //       can be omitted by constructing the temporary object
7295  //       directly into the target of the omitted copy/move
7296  if (ConstructKind == CXXConstructExpr::CK_Complete &&
7297      Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
7298    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
7299    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
7300  }
7301
7302  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
7303                               Elidable, move(ExprArgs), RequiresZeroInit,
7304                               ConstructKind, ParenRange);
7305}
7306
7307/// BuildCXXConstructExpr - Creates a complete call to a constructor,
7308/// including handling of its default argument expressions.
7309ExprResult
7310Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7311                            CXXConstructorDecl *Constructor, bool Elidable,
7312                            MultiExprArg ExprArgs,
7313                            bool RequiresZeroInit,
7314                            unsigned ConstructKind,
7315                            SourceRange ParenRange) {
7316  unsigned NumExprs = ExprArgs.size();
7317  Expr **Exprs = (Expr **)ExprArgs.release();
7318
7319  for (specific_attr_iterator<NonNullAttr>
7320           i = Constructor->specific_attr_begin<NonNullAttr>(),
7321           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7322    const NonNullAttr *NonNull = *i;
7323    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7324  }
7325
7326  MarkDeclarationReferenced(ConstructLoc, Constructor);
7327  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
7328                                        Constructor, Elidable, Exprs, NumExprs,
7329                                        RequiresZeroInit,
7330              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7331                                        ParenRange));
7332}
7333
7334bool Sema::InitializeVarWithConstructor(VarDecl *VD,
7335                                        CXXConstructorDecl *Constructor,
7336                                        MultiExprArg Exprs) {
7337  // FIXME: Provide the correct paren SourceRange when available.
7338  ExprResult TempResult =
7339    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
7340                          move(Exprs), false, CXXConstructExpr::CK_Complete,
7341                          SourceRange());
7342  if (TempResult.isInvalid())
7343    return true;
7344
7345  Expr *Temp = TempResult.takeAs<Expr>();
7346  CheckImplicitConversions(Temp, VD->getLocation());
7347  MarkDeclarationReferenced(VD->getLocation(), Constructor);
7348  Temp = MaybeCreateExprWithCleanups(Temp);
7349  VD->setInit(Temp);
7350
7351  return false;
7352}
7353
7354void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
7355  if (VD->isInvalidDecl()) return;
7356
7357  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
7358  if (ClassDecl->isInvalidDecl()) return;
7359  if (ClassDecl->hasTrivialDestructor()) return;
7360  if (ClassDecl->isDependentContext()) return;
7361
7362  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7363  MarkDeclarationReferenced(VD->getLocation(), Destructor);
7364  CheckDestructorAccess(VD->getLocation(), Destructor,
7365                        PDiag(diag::err_access_dtor_var)
7366                        << VD->getDeclName()
7367                        << VD->getType());
7368
7369  if (!VD->hasGlobalStorage()) return;
7370
7371  // Emit warning for non-trivial dtor in global scope (a real global,
7372  // class-static, function-static).
7373  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7374
7375  // TODO: this should be re-enabled for static locals by !CXAAtExit
7376  if (!VD->isStaticLocal())
7377    Diag(VD->getLocation(), diag::warn_global_destructor);
7378}
7379
7380/// AddCXXDirectInitializerToDecl - This action is called immediately after
7381/// ActOnDeclarator, when a C++ direct initializer is present.
7382/// e.g: "int x(1);"
7383void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
7384                                         SourceLocation LParenLoc,
7385                                         MultiExprArg Exprs,
7386                                         SourceLocation RParenLoc,
7387                                         bool TypeMayContainAuto) {
7388  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
7389
7390  // If there is no declaration, there was an error parsing it.  Just ignore
7391  // the initializer.
7392  if (RealDecl == 0)
7393    return;
7394
7395  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7396  if (!VDecl) {
7397    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7398    RealDecl->setInvalidDecl();
7399    return;
7400  }
7401
7402  // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7403  if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
7404    // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7405    if (Exprs.size() > 1) {
7406      Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7407           diag::err_auto_var_init_multiple_expressions)
7408        << VDecl->getDeclName() << VDecl->getType()
7409        << VDecl->getSourceRange();
7410      RealDecl->setInvalidDecl();
7411      return;
7412    }
7413
7414    Expr *Init = Exprs.get()[0];
7415    TypeSourceInfo *DeducedType = 0;
7416    if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
7417      Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7418        << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7419        << Init->getSourceRange();
7420    if (!DeducedType) {
7421      RealDecl->setInvalidDecl();
7422      return;
7423    }
7424    VDecl->setTypeSourceInfo(DeducedType);
7425    VDecl->setType(DeducedType->getType());
7426
7427    // In ARC, infer lifetime.
7428    if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
7429      VDecl->setInvalidDecl();
7430
7431    // If this is a redeclaration, check that the type we just deduced matches
7432    // the previously declared type.
7433    if (VarDecl *Old = VDecl->getPreviousDeclaration())
7434      MergeVarDeclTypes(VDecl, Old);
7435  }
7436
7437  // We will represent direct-initialization similarly to copy-initialization:
7438  //    int x(1);  -as-> int x = 1;
7439  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7440  //
7441  // Clients that want to distinguish between the two forms, can check for
7442  // direct initializer using VarDecl::hasCXXDirectInitializer().
7443  // A major benefit is that clients that don't particularly care about which
7444  // exactly form was it (like the CodeGen) can handle both cases without
7445  // special case code.
7446
7447  // C++ 8.5p11:
7448  // The form of initialization (using parentheses or '=') is generally
7449  // insignificant, but does matter when the entity being initialized has a
7450  // class type.
7451
7452  if (!VDecl->getType()->isDependentType() &&
7453      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
7454                          diag::err_typecheck_decl_incomplete_type)) {
7455    VDecl->setInvalidDecl();
7456    return;
7457  }
7458
7459  // The variable can not have an abstract class type.
7460  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7461                             diag::err_abstract_type_in_decl,
7462                             AbstractVariableType))
7463    VDecl->setInvalidDecl();
7464
7465  const VarDecl *Def;
7466  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
7467    Diag(VDecl->getLocation(), diag::err_redefinition)
7468    << VDecl->getDeclName();
7469    Diag(Def->getLocation(), diag::note_previous_definition);
7470    VDecl->setInvalidDecl();
7471    return;
7472  }
7473
7474  // C++ [class.static.data]p4
7475  //   If a static data member is of const integral or const
7476  //   enumeration type, its declaration in the class definition can
7477  //   specify a constant-initializer which shall be an integral
7478  //   constant expression (5.19). In that case, the member can appear
7479  //   in integral constant expressions. The member shall still be
7480  //   defined in a namespace scope if it is used in the program and the
7481  //   namespace scope definition shall not contain an initializer.
7482  //
7483  // We already performed a redefinition check above, but for static
7484  // data members we also need to check whether there was an in-class
7485  // declaration with an initializer.
7486  const VarDecl* PrevInit = 0;
7487  if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7488    Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7489    Diag(PrevInit->getLocation(), diag::note_previous_definition);
7490    return;
7491  }
7492
7493  bool IsDependent = false;
7494  for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7495    if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7496      VDecl->setInvalidDecl();
7497      return;
7498    }
7499
7500    if (Exprs.get()[I]->isTypeDependent())
7501      IsDependent = true;
7502  }
7503
7504  // If either the declaration has a dependent type or if any of the
7505  // expressions is type-dependent, we represent the initialization
7506  // via a ParenListExpr for later use during template instantiation.
7507  if (VDecl->getType()->isDependentType() || IsDependent) {
7508    // Let clients know that initialization was done with a direct initializer.
7509    VDecl->setCXXDirectInitializer(true);
7510
7511    // Store the initialization expressions as a ParenListExpr.
7512    unsigned NumExprs = Exprs.size();
7513    VDecl->setInit(new (Context) ParenListExpr(
7514        Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
7515        VDecl->getType().getNonReferenceType()));
7516    return;
7517  }
7518
7519  // Capture the variable that is being initialized and the style of
7520  // initialization.
7521  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7522
7523  // FIXME: Poor source location information.
7524  InitializationKind Kind
7525    = InitializationKind::CreateDirect(VDecl->getLocation(),
7526                                       LParenLoc, RParenLoc);
7527
7528  InitializationSequence InitSeq(*this, Entity, Kind,
7529                                 Exprs.get(), Exprs.size());
7530  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
7531  if (Result.isInvalid()) {
7532    VDecl->setInvalidDecl();
7533    return;
7534  }
7535
7536  CheckImplicitConversions(Result.get(), LParenLoc);
7537
7538  Result = MaybeCreateExprWithCleanups(Result);
7539  VDecl->setInit(Result.takeAs<Expr>());
7540  VDecl->setCXXDirectInitializer(true);
7541
7542  CheckCompleteVariableDeclaration(VDecl);
7543}
7544
7545/// \brief Given a constructor and the set of arguments provided for the
7546/// constructor, convert the arguments and add any required default arguments
7547/// to form a proper call to this constructor.
7548///
7549/// \returns true if an error occurred, false otherwise.
7550bool
7551Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7552                              MultiExprArg ArgsPtr,
7553                              SourceLocation Loc,
7554                              ASTOwningVector<Expr*> &ConvertedArgs) {
7555  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7556  unsigned NumArgs = ArgsPtr.size();
7557  Expr **Args = (Expr **)ArgsPtr.get();
7558
7559  const FunctionProtoType *Proto
7560    = Constructor->getType()->getAs<FunctionProtoType>();
7561  assert(Proto && "Constructor without a prototype?");
7562  unsigned NumArgsInProto = Proto->getNumArgs();
7563
7564  // If too few arguments are available, we'll fill in the rest with defaults.
7565  if (NumArgs < NumArgsInProto)
7566    ConvertedArgs.reserve(NumArgsInProto);
7567  else
7568    ConvertedArgs.reserve(NumArgs);
7569
7570  VariadicCallType CallType =
7571    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7572  llvm::SmallVector<Expr *, 8> AllArgs;
7573  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7574                                        Proto, 0, Args, NumArgs, AllArgs,
7575                                        CallType);
7576  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7577    ConvertedArgs.push_back(AllArgs[i]);
7578  return Invalid;
7579}
7580
7581static inline bool
7582CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7583                                       const FunctionDecl *FnDecl) {
7584  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
7585  if (isa<NamespaceDecl>(DC)) {
7586    return SemaRef.Diag(FnDecl->getLocation(),
7587                        diag::err_operator_new_delete_declared_in_namespace)
7588      << FnDecl->getDeclName();
7589  }
7590
7591  if (isa<TranslationUnitDecl>(DC) &&
7592      FnDecl->getStorageClass() == SC_Static) {
7593    return SemaRef.Diag(FnDecl->getLocation(),
7594                        diag::err_operator_new_delete_declared_static)
7595      << FnDecl->getDeclName();
7596  }
7597
7598  return false;
7599}
7600
7601static inline bool
7602CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7603                            CanQualType ExpectedResultType,
7604                            CanQualType ExpectedFirstParamType,
7605                            unsigned DependentParamTypeDiag,
7606                            unsigned InvalidParamTypeDiag) {
7607  QualType ResultType =
7608    FnDecl->getType()->getAs<FunctionType>()->getResultType();
7609
7610  // Check that the result type is not dependent.
7611  if (ResultType->isDependentType())
7612    return SemaRef.Diag(FnDecl->getLocation(),
7613                        diag::err_operator_new_delete_dependent_result_type)
7614    << FnDecl->getDeclName() << ExpectedResultType;
7615
7616  // Check that the result type is what we expect.
7617  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7618    return SemaRef.Diag(FnDecl->getLocation(),
7619                        diag::err_operator_new_delete_invalid_result_type)
7620    << FnDecl->getDeclName() << ExpectedResultType;
7621
7622  // A function template must have at least 2 parameters.
7623  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7624    return SemaRef.Diag(FnDecl->getLocation(),
7625                      diag::err_operator_new_delete_template_too_few_parameters)
7626        << FnDecl->getDeclName();
7627
7628  // The function decl must have at least 1 parameter.
7629  if (FnDecl->getNumParams() == 0)
7630    return SemaRef.Diag(FnDecl->getLocation(),
7631                        diag::err_operator_new_delete_too_few_parameters)
7632      << FnDecl->getDeclName();
7633
7634  // Check the the first parameter type is not dependent.
7635  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7636  if (FirstParamType->isDependentType())
7637    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7638      << FnDecl->getDeclName() << ExpectedFirstParamType;
7639
7640  // Check that the first parameter type is what we expect.
7641  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
7642      ExpectedFirstParamType)
7643    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7644    << FnDecl->getDeclName() << ExpectedFirstParamType;
7645
7646  return false;
7647}
7648
7649static bool
7650CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7651  // C++ [basic.stc.dynamic.allocation]p1:
7652  //   A program is ill-formed if an allocation function is declared in a
7653  //   namespace scope other than global scope or declared static in global
7654  //   scope.
7655  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7656    return true;
7657
7658  CanQualType SizeTy =
7659    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7660
7661  // C++ [basic.stc.dynamic.allocation]p1:
7662  //  The return type shall be void*. The first parameter shall have type
7663  //  std::size_t.
7664  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7665                                  SizeTy,
7666                                  diag::err_operator_new_dependent_param_type,
7667                                  diag::err_operator_new_param_type))
7668    return true;
7669
7670  // C++ [basic.stc.dynamic.allocation]p1:
7671  //  The first parameter shall not have an associated default argument.
7672  if (FnDecl->getParamDecl(0)->hasDefaultArg())
7673    return SemaRef.Diag(FnDecl->getLocation(),
7674                        diag::err_operator_new_default_arg)
7675      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7676
7677  return false;
7678}
7679
7680static bool
7681CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7682  // C++ [basic.stc.dynamic.deallocation]p1:
7683  //   A program is ill-formed if deallocation functions are declared in a
7684  //   namespace scope other than global scope or declared static in global
7685  //   scope.
7686  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7687    return true;
7688
7689  // C++ [basic.stc.dynamic.deallocation]p2:
7690  //   Each deallocation function shall return void and its first parameter
7691  //   shall be void*.
7692  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7693                                  SemaRef.Context.VoidPtrTy,
7694                                 diag::err_operator_delete_dependent_param_type,
7695                                 diag::err_operator_delete_param_type))
7696    return true;
7697
7698  return false;
7699}
7700
7701/// CheckOverloadedOperatorDeclaration - Check whether the declaration
7702/// of this overloaded operator is well-formed. If so, returns false;
7703/// otherwise, emits appropriate diagnostics and returns true.
7704bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
7705  assert(FnDecl && FnDecl->isOverloadedOperator() &&
7706         "Expected an overloaded operator declaration");
7707
7708  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7709
7710  // C++ [over.oper]p5:
7711  //   The allocation and deallocation functions, operator new,
7712  //   operator new[], operator delete and operator delete[], are
7713  //   described completely in 3.7.3. The attributes and restrictions
7714  //   found in the rest of this subclause do not apply to them unless
7715  //   explicitly stated in 3.7.3.
7716  if (Op == OO_Delete || Op == OO_Array_Delete)
7717    return CheckOperatorDeleteDeclaration(*this, FnDecl);
7718
7719  if (Op == OO_New || Op == OO_Array_New)
7720    return CheckOperatorNewDeclaration(*this, FnDecl);
7721
7722  // C++ [over.oper]p6:
7723  //   An operator function shall either be a non-static member
7724  //   function or be a non-member function and have at least one
7725  //   parameter whose type is a class, a reference to a class, an
7726  //   enumeration, or a reference to an enumeration.
7727  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7728    if (MethodDecl->isStatic())
7729      return Diag(FnDecl->getLocation(),
7730                  diag::err_operator_overload_static) << FnDecl->getDeclName();
7731  } else {
7732    bool ClassOrEnumParam = false;
7733    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7734                                   ParamEnd = FnDecl->param_end();
7735         Param != ParamEnd; ++Param) {
7736      QualType ParamType = (*Param)->getType().getNonReferenceType();
7737      if (ParamType->isDependentType() || ParamType->isRecordType() ||
7738          ParamType->isEnumeralType()) {
7739        ClassOrEnumParam = true;
7740        break;
7741      }
7742    }
7743
7744    if (!ClassOrEnumParam)
7745      return Diag(FnDecl->getLocation(),
7746                  diag::err_operator_overload_needs_class_or_enum)
7747        << FnDecl->getDeclName();
7748  }
7749
7750  // C++ [over.oper]p8:
7751  //   An operator function cannot have default arguments (8.3.6),
7752  //   except where explicitly stated below.
7753  //
7754  // Only the function-call operator allows default arguments
7755  // (C++ [over.call]p1).
7756  if (Op != OO_Call) {
7757    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7758         Param != FnDecl->param_end(); ++Param) {
7759      if ((*Param)->hasDefaultArg())
7760        return Diag((*Param)->getLocation(),
7761                    diag::err_operator_overload_default_arg)
7762          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
7763    }
7764  }
7765
7766  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7767    { false, false, false }
7768#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7769    , { Unary, Binary, MemberOnly }
7770#include "clang/Basic/OperatorKinds.def"
7771  };
7772
7773  bool CanBeUnaryOperator = OperatorUses[Op][0];
7774  bool CanBeBinaryOperator = OperatorUses[Op][1];
7775  bool MustBeMemberOperator = OperatorUses[Op][2];
7776
7777  // C++ [over.oper]p8:
7778  //   [...] Operator functions cannot have more or fewer parameters
7779  //   than the number required for the corresponding operator, as
7780  //   described in the rest of this subclause.
7781  unsigned NumParams = FnDecl->getNumParams()
7782                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
7783  if (Op != OO_Call &&
7784      ((NumParams == 1 && !CanBeUnaryOperator) ||
7785       (NumParams == 2 && !CanBeBinaryOperator) ||
7786       (NumParams < 1) || (NumParams > 2))) {
7787    // We have the wrong number of parameters.
7788    unsigned ErrorKind;
7789    if (CanBeUnaryOperator && CanBeBinaryOperator) {
7790      ErrorKind = 2;  // 2 -> unary or binary.
7791    } else if (CanBeUnaryOperator) {
7792      ErrorKind = 0;  // 0 -> unary
7793    } else {
7794      assert(CanBeBinaryOperator &&
7795             "All non-call overloaded operators are unary or binary!");
7796      ErrorKind = 1;  // 1 -> binary
7797    }
7798
7799    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
7800      << FnDecl->getDeclName() << NumParams << ErrorKind;
7801  }
7802
7803  // Overloaded operators other than operator() cannot be variadic.
7804  if (Op != OO_Call &&
7805      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
7806    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
7807      << FnDecl->getDeclName();
7808  }
7809
7810  // Some operators must be non-static member functions.
7811  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7812    return Diag(FnDecl->getLocation(),
7813                diag::err_operator_overload_must_be_member)
7814      << FnDecl->getDeclName();
7815  }
7816
7817  // C++ [over.inc]p1:
7818  //   The user-defined function called operator++ implements the
7819  //   prefix and postfix ++ operator. If this function is a member
7820  //   function with no parameters, or a non-member function with one
7821  //   parameter of class or enumeration type, it defines the prefix
7822  //   increment operator ++ for objects of that type. If the function
7823  //   is a member function with one parameter (which shall be of type
7824  //   int) or a non-member function with two parameters (the second
7825  //   of which shall be of type int), it defines the postfix
7826  //   increment operator ++ for objects of that type.
7827  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7828    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7829    bool ParamIsInt = false;
7830    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
7831      ParamIsInt = BT->getKind() == BuiltinType::Int;
7832
7833    if (!ParamIsInt)
7834      return Diag(LastParam->getLocation(),
7835                  diag::err_operator_overload_post_incdec_must_be_int)
7836        << LastParam->getType() << (Op == OO_MinusMinus);
7837  }
7838
7839  return false;
7840}
7841
7842/// CheckLiteralOperatorDeclaration - Check whether the declaration
7843/// of this literal operator function is well-formed. If so, returns
7844/// false; otherwise, emits appropriate diagnostics and returns true.
7845bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7846  DeclContext *DC = FnDecl->getDeclContext();
7847  Decl::Kind Kind = DC->getDeclKind();
7848  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7849      Kind != Decl::LinkageSpec) {
7850    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7851      << FnDecl->getDeclName();
7852    return true;
7853  }
7854
7855  bool Valid = false;
7856
7857  // template <char...> type operator "" name() is the only valid template
7858  // signature, and the only valid signature with no parameters.
7859  if (FnDecl->param_size() == 0) {
7860    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7861      // Must have only one template parameter
7862      TemplateParameterList *Params = TpDecl->getTemplateParameters();
7863      if (Params->size() == 1) {
7864        NonTypeTemplateParmDecl *PmDecl =
7865          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
7866
7867        // The template parameter must be a char parameter pack.
7868        if (PmDecl && PmDecl->isTemplateParameterPack() &&
7869            Context.hasSameType(PmDecl->getType(), Context.CharTy))
7870          Valid = true;
7871      }
7872    }
7873  } else {
7874    // Check the first parameter
7875    FunctionDecl::param_iterator Param = FnDecl->param_begin();
7876
7877    QualType T = (*Param)->getType();
7878
7879    // unsigned long long int, long double, and any character type are allowed
7880    // as the only parameters.
7881    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7882        Context.hasSameType(T, Context.LongDoubleTy) ||
7883        Context.hasSameType(T, Context.CharTy) ||
7884        Context.hasSameType(T, Context.WCharTy) ||
7885        Context.hasSameType(T, Context.Char16Ty) ||
7886        Context.hasSameType(T, Context.Char32Ty)) {
7887      if (++Param == FnDecl->param_end())
7888        Valid = true;
7889      goto FinishedParams;
7890    }
7891
7892    // Otherwise it must be a pointer to const; let's strip those qualifiers.
7893    const PointerType *PT = T->getAs<PointerType>();
7894    if (!PT)
7895      goto FinishedParams;
7896    T = PT->getPointeeType();
7897    if (!T.isConstQualified())
7898      goto FinishedParams;
7899    T = T.getUnqualifiedType();
7900
7901    // Move on to the second parameter;
7902    ++Param;
7903
7904    // If there is no second parameter, the first must be a const char *
7905    if (Param == FnDecl->param_end()) {
7906      if (Context.hasSameType(T, Context.CharTy))
7907        Valid = true;
7908      goto FinishedParams;
7909    }
7910
7911    // const char *, const wchar_t*, const char16_t*, and const char32_t*
7912    // are allowed as the first parameter to a two-parameter function
7913    if (!(Context.hasSameType(T, Context.CharTy) ||
7914          Context.hasSameType(T, Context.WCharTy) ||
7915          Context.hasSameType(T, Context.Char16Ty) ||
7916          Context.hasSameType(T, Context.Char32Ty)))
7917      goto FinishedParams;
7918
7919    // The second and final parameter must be an std::size_t
7920    T = (*Param)->getType().getUnqualifiedType();
7921    if (Context.hasSameType(T, Context.getSizeType()) &&
7922        ++Param == FnDecl->param_end())
7923      Valid = true;
7924  }
7925
7926  // FIXME: This diagnostic is absolutely terrible.
7927FinishedParams:
7928  if (!Valid) {
7929    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
7930      << FnDecl->getDeclName();
7931    return true;
7932  }
7933
7934  return false;
7935}
7936
7937/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
7938/// linkage specification, including the language and (if present)
7939/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
7940/// the location of the language string literal, which is provided
7941/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
7942/// the '{' brace. Otherwise, this linkage specification does not
7943/// have any braces.
7944Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
7945                                           SourceLocation LangLoc,
7946                                           llvm::StringRef Lang,
7947                                           SourceLocation LBraceLoc) {
7948  LinkageSpecDecl::LanguageIDs Language;
7949  if (Lang == "\"C\"")
7950    Language = LinkageSpecDecl::lang_c;
7951  else if (Lang == "\"C++\"")
7952    Language = LinkageSpecDecl::lang_cxx;
7953  else {
7954    Diag(LangLoc, diag::err_bad_language);
7955    return 0;
7956  }
7957
7958  // FIXME: Add all the various semantics of linkage specifications
7959
7960  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
7961                                               ExternLoc, LangLoc, Language);
7962  CurContext->addDecl(D);
7963  PushDeclContext(S, D);
7964  return D;
7965}
7966
7967/// ActOnFinishLinkageSpecification - Complete the definition of
7968/// the C++ linkage specification LinkageSpec. If RBraceLoc is
7969/// valid, it's the position of the closing '}' brace in a linkage
7970/// specification that uses braces.
7971Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
7972                                            Decl *LinkageSpec,
7973                                            SourceLocation RBraceLoc) {
7974  if (LinkageSpec) {
7975    if (RBraceLoc.isValid()) {
7976      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
7977      LSDecl->setRBraceLoc(RBraceLoc);
7978    }
7979    PopDeclContext();
7980  }
7981  return LinkageSpec;
7982}
7983
7984/// \brief Perform semantic analysis for the variable declaration that
7985/// occurs within a C++ catch clause, returning the newly-created
7986/// variable.
7987VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
7988                                         TypeSourceInfo *TInfo,
7989                                         SourceLocation StartLoc,
7990                                         SourceLocation Loc,
7991                                         IdentifierInfo *Name) {
7992  bool Invalid = false;
7993  QualType ExDeclType = TInfo->getType();
7994
7995  // Arrays and functions decay.
7996  if (ExDeclType->isArrayType())
7997    ExDeclType = Context.getArrayDecayedType(ExDeclType);
7998  else if (ExDeclType->isFunctionType())
7999    ExDeclType = Context.getPointerType(ExDeclType);
8000
8001  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8002  // The exception-declaration shall not denote a pointer or reference to an
8003  // incomplete type, other than [cv] void*.
8004  // N2844 forbids rvalue references.
8005  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
8006    Diag(Loc, diag::err_catch_rvalue_ref);
8007    Invalid = true;
8008  }
8009
8010  // GCC allows catching pointers and references to incomplete types
8011  // as an extension; so do we, but we warn by default.
8012
8013  QualType BaseType = ExDeclType;
8014  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
8015  unsigned DK = diag::err_catch_incomplete;
8016  bool IncompleteCatchIsInvalid = true;
8017  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
8018    BaseType = Ptr->getPointeeType();
8019    Mode = 1;
8020    DK = diag::ext_catch_incomplete_ptr;
8021    IncompleteCatchIsInvalid = false;
8022  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
8023    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
8024    BaseType = Ref->getPointeeType();
8025    Mode = 2;
8026    DK = diag::ext_catch_incomplete_ref;
8027    IncompleteCatchIsInvalid = false;
8028  }
8029  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
8030      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8031      IncompleteCatchIsInvalid)
8032    Invalid = true;
8033
8034  if (!Invalid && !ExDeclType->isDependentType() &&
8035      RequireNonAbstractType(Loc, ExDeclType,
8036                             diag::err_abstract_type_in_decl,
8037                             AbstractVariableType))
8038    Invalid = true;
8039
8040  // Only the non-fragile NeXT runtime currently supports C++ catches
8041  // of ObjC types, and no runtime supports catching ObjC types by value.
8042  if (!Invalid && getLangOptions().ObjC1) {
8043    QualType T = ExDeclType;
8044    if (const ReferenceType *RT = T->getAs<ReferenceType>())
8045      T = RT->getPointeeType();
8046
8047    if (T->isObjCObjectType()) {
8048      Diag(Loc, diag::err_objc_object_catch);
8049      Invalid = true;
8050    } else if (T->isObjCObjectPointerType()) {
8051      if (!getLangOptions().ObjCNonFragileABI)
8052        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
8053    }
8054  }
8055
8056  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8057                                    ExDeclType, TInfo, SC_None, SC_None);
8058  ExDecl->setExceptionVariable(true);
8059
8060  if (!Invalid && !ExDeclType->isDependentType()) {
8061    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
8062      // C++ [except.handle]p16:
8063      //   The object declared in an exception-declaration or, if the
8064      //   exception-declaration does not specify a name, a temporary (12.2) is
8065      //   copy-initialized (8.5) from the exception object. [...]
8066      //   The object is destroyed when the handler exits, after the destruction
8067      //   of any automatic objects initialized within the handler.
8068      //
8069      // We just pretend to initialize the object with itself, then make sure
8070      // it can be destroyed later.
8071      QualType initType = ExDeclType;
8072
8073      InitializedEntity entity =
8074        InitializedEntity::InitializeVariable(ExDecl);
8075      InitializationKind initKind =
8076        InitializationKind::CreateCopy(Loc, SourceLocation());
8077
8078      Expr *opaqueValue =
8079        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8080      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8081      ExprResult result = sequence.Perform(*this, entity, initKind,
8082                                           MultiExprArg(&opaqueValue, 1));
8083      if (result.isInvalid())
8084        Invalid = true;
8085      else {
8086        // If the constructor used was non-trivial, set this as the
8087        // "initializer".
8088        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8089        if (!construct->getConstructor()->isTrivial()) {
8090          Expr *init = MaybeCreateExprWithCleanups(construct);
8091          ExDecl->setInit(init);
8092        }
8093
8094        // And make sure it's destructable.
8095        FinalizeVarWithDestructor(ExDecl, recordType);
8096      }
8097    }
8098  }
8099
8100  if (Invalid)
8101    ExDecl->setInvalidDecl();
8102
8103  return ExDecl;
8104}
8105
8106/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8107/// handler.
8108Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
8109  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8110  bool Invalid = D.isInvalidType();
8111
8112  // Check for unexpanded parameter packs.
8113  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8114                                               UPPC_ExceptionType)) {
8115    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8116                                             D.getIdentifierLoc());
8117    Invalid = true;
8118  }
8119
8120  IdentifierInfo *II = D.getIdentifier();
8121  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
8122                                             LookupOrdinaryName,
8123                                             ForRedeclaration)) {
8124    // The scope should be freshly made just for us. There is just no way
8125    // it contains any previous declaration.
8126    assert(!S->isDeclScope(PrevDecl));
8127    if (PrevDecl->isTemplateParameter()) {
8128      // Maybe we will complain about the shadowed template parameter.
8129      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8130    }
8131  }
8132
8133  if (D.getCXXScopeSpec().isSet() && !Invalid) {
8134    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8135      << D.getCXXScopeSpec().getRange();
8136    Invalid = true;
8137  }
8138
8139  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
8140                                              D.getSourceRange().getBegin(),
8141                                              D.getIdentifierLoc(),
8142                                              D.getIdentifier());
8143  if (Invalid)
8144    ExDecl->setInvalidDecl();
8145
8146  // Add the exception declaration into this scope.
8147  if (II)
8148    PushOnScopeChains(ExDecl, S);
8149  else
8150    CurContext->addDecl(ExDecl);
8151
8152  ProcessDeclAttributes(S, ExDecl, D);
8153  return ExDecl;
8154}
8155
8156Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
8157                                         Expr *AssertExpr,
8158                                         Expr *AssertMessageExpr_,
8159                                         SourceLocation RParenLoc) {
8160  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
8161
8162  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8163    llvm::APSInt Value(32);
8164    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
8165      Diag(StaticAssertLoc,
8166           diag::err_static_assert_expression_is_not_constant) <<
8167        AssertExpr->getSourceRange();
8168      return 0;
8169    }
8170
8171    if (Value == 0) {
8172      Diag(StaticAssertLoc, diag::err_static_assert_failed)
8173        << AssertMessage->getString() << AssertExpr->getSourceRange();
8174    }
8175  }
8176
8177  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8178    return 0;
8179
8180  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8181                                        AssertExpr, AssertMessage, RParenLoc);
8182
8183  CurContext->addDecl(Decl);
8184  return Decl;
8185}
8186
8187/// \brief Perform semantic analysis of the given friend type declaration.
8188///
8189/// \returns A friend declaration that.
8190FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8191                                      TypeSourceInfo *TSInfo) {
8192  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8193
8194  QualType T = TSInfo->getType();
8195  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
8196
8197  if (!getLangOptions().CPlusPlus0x) {
8198    // C++03 [class.friend]p2:
8199    //   An elaborated-type-specifier shall be used in a friend declaration
8200    //   for a class.*
8201    //
8202    //   * The class-key of the elaborated-type-specifier is required.
8203    if (!ActiveTemplateInstantiations.empty()) {
8204      // Do not complain about the form of friend template types during
8205      // template instantiation; we will already have complained when the
8206      // template was declared.
8207    } else if (!T->isElaboratedTypeSpecifier()) {
8208      // If we evaluated the type to a record type, suggest putting
8209      // a tag in front.
8210      if (const RecordType *RT = T->getAs<RecordType>()) {
8211        RecordDecl *RD = RT->getDecl();
8212
8213        std::string InsertionText = std::string(" ") + RD->getKindName();
8214
8215        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8216          << (unsigned) RD->getTagKind()
8217          << T
8218          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8219                                        InsertionText);
8220      } else {
8221        Diag(FriendLoc, diag::ext_nonclass_type_friend)
8222          << T
8223          << SourceRange(FriendLoc, TypeRange.getEnd());
8224      }
8225    } else if (T->getAs<EnumType>()) {
8226      Diag(FriendLoc, diag::ext_enum_friend)
8227        << T
8228        << SourceRange(FriendLoc, TypeRange.getEnd());
8229    }
8230  }
8231
8232  // C++0x [class.friend]p3:
8233  //   If the type specifier in a friend declaration designates a (possibly
8234  //   cv-qualified) class type, that class is declared as a friend; otherwise,
8235  //   the friend declaration is ignored.
8236
8237  // FIXME: C++0x has some syntactic restrictions on friend type declarations
8238  // in [class.friend]p3 that we do not implement.
8239
8240  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8241}
8242
8243/// Handle a friend tag declaration where the scope specifier was
8244/// templated.
8245Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8246                                    unsigned TagSpec, SourceLocation TagLoc,
8247                                    CXXScopeSpec &SS,
8248                                    IdentifierInfo *Name, SourceLocation NameLoc,
8249                                    AttributeList *Attr,
8250                                    MultiTemplateParamsArg TempParamLists) {
8251  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8252
8253  bool isExplicitSpecialization = false;
8254  bool Invalid = false;
8255
8256  if (TemplateParameterList *TemplateParams
8257        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
8258                                                  TempParamLists.get(),
8259                                                  TempParamLists.size(),
8260                                                  /*friend*/ true,
8261                                                  isExplicitSpecialization,
8262                                                  Invalid)) {
8263    if (TemplateParams->size() > 0) {
8264      // This is a declaration of a class template.
8265      if (Invalid)
8266        return 0;
8267
8268      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8269                                SS, Name, NameLoc, Attr,
8270                                TemplateParams, AS_public,
8271                                TempParamLists.size() - 1,
8272                   (TemplateParameterList**) TempParamLists.release()).take();
8273    } else {
8274      // The "template<>" header is extraneous.
8275      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8276        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8277      isExplicitSpecialization = true;
8278    }
8279  }
8280
8281  if (Invalid) return 0;
8282
8283  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8284
8285  bool isAllExplicitSpecializations = true;
8286  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
8287    if (TempParamLists.get()[I]->size()) {
8288      isAllExplicitSpecializations = false;
8289      break;
8290    }
8291  }
8292
8293  // FIXME: don't ignore attributes.
8294
8295  // If it's explicit specializations all the way down, just forget
8296  // about the template header and build an appropriate non-templated
8297  // friend.  TODO: for source fidelity, remember the headers.
8298  if (isAllExplicitSpecializations) {
8299    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8300    ElaboratedTypeKeyword Keyword
8301      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8302    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
8303                                   *Name, NameLoc);
8304    if (T.isNull())
8305      return 0;
8306
8307    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8308    if (isa<DependentNameType>(T)) {
8309      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8310      TL.setKeywordLoc(TagLoc);
8311      TL.setQualifierLoc(QualifierLoc);
8312      TL.setNameLoc(NameLoc);
8313    } else {
8314      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8315      TL.setKeywordLoc(TagLoc);
8316      TL.setQualifierLoc(QualifierLoc);
8317      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8318    }
8319
8320    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8321                                            TSI, FriendLoc);
8322    Friend->setAccess(AS_public);
8323    CurContext->addDecl(Friend);
8324    return Friend;
8325  }
8326
8327  // Handle the case of a templated-scope friend class.  e.g.
8328  //   template <class T> class A<T>::B;
8329  // FIXME: we don't support these right now.
8330  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8331  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8332  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8333  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8334  TL.setKeywordLoc(TagLoc);
8335  TL.setQualifierLoc(SS.getWithLocInContext(Context));
8336  TL.setNameLoc(NameLoc);
8337
8338  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8339                                          TSI, FriendLoc);
8340  Friend->setAccess(AS_public);
8341  Friend->setUnsupportedFriend(true);
8342  CurContext->addDecl(Friend);
8343  return Friend;
8344}
8345
8346
8347/// Handle a friend type declaration.  This works in tandem with
8348/// ActOnTag.
8349///
8350/// Notes on friend class templates:
8351///
8352/// We generally treat friend class declarations as if they were
8353/// declaring a class.  So, for example, the elaborated type specifier
8354/// in a friend declaration is required to obey the restrictions of a
8355/// class-head (i.e. no typedefs in the scope chain), template
8356/// parameters are required to match up with simple template-ids, &c.
8357/// However, unlike when declaring a template specialization, it's
8358/// okay to refer to a template specialization without an empty
8359/// template parameter declaration, e.g.
8360///   friend class A<T>::B<unsigned>;
8361/// We permit this as a special case; if there are any template
8362/// parameters present at all, require proper matching, i.e.
8363///   template <> template <class T> friend class A<int>::B;
8364Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
8365                                MultiTemplateParamsArg TempParams) {
8366  SourceLocation Loc = DS.getSourceRange().getBegin();
8367
8368  assert(DS.isFriendSpecified());
8369  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8370
8371  // Try to convert the decl specifier to a type.  This works for
8372  // friend templates because ActOnTag never produces a ClassTemplateDecl
8373  // for a TUK_Friend.
8374  Declarator TheDeclarator(DS, Declarator::MemberContext);
8375  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8376  QualType T = TSI->getType();
8377  if (TheDeclarator.isInvalidType())
8378    return 0;
8379
8380  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8381    return 0;
8382
8383  // This is definitely an error in C++98.  It's probably meant to
8384  // be forbidden in C++0x, too, but the specification is just
8385  // poorly written.
8386  //
8387  // The problem is with declarations like the following:
8388  //   template <T> friend A<T>::foo;
8389  // where deciding whether a class C is a friend or not now hinges
8390  // on whether there exists an instantiation of A that causes
8391  // 'foo' to equal C.  There are restrictions on class-heads
8392  // (which we declare (by fiat) elaborated friend declarations to
8393  // be) that makes this tractable.
8394  //
8395  // FIXME: handle "template <> friend class A<T>;", which
8396  // is possibly well-formed?  Who even knows?
8397  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
8398    Diag(Loc, diag::err_tagless_friend_type_template)
8399      << DS.getSourceRange();
8400    return 0;
8401  }
8402
8403  // C++98 [class.friend]p1: A friend of a class is a function
8404  //   or class that is not a member of the class . . .
8405  // This is fixed in DR77, which just barely didn't make the C++03
8406  // deadline.  It's also a very silly restriction that seriously
8407  // affects inner classes and which nobody else seems to implement;
8408  // thus we never diagnose it, not even in -pedantic.
8409  //
8410  // But note that we could warn about it: it's always useless to
8411  // friend one of your own members (it's not, however, worthless to
8412  // friend a member of an arbitrary specialization of your template).
8413
8414  Decl *D;
8415  if (unsigned NumTempParamLists = TempParams.size())
8416    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
8417                                   NumTempParamLists,
8418                                   TempParams.release(),
8419                                   TSI,
8420                                   DS.getFriendSpecLoc());
8421  else
8422    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8423
8424  if (!D)
8425    return 0;
8426
8427  D->setAccess(AS_public);
8428  CurContext->addDecl(D);
8429
8430  return D;
8431}
8432
8433Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8434                                    MultiTemplateParamsArg TemplateParams) {
8435  const DeclSpec &DS = D.getDeclSpec();
8436
8437  assert(DS.isFriendSpecified());
8438  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8439
8440  SourceLocation Loc = D.getIdentifierLoc();
8441  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8442  QualType T = TInfo->getType();
8443
8444  // C++ [class.friend]p1
8445  //   A friend of a class is a function or class....
8446  // Note that this sees through typedefs, which is intended.
8447  // It *doesn't* see through dependent types, which is correct
8448  // according to [temp.arg.type]p3:
8449  //   If a declaration acquires a function type through a
8450  //   type dependent on a template-parameter and this causes
8451  //   a declaration that does not use the syntactic form of a
8452  //   function declarator to have a function type, the program
8453  //   is ill-formed.
8454  if (!T->isFunctionType()) {
8455    Diag(Loc, diag::err_unexpected_friend);
8456
8457    // It might be worthwhile to try to recover by creating an
8458    // appropriate declaration.
8459    return 0;
8460  }
8461
8462  // C++ [namespace.memdef]p3
8463  //  - If a friend declaration in a non-local class first declares a
8464  //    class or function, the friend class or function is a member
8465  //    of the innermost enclosing namespace.
8466  //  - The name of the friend is not found by simple name lookup
8467  //    until a matching declaration is provided in that namespace
8468  //    scope (either before or after the class declaration granting
8469  //    friendship).
8470  //  - If a friend function is called, its name may be found by the
8471  //    name lookup that considers functions from namespaces and
8472  //    classes associated with the types of the function arguments.
8473  //  - When looking for a prior declaration of a class or a function
8474  //    declared as a friend, scopes outside the innermost enclosing
8475  //    namespace scope are not considered.
8476
8477  CXXScopeSpec &SS = D.getCXXScopeSpec();
8478  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8479  DeclarationName Name = NameInfo.getName();
8480  assert(Name);
8481
8482  // Check for unexpanded parameter packs.
8483  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8484      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8485      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8486    return 0;
8487
8488  // The context we found the declaration in, or in which we should
8489  // create the declaration.
8490  DeclContext *DC;
8491  Scope *DCScope = S;
8492  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8493                        ForRedeclaration);
8494
8495  // FIXME: there are different rules in local classes
8496
8497  // There are four cases here.
8498  //   - There's no scope specifier, in which case we just go to the
8499  //     appropriate scope and look for a function or function template
8500  //     there as appropriate.
8501  // Recover from invalid scope qualifiers as if they just weren't there.
8502  if (SS.isInvalid() || !SS.isSet()) {
8503    // C++0x [namespace.memdef]p3:
8504    //   If the name in a friend declaration is neither qualified nor
8505    //   a template-id and the declaration is a function or an
8506    //   elaborated-type-specifier, the lookup to determine whether
8507    //   the entity has been previously declared shall not consider
8508    //   any scopes outside the innermost enclosing namespace.
8509    // C++0x [class.friend]p11:
8510    //   If a friend declaration appears in a local class and the name
8511    //   specified is an unqualified name, a prior declaration is
8512    //   looked up without considering scopes that are outside the
8513    //   innermost enclosing non-class scope. For a friend function
8514    //   declaration, if there is no prior declaration, the program is
8515    //   ill-formed.
8516    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
8517    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
8518
8519    // Find the appropriate context according to the above.
8520    DC = CurContext;
8521    while (true) {
8522      // Skip class contexts.  If someone can cite chapter and verse
8523      // for this behavior, that would be nice --- it's what GCC and
8524      // EDG do, and it seems like a reasonable intent, but the spec
8525      // really only says that checks for unqualified existing
8526      // declarations should stop at the nearest enclosing namespace,
8527      // not that they should only consider the nearest enclosing
8528      // namespace.
8529      while (DC->isRecord())
8530        DC = DC->getParent();
8531
8532      LookupQualifiedName(Previous, DC);
8533
8534      // TODO: decide what we think about using declarations.
8535      if (isLocal || !Previous.empty())
8536        break;
8537
8538      if (isTemplateId) {
8539        if (isa<TranslationUnitDecl>(DC)) break;
8540      } else {
8541        if (DC->isFileContext()) break;
8542      }
8543      DC = DC->getParent();
8544    }
8545
8546    // C++ [class.friend]p1: A friend of a class is a function or
8547    //   class that is not a member of the class . . .
8548    // C++0x changes this for both friend types and functions.
8549    // Most C++ 98 compilers do seem to give an error here, so
8550    // we do, too.
8551    if (!Previous.empty() && DC->Equals(CurContext)
8552        && !getLangOptions().CPlusPlus0x)
8553      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8554
8555    DCScope = getScopeForDeclContext(S, DC);
8556
8557  //   - There's a non-dependent scope specifier, in which case we
8558  //     compute it and do a previous lookup there for a function
8559  //     or function template.
8560  } else if (!SS.getScopeRep()->isDependent()) {
8561    DC = computeDeclContext(SS);
8562    if (!DC) return 0;
8563
8564    if (RequireCompleteDeclContext(SS, DC)) return 0;
8565
8566    LookupQualifiedName(Previous, DC);
8567
8568    // Ignore things found implicitly in the wrong scope.
8569    // TODO: better diagnostics for this case.  Suggesting the right
8570    // qualified scope would be nice...
8571    LookupResult::Filter F = Previous.makeFilter();
8572    while (F.hasNext()) {
8573      NamedDecl *D = F.next();
8574      if (!DC->InEnclosingNamespaceSetOf(
8575              D->getDeclContext()->getRedeclContext()))
8576        F.erase();
8577    }
8578    F.done();
8579
8580    if (Previous.empty()) {
8581      D.setInvalidType();
8582      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8583      return 0;
8584    }
8585
8586    // C++ [class.friend]p1: A friend of a class is a function or
8587    //   class that is not a member of the class . . .
8588    if (DC->Equals(CurContext))
8589      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8590
8591  //   - There's a scope specifier that does not match any template
8592  //     parameter lists, in which case we use some arbitrary context,
8593  //     create a method or method template, and wait for instantiation.
8594  //   - There's a scope specifier that does match some template
8595  //     parameter lists, which we don't handle right now.
8596  } else {
8597    DC = CurContext;
8598    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
8599  }
8600
8601  if (!DC->isRecord()) {
8602    // This implies that it has to be an operator or function.
8603    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8604        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8605        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
8606      Diag(Loc, diag::err_introducing_special_friend) <<
8607        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8608         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
8609      return 0;
8610    }
8611  }
8612
8613  bool Redeclaration = false;
8614  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
8615                                          move(TemplateParams),
8616                                          IsDefinition,
8617                                          Redeclaration);
8618  if (!ND) return 0;
8619
8620  assert(ND->getDeclContext() == DC);
8621  assert(ND->getLexicalDeclContext() == CurContext);
8622
8623  // Add the function declaration to the appropriate lookup tables,
8624  // adjusting the redeclarations list as necessary.  We don't
8625  // want to do this yet if the friending class is dependent.
8626  //
8627  // Also update the scope-based lookup if the target context's
8628  // lookup context is in lexical scope.
8629  if (!CurContext->isDependentContext()) {
8630    DC = DC->getRedeclContext();
8631    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
8632    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8633      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
8634  }
8635
8636  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
8637                                       D.getIdentifierLoc(), ND,
8638                                       DS.getFriendSpecLoc());
8639  FrD->setAccess(AS_public);
8640  CurContext->addDecl(FrD);
8641
8642  if (ND->isInvalidDecl())
8643    FrD->setInvalidDecl();
8644  else {
8645    FunctionDecl *FD;
8646    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8647      FD = FTD->getTemplatedDecl();
8648    else
8649      FD = cast<FunctionDecl>(ND);
8650
8651    // Mark templated-scope function declarations as unsupported.
8652    if (FD->getNumTemplateParameterLists())
8653      FrD->setUnsupportedFriend(true);
8654  }
8655
8656  return ND;
8657}
8658
8659void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8660  AdjustDeclIfTemplate(Dcl);
8661
8662  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8663  if (!Fn) {
8664    Diag(DelLoc, diag::err_deleted_non_function);
8665    return;
8666  }
8667  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8668    Diag(DelLoc, diag::err_deleted_decl_not_first);
8669    Diag(Prev->getLocation(), diag::note_previous_declaration);
8670    // If the declaration wasn't the first, we delete the function anyway for
8671    // recovery.
8672  }
8673  Fn->setDeletedAsWritten();
8674}
8675
8676void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8677  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8678
8679  if (MD) {
8680    if (MD->getParent()->isDependentType()) {
8681      MD->setDefaulted();
8682      MD->setExplicitlyDefaulted();
8683      return;
8684    }
8685
8686    CXXSpecialMember Member = getSpecialMember(MD);
8687    if (Member == CXXInvalid) {
8688      Diag(DefaultLoc, diag::err_default_special_members);
8689      return;
8690    }
8691
8692    MD->setDefaulted();
8693    MD->setExplicitlyDefaulted();
8694
8695    // If this definition appears within the record, do the checking when
8696    // the record is complete.
8697    const FunctionDecl *Primary = MD;
8698    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8699      // Find the uninstantiated declaration that actually had the '= default'
8700      // on it.
8701      MD->getTemplateInstantiationPattern()->isDefined(Primary);
8702
8703    if (Primary == Primary->getCanonicalDecl())
8704      return;
8705
8706    switch (Member) {
8707    case CXXDefaultConstructor: {
8708      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8709      CheckExplicitlyDefaultedDefaultConstructor(CD);
8710      if (!CD->isInvalidDecl())
8711        DefineImplicitDefaultConstructor(DefaultLoc, CD);
8712      break;
8713    }
8714
8715    case CXXCopyConstructor: {
8716      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8717      CheckExplicitlyDefaultedCopyConstructor(CD);
8718      if (!CD->isInvalidDecl())
8719        DefineImplicitCopyConstructor(DefaultLoc, CD);
8720      break;
8721    }
8722
8723    case CXXCopyAssignment: {
8724      CheckExplicitlyDefaultedCopyAssignment(MD);
8725      if (!MD->isInvalidDecl())
8726        DefineImplicitCopyAssignment(DefaultLoc, MD);
8727      break;
8728    }
8729
8730    case CXXDestructor: {
8731      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8732      CheckExplicitlyDefaultedDestructor(DD);
8733      if (!DD->isInvalidDecl())
8734        DefineImplicitDestructor(DefaultLoc, DD);
8735      break;
8736    }
8737
8738    case CXXMoveConstructor:
8739    case CXXMoveAssignment:
8740      Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8741      break;
8742
8743    default:
8744      // FIXME: Do the rest once we have move functions
8745      break;
8746    }
8747  } else {
8748    Diag(DefaultLoc, diag::err_default_special_members);
8749  }
8750}
8751
8752static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
8753  for (Stmt::child_range CI = S->children(); CI; ++CI) {
8754    Stmt *SubStmt = *CI;
8755    if (!SubStmt)
8756      continue;
8757    if (isa<ReturnStmt>(SubStmt))
8758      Self.Diag(SubStmt->getSourceRange().getBegin(),
8759           diag::err_return_in_constructor_handler);
8760    if (!isa<Expr>(SubStmt))
8761      SearchForReturnInStmt(Self, SubStmt);
8762  }
8763}
8764
8765void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8766  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8767    CXXCatchStmt *Handler = TryBlock->getHandler(I);
8768    SearchForReturnInStmt(*this, Handler);
8769  }
8770}
8771
8772bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
8773                                             const CXXMethodDecl *Old) {
8774  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8775  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
8776
8777  if (Context.hasSameType(NewTy, OldTy) ||
8778      NewTy->isDependentType() || OldTy->isDependentType())
8779    return false;
8780
8781  // Check if the return types are covariant
8782  QualType NewClassTy, OldClassTy;
8783
8784  /// Both types must be pointers or references to classes.
8785  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8786    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
8787      NewClassTy = NewPT->getPointeeType();
8788      OldClassTy = OldPT->getPointeeType();
8789    }
8790  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8791    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8792      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8793        NewClassTy = NewRT->getPointeeType();
8794        OldClassTy = OldRT->getPointeeType();
8795      }
8796    }
8797  }
8798
8799  // The return types aren't either both pointers or references to a class type.
8800  if (NewClassTy.isNull()) {
8801    Diag(New->getLocation(),
8802         diag::err_different_return_type_for_overriding_virtual_function)
8803      << New->getDeclName() << NewTy << OldTy;
8804    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8805
8806    return true;
8807  }
8808
8809  // C++ [class.virtual]p6:
8810  //   If the return type of D::f differs from the return type of B::f, the
8811  //   class type in the return type of D::f shall be complete at the point of
8812  //   declaration of D::f or shall be the class type D.
8813  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8814    if (!RT->isBeingDefined() &&
8815        RequireCompleteType(New->getLocation(), NewClassTy,
8816                            PDiag(diag::err_covariant_return_incomplete)
8817                              << New->getDeclName()))
8818    return true;
8819  }
8820
8821  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
8822    // Check if the new class derives from the old class.
8823    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8824      Diag(New->getLocation(),
8825           diag::err_covariant_return_not_derived)
8826      << New->getDeclName() << NewTy << OldTy;
8827      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8828      return true;
8829    }
8830
8831    // Check if we the conversion from derived to base is valid.
8832    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
8833                    diag::err_covariant_return_inaccessible_base,
8834                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
8835                    // FIXME: Should this point to the return type?
8836                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
8837      // FIXME: this note won't trigger for delayed access control
8838      // diagnostics, and it's impossible to get an undelayed error
8839      // here from access control during the original parse because
8840      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
8841      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8842      return true;
8843    }
8844  }
8845
8846  // The qualifiers of the return types must be the same.
8847  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
8848    Diag(New->getLocation(),
8849         diag::err_covariant_return_type_different_qualifications)
8850    << New->getDeclName() << NewTy << OldTy;
8851    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8852    return true;
8853  };
8854
8855
8856  // The new class type must have the same or less qualifiers as the old type.
8857  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8858    Diag(New->getLocation(),
8859         diag::err_covariant_return_type_class_type_more_qualified)
8860    << New->getDeclName() << NewTy << OldTy;
8861    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8862    return true;
8863  };
8864
8865  return false;
8866}
8867
8868/// \brief Mark the given method pure.
8869///
8870/// \param Method the method to be marked pure.
8871///
8872/// \param InitRange the source range that covers the "0" initializer.
8873bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
8874  SourceLocation EndLoc = InitRange.getEnd();
8875  if (EndLoc.isValid())
8876    Method->setRangeEnd(EndLoc);
8877
8878  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8879    Method->setPure();
8880    return false;
8881  }
8882
8883  if (!Method->isInvalidDecl())
8884    Diag(Method->getLocation(), diag::err_non_virtual_pure)
8885      << Method->getDeclName() << InitRange;
8886  return true;
8887}
8888
8889/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8890/// an initializer for the out-of-line declaration 'Dcl'.  The scope
8891/// is a fresh scope pushed for just this purpose.
8892///
8893/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8894/// static data member of class X, names should be looked up in the scope of
8895/// class X.
8896void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
8897  // If there is no declaration, there was an error parsing it.
8898  if (D == 0 || D->isInvalidDecl()) return;
8899
8900  // We should only get called for declarations with scope specifiers, like:
8901  //   int foo::bar;
8902  assert(D->isOutOfLine());
8903  EnterDeclaratorContext(S, D->getDeclContext());
8904}
8905
8906/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
8907/// initializer for the out-of-line declaration 'D'.
8908void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
8909  // If there is no declaration, there was an error parsing it.
8910  if (D == 0 || D->isInvalidDecl()) return;
8911
8912  assert(D->isOutOfLine());
8913  ExitDeclaratorContext(S);
8914}
8915
8916/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
8917/// C++ if/switch/while/for statement.
8918/// e.g: "if (int x = f()) {...}"
8919DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
8920  // C++ 6.4p2:
8921  // The declarator shall not specify a function or an array.
8922  // The type-specifier-seq shall not contain typedef and shall not declare a
8923  // new class or enumeration.
8924  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
8925         "Parser allowed 'typedef' as storage class of condition decl.");
8926
8927  Decl *Dcl = ActOnDeclarator(S, D);
8928  if (!Dcl)
8929    return true;
8930
8931  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
8932    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
8933      << D.getSourceRange();
8934    return true;
8935  }
8936
8937  return Dcl;
8938}
8939
8940void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
8941                          bool DefinitionRequired) {
8942  // Ignore any vtable uses in unevaluated operands or for classes that do
8943  // not have a vtable.
8944  if (!Class->isDynamicClass() || Class->isDependentContext() ||
8945      CurContext->isDependentContext() ||
8946      ExprEvalContexts.back().Context == Unevaluated)
8947    return;
8948
8949  // Try to insert this class into the map.
8950  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
8951  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
8952    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
8953  if (!Pos.second) {
8954    // If we already had an entry, check to see if we are promoting this vtable
8955    // to required a definition. If so, we need to reappend to the VTableUses
8956    // list, since we may have already processed the first entry.
8957    if (DefinitionRequired && !Pos.first->second) {
8958      Pos.first->second = true;
8959    } else {
8960      // Otherwise, we can early exit.
8961      return;
8962    }
8963  }
8964
8965  // Local classes need to have their virtual members marked
8966  // immediately. For all other classes, we mark their virtual members
8967  // at the end of the translation unit.
8968  if (Class->isLocalClass())
8969    MarkVirtualMembersReferenced(Loc, Class);
8970  else
8971    VTableUses.push_back(std::make_pair(Class, Loc));
8972}
8973
8974bool Sema::DefineUsedVTables() {
8975  if (VTableUses.empty())
8976    return false;
8977
8978  // Note: The VTableUses vector could grow as a result of marking
8979  // the members of a class as "used", so we check the size each
8980  // time through the loop and prefer indices (with are stable) to
8981  // iterators (which are not).
8982  bool DefinedAnything = false;
8983  for (unsigned I = 0; I != VTableUses.size(); ++I) {
8984    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
8985    if (!Class)
8986      continue;
8987
8988    SourceLocation Loc = VTableUses[I].second;
8989
8990    // If this class has a key function, but that key function is
8991    // defined in another translation unit, we don't need to emit the
8992    // vtable even though we're using it.
8993    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
8994    if (KeyFunction && !KeyFunction->hasBody()) {
8995      switch (KeyFunction->getTemplateSpecializationKind()) {
8996      case TSK_Undeclared:
8997      case TSK_ExplicitSpecialization:
8998      case TSK_ExplicitInstantiationDeclaration:
8999        // The key function is in another translation unit.
9000        continue;
9001
9002      case TSK_ExplicitInstantiationDefinition:
9003      case TSK_ImplicitInstantiation:
9004        // We will be instantiating the key function.
9005        break;
9006      }
9007    } else if (!KeyFunction) {
9008      // If we have a class with no key function that is the subject
9009      // of an explicit instantiation declaration, suppress the
9010      // vtable; it will live with the explicit instantiation
9011      // definition.
9012      bool IsExplicitInstantiationDeclaration
9013        = Class->getTemplateSpecializationKind()
9014                                      == TSK_ExplicitInstantiationDeclaration;
9015      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9016                                 REnd = Class->redecls_end();
9017           R != REnd; ++R) {
9018        TemplateSpecializationKind TSK
9019          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9020        if (TSK == TSK_ExplicitInstantiationDeclaration)
9021          IsExplicitInstantiationDeclaration = true;
9022        else if (TSK == TSK_ExplicitInstantiationDefinition) {
9023          IsExplicitInstantiationDeclaration = false;
9024          break;
9025        }
9026      }
9027
9028      if (IsExplicitInstantiationDeclaration)
9029        continue;
9030    }
9031
9032    // Mark all of the virtual members of this class as referenced, so
9033    // that we can build a vtable. Then, tell the AST consumer that a
9034    // vtable for this class is required.
9035    DefinedAnything = true;
9036    MarkVirtualMembersReferenced(Loc, Class);
9037    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9038    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9039
9040    // Optionally warn if we're emitting a weak vtable.
9041    if (Class->getLinkage() == ExternalLinkage &&
9042        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
9043      if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
9044        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9045    }
9046  }
9047  VTableUses.clear();
9048
9049  return DefinedAnything;
9050}
9051
9052void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9053                                        const CXXRecordDecl *RD) {
9054  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9055       e = RD->method_end(); i != e; ++i) {
9056    CXXMethodDecl *MD = *i;
9057
9058    // C++ [basic.def.odr]p2:
9059    //   [...] A virtual member function is used if it is not pure. [...]
9060    if (MD->isVirtual() && !MD->isPure())
9061      MarkDeclarationReferenced(Loc, MD);
9062  }
9063
9064  // Only classes that have virtual bases need a VTT.
9065  if (RD->getNumVBases() == 0)
9066    return;
9067
9068  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9069           e = RD->bases_end(); i != e; ++i) {
9070    const CXXRecordDecl *Base =
9071        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
9072    if (Base->getNumVBases() == 0)
9073      continue;
9074    MarkVirtualMembersReferenced(Loc, Base);
9075  }
9076}
9077
9078/// SetIvarInitializers - This routine builds initialization ASTs for the
9079/// Objective-C implementation whose ivars need be initialized.
9080void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9081  if (!getLangOptions().CPlusPlus)
9082    return;
9083  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
9084    llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9085    CollectIvarsToConstructOrDestruct(OID, ivars);
9086    if (ivars.empty())
9087      return;
9088    llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
9089    for (unsigned i = 0; i < ivars.size(); i++) {
9090      FieldDecl *Field = ivars[i];
9091      if (Field->isInvalidDecl())
9092        continue;
9093
9094      CXXCtorInitializer *Member;
9095      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9096      InitializationKind InitKind =
9097        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9098
9099      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
9100      ExprResult MemberInit =
9101        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
9102      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
9103      // Note, MemberInit could actually come back empty if no initialization
9104      // is required (e.g., because it would call a trivial default constructor)
9105      if (!MemberInit.get() || MemberInit.isInvalid())
9106        continue;
9107
9108      Member =
9109        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9110                                         SourceLocation(),
9111                                         MemberInit.takeAs<Expr>(),
9112                                         SourceLocation());
9113      AllToInit.push_back(Member);
9114
9115      // Be sure that the destructor is accessible and is marked as referenced.
9116      if (const RecordType *RecordTy
9117                  = Context.getBaseElementType(Field->getType())
9118                                                        ->getAs<RecordType>()) {
9119                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
9120        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
9121          MarkDeclarationReferenced(Field->getLocation(), Destructor);
9122          CheckDestructorAccess(Field->getLocation(), Destructor,
9123                            PDiag(diag::err_access_dtor_ivar)
9124                              << Context.getBaseElementType(Field->getType()));
9125        }
9126      }
9127    }
9128    ObjCImplementation->setIvarInitializers(Context,
9129                                            AllToInit.data(), AllToInit.size());
9130  }
9131}
9132
9133static
9134void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9135                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9136                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9137                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9138                           Sema &S) {
9139  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9140                                                   CE = Current.end();
9141  if (Ctor->isInvalidDecl())
9142    return;
9143
9144  const FunctionDecl *FNTarget = 0;
9145  CXXConstructorDecl *Target;
9146
9147  // We ignore the result here since if we don't have a body, Target will be
9148  // null below.
9149  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9150  Target
9151= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9152
9153  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9154                     // Avoid dereferencing a null pointer here.
9155                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9156
9157  if (!Current.insert(Canonical))
9158    return;
9159
9160  // We know that beyond here, we aren't chaining into a cycle.
9161  if (!Target || !Target->isDelegatingConstructor() ||
9162      Target->isInvalidDecl() || Valid.count(TCanonical)) {
9163    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9164      Valid.insert(*CI);
9165    Current.clear();
9166  // We've hit a cycle.
9167  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9168             Current.count(TCanonical)) {
9169    // If we haven't diagnosed this cycle yet, do so now.
9170    if (!Invalid.count(TCanonical)) {
9171      S.Diag((*Ctor->init_begin())->getSourceLocation(),
9172             diag::warn_delegating_ctor_cycle)
9173        << Ctor;
9174
9175      // Don't add a note for a function delegating directo to itself.
9176      if (TCanonical != Canonical)
9177        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9178
9179      CXXConstructorDecl *C = Target;
9180      while (C->getCanonicalDecl() != Canonical) {
9181        (void)C->getTargetConstructor()->hasBody(FNTarget);
9182        assert(FNTarget && "Ctor cycle through bodiless function");
9183
9184        C
9185       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9186        S.Diag(C->getLocation(), diag::note_which_delegates_to);
9187      }
9188    }
9189
9190    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9191      Invalid.insert(*CI);
9192    Current.clear();
9193  } else {
9194    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9195  }
9196}
9197
9198
9199void Sema::CheckDelegatingCtorCycles() {
9200  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9201
9202  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9203                                                   CE = Current.end();
9204
9205  for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
9206         I = DelegatingCtorDecls.begin(),
9207         E = DelegatingCtorDecls.end();
9208       I != E; ++I) {
9209   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
9210  }
9211
9212  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9213    (*CI)->setInvalidDecl();
9214}
9215