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