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