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