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