SemaDeclCXX.cpp revision 3e93ab1a7228f50b8051c167af25cafcffed2852
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/RecordLayout.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Lex/Preprocessor.h"
29#include "llvm/ADT/STLExtras.h"
30#include <map>
31#include <set>
32
33using namespace clang;
34
35//===----------------------------------------------------------------------===//
36// CheckDefaultArgumentVisitor
37//===----------------------------------------------------------------------===//
38
39namespace {
40  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
41  /// the default argument of a parameter to determine whether it
42  /// contains any ill-formed subexpressions. For example, this will
43  /// diagnose the use of local variables or parameters within the
44  /// default argument expression.
45  class CheckDefaultArgumentVisitor
46    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
47    Expr *DefaultArg;
48    Sema *S;
49
50  public:
51    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
52      : DefaultArg(defarg), S(s) {}
53
54    bool VisitExpr(Expr *Node);
55    bool VisitDeclRefExpr(DeclRefExpr *DRE);
56    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
57  };
58
59  /// VisitExpr - Visit all of the children of this expression.
60  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
61    bool IsInvalid = false;
62    for (Stmt::child_iterator I = Node->child_begin(),
63         E = Node->child_end(); I != E; ++I)
64      IsInvalid |= Visit(*I);
65    return IsInvalid;
66  }
67
68  /// VisitDeclRefExpr - Visit a reference to a declaration, to
69  /// determine whether this declaration can be used in the default
70  /// argument expression.
71  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
72    NamedDecl *Decl = DRE->getDecl();
73    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
74      // C++ [dcl.fct.default]p9
75      //   Default arguments are evaluated each time the function is
76      //   called. The order of evaluation of function arguments is
77      //   unspecified. Consequently, parameters of a function shall not
78      //   be used in default argument expressions, even if they are not
79      //   evaluated. Parameters of a function declared before a default
80      //   argument expression are in scope and can hide namespace and
81      //   class member names.
82      return S->Diag(DRE->getSourceRange().getBegin(),
83                     diag::err_param_default_argument_references_param)
84         << Param->getDeclName() << DefaultArg->getSourceRange();
85    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
86      // C++ [dcl.fct.default]p7
87      //   Local variables shall not be used in default argument
88      //   expressions.
89      if (VDecl->isBlockVarDecl())
90        return S->Diag(DRE->getSourceRange().getBegin(),
91                       diag::err_param_default_argument_references_local)
92          << VDecl->getDeclName() << DefaultArg->getSourceRange();
93    }
94
95    return false;
96  }
97
98  /// VisitCXXThisExpr - Visit a C++ "this" expression.
99  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
100    // C++ [dcl.fct.default]p8:
101    //   The keyword this shall not be used in a default argument of a
102    //   member function.
103    return S->Diag(ThisE->getSourceRange().getBegin(),
104                   diag::err_param_default_argument_references_this)
105               << ThisE->getSourceRange();
106  }
107}
108
109bool
110Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
111                              SourceLocation EqualLoc) {
112  if (RequireCompleteType(Param->getLocation(), Param->getType(),
113                          diag::err_typecheck_decl_incomplete_type)) {
114    Param->setInvalidDecl();
115    return true;
116  }
117
118  Expr *Arg = (Expr *)DefaultArg.get();
119
120  // C++ [dcl.fct.default]p5
121  //   A default argument expression is implicitly converted (clause
122  //   4) to the parameter type. The default argument expression has
123  //   the same semantic constraints as the initializer expression in
124  //   a declaration of a variable of the parameter type, using the
125  //   copy-initialization semantics (8.5).
126  InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
127  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
128                                                           EqualLoc);
129  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
130  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
131                                          MultiExprArg(*this, (void**)&Arg, 1));
132  if (Result.isInvalid())
133    return true;
134  Arg = Result.takeAs<Expr>();
135
136  Arg = MaybeCreateCXXExprWithTemporaries(Arg);
137
138  // Okay: add the default argument to the parameter
139  Param->setDefaultArg(Arg);
140
141  DefaultArg.release();
142
143  return false;
144}
145
146/// ActOnParamDefaultArgument - Check whether the default argument
147/// provided for a function parameter is well-formed. If so, attach it
148/// to the parameter declaration.
149void
150Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
151                                ExprArg defarg) {
152  if (!param || !defarg.get())
153    return;
154
155  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
156  UnparsedDefaultArgLocs.erase(Param);
157
158  ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
159
160  // Default arguments are only permitted in C++
161  if (!getLangOptions().CPlusPlus) {
162    Diag(EqualLoc, diag::err_param_default_argument)
163      << DefaultArg->getSourceRange();
164    Param->setInvalidDecl();
165    return;
166  }
167
168  // Check that the default argument is well-formed
169  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
170  if (DefaultArgChecker.Visit(DefaultArg.get())) {
171    Param->setInvalidDecl();
172    return;
173  }
174
175  SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
176}
177
178/// ActOnParamUnparsedDefaultArgument - We've seen a default
179/// argument for a function parameter, but we can't parse it yet
180/// because we're inside a class definition. Note that this default
181/// argument will be parsed later.
182void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
183                                             SourceLocation EqualLoc,
184                                             SourceLocation ArgLoc) {
185  if (!param)
186    return;
187
188  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
189  if (Param)
190    Param->setUnparsedDefaultArg();
191
192  UnparsedDefaultArgLocs[Param] = ArgLoc;
193}
194
195/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
196/// the default argument for the parameter param failed.
197void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
198  if (!param)
199    return;
200
201  ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
202
203  Param->setInvalidDecl();
204
205  UnparsedDefaultArgLocs.erase(Param);
206}
207
208/// CheckExtraCXXDefaultArguments - Check for any extra default
209/// arguments in the declarator, which is not a function declaration
210/// or definition and therefore is not permitted to have default
211/// arguments. This routine should be invoked for every declarator
212/// that is not a function declaration or definition.
213void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
214  // C++ [dcl.fct.default]p3
215  //   A default argument expression shall be specified only in the
216  //   parameter-declaration-clause of a function declaration or in a
217  //   template-parameter (14.1). It shall not be specified for a
218  //   parameter pack. If it is specified in a
219  //   parameter-declaration-clause, it shall not occur within a
220  //   declarator or abstract-declarator of a parameter-declaration.
221  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
222    DeclaratorChunk &chunk = D.getTypeObject(i);
223    if (chunk.Kind == DeclaratorChunk::Function) {
224      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
225        ParmVarDecl *Param =
226          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
227        if (Param->hasUnparsedDefaultArg()) {
228          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
229          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
230            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
231          delete Toks;
232          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
233        } else if (Param->getDefaultArg()) {
234          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
235            << Param->getDefaultArg()->getSourceRange();
236          Param->setDefaultArg(0);
237        }
238      }
239    }
240  }
241}
242
243// MergeCXXFunctionDecl - Merge two declarations of the same C++
244// function, once we already know that they have the same
245// type. Subroutine of MergeFunctionDecl. Returns true if there was an
246// error, false otherwise.
247bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
248  bool Invalid = false;
249
250  // C++ [dcl.fct.default]p4:
251  //   For non-template functions, default arguments can be added in
252  //   later declarations of a function in the same
253  //   scope. Declarations in different scopes have completely
254  //   distinct sets of default arguments. That is, declarations in
255  //   inner scopes do not acquire default arguments from
256  //   declarations in outer scopes, and vice versa. In a given
257  //   function declaration, all parameters subsequent to a
258  //   parameter with a default argument shall have default
259  //   arguments supplied in this or previous declarations. A
260  //   default argument shall not be redefined by a later
261  //   declaration (not even to the same value).
262  //
263  // C++ [dcl.fct.default]p6:
264  //   Except for member functions of class templates, the default arguments
265  //   in a member function definition that appears outside of the class
266  //   definition are added to the set of default arguments provided by the
267  //   member function declaration in the class definition.
268  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
269    ParmVarDecl *OldParam = Old->getParamDecl(p);
270    ParmVarDecl *NewParam = New->getParamDecl(p);
271
272    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
273      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
274      // hint here. Alternatively, we could walk the type-source information
275      // for NewParam to find the last source location in the type... but it
276      // isn't worth the effort right now. This is the kind of test case that
277      // is hard to get right:
278
279      //   int f(int);
280      //   void g(int (*fp)(int) = f);
281      //   void g(int (*fp)(int) = &f);
282      Diag(NewParam->getLocation(),
283           diag::err_param_default_argument_redefinition)
284        << NewParam->getDefaultArgRange();
285
286      // Look for the function declaration where the default argument was
287      // actually written, which may be a declaration prior to Old.
288      for (FunctionDecl *Older = Old->getPreviousDeclaration();
289           Older; Older = Older->getPreviousDeclaration()) {
290        if (!Older->getParamDecl(p)->hasDefaultArg())
291          break;
292
293        OldParam = Older->getParamDecl(p);
294      }
295
296      Diag(OldParam->getLocation(), diag::note_previous_definition)
297        << OldParam->getDefaultArgRange();
298      Invalid = true;
299    } else if (OldParam->hasDefaultArg()) {
300      // Merge the old default argument into the new parameter
301      NewParam->setHasInheritedDefaultArg();
302      if (OldParam->hasUninstantiatedDefaultArg())
303        NewParam->setUninstantiatedDefaultArg(
304                                      OldParam->getUninstantiatedDefaultArg());
305      else
306        NewParam->setDefaultArg(OldParam->getDefaultArg());
307    } else if (NewParam->hasDefaultArg()) {
308      if (New->getDescribedFunctionTemplate()) {
309        // Paragraph 4, quoted above, only applies to non-template functions.
310        Diag(NewParam->getLocation(),
311             diag::err_param_default_argument_template_redecl)
312          << NewParam->getDefaultArgRange();
313        Diag(Old->getLocation(), diag::note_template_prev_declaration)
314          << false;
315      } else if (New->getTemplateSpecializationKind()
316                   != TSK_ImplicitInstantiation &&
317                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
318        // C++ [temp.expr.spec]p21:
319        //   Default function arguments shall not be specified in a declaration
320        //   or a definition for one of the following explicit specializations:
321        //     - the explicit specialization of a function template;
322        //     - the explicit specialization of a member function template;
323        //     - the explicit specialization of a member function of a class
324        //       template where the class template specialization to which the
325        //       member function specialization belongs is implicitly
326        //       instantiated.
327        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
328          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
329          << New->getDeclName()
330          << NewParam->getDefaultArgRange();
331      } else if (New->getDeclContext()->isDependentContext()) {
332        // C++ [dcl.fct.default]p6 (DR217):
333        //   Default arguments for a member function of a class template shall
334        //   be specified on the initial declaration of the member function
335        //   within the class template.
336        //
337        // Reading the tea leaves a bit in DR217 and its reference to DR205
338        // leads me to the conclusion that one cannot add default function
339        // arguments for an out-of-line definition of a member function of a
340        // dependent type.
341        int WhichKind = 2;
342        if (CXXRecordDecl *Record
343              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
344          if (Record->getDescribedClassTemplate())
345            WhichKind = 0;
346          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
347            WhichKind = 1;
348          else
349            WhichKind = 2;
350        }
351
352        Diag(NewParam->getLocation(),
353             diag::err_param_default_argument_member_template_redecl)
354          << WhichKind
355          << NewParam->getDefaultArgRange();
356      }
357    }
358  }
359
360  if (CheckEquivalentExceptionSpec(Old, New))
361    Invalid = true;
362
363  return Invalid;
364}
365
366/// CheckCXXDefaultArguments - Verify that the default arguments for a
367/// function declaration are well-formed according to C++
368/// [dcl.fct.default].
369void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
370  unsigned NumParams = FD->getNumParams();
371  unsigned p;
372
373  // Find first parameter with a default argument
374  for (p = 0; p < NumParams; ++p) {
375    ParmVarDecl *Param = FD->getParamDecl(p);
376    if (Param->hasDefaultArg())
377      break;
378  }
379
380  // C++ [dcl.fct.default]p4:
381  //   In a given function declaration, all parameters
382  //   subsequent to a parameter with a default argument shall
383  //   have default arguments supplied in this or previous
384  //   declarations. A default argument shall not be redefined
385  //   by a later declaration (not even to the same value).
386  unsigned LastMissingDefaultArg = 0;
387  for (; p < NumParams; ++p) {
388    ParmVarDecl *Param = FD->getParamDecl(p);
389    if (!Param->hasDefaultArg()) {
390      if (Param->isInvalidDecl())
391        /* We already complained about this parameter. */;
392      else if (Param->getIdentifier())
393        Diag(Param->getLocation(),
394             diag::err_param_default_argument_missing_name)
395          << Param->getIdentifier();
396      else
397        Diag(Param->getLocation(),
398             diag::err_param_default_argument_missing);
399
400      LastMissingDefaultArg = p;
401    }
402  }
403
404  if (LastMissingDefaultArg > 0) {
405    // Some default arguments were missing. Clear out all of the
406    // default arguments up to (and including) the last missing
407    // default argument, so that we leave the function parameters
408    // in a semantically valid state.
409    for (p = 0; p <= LastMissingDefaultArg; ++p) {
410      ParmVarDecl *Param = FD->getParamDecl(p);
411      if (Param->hasDefaultArg()) {
412        if (!Param->hasUnparsedDefaultArg())
413          Param->getDefaultArg()->Destroy(Context);
414        Param->setDefaultArg(0);
415      }
416    }
417  }
418}
419
420/// isCurrentClassName - Determine whether the identifier II is the
421/// name of the class type currently being defined. In the case of
422/// nested classes, this will only return true if II is the name of
423/// the innermost class.
424bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
425                              const CXXScopeSpec *SS) {
426  assert(getLangOptions().CPlusPlus && "No class names in C!");
427
428  CXXRecordDecl *CurDecl;
429  if (SS && SS->isSet() && !SS->isInvalid()) {
430    DeclContext *DC = computeDeclContext(*SS, true);
431    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
432  } else
433    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
434
435  if (CurDecl && CurDecl->getIdentifier())
436    return &II == CurDecl->getIdentifier();
437  else
438    return false;
439}
440
441/// \brief Check the validity of a C++ base class specifier.
442///
443/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
444/// and returns NULL otherwise.
445CXXBaseSpecifier *
446Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
447                         SourceRange SpecifierRange,
448                         bool Virtual, AccessSpecifier Access,
449                         QualType BaseType,
450                         SourceLocation BaseLoc) {
451  // C++ [class.union]p1:
452  //   A union shall not have base classes.
453  if (Class->isUnion()) {
454    Diag(Class->getLocation(), diag::err_base_clause_on_union)
455      << SpecifierRange;
456    return 0;
457  }
458
459  if (BaseType->isDependentType())
460    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
461                                Class->getTagKind() == RecordDecl::TK_class,
462                                Access, BaseType);
463
464  // Base specifiers must be record types.
465  if (!BaseType->isRecordType()) {
466    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
467    return 0;
468  }
469
470  // C++ [class.union]p1:
471  //   A union shall not be used as a base class.
472  if (BaseType->isUnionType()) {
473    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
474    return 0;
475  }
476
477  // C++ [class.derived]p2:
478  //   The class-name in a base-specifier shall not be an incompletely
479  //   defined class.
480  if (RequireCompleteType(BaseLoc, BaseType,
481                          PDiag(diag::err_incomplete_base_class)
482                            << SpecifierRange))
483    return 0;
484
485  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
486  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
487  assert(BaseDecl && "Record type has no declaration");
488  BaseDecl = BaseDecl->getDefinition();
489  assert(BaseDecl && "Base type is not incomplete, but has no definition");
490  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
491  assert(CXXBaseDecl && "Base type is not a C++ type");
492
493  // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
494  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
495    Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
496    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
497      << BaseType;
498    return 0;
499  }
500
501  SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
502
503  // Create the base specifier.
504  // FIXME: Allocate via ASTContext?
505  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
506                              Class->getTagKind() == RecordDecl::TK_class,
507                              Access, BaseType);
508}
509
510void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
511                                          const CXXRecordDecl *BaseClass,
512                                          bool BaseIsVirtual) {
513  // A class with a non-empty base class is not empty.
514  // FIXME: Standard ref?
515  if (!BaseClass->isEmpty())
516    Class->setEmpty(false);
517
518  // C++ [class.virtual]p1:
519  //   A class that [...] inherits a virtual function is called a polymorphic
520  //   class.
521  if (BaseClass->isPolymorphic())
522    Class->setPolymorphic(true);
523
524  // C++ [dcl.init.aggr]p1:
525  //   An aggregate is [...] a class with [...] no base classes [...].
526  Class->setAggregate(false);
527
528  // C++ [class]p4:
529  //   A POD-struct is an aggregate class...
530  Class->setPOD(false);
531
532  if (BaseIsVirtual) {
533    // C++ [class.ctor]p5:
534    //   A constructor is trivial if its class has no virtual base classes.
535    Class->setHasTrivialConstructor(false);
536
537    // C++ [class.copy]p6:
538    //   A copy constructor is trivial if its class has no virtual base classes.
539    Class->setHasTrivialCopyConstructor(false);
540
541    // C++ [class.copy]p11:
542    //   A copy assignment operator is trivial if its class has no virtual
543    //   base classes.
544    Class->setHasTrivialCopyAssignment(false);
545
546    // C++0x [meta.unary.prop] is_empty:
547    //    T is a class type, but not a union type, with ... no virtual base
548    //    classes
549    Class->setEmpty(false);
550  } else {
551    // C++ [class.ctor]p5:
552    //   A constructor is trivial if all the direct base classes of its
553    //   class have trivial constructors.
554    if (!BaseClass->hasTrivialConstructor())
555      Class->setHasTrivialConstructor(false);
556
557    // C++ [class.copy]p6:
558    //   A copy constructor is trivial if all the direct base classes of its
559    //   class have trivial copy constructors.
560    if (!BaseClass->hasTrivialCopyConstructor())
561      Class->setHasTrivialCopyConstructor(false);
562
563    // C++ [class.copy]p11:
564    //   A copy assignment operator is trivial if all the direct base classes
565    //   of its class have trivial copy assignment operators.
566    if (!BaseClass->hasTrivialCopyAssignment())
567      Class->setHasTrivialCopyAssignment(false);
568  }
569
570  // C++ [class.ctor]p3:
571  //   A destructor is trivial if all the direct base classes of its class
572  //   have trivial destructors.
573  if (!BaseClass->hasTrivialDestructor())
574    Class->setHasTrivialDestructor(false);
575}
576
577/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
578/// one entry in the base class list of a class specifier, for
579/// example:
580///    class foo : public bar, virtual private baz {
581/// 'public bar' and 'virtual private baz' are each base-specifiers.
582Sema::BaseResult
583Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
584                         bool Virtual, AccessSpecifier Access,
585                         TypeTy *basetype, SourceLocation BaseLoc) {
586  if (!classdecl)
587    return true;
588
589  AdjustDeclIfTemplate(classdecl);
590  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
591  if (!Class)
592    return true;
593
594  QualType BaseType = GetTypeFromParser(basetype);
595  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
596                                                      Virtual, Access,
597                                                      BaseType, BaseLoc))
598    return BaseSpec;
599
600  return true;
601}
602
603/// \brief Performs the actual work of attaching the given base class
604/// specifiers to a C++ class.
605bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
606                                unsigned NumBases) {
607 if (NumBases == 0)
608    return false;
609
610  // Used to keep track of which base types we have already seen, so
611  // that we can properly diagnose redundant direct base types. Note
612  // that the key is always the unqualified canonical type of the base
613  // class.
614  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
615
616  // Copy non-redundant base specifiers into permanent storage.
617  unsigned NumGoodBases = 0;
618  bool Invalid = false;
619  for (unsigned idx = 0; idx < NumBases; ++idx) {
620    QualType NewBaseType
621      = Context.getCanonicalType(Bases[idx]->getType());
622    NewBaseType = NewBaseType.getLocalUnqualifiedType();
623
624    if (KnownBaseTypes[NewBaseType]) {
625      // C++ [class.mi]p3:
626      //   A class shall not be specified as a direct base class of a
627      //   derived class more than once.
628      Diag(Bases[idx]->getSourceRange().getBegin(),
629           diag::err_duplicate_base_class)
630        << KnownBaseTypes[NewBaseType]->getType()
631        << Bases[idx]->getSourceRange();
632
633      // Delete the duplicate base class specifier; we're going to
634      // overwrite its pointer later.
635      Context.Deallocate(Bases[idx]);
636
637      Invalid = true;
638    } else {
639      // Okay, add this new base class.
640      KnownBaseTypes[NewBaseType] = Bases[idx];
641      Bases[NumGoodBases++] = Bases[idx];
642    }
643  }
644
645  // Attach the remaining base class specifiers to the derived class.
646  Class->setBases(Bases, NumGoodBases);
647
648  // Delete the remaining (good) base class specifiers, since their
649  // data has been copied into the CXXRecordDecl.
650  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
651    Context.Deallocate(Bases[idx]);
652
653  return Invalid;
654}
655
656/// ActOnBaseSpecifiers - Attach the given base specifiers to the
657/// class, after checking whether there are any duplicate base
658/// classes.
659void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
660                               unsigned NumBases) {
661  if (!ClassDecl || !Bases || !NumBases)
662    return;
663
664  AdjustDeclIfTemplate(ClassDecl);
665  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
666                       (CXXBaseSpecifier**)(Bases), NumBases);
667}
668
669static CXXRecordDecl *GetClassForType(QualType T) {
670  if (const RecordType *RT = T->getAs<RecordType>())
671    return cast<CXXRecordDecl>(RT->getDecl());
672  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
673    return ICT->getDecl();
674  else
675    return 0;
676}
677
678/// \brief Determine whether the type \p Derived is a C++ class that is
679/// derived from the type \p Base.
680bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
681  if (!getLangOptions().CPlusPlus)
682    return false;
683
684  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
685  if (!DerivedRD)
686    return false;
687
688  CXXRecordDecl *BaseRD = GetClassForType(Base);
689  if (!BaseRD)
690    return false;
691
692  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
693  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
694}
695
696/// \brief Determine whether the type \p Derived is a C++ class that is
697/// derived from the type \p Base.
698bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
699  if (!getLangOptions().CPlusPlus)
700    return false;
701
702  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
703  if (!DerivedRD)
704    return false;
705
706  CXXRecordDecl *BaseRD = GetClassForType(Base);
707  if (!BaseRD)
708    return false;
709
710  return DerivedRD->isDerivedFrom(BaseRD, Paths);
711}
712
713void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
714                              CXXBaseSpecifierArray &BasePathArray) {
715  assert(BasePathArray.empty() && "Base path array must be empty!");
716  assert(Paths.isRecordingPaths() && "Must record paths!");
717
718  const CXXBasePath &Path = Paths.front();
719
720  // We first go backward and check if we have a virtual base.
721  // FIXME: It would be better if CXXBasePath had the base specifier for
722  // the nearest virtual base.
723  unsigned Start = 0;
724  for (unsigned I = Path.size(); I != 0; --I) {
725    if (Path[I - 1].Base->isVirtual()) {
726      Start = I - 1;
727      break;
728    }
729  }
730
731  // Now add all bases.
732  for (unsigned I = Start, E = Path.size(); I != E; ++I)
733    BasePathArray.push_back(Path[I].Base);
734}
735
736/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
737/// conversion (where Derived and Base are class types) is
738/// well-formed, meaning that the conversion is unambiguous (and
739/// that all of the base classes are accessible). Returns true
740/// and emits a diagnostic if the code is ill-formed, returns false
741/// otherwise. Loc is the location where this routine should point to
742/// if there is an error, and Range is the source range to highlight
743/// if there is an error.
744bool
745Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
746                                   unsigned InaccessibleBaseID,
747                                   unsigned AmbigiousBaseConvID,
748                                   SourceLocation Loc, SourceRange Range,
749                                   DeclarationName Name,
750                                   CXXBaseSpecifierArray *BasePath) {
751  // First, determine whether the path from Derived to Base is
752  // ambiguous. This is slightly more expensive than checking whether
753  // the Derived to Base conversion exists, because here we need to
754  // explore multiple paths to determine if there is an ambiguity.
755  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
756                     /*DetectVirtual=*/false);
757  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
758  assert(DerivationOkay &&
759         "Can only be used with a derived-to-base conversion");
760  (void)DerivationOkay;
761
762  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
763    if (InaccessibleBaseID) {
764      // Check that the base class can be accessed.
765      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
766                                   InaccessibleBaseID)) {
767        case AR_inaccessible:
768          return true;
769        case AR_accessible:
770        case AR_dependent:
771        case AR_delayed:
772          break;
773      }
774    }
775
776    // Build a base path if necessary.
777    if (BasePath)
778      BuildBasePathArray(Paths, *BasePath);
779    return false;
780  }
781
782  // We know that the derived-to-base conversion is ambiguous, and
783  // we're going to produce a diagnostic. Perform the derived-to-base
784  // search just one more time to compute all of the possible paths so
785  // that we can print them out. This is more expensive than any of
786  // the previous derived-to-base checks we've done, but at this point
787  // performance isn't as much of an issue.
788  Paths.clear();
789  Paths.setRecordingPaths(true);
790  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
791  assert(StillOkay && "Can only be used with a derived-to-base conversion");
792  (void)StillOkay;
793
794  // Build up a textual representation of the ambiguous paths, e.g.,
795  // D -> B -> A, that will be used to illustrate the ambiguous
796  // conversions in the diagnostic. We only print one of the paths
797  // to each base class subobject.
798  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
799
800  Diag(Loc, AmbigiousBaseConvID)
801  << Derived << Base << PathDisplayStr << Range << Name;
802  return true;
803}
804
805bool
806Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
807                                   SourceLocation Loc, SourceRange Range,
808                                   CXXBaseSpecifierArray *BasePath,
809                                   bool IgnoreAccess) {
810  return CheckDerivedToBaseConversion(Derived, Base,
811                                      IgnoreAccess ? 0
812                                       : diag::err_upcast_to_inaccessible_base,
813                                      diag::err_ambiguous_derived_to_base_conv,
814                                      Loc, Range, DeclarationName(),
815                                      BasePath);
816}
817
818
819/// @brief Builds a string representing ambiguous paths from a
820/// specific derived class to different subobjects of the same base
821/// class.
822///
823/// This function builds a string that can be used in error messages
824/// to show the different paths that one can take through the
825/// inheritance hierarchy to go from the derived class to different
826/// subobjects of a base class. The result looks something like this:
827/// @code
828/// struct D -> struct B -> struct A
829/// struct D -> struct C -> struct A
830/// @endcode
831std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
832  std::string PathDisplayStr;
833  std::set<unsigned> DisplayedPaths;
834  for (CXXBasePaths::paths_iterator Path = Paths.begin();
835       Path != Paths.end(); ++Path) {
836    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
837      // We haven't displayed a path to this particular base
838      // class subobject yet.
839      PathDisplayStr += "\n    ";
840      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
841      for (CXXBasePath::const_iterator Element = Path->begin();
842           Element != Path->end(); ++Element)
843        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
844    }
845  }
846
847  return PathDisplayStr;
848}
849
850//===----------------------------------------------------------------------===//
851// C++ class member Handling
852//===----------------------------------------------------------------------===//
853
854/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
855/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
856/// bitfield width if there is one and 'InitExpr' specifies the initializer if
857/// any.
858Sema::DeclPtrTy
859Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
860                               MultiTemplateParamsArg TemplateParameterLists,
861                               ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
862                               bool Deleted) {
863  const DeclSpec &DS = D.getDeclSpec();
864  DeclarationName Name = GetNameForDeclarator(D);
865  Expr *BitWidth = static_cast<Expr*>(BW);
866  Expr *Init = static_cast<Expr*>(InitExpr);
867  SourceLocation Loc = D.getIdentifierLoc();
868
869  bool isFunc = D.isFunctionDeclarator();
870
871  assert(!DS.isFriendSpecified());
872
873  // C++ 9.2p6: A member shall not be declared to have automatic storage
874  // duration (auto, register) or with the extern storage-class-specifier.
875  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
876  // data members and cannot be applied to names declared const or static,
877  // and cannot be applied to reference members.
878  switch (DS.getStorageClassSpec()) {
879    case DeclSpec::SCS_unspecified:
880    case DeclSpec::SCS_typedef:
881    case DeclSpec::SCS_static:
882      // FALL THROUGH.
883      break;
884    case DeclSpec::SCS_mutable:
885      if (isFunc) {
886        if (DS.getStorageClassSpecLoc().isValid())
887          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
888        else
889          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
890
891        // FIXME: It would be nicer if the keyword was ignored only for this
892        // declarator. Otherwise we could get follow-up errors.
893        D.getMutableDeclSpec().ClearStorageClassSpecs();
894      } else {
895        QualType T = GetTypeForDeclarator(D, S);
896        diag::kind err = static_cast<diag::kind>(0);
897        if (T->isReferenceType())
898          err = diag::err_mutable_reference;
899        else if (T.isConstQualified())
900          err = diag::err_mutable_const;
901        if (err != 0) {
902          if (DS.getStorageClassSpecLoc().isValid())
903            Diag(DS.getStorageClassSpecLoc(), err);
904          else
905            Diag(DS.getThreadSpecLoc(), err);
906          // FIXME: It would be nicer if the keyword was ignored only for this
907          // declarator. Otherwise we could get follow-up errors.
908          D.getMutableDeclSpec().ClearStorageClassSpecs();
909        }
910      }
911      break;
912    default:
913      if (DS.getStorageClassSpecLoc().isValid())
914        Diag(DS.getStorageClassSpecLoc(),
915             diag::err_storageclass_invalid_for_member);
916      else
917        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
918      D.getMutableDeclSpec().ClearStorageClassSpecs();
919  }
920
921  if (!isFunc &&
922      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
923      D.getNumTypeObjects() == 0) {
924    // Check also for this case:
925    //
926    // typedef int f();
927    // f a;
928    //
929    QualType TDType = GetTypeFromParser(DS.getTypeRep());
930    isFunc = TDType->isFunctionType();
931  }
932
933  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
934                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
935                      !isFunc);
936
937  Decl *Member;
938  if (isInstField) {
939    // FIXME: Check for template parameters!
940    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
941                         AS);
942    assert(Member && "HandleField never returns null");
943  } else {
944    Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
945               .getAs<Decl>();
946    if (!Member) {
947      if (BitWidth) DeleteExpr(BitWidth);
948      return DeclPtrTy();
949    }
950
951    // Non-instance-fields can't have a bitfield.
952    if (BitWidth) {
953      if (Member->isInvalidDecl()) {
954        // don't emit another diagnostic.
955      } else if (isa<VarDecl>(Member)) {
956        // C++ 9.6p3: A bit-field shall not be a static member.
957        // "static member 'A' cannot be a bit-field"
958        Diag(Loc, diag::err_static_not_bitfield)
959          << Name << BitWidth->getSourceRange();
960      } else if (isa<TypedefDecl>(Member)) {
961        // "typedef member 'x' cannot be a bit-field"
962        Diag(Loc, diag::err_typedef_not_bitfield)
963          << Name << BitWidth->getSourceRange();
964      } else {
965        // A function typedef ("typedef int f(); f a;").
966        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
967        Diag(Loc, diag::err_not_integral_type_bitfield)
968          << Name << cast<ValueDecl>(Member)->getType()
969          << BitWidth->getSourceRange();
970      }
971
972      DeleteExpr(BitWidth);
973      BitWidth = 0;
974      Member->setInvalidDecl();
975    }
976
977    Member->setAccess(AS);
978
979    // If we have declared a member function template, set the access of the
980    // templated declaration as well.
981    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
982      FunTmpl->getTemplatedDecl()->setAccess(AS);
983  }
984
985  assert((Name || isInstField) && "No identifier for non-field ?");
986
987  if (Init)
988    AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
989  if (Deleted) // FIXME: Source location is not very good.
990    SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
991
992  if (isInstField) {
993    FieldCollector->Add(cast<FieldDecl>(Member));
994    return DeclPtrTy();
995  }
996  return DeclPtrTy::make(Member);
997}
998
999/// \brief Find the direct and/or virtual base specifiers that
1000/// correspond to the given base type, for use in base initialization
1001/// within a constructor.
1002static bool FindBaseInitializer(Sema &SemaRef,
1003                                CXXRecordDecl *ClassDecl,
1004                                QualType BaseType,
1005                                const CXXBaseSpecifier *&DirectBaseSpec,
1006                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1007  // First, check for a direct base class.
1008  DirectBaseSpec = 0;
1009  for (CXXRecordDecl::base_class_const_iterator Base
1010         = ClassDecl->bases_begin();
1011       Base != ClassDecl->bases_end(); ++Base) {
1012    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1013      // We found a direct base of this type. That's what we're
1014      // initializing.
1015      DirectBaseSpec = &*Base;
1016      break;
1017    }
1018  }
1019
1020  // Check for a virtual base class.
1021  // FIXME: We might be able to short-circuit this if we know in advance that
1022  // there are no virtual bases.
1023  VirtualBaseSpec = 0;
1024  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1025    // We haven't found a base yet; search the class hierarchy for a
1026    // virtual base class.
1027    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1028                       /*DetectVirtual=*/false);
1029    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1030                              BaseType, Paths)) {
1031      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1032           Path != Paths.end(); ++Path) {
1033        if (Path->back().Base->isVirtual()) {
1034          VirtualBaseSpec = Path->back().Base;
1035          break;
1036        }
1037      }
1038    }
1039  }
1040
1041  return DirectBaseSpec || VirtualBaseSpec;
1042}
1043
1044/// ActOnMemInitializer - Handle a C++ member initializer.
1045Sema::MemInitResult
1046Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
1047                          Scope *S,
1048                          CXXScopeSpec &SS,
1049                          IdentifierInfo *MemberOrBase,
1050                          TypeTy *TemplateTypeTy,
1051                          SourceLocation IdLoc,
1052                          SourceLocation LParenLoc,
1053                          ExprTy **Args, unsigned NumArgs,
1054                          SourceLocation *CommaLocs,
1055                          SourceLocation RParenLoc) {
1056  if (!ConstructorD)
1057    return true;
1058
1059  AdjustDeclIfTemplate(ConstructorD);
1060
1061  CXXConstructorDecl *Constructor
1062    = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
1063  if (!Constructor) {
1064    // The user wrote a constructor initializer on a function that is
1065    // not a C++ constructor. Ignore the error for now, because we may
1066    // have more member initializers coming; we'll diagnose it just
1067    // once in ActOnMemInitializers.
1068    return true;
1069  }
1070
1071  CXXRecordDecl *ClassDecl = Constructor->getParent();
1072
1073  // C++ [class.base.init]p2:
1074  //   Names in a mem-initializer-id are looked up in the scope of the
1075  //   constructor’s class and, if not found in that scope, are looked
1076  //   up in the scope containing the constructor’s
1077  //   definition. [Note: if the constructor’s class contains a member
1078  //   with the same name as a direct or virtual base class of the
1079  //   class, a mem-initializer-id naming the member or base class and
1080  //   composed of a single identifier refers to the class member. A
1081  //   mem-initializer-id for the hidden base class may be specified
1082  //   using a qualified name. ]
1083  if (!SS.getScopeRep() && !TemplateTypeTy) {
1084    // Look for a member, first.
1085    FieldDecl *Member = 0;
1086    DeclContext::lookup_result Result
1087      = ClassDecl->lookup(MemberOrBase);
1088    if (Result.first != Result.second)
1089      Member = dyn_cast<FieldDecl>(*Result.first);
1090
1091    // FIXME: Handle members of an anonymous union.
1092
1093    if (Member)
1094      return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1095                                    LParenLoc, RParenLoc);
1096  }
1097  // It didn't name a member, so see if it names a class.
1098  QualType BaseType;
1099  TypeSourceInfo *TInfo = 0;
1100
1101  if (TemplateTypeTy) {
1102    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1103  } else {
1104    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1105    LookupParsedName(R, S, &SS);
1106
1107    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1108    if (!TyD) {
1109      if (R.isAmbiguous()) return true;
1110
1111      // We don't want access-control diagnostics here.
1112      R.suppressDiagnostics();
1113
1114      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1115        bool NotUnknownSpecialization = false;
1116        DeclContext *DC = computeDeclContext(SS, false);
1117        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1118          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1119
1120        if (!NotUnknownSpecialization) {
1121          // When the scope specifier can refer to a member of an unknown
1122          // specialization, we take it as a type name.
1123          BaseType = CheckTypenameType(ETK_None,
1124                                       (NestedNameSpecifier *)SS.getScopeRep(),
1125                                       *MemberOrBase, SS.getRange());
1126          if (BaseType.isNull())
1127            return true;
1128
1129          R.clear();
1130        }
1131      }
1132
1133      // If no results were found, try to correct typos.
1134      if (R.empty() && BaseType.isNull() &&
1135          CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1136          R.isSingleResult()) {
1137        if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1138          if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1139            // We have found a non-static data member with a similar
1140            // name to what was typed; complain and initialize that
1141            // member.
1142            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1143              << MemberOrBase << true << R.getLookupName()
1144              << FixItHint::CreateReplacement(R.getNameLoc(),
1145                                              R.getLookupName().getAsString());
1146            Diag(Member->getLocation(), diag::note_previous_decl)
1147              << Member->getDeclName();
1148
1149            return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1150                                          LParenLoc, RParenLoc);
1151          }
1152        } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1153          const CXXBaseSpecifier *DirectBaseSpec;
1154          const CXXBaseSpecifier *VirtualBaseSpec;
1155          if (FindBaseInitializer(*this, ClassDecl,
1156                                  Context.getTypeDeclType(Type),
1157                                  DirectBaseSpec, VirtualBaseSpec)) {
1158            // We have found a direct or virtual base class with a
1159            // similar name to what was typed; complain and initialize
1160            // that base class.
1161            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1162              << MemberOrBase << false << R.getLookupName()
1163              << FixItHint::CreateReplacement(R.getNameLoc(),
1164                                              R.getLookupName().getAsString());
1165
1166            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1167                                                             : VirtualBaseSpec;
1168            Diag(BaseSpec->getSourceRange().getBegin(),
1169                 diag::note_base_class_specified_here)
1170              << BaseSpec->getType()
1171              << BaseSpec->getSourceRange();
1172
1173            TyD = Type;
1174          }
1175        }
1176      }
1177
1178      if (!TyD && BaseType.isNull()) {
1179        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1180          << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1181        return true;
1182      }
1183    }
1184
1185    if (BaseType.isNull()) {
1186      BaseType = Context.getTypeDeclType(TyD);
1187      if (SS.isSet()) {
1188        NestedNameSpecifier *Qualifier =
1189          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1190
1191        // FIXME: preserve source range information
1192        BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1193      }
1194    }
1195  }
1196
1197  if (!TInfo)
1198    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1199
1200  return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1201                              LParenLoc, RParenLoc, ClassDecl);
1202}
1203
1204/// Checks an initializer expression for use of uninitialized fields, such as
1205/// containing the field that is being initialized. Returns true if there is an
1206/// uninitialized field was used an updates the SourceLocation parameter; false
1207/// otherwise.
1208static bool InitExprContainsUninitializedFields(const Stmt* S,
1209                                                const FieldDecl* LhsField,
1210                                                SourceLocation* L) {
1211  const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1212  if (ME) {
1213    const NamedDecl* RhsField = ME->getMemberDecl();
1214    if (RhsField == LhsField) {
1215      // Initializing a field with itself. Throw a warning.
1216      // But wait; there are exceptions!
1217      // Exception #1:  The field may not belong to this record.
1218      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1219      const Expr* base = ME->getBase();
1220      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1221        // Even though the field matches, it does not belong to this record.
1222        return false;
1223      }
1224      // None of the exceptions triggered; return true to indicate an
1225      // uninitialized field was used.
1226      *L = ME->getMemberLoc();
1227      return true;
1228    }
1229  }
1230  bool found = false;
1231  for (Stmt::const_child_iterator it = S->child_begin();
1232       it != S->child_end() && found == false;
1233       ++it) {
1234    if (isa<CallExpr>(S)) {
1235      // Do not descend into function calls or constructors, as the use
1236      // of an uninitialized field may be valid. One would have to inspect
1237      // the contents of the function/ctor to determine if it is safe or not.
1238      // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1239      // may be safe, depending on what the function/ctor does.
1240      continue;
1241    }
1242    found = InitExprContainsUninitializedFields(*it, LhsField, L);
1243  }
1244  return found;
1245}
1246
1247Sema::MemInitResult
1248Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1249                             unsigned NumArgs, SourceLocation IdLoc,
1250                             SourceLocation LParenLoc,
1251                             SourceLocation RParenLoc) {
1252  // Diagnose value-uses of fields to initialize themselves, e.g.
1253  //   foo(foo)
1254  // where foo is not also a parameter to the constructor.
1255  // TODO: implement -Wuninitialized and fold this into that framework.
1256  for (unsigned i = 0; i < NumArgs; ++i) {
1257    SourceLocation L;
1258    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1259      // FIXME: Return true in the case when other fields are used before being
1260      // uninitialized. For example, let this field be the i'th field. When
1261      // initializing the i'th field, throw a warning if any of the >= i'th
1262      // fields are used, as they are not yet initialized.
1263      // Right now we are only handling the case where the i'th field uses
1264      // itself in its initializer.
1265      Diag(L, diag::warn_field_is_uninit);
1266    }
1267  }
1268
1269  bool HasDependentArg = false;
1270  for (unsigned i = 0; i < NumArgs; i++)
1271    HasDependentArg |= Args[i]->isTypeDependent();
1272
1273  QualType FieldType = Member->getType();
1274  if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1275    FieldType = Array->getElementType();
1276  if (FieldType->isDependentType() || HasDependentArg) {
1277    // Can't check initialization for a member of dependent type or when
1278    // any of the arguments are type-dependent expressions.
1279    OwningExprResult Init
1280      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1281                                          RParenLoc));
1282
1283    // Erase any temporaries within this evaluation context; we're not
1284    // going to track them in the AST, since we'll be rebuilding the
1285    // ASTs during template instantiation.
1286    ExprTemporaries.erase(
1287              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1288                          ExprTemporaries.end());
1289
1290    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1291                                                    LParenLoc,
1292                                                    Init.takeAs<Expr>(),
1293                                                    RParenLoc);
1294
1295  }
1296
1297  if (Member->isInvalidDecl())
1298    return true;
1299
1300  // Initialize the member.
1301  InitializedEntity MemberEntity =
1302    InitializedEntity::InitializeMember(Member, 0);
1303  InitializationKind Kind =
1304    InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1305
1306  InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1307
1308  OwningExprResult MemberInit =
1309    InitSeq.Perform(*this, MemberEntity, Kind,
1310                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1311  if (MemberInit.isInvalid())
1312    return true;
1313
1314  // C++0x [class.base.init]p7:
1315  //   The initialization of each base and member constitutes a
1316  //   full-expression.
1317  MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1318  if (MemberInit.isInvalid())
1319    return true;
1320
1321  // If we are in a dependent context, template instantiation will
1322  // perform this type-checking again. Just save the arguments that we
1323  // received in a ParenListExpr.
1324  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1325  // of the information that we have about the member
1326  // initializer. However, deconstructing the ASTs is a dicey process,
1327  // and this approach is far more likely to get the corner cases right.
1328  if (CurContext->isDependentContext()) {
1329    // Bump the reference count of all of the arguments.
1330    for (unsigned I = 0; I != NumArgs; ++I)
1331      Args[I]->Retain();
1332
1333    OwningExprResult Init
1334      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1335                                          RParenLoc));
1336    return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1337                                                    LParenLoc,
1338                                                    Init.takeAs<Expr>(),
1339                                                    RParenLoc);
1340  }
1341
1342  return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1343                                                  LParenLoc,
1344                                                  MemberInit.takeAs<Expr>(),
1345                                                  RParenLoc);
1346}
1347
1348Sema::MemInitResult
1349Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1350                           Expr **Args, unsigned NumArgs,
1351                           SourceLocation LParenLoc, SourceLocation RParenLoc,
1352                           CXXRecordDecl *ClassDecl) {
1353  bool HasDependentArg = false;
1354  for (unsigned i = 0; i < NumArgs; i++)
1355    HasDependentArg |= Args[i]->isTypeDependent();
1356
1357  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
1358  if (BaseType->isDependentType() || HasDependentArg) {
1359    // Can't check initialization for a base of dependent type or when
1360    // any of the arguments are type-dependent expressions.
1361    OwningExprResult BaseInit
1362      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1363                                          RParenLoc));
1364
1365    // Erase any temporaries within this evaluation context; we're not
1366    // going to track them in the AST, since we'll be rebuilding the
1367    // ASTs during template instantiation.
1368    ExprTemporaries.erase(
1369              ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1370                          ExprTemporaries.end());
1371
1372    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1373                                                    /*IsVirtual=*/false,
1374                                                    LParenLoc,
1375                                                    BaseInit.takeAs<Expr>(),
1376                                                    RParenLoc);
1377  }
1378
1379  if (!BaseType->isRecordType())
1380    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1381             << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1382
1383  // C++ [class.base.init]p2:
1384  //   [...] Unless the mem-initializer-id names a nonstatic data
1385  //   member of the constructor’s class or a direct or virtual base
1386  //   of that class, the mem-initializer is ill-formed. A
1387  //   mem-initializer-list can initialize a base class using any
1388  //   name that denotes that base class type.
1389
1390  // Check for direct and virtual base classes.
1391  const CXXBaseSpecifier *DirectBaseSpec = 0;
1392  const CXXBaseSpecifier *VirtualBaseSpec = 0;
1393  FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1394                      VirtualBaseSpec);
1395
1396  // C++ [base.class.init]p2:
1397  //   If a mem-initializer-id is ambiguous because it designates both
1398  //   a direct non-virtual base class and an inherited virtual base
1399  //   class, the mem-initializer is ill-formed.
1400  if (DirectBaseSpec && VirtualBaseSpec)
1401    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1402      << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1403  // C++ [base.class.init]p2:
1404  // Unless the mem-initializer-id names a nonstatic data membeer of the
1405  // constructor's class ot a direst or virtual base of that class, the
1406  // mem-initializer is ill-formed.
1407  if (!DirectBaseSpec && !VirtualBaseSpec)
1408    return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1409      << BaseType << ClassDecl->getNameAsCString()
1410      << BaseTInfo->getTypeLoc().getSourceRange();
1411
1412  CXXBaseSpecifier *BaseSpec
1413    = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1414  if (!BaseSpec)
1415    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1416
1417  // Initialize the base.
1418  InitializedEntity BaseEntity =
1419    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1420  InitializationKind Kind =
1421    InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1422
1423  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1424
1425  OwningExprResult BaseInit =
1426    InitSeq.Perform(*this, BaseEntity, Kind,
1427                    MultiExprArg(*this, (void**)Args, NumArgs), 0);
1428  if (BaseInit.isInvalid())
1429    return true;
1430
1431  // C++0x [class.base.init]p7:
1432  //   The initialization of each base and member constitutes a
1433  //   full-expression.
1434  BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1435  if (BaseInit.isInvalid())
1436    return true;
1437
1438  // If we are in a dependent context, template instantiation will
1439  // perform this type-checking again. Just save the arguments that we
1440  // received in a ParenListExpr.
1441  // FIXME: This isn't quite ideal, since our ASTs don't capture all
1442  // of the information that we have about the base
1443  // initializer. However, deconstructing the ASTs is a dicey process,
1444  // and this approach is far more likely to get the corner cases right.
1445  if (CurContext->isDependentContext()) {
1446    // Bump the reference count of all of the arguments.
1447    for (unsigned I = 0; I != NumArgs; ++I)
1448      Args[I]->Retain();
1449
1450    OwningExprResult Init
1451      = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1452                                          RParenLoc));
1453    return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1454                                                    BaseSpec->isVirtual(),
1455                                                    LParenLoc,
1456                                                    Init.takeAs<Expr>(),
1457                                                    RParenLoc);
1458  }
1459
1460  return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
1461                                                  BaseSpec->isVirtual(),
1462                                                  LParenLoc,
1463                                                  BaseInit.takeAs<Expr>(),
1464                                                  RParenLoc);
1465}
1466
1467/// ImplicitInitializerKind - How an implicit base or member initializer should
1468/// initialize its base or member.
1469enum ImplicitInitializerKind {
1470  IIK_Default,
1471  IIK_Copy,
1472  IIK_Move
1473};
1474
1475static bool
1476BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1477                             ImplicitInitializerKind ImplicitInitKind,
1478                             CXXBaseSpecifier *BaseSpec,
1479                             bool IsInheritedVirtualBase,
1480                             CXXBaseOrMemberInitializer *&CXXBaseInit) {
1481  InitializedEntity InitEntity
1482    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1483                                        IsInheritedVirtualBase);
1484
1485  Sema::OwningExprResult BaseInit(SemaRef);
1486
1487  switch (ImplicitInitKind) {
1488  case IIK_Default: {
1489    InitializationKind InitKind
1490      = InitializationKind::CreateDefault(Constructor->getLocation());
1491    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1492    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1493                               Sema::MultiExprArg(SemaRef, 0, 0));
1494    break;
1495  }
1496
1497  case IIK_Copy: {
1498    ParmVarDecl *Param = Constructor->getParamDecl(0);
1499    QualType ParamType = Param->getType().getNonReferenceType();
1500
1501    Expr *CopyCtorArg =
1502      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1503                          SourceLocation(), ParamType, 0);
1504
1505    // Cast to the base class to avoid ambiguities.
1506    SemaRef.ImpCastExprToType(CopyCtorArg, BaseSpec->getType(),
1507                              CastExpr::CK_UncheckedDerivedToBase,
1508                              /*isLvalue=*/true,
1509                              CXXBaseSpecifierArray(BaseSpec));
1510
1511    InitializationKind InitKind
1512      = InitializationKind::CreateDirect(Constructor->getLocation(),
1513                                         SourceLocation(), SourceLocation());
1514    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1515                                   &CopyCtorArg, 1);
1516    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1517                               Sema::MultiExprArg(SemaRef,
1518                                                  (void**)&CopyCtorArg, 1));
1519    break;
1520  }
1521
1522  case IIK_Move:
1523    assert(false && "Unhandled initializer kind!");
1524  }
1525
1526  BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1527  if (BaseInit.isInvalid())
1528    return true;
1529
1530  CXXBaseInit =
1531    new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1532               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1533                                                        SourceLocation()),
1534                                             BaseSpec->isVirtual(),
1535                                             SourceLocation(),
1536                                             BaseInit.takeAs<Expr>(),
1537                                             SourceLocation());
1538
1539  return false;
1540}
1541
1542static bool
1543BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1544                               ImplicitInitializerKind ImplicitInitKind,
1545                               FieldDecl *Field,
1546                               CXXBaseOrMemberInitializer *&CXXMemberInit) {
1547  if (ImplicitInitKind == IIK_Copy) {
1548    // FIXME: We shouldn't return early here. The reason we do it is that
1549    // we don't handle copying arrays.
1550    CXXMemberInit = 0;
1551    return false;
1552
1553    ParmVarDecl *Param = Constructor->getParamDecl(0);
1554    QualType ParamType = Param->getType().getNonReferenceType();
1555
1556    Expr *MemberExprBase =
1557      DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1558                          SourceLocation(), ParamType, 0);
1559
1560
1561    Expr *CopyCtorArg =
1562      MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false,
1563                         0, SourceRange(), Field,
1564                         DeclAccessPair::make(Field, Field->getAccess()),
1565                         SourceLocation(), 0,
1566                         Field->getType().getNonReferenceType());
1567
1568    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1569    InitializationKind InitKind =
1570      InitializationKind::CreateDirect(Constructor->getLocation(),
1571                                       SourceLocation(), SourceLocation());
1572
1573    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1574                                   &CopyCtorArg, 1);
1575
1576    Sema::OwningExprResult MemberInit =
1577      InitSeq.Perform(SemaRef, InitEntity, InitKind,
1578                      Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0);
1579    if (MemberInit.isInvalid())
1580      return true;
1581
1582    CXXMemberInit = 0;
1583    return false;
1584  }
1585
1586  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1587
1588  QualType FieldBaseElementType =
1589    SemaRef.Context.getBaseElementType(Field->getType());
1590
1591  if (FieldBaseElementType->isRecordType()) {
1592    InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1593    InitializationKind InitKind =
1594      InitializationKind::CreateDefault(Constructor->getLocation());
1595
1596    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1597    Sema::OwningExprResult MemberInit =
1598      InitSeq.Perform(SemaRef, InitEntity, InitKind,
1599                      Sema::MultiExprArg(SemaRef, 0, 0));
1600    MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1601    if (MemberInit.isInvalid())
1602      return true;
1603
1604    CXXMemberInit =
1605      new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1606                                                       Field, SourceLocation(),
1607                                                       SourceLocation(),
1608                                                      MemberInit.takeAs<Expr>(),
1609                                                       SourceLocation());
1610    return false;
1611  }
1612
1613  if (FieldBaseElementType->isReferenceType()) {
1614    SemaRef.Diag(Constructor->getLocation(),
1615                 diag::err_uninitialized_member_in_ctor)
1616    << (int)Constructor->isImplicit()
1617    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1618    << 0 << Field->getDeclName();
1619    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1620    return true;
1621  }
1622
1623  if (FieldBaseElementType.isConstQualified()) {
1624    SemaRef.Diag(Constructor->getLocation(),
1625                 diag::err_uninitialized_member_in_ctor)
1626    << (int)Constructor->isImplicit()
1627    << SemaRef.Context.getTagDeclType(Constructor->getParent())
1628    << 1 << Field->getDeclName();
1629    SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1630    return true;
1631  }
1632
1633  // Nothing to initialize.
1634  CXXMemberInit = 0;
1635  return false;
1636}
1637
1638bool
1639Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
1640                                  CXXBaseOrMemberInitializer **Initializers,
1641                                  unsigned NumInitializers,
1642                                  bool AnyErrors) {
1643  if (Constructor->getDeclContext()->isDependentContext()) {
1644    // Just store the initializers as written, they will be checked during
1645    // instantiation.
1646    if (NumInitializers > 0) {
1647      Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1648      CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1649        new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1650      memcpy(baseOrMemberInitializers, Initializers,
1651             NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1652      Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1653    }
1654
1655    return false;
1656  }
1657
1658  ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1659
1660  // FIXME: Handle implicit move constructors.
1661  if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1662    ImplicitInitKind = IIK_Copy;
1663
1664  // We need to build the initializer AST according to order of construction
1665  // and not what user specified in the Initializers list.
1666  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
1667  if (!ClassDecl)
1668    return true;
1669
1670  llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1671  llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1672  bool HadError = false;
1673
1674  for (unsigned i = 0; i < NumInitializers; i++) {
1675    CXXBaseOrMemberInitializer *Member = Initializers[i];
1676
1677    if (Member->isBaseInitializer())
1678      AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
1679    else
1680      AllBaseFields[Member->getMember()] = Member;
1681  }
1682
1683  // Keep track of the direct virtual bases.
1684  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1685  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1686       E = ClassDecl->bases_end(); I != E; ++I) {
1687    if (I->isVirtual())
1688      DirectVBases.insert(I);
1689  }
1690
1691  // Push virtual bases before others.
1692  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1693       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1694
1695    if (CXXBaseOrMemberInitializer *Value
1696        = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1697      AllToInit.push_back(Value);
1698    } else if (!AnyErrors) {
1699      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
1700      CXXBaseOrMemberInitializer *CXXBaseInit;
1701      if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1702                                       VBase, IsInheritedVirtualBase,
1703                                       CXXBaseInit)) {
1704        HadError = true;
1705        continue;
1706      }
1707
1708      AllToInit.push_back(CXXBaseInit);
1709    }
1710  }
1711
1712  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1713       E = ClassDecl->bases_end(); Base != E; ++Base) {
1714    // Virtuals are in the virtual base list and already constructed.
1715    if (Base->isVirtual())
1716      continue;
1717
1718    if (CXXBaseOrMemberInitializer *Value
1719          = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1720      AllToInit.push_back(Value);
1721    } else if (!AnyErrors) {
1722      CXXBaseOrMemberInitializer *CXXBaseInit;
1723      if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1724                                       Base, /*IsInheritedVirtualBase=*/false,
1725                                       CXXBaseInit)) {
1726        HadError = true;
1727        continue;
1728      }
1729
1730      AllToInit.push_back(CXXBaseInit);
1731    }
1732  }
1733
1734  // non-static data members.
1735  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1736       E = ClassDecl->field_end(); Field != E; ++Field) {
1737    if ((*Field)->isAnonymousStructOrUnion()) {
1738      if (const RecordType *FieldClassType =
1739          Field->getType()->getAs<RecordType>()) {
1740        CXXRecordDecl *FieldClassDecl
1741          = cast<CXXRecordDecl>(FieldClassType->getDecl());
1742        for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1743            EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1744          if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1745            // 'Member' is the anonymous union field and 'AnonUnionMember' is
1746            // set to the anonymous union data member used in the initializer
1747            // list.
1748            Value->setMember(*Field);
1749            Value->setAnonUnionMember(*FA);
1750            AllToInit.push_back(Value);
1751            break;
1752          }
1753        }
1754      }
1755      continue;
1756    }
1757    if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1758      AllToInit.push_back(Value);
1759      continue;
1760    }
1761
1762    if (AnyErrors)
1763      continue;
1764
1765    CXXBaseOrMemberInitializer *Member;
1766    if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1767                                       *Field, Member)) {
1768      HadError = true;
1769      continue;
1770    }
1771
1772    // If the member doesn't need to be initialized, it will be null.
1773    if (Member)
1774      AllToInit.push_back(Member);
1775  }
1776
1777  NumInitializers = AllToInit.size();
1778  if (NumInitializers > 0) {
1779    Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1780    CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1781      new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1782    memcpy(baseOrMemberInitializers, AllToInit.data(),
1783           NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1784    Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1785
1786    // Constructors implicitly reference the base and member
1787    // destructors.
1788    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1789                                           Constructor->getParent());
1790  }
1791
1792  return HadError;
1793}
1794
1795static void *GetKeyForTopLevelField(FieldDecl *Field) {
1796  // For anonymous unions, use the class declaration as the key.
1797  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
1798    if (RT->getDecl()->isAnonymousStructOrUnion())
1799      return static_cast<void *>(RT->getDecl());
1800  }
1801  return static_cast<void *>(Field);
1802}
1803
1804static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1805  return Context.getCanonicalType(BaseType).getTypePtr();
1806}
1807
1808static void *GetKeyForMember(ASTContext &Context,
1809                             CXXBaseOrMemberInitializer *Member,
1810                             bool MemberMaybeAnon = false) {
1811  if (!Member->isMemberInitializer())
1812    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
1813
1814  // For fields injected into the class via declaration of an anonymous union,
1815  // use its anonymous union class declaration as the unique key.
1816  FieldDecl *Field = Member->getMember();
1817
1818  // After SetBaseOrMemberInitializers call, Field is the anonymous union
1819  // data member of the class. Data member used in the initializer list is
1820  // in AnonUnionMember field.
1821  if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1822    Field = Member->getAnonUnionMember();
1823
1824  // If the field is a member of an anonymous struct or union, our key
1825  // is the anonymous record decl that's a direct child of the class.
1826  RecordDecl *RD = Field->getParent();
1827  if (RD->isAnonymousStructOrUnion()) {
1828    while (true) {
1829      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1830      if (Parent->isAnonymousStructOrUnion())
1831        RD = Parent;
1832      else
1833        break;
1834    }
1835
1836    return static_cast<void *>(RD);
1837  }
1838
1839  return static_cast<void *>(Field);
1840}
1841
1842static void
1843DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
1844                                  const CXXConstructorDecl *Constructor,
1845                                  CXXBaseOrMemberInitializer **Inits,
1846                                  unsigned NumInits) {
1847  if (Constructor->getDeclContext()->isDependentContext())
1848    return;
1849
1850  if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1851        == Diagnostic::Ignored)
1852    return;
1853
1854  // Build the list of bases and members in the order that they'll
1855  // actually be initialized.  The explicit initializers should be in
1856  // this same order but may be missing things.
1857  llvm::SmallVector<const void*, 32> IdealInitKeys;
1858
1859  const CXXRecordDecl *ClassDecl = Constructor->getParent();
1860
1861  // 1. Virtual bases.
1862  for (CXXRecordDecl::base_class_const_iterator VBase =
1863       ClassDecl->vbases_begin(),
1864       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1865    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
1866
1867  // 2. Non-virtual bases.
1868  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
1869       E = ClassDecl->bases_end(); Base != E; ++Base) {
1870    if (Base->isVirtual())
1871      continue;
1872    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
1873  }
1874
1875  // 3. Direct fields.
1876  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1877       E = ClassDecl->field_end(); Field != E; ++Field)
1878    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
1879
1880  unsigned NumIdealInits = IdealInitKeys.size();
1881  unsigned IdealIndex = 0;
1882
1883  CXXBaseOrMemberInitializer *PrevInit = 0;
1884  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1885    CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1886    void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1887
1888    // Scan forward to try to find this initializer in the idealized
1889    // initializers list.
1890    for (; IdealIndex != NumIdealInits; ++IdealIndex)
1891      if (InitKey == IdealInitKeys[IdealIndex])
1892        break;
1893
1894    // If we didn't find this initializer, it must be because we
1895    // scanned past it on a previous iteration.  That can only
1896    // happen if we're out of order;  emit a warning.
1897    if (IdealIndex == NumIdealInits) {
1898      assert(PrevInit && "initializer not found in initializer list");
1899
1900      Sema::SemaDiagnosticBuilder D =
1901        SemaRef.Diag(PrevInit->getSourceLocation(),
1902                     diag::warn_initializer_out_of_order);
1903
1904      if (PrevInit->isMemberInitializer())
1905        D << 0 << PrevInit->getMember()->getDeclName();
1906      else
1907        D << 1 << PrevInit->getBaseClassInfo()->getType();
1908
1909      if (Init->isMemberInitializer())
1910        D << 0 << Init->getMember()->getDeclName();
1911      else
1912        D << 1 << Init->getBaseClassInfo()->getType();
1913
1914      // Move back to the initializer's location in the ideal list.
1915      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1916        if (InitKey == IdealInitKeys[IdealIndex])
1917          break;
1918
1919      assert(IdealIndex != NumIdealInits &&
1920             "initializer not found in initializer list");
1921    }
1922
1923    PrevInit = Init;
1924  }
1925}
1926
1927namespace {
1928bool CheckRedundantInit(Sema &S,
1929                        CXXBaseOrMemberInitializer *Init,
1930                        CXXBaseOrMemberInitializer *&PrevInit) {
1931  if (!PrevInit) {
1932    PrevInit = Init;
1933    return false;
1934  }
1935
1936  if (FieldDecl *Field = Init->getMember())
1937    S.Diag(Init->getSourceLocation(),
1938           diag::err_multiple_mem_initialization)
1939      << Field->getDeclName()
1940      << Init->getSourceRange();
1941  else {
1942    Type *BaseClass = Init->getBaseClass();
1943    assert(BaseClass && "neither field nor base");
1944    S.Diag(Init->getSourceLocation(),
1945           diag::err_multiple_base_initialization)
1946      << QualType(BaseClass, 0)
1947      << Init->getSourceRange();
1948  }
1949  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
1950    << 0 << PrevInit->getSourceRange();
1951
1952  return true;
1953}
1954
1955typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
1956typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
1957
1958bool CheckRedundantUnionInit(Sema &S,
1959                             CXXBaseOrMemberInitializer *Init,
1960                             RedundantUnionMap &Unions) {
1961  FieldDecl *Field = Init->getMember();
1962  RecordDecl *Parent = Field->getParent();
1963  if (!Parent->isAnonymousStructOrUnion())
1964    return false;
1965
1966  NamedDecl *Child = Field;
1967  do {
1968    if (Parent->isUnion()) {
1969      UnionEntry &En = Unions[Parent];
1970      if (En.first && En.first != Child) {
1971        S.Diag(Init->getSourceLocation(),
1972               diag::err_multiple_mem_union_initialization)
1973          << Field->getDeclName()
1974          << Init->getSourceRange();
1975        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
1976          << 0 << En.second->getSourceRange();
1977        return true;
1978      } else if (!En.first) {
1979        En.first = Child;
1980        En.second = Init;
1981      }
1982    }
1983
1984    Child = Parent;
1985    Parent = cast<RecordDecl>(Parent->getDeclContext());
1986  } while (Parent->isAnonymousStructOrUnion());
1987
1988  return false;
1989}
1990}
1991
1992/// ActOnMemInitializers - Handle the member initializers for a constructor.
1993void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
1994                                SourceLocation ColonLoc,
1995                                MemInitTy **meminits, unsigned NumMemInits,
1996                                bool AnyErrors) {
1997  if (!ConstructorDecl)
1998    return;
1999
2000  AdjustDeclIfTemplate(ConstructorDecl);
2001
2002  CXXConstructorDecl *Constructor
2003    = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2004
2005  if (!Constructor) {
2006    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2007    return;
2008  }
2009
2010  CXXBaseOrMemberInitializer **MemInits =
2011    reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
2012
2013  // Mapping for the duplicate initializers check.
2014  // For member initializers, this is keyed with a FieldDecl*.
2015  // For base initializers, this is keyed with a Type*.
2016  llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
2017
2018  // Mapping for the inconsistent anonymous-union initializers check.
2019  RedundantUnionMap MemberUnions;
2020
2021  bool HadError = false;
2022  for (unsigned i = 0; i < NumMemInits; i++) {
2023    CXXBaseOrMemberInitializer *Init = MemInits[i];
2024
2025    if (Init->isMemberInitializer()) {
2026      FieldDecl *Field = Init->getMember();
2027      if (CheckRedundantInit(*this, Init, Members[Field]) ||
2028          CheckRedundantUnionInit(*this, Init, MemberUnions))
2029        HadError = true;
2030    } else {
2031      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2032      if (CheckRedundantInit(*this, Init, Members[Key]))
2033        HadError = true;
2034    }
2035  }
2036
2037  if (HadError)
2038    return;
2039
2040  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2041
2042  SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2043}
2044
2045void
2046Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2047                                             CXXRecordDecl *ClassDecl) {
2048  // Ignore dependent contexts.
2049  if (ClassDecl->isDependentContext())
2050    return;
2051
2052  // FIXME: all the access-control diagnostics are positioned on the
2053  // field/base declaration.  That's probably good; that said, the
2054  // user might reasonably want to know why the destructor is being
2055  // emitted, and we currently don't say.
2056
2057  // Non-static data members.
2058  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2059       E = ClassDecl->field_end(); I != E; ++I) {
2060    FieldDecl *Field = *I;
2061
2062    QualType FieldType = Context.getBaseElementType(Field->getType());
2063
2064    const RecordType* RT = FieldType->getAs<RecordType>();
2065    if (!RT)
2066      continue;
2067
2068    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2069    if (FieldClassDecl->hasTrivialDestructor())
2070      continue;
2071
2072    CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2073    CheckDestructorAccess(Field->getLocation(), Dtor,
2074                          PDiag(diag::err_access_dtor_field)
2075                            << Field->getDeclName()
2076                            << FieldType);
2077
2078    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2079  }
2080
2081  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2082
2083  // Bases.
2084  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2085       E = ClassDecl->bases_end(); Base != E; ++Base) {
2086    // Bases are always records in a well-formed non-dependent class.
2087    const RecordType *RT = Base->getType()->getAs<RecordType>();
2088
2089    // Remember direct virtual bases.
2090    if (Base->isVirtual())
2091      DirectVirtualBases.insert(RT);
2092
2093    // Ignore trivial destructors.
2094    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2095    if (BaseClassDecl->hasTrivialDestructor())
2096      continue;
2097
2098    CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2099
2100    // FIXME: caret should be on the start of the class name
2101    CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2102                          PDiag(diag::err_access_dtor_base)
2103                            << Base->getType()
2104                            << Base->getSourceRange());
2105
2106    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2107  }
2108
2109  // Virtual bases.
2110  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2111       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2112
2113    // Bases are always records in a well-formed non-dependent class.
2114    const RecordType *RT = VBase->getType()->getAs<RecordType>();
2115
2116    // Ignore direct virtual bases.
2117    if (DirectVirtualBases.count(RT))
2118      continue;
2119
2120    // Ignore trivial destructors.
2121    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2122    if (BaseClassDecl->hasTrivialDestructor())
2123      continue;
2124
2125    CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2126    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2127                          PDiag(diag::err_access_dtor_vbase)
2128                            << VBase->getType());
2129
2130    MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2131  }
2132}
2133
2134void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
2135  if (!CDtorDecl)
2136    return;
2137
2138  if (CXXConstructorDecl *Constructor
2139      = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
2140    SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2141}
2142
2143bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2144                                  unsigned DiagID, AbstractDiagSelID SelID,
2145                                  const CXXRecordDecl *CurrentRD) {
2146  if (SelID == -1)
2147    return RequireNonAbstractType(Loc, T,
2148                                  PDiag(DiagID), CurrentRD);
2149  else
2150    return RequireNonAbstractType(Loc, T,
2151                                  PDiag(DiagID) << SelID, CurrentRD);
2152}
2153
2154bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2155                                  const PartialDiagnostic &PD,
2156                                  const CXXRecordDecl *CurrentRD) {
2157  if (!getLangOptions().CPlusPlus)
2158    return false;
2159
2160  if (const ArrayType *AT = Context.getAsArrayType(T))
2161    return RequireNonAbstractType(Loc, AT->getElementType(), PD,
2162                                  CurrentRD);
2163
2164  if (const PointerType *PT = T->getAs<PointerType>()) {
2165    // Find the innermost pointer type.
2166    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2167      PT = T;
2168
2169    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2170      return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
2171  }
2172
2173  const RecordType *RT = T->getAs<RecordType>();
2174  if (!RT)
2175    return false;
2176
2177  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2178
2179  if (CurrentRD && CurrentRD != RD)
2180    return false;
2181
2182  // FIXME: is this reasonable?  It matches current behavior, but....
2183  if (!RD->getDefinition())
2184    return false;
2185
2186  if (!RD->isAbstract())
2187    return false;
2188
2189  Diag(Loc, PD) << RD->getDeclName();
2190
2191  // Check if we've already emitted the list of pure virtual functions for this
2192  // class.
2193  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2194    return true;
2195
2196  CXXFinalOverriderMap FinalOverriders;
2197  RD->getFinalOverriders(FinalOverriders);
2198
2199  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2200                                   MEnd = FinalOverriders.end();
2201       M != MEnd;
2202       ++M) {
2203    for (OverridingMethods::iterator SO = M->second.begin(),
2204                                  SOEnd = M->second.end();
2205         SO != SOEnd; ++SO) {
2206      // C++ [class.abstract]p4:
2207      //   A class is abstract if it contains or inherits at least one
2208      //   pure virtual function for which the final overrider is pure
2209      //   virtual.
2210
2211      //
2212      if (SO->second.size() != 1)
2213        continue;
2214
2215      if (!SO->second.front().Method->isPure())
2216        continue;
2217
2218      Diag(SO->second.front().Method->getLocation(),
2219           diag::note_pure_virtual_function)
2220        << SO->second.front().Method->getDeclName();
2221    }
2222  }
2223
2224  if (!PureVirtualClassDiagSet)
2225    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2226  PureVirtualClassDiagSet->insert(RD);
2227
2228  return true;
2229}
2230
2231namespace {
2232  class AbstractClassUsageDiagnoser
2233    : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2234    Sema &SemaRef;
2235    CXXRecordDecl *AbstractClass;
2236
2237    bool VisitDeclContext(const DeclContext *DC) {
2238      bool Invalid = false;
2239
2240      for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2241           E = DC->decls_end(); I != E; ++I)
2242        Invalid |= Visit(*I);
2243
2244      return Invalid;
2245    }
2246
2247  public:
2248    AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2249      : SemaRef(SemaRef), AbstractClass(ac) {
2250        Visit(SemaRef.Context.getTranslationUnitDecl());
2251    }
2252
2253    bool VisitFunctionDecl(const FunctionDecl *FD) {
2254      if (FD->isThisDeclarationADefinition()) {
2255        // No need to do the check if we're in a definition, because it requires
2256        // that the return/param types are complete.
2257        // because that requires
2258        return VisitDeclContext(FD);
2259      }
2260
2261      // Check the return type.
2262      QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
2263      bool Invalid =
2264        SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2265                                       diag::err_abstract_type_in_decl,
2266                                       Sema::AbstractReturnType,
2267                                       AbstractClass);
2268
2269      for (FunctionDecl::param_const_iterator I = FD->param_begin(),
2270           E = FD->param_end(); I != E; ++I) {
2271        const ParmVarDecl *VD = *I;
2272        Invalid |=
2273          SemaRef.RequireNonAbstractType(VD->getLocation(),
2274                                         VD->getOriginalType(),
2275                                         diag::err_abstract_type_in_decl,
2276                                         Sema::AbstractParamType,
2277                                         AbstractClass);
2278      }
2279
2280      return Invalid;
2281    }
2282
2283    bool VisitDecl(const Decl* D) {
2284      if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2285        return VisitDeclContext(DC);
2286
2287      return false;
2288    }
2289  };
2290}
2291
2292/// \brief Perform semantic checks on a class definition that has been
2293/// completing, introducing implicitly-declared members, checking for
2294/// abstract types, etc.
2295void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
2296  if (!Record || Record->isInvalidDecl())
2297    return;
2298
2299  if (!Record->isDependentType())
2300    AddImplicitlyDeclaredMembersToClass(S, Record);
2301
2302  if (Record->isInvalidDecl())
2303    return;
2304
2305  // Set access bits correctly on the directly-declared conversions.
2306  UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2307  for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2308    Convs->setAccess(I, (*I)->getAccess());
2309
2310  // Determine whether we need to check for final overriders. We do
2311  // this either when there are virtual base classes (in which case we
2312  // may end up finding multiple final overriders for a given virtual
2313  // function) or any of the base classes is abstract (in which case
2314  // we might detect that this class is abstract).
2315  bool CheckFinalOverriders = false;
2316  if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2317      !Record->isDependentType()) {
2318    if (Record->getNumVBases())
2319      CheckFinalOverriders = true;
2320    else if (!Record->isAbstract()) {
2321      for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2322                                                 BEnd = Record->bases_end();
2323           B != BEnd; ++B) {
2324        CXXRecordDecl *BaseDecl
2325          = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2326        if (BaseDecl->isAbstract()) {
2327          CheckFinalOverriders = true;
2328          break;
2329        }
2330      }
2331    }
2332  }
2333
2334  if (CheckFinalOverriders) {
2335    CXXFinalOverriderMap FinalOverriders;
2336    Record->getFinalOverriders(FinalOverriders);
2337
2338    for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2339                                     MEnd = FinalOverriders.end();
2340         M != MEnd; ++M) {
2341      for (OverridingMethods::iterator SO = M->second.begin(),
2342                                    SOEnd = M->second.end();
2343           SO != SOEnd; ++SO) {
2344        assert(SO->second.size() > 0 &&
2345               "All virtual functions have overridding virtual functions");
2346        if (SO->second.size() == 1) {
2347          // C++ [class.abstract]p4:
2348          //   A class is abstract if it contains or inherits at least one
2349          //   pure virtual function for which the final overrider is pure
2350          //   virtual.
2351          if (SO->second.front().Method->isPure())
2352            Record->setAbstract(true);
2353          continue;
2354        }
2355
2356        // C++ [class.virtual]p2:
2357        //   In a derived class, if a virtual member function of a base
2358        //   class subobject has more than one final overrider the
2359        //   program is ill-formed.
2360        Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2361          << (NamedDecl *)M->first << Record;
2362        Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2363        for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2364                                                 OMEnd = SO->second.end();
2365             OM != OMEnd; ++OM)
2366          Diag(OM->Method->getLocation(), diag::note_final_overrider)
2367            << (NamedDecl *)M->first << OM->Method->getParent();
2368
2369        Record->setInvalidDecl();
2370      }
2371    }
2372  }
2373
2374  if (Record->isAbstract() && !Record->isInvalidDecl())
2375    (void)AbstractClassUsageDiagnoser(*this, Record);
2376
2377  // If this is not an aggregate type and has no user-declared constructor,
2378  // complain about any non-static data members of reference or const scalar
2379  // type, since they will never get initializers.
2380  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2381      !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2382    bool Complained = false;
2383    for (RecordDecl::field_iterator F = Record->field_begin(),
2384                                 FEnd = Record->field_end();
2385         F != FEnd; ++F) {
2386      if (F->getType()->isReferenceType() ||
2387          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
2388        if (!Complained) {
2389          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2390            << Record->getTagKind() << Record;
2391          Complained = true;
2392        }
2393
2394        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2395          << F->getType()->isReferenceType()
2396          << F->getDeclName();
2397      }
2398    }
2399  }
2400}
2401
2402void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
2403                                             DeclPtrTy TagDecl,
2404                                             SourceLocation LBrac,
2405                                             SourceLocation RBrac,
2406                                             AttributeList *AttrList) {
2407  if (!TagDecl)
2408    return;
2409
2410  AdjustDeclIfTemplate(TagDecl);
2411
2412  ActOnFields(S, RLoc, TagDecl,
2413              (DeclPtrTy*)FieldCollector->getCurFields(),
2414              FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
2415
2416  CheckCompletedCXXClass(S,
2417                      dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
2418}
2419
2420/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2421/// special functions, such as the default constructor, copy
2422/// constructor, or destructor, to the given C++ class (C++
2423/// [special]p1).  This routine can only be executed just before the
2424/// definition of the class is complete.
2425///
2426/// The scope, if provided, is the class scope.
2427void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2428                                               CXXRecordDecl *ClassDecl) {
2429  CanQualType ClassType
2430    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
2431
2432  // FIXME: Implicit declarations have exception specifications, which are
2433  // the union of the specifications of the implicitly called functions.
2434
2435  if (!ClassDecl->hasUserDeclaredConstructor()) {
2436    // C++ [class.ctor]p5:
2437    //   A default constructor for a class X is a constructor of class X
2438    //   that can be called without an argument. If there is no
2439    //   user-declared constructor for class X, a default constructor is
2440    //   implicitly declared. An implicitly-declared default constructor
2441    //   is an inline public member of its class.
2442    DeclarationName Name
2443      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2444    CXXConstructorDecl *DefaultCon =
2445      CXXConstructorDecl::Create(Context, ClassDecl,
2446                                 ClassDecl->getLocation(), Name,
2447                                 Context.getFunctionType(Context.VoidTy,
2448                                                         0, 0, false, 0,
2449                                                         /*FIXME*/false, false,
2450                                                         0, 0,
2451                                                       FunctionType::ExtInfo()),
2452                                 /*TInfo=*/0,
2453                                 /*isExplicit=*/false,
2454                                 /*isInline=*/true,
2455                                 /*isImplicitlyDeclared=*/true);
2456    DefaultCon->setAccess(AS_public);
2457    DefaultCon->setImplicit();
2458    DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
2459    if (S)
2460      PushOnScopeChains(DefaultCon, S, true);
2461    else
2462      ClassDecl->addDecl(DefaultCon);
2463  }
2464
2465  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2466    // C++ [class.copy]p4:
2467    //   If the class definition does not explicitly declare a copy
2468    //   constructor, one is declared implicitly.
2469
2470    // C++ [class.copy]p5:
2471    //   The implicitly-declared copy constructor for a class X will
2472    //   have the form
2473    //
2474    //       X::X(const X&)
2475    //
2476    //   if
2477    bool HasConstCopyConstructor = true;
2478
2479    //     -- each direct or virtual base class B of X has a copy
2480    //        constructor whose first parameter is of type const B& or
2481    //        const volatile B&, and
2482    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2483         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2484      const CXXRecordDecl *BaseClassDecl
2485        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2486      HasConstCopyConstructor
2487        = BaseClassDecl->hasConstCopyConstructor(Context);
2488    }
2489
2490    //     -- for all the nonstatic data members of X that are of a
2491    //        class type M (or array thereof), each such class type
2492    //        has a copy constructor whose first parameter is of type
2493    //        const M& or const volatile M&.
2494    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2495         HasConstCopyConstructor && Field != ClassDecl->field_end();
2496         ++Field) {
2497      QualType FieldType = (*Field)->getType();
2498      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2499        FieldType = Array->getElementType();
2500      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2501        const CXXRecordDecl *FieldClassDecl
2502          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2503        HasConstCopyConstructor
2504          = FieldClassDecl->hasConstCopyConstructor(Context);
2505      }
2506    }
2507
2508    //   Otherwise, the implicitly declared copy constructor will have
2509    //   the form
2510    //
2511    //       X::X(X&)
2512    QualType ArgType = ClassType;
2513    if (HasConstCopyConstructor)
2514      ArgType = ArgType.withConst();
2515    ArgType = Context.getLValueReferenceType(ArgType);
2516
2517    //   An implicitly-declared copy constructor is an inline public
2518    //   member of its class.
2519    DeclarationName Name
2520      = Context.DeclarationNames.getCXXConstructorName(ClassType);
2521    CXXConstructorDecl *CopyConstructor
2522      = CXXConstructorDecl::Create(Context, ClassDecl,
2523                                   ClassDecl->getLocation(), Name,
2524                                   Context.getFunctionType(Context.VoidTy,
2525                                                           &ArgType, 1,
2526                                                           false, 0,
2527                                                           /*FIXME:*/false,
2528                                                           false, 0, 0,
2529                                                       FunctionType::ExtInfo()),
2530                                   /*TInfo=*/0,
2531                                   /*isExplicit=*/false,
2532                                   /*isInline=*/true,
2533                                   /*isImplicitlyDeclared=*/true);
2534    CopyConstructor->setAccess(AS_public);
2535    CopyConstructor->setImplicit();
2536    CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
2537
2538    // Add the parameter to the constructor.
2539    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2540                                                 ClassDecl->getLocation(),
2541                                                 /*IdentifierInfo=*/0,
2542                                                 ArgType, /*TInfo=*/0,
2543                                                 VarDecl::None,
2544                                                 VarDecl::None, 0);
2545    CopyConstructor->setParams(&FromParam, 1);
2546    if (S)
2547      PushOnScopeChains(CopyConstructor, S, true);
2548    else
2549      ClassDecl->addDecl(CopyConstructor);
2550  }
2551
2552  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2553    // Note: The following rules are largely analoguous to the copy
2554    // constructor rules. Note that virtual bases are not taken into account
2555    // for determining the argument type of the operator. Note also that
2556    // operators taking an object instead of a reference are allowed.
2557    //
2558    // C++ [class.copy]p10:
2559    //   If the class definition does not explicitly declare a copy
2560    //   assignment operator, one is declared implicitly.
2561    //   The implicitly-defined copy assignment operator for a class X
2562    //   will have the form
2563    //
2564    //       X& X::operator=(const X&)
2565    //
2566    //   if
2567    bool HasConstCopyAssignment = true;
2568
2569    //       -- each direct base class B of X has a copy assignment operator
2570    //          whose parameter is of type const B&, const volatile B& or B,
2571    //          and
2572    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2573         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
2574      assert(!Base->getType()->isDependentType() &&
2575            "Cannot generate implicit members for class with dependent bases.");
2576      const CXXRecordDecl *BaseClassDecl
2577        = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
2578      const CXXMethodDecl *MD = 0;
2579      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
2580                                                                     MD);
2581    }
2582
2583    //       -- for all the nonstatic data members of X that are of a class
2584    //          type M (or array thereof), each such class type has a copy
2585    //          assignment operator whose parameter is of type const M&,
2586    //          const volatile M& or M.
2587    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2588         HasConstCopyAssignment && Field != ClassDecl->field_end();
2589         ++Field) {
2590      QualType FieldType = (*Field)->getType();
2591      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2592        FieldType = Array->getElementType();
2593      if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
2594        const CXXRecordDecl *FieldClassDecl
2595          = cast<CXXRecordDecl>(FieldClassType->getDecl());
2596        const CXXMethodDecl *MD = 0;
2597        HasConstCopyAssignment
2598          = FieldClassDecl->hasConstCopyAssignment(Context, MD);
2599      }
2600    }
2601
2602    //   Otherwise, the implicitly declared copy assignment operator will
2603    //   have the form
2604    //
2605    //       X& X::operator=(X&)
2606    QualType ArgType = ClassType;
2607    QualType RetType = Context.getLValueReferenceType(ArgType);
2608    if (HasConstCopyAssignment)
2609      ArgType = ArgType.withConst();
2610    ArgType = Context.getLValueReferenceType(ArgType);
2611
2612    //   An implicitly-declared copy assignment operator is an inline public
2613    //   member of its class.
2614    DeclarationName Name =
2615      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2616    CXXMethodDecl *CopyAssignment =
2617      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2618                            Context.getFunctionType(RetType, &ArgType, 1,
2619                                                    false, 0,
2620                                                    /*FIXME:*/false,
2621                                                    false, 0, 0,
2622                                                    FunctionType::ExtInfo()),
2623                            /*TInfo=*/0, /*isStatic=*/false,
2624                            /*StorageClassAsWritten=*/FunctionDecl::None,
2625                            /*isInline=*/true);
2626    CopyAssignment->setAccess(AS_public);
2627    CopyAssignment->setImplicit();
2628    CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
2629    CopyAssignment->setCopyAssignment(true);
2630
2631    // Add the parameter to the operator.
2632    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2633                                                 ClassDecl->getLocation(),
2634                                                 /*IdentifierInfo=*/0,
2635                                                 ArgType, /*TInfo=*/0,
2636                                                 VarDecl::None,
2637                                                 VarDecl::None, 0);
2638    CopyAssignment->setParams(&FromParam, 1);
2639
2640    // Don't call addedAssignmentOperator. There is no way to distinguish an
2641    // implicit from an explicit assignment operator.
2642    if (S)
2643      PushOnScopeChains(CopyAssignment, S, true);
2644    else
2645      ClassDecl->addDecl(CopyAssignment);
2646    AddOverriddenMethods(ClassDecl, CopyAssignment);
2647  }
2648
2649  if (!ClassDecl->hasUserDeclaredDestructor()) {
2650    // C++ [class.dtor]p2:
2651    //   If a class has no user-declared destructor, a destructor is
2652    //   declared implicitly. An implicitly-declared destructor is an
2653    //   inline public member of its class.
2654    QualType Ty = Context.getFunctionType(Context.VoidTy,
2655                                          0, 0, false, 0,
2656                                          /*FIXME:*/false,
2657                                          false, 0, 0, FunctionType::ExtInfo());
2658
2659    DeclarationName Name
2660      = Context.DeclarationNames.getCXXDestructorName(ClassType);
2661    CXXDestructorDecl *Destructor
2662      = CXXDestructorDecl::Create(Context, ClassDecl,
2663                                  ClassDecl->getLocation(), Name, Ty,
2664                                  /*isInline=*/true,
2665                                  /*isImplicitlyDeclared=*/true);
2666    Destructor->setAccess(AS_public);
2667    Destructor->setImplicit();
2668    Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
2669    if (S)
2670      PushOnScopeChains(Destructor, S, true);
2671    else
2672      ClassDecl->addDecl(Destructor);
2673
2674    // This could be uniqued if it ever proves significant.
2675    Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
2676
2677    AddOverriddenMethods(ClassDecl, Destructor);
2678  }
2679}
2680
2681void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
2682  Decl *D = TemplateD.getAs<Decl>();
2683  if (!D)
2684    return;
2685
2686  TemplateParameterList *Params = 0;
2687  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2688    Params = Template->getTemplateParameters();
2689  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2690           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2691    Params = PartialSpec->getTemplateParameters();
2692  else
2693    return;
2694
2695  for (TemplateParameterList::iterator Param = Params->begin(),
2696                                    ParamEnd = Params->end();
2697       Param != ParamEnd; ++Param) {
2698    NamedDecl *Named = cast<NamedDecl>(*Param);
2699    if (Named->getDeclName()) {
2700      S->AddDecl(DeclPtrTy::make(Named));
2701      IdResolver.AddDecl(Named);
2702    }
2703  }
2704}
2705
2706void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2707  if (!RecordD) return;
2708  AdjustDeclIfTemplate(RecordD);
2709  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2710  PushDeclContext(S, Record);
2711}
2712
2713void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2714  if (!RecordD) return;
2715  PopDeclContext();
2716}
2717
2718/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2719/// parsing a top-level (non-nested) C++ class, and we are now
2720/// parsing those parts of the given Method declaration that could
2721/// not be parsed earlier (C++ [class.mem]p2), such as default
2722/// arguments. This action should enter the scope of the given
2723/// Method declaration as if we had just parsed the qualified method
2724/// name. However, it should not bring the parameters into scope;
2725/// that will be performed by ActOnDelayedCXXMethodParameter.
2726void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2727}
2728
2729/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2730/// C++ method declaration. We're (re-)introducing the given
2731/// function parameter into scope for use in parsing later parts of
2732/// the method declaration. For example, we could see an
2733/// ActOnParamDefaultArgument event for this parameter.
2734void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
2735  if (!ParamD)
2736    return;
2737
2738  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
2739
2740  // If this parameter has an unparsed default argument, clear it out
2741  // to make way for the parsed default argument.
2742  if (Param->hasUnparsedDefaultArg())
2743    Param->setDefaultArg(0);
2744
2745  S->AddDecl(DeclPtrTy::make(Param));
2746  if (Param->getDeclName())
2747    IdResolver.AddDecl(Param);
2748}
2749
2750/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2751/// processing the delayed method declaration for Method. The method
2752/// declaration is now considered finished. There may be a separate
2753/// ActOnStartOfFunctionDef action later (not necessarily
2754/// immediately!) for this method, if it was also defined inside the
2755/// class body.
2756void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
2757  if (!MethodD)
2758    return;
2759
2760  AdjustDeclIfTemplate(MethodD);
2761
2762  FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
2763
2764  // Now that we have our default arguments, check the constructor
2765  // again. It could produce additional diagnostics or affect whether
2766  // the class has implicitly-declared destructors, among other
2767  // things.
2768  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2769    CheckConstructor(Constructor);
2770
2771  // Check the default arguments, which we may have added.
2772  if (!Method->isInvalidDecl())
2773    CheckCXXDefaultArguments(Method);
2774}
2775
2776/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2777/// the well-formedness of the constructor declarator @p D with type @p
2778/// R. If there are any errors in the declarator, this routine will
2779/// emit diagnostics and set the invalid bit to true.  In any case, the type
2780/// will be updated to reflect a well-formed type for the constructor and
2781/// returned.
2782QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2783                                          FunctionDecl::StorageClass &SC) {
2784  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2785
2786  // C++ [class.ctor]p3:
2787  //   A constructor shall not be virtual (10.3) or static (9.4). A
2788  //   constructor can be invoked for a const, volatile or const
2789  //   volatile object. A constructor shall not be declared const,
2790  //   volatile, or const volatile (9.3.2).
2791  if (isVirtual) {
2792    if (!D.isInvalidType())
2793      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2794        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2795        << SourceRange(D.getIdentifierLoc());
2796    D.setInvalidType();
2797  }
2798  if (SC == FunctionDecl::Static) {
2799    if (!D.isInvalidType())
2800      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2801        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2802        << SourceRange(D.getIdentifierLoc());
2803    D.setInvalidType();
2804    SC = FunctionDecl::None;
2805  }
2806
2807  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2808  if (FTI.TypeQuals != 0) {
2809    if (FTI.TypeQuals & Qualifiers::Const)
2810      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2811        << "const" << SourceRange(D.getIdentifierLoc());
2812    if (FTI.TypeQuals & Qualifiers::Volatile)
2813      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2814        << "volatile" << SourceRange(D.getIdentifierLoc());
2815    if (FTI.TypeQuals & Qualifiers::Restrict)
2816      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2817        << "restrict" << SourceRange(D.getIdentifierLoc());
2818  }
2819
2820  // Rebuild the function type "R" without any type qualifiers (in
2821  // case any of the errors above fired) and with "void" as the
2822  // return type, since constructors don't have return types. We
2823  // *always* have to do this, because GetTypeForDeclarator will
2824  // put in a result type of "int" when none was specified.
2825  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2826  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2827                                 Proto->getNumArgs(),
2828                                 Proto->isVariadic(), 0,
2829                                 Proto->hasExceptionSpec(),
2830                                 Proto->hasAnyExceptionSpec(),
2831                                 Proto->getNumExceptions(),
2832                                 Proto->exception_begin(),
2833                                 Proto->getExtInfo());
2834}
2835
2836/// CheckConstructor - Checks a fully-formed constructor for
2837/// well-formedness, issuing any diagnostics required. Returns true if
2838/// the constructor declarator is invalid.
2839void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
2840  CXXRecordDecl *ClassDecl
2841    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2842  if (!ClassDecl)
2843    return Constructor->setInvalidDecl();
2844
2845  // C++ [class.copy]p3:
2846  //   A declaration of a constructor for a class X is ill-formed if
2847  //   its first parameter is of type (optionally cv-qualified) X and
2848  //   either there are no other parameters or else all other
2849  //   parameters have default arguments.
2850  if (!Constructor->isInvalidDecl() &&
2851      ((Constructor->getNumParams() == 1) ||
2852       (Constructor->getNumParams() > 1 &&
2853        Constructor->getParamDecl(1)->hasDefaultArg())) &&
2854      Constructor->getTemplateSpecializationKind()
2855                                              != TSK_ImplicitInstantiation) {
2856    QualType ParamType = Constructor->getParamDecl(0)->getType();
2857    QualType ClassTy = Context.getTagDeclType(ClassDecl);
2858    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
2859      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2860      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
2861        << FixItHint::CreateInsertion(ParamLoc, " const &");
2862
2863      // FIXME: Rather that making the constructor invalid, we should endeavor
2864      // to fix the type.
2865      Constructor->setInvalidDecl();
2866    }
2867  }
2868
2869  // Notify the class that we've added a constructor.  In principle we
2870  // don't need to do this for out-of-line declarations; in practice
2871  // we only instantiate the most recent declaration of a method, so
2872  // we have to call this for everything but friends.
2873  if (!Constructor->getFriendObjectKind())
2874    ClassDecl->addedConstructor(Context, Constructor);
2875}
2876
2877/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2878/// issuing any diagnostics required. Returns true on error.
2879bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
2880  CXXRecordDecl *RD = Destructor->getParent();
2881
2882  if (Destructor->isVirtual()) {
2883    SourceLocation Loc;
2884
2885    if (!Destructor->isImplicit())
2886      Loc = Destructor->getLocation();
2887    else
2888      Loc = RD->getLocation();
2889
2890    // If we have a virtual destructor, look up the deallocation function
2891    FunctionDecl *OperatorDelete = 0;
2892    DeclarationName Name =
2893    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2894    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2895      return true;
2896
2897    Destructor->setOperatorDelete(OperatorDelete);
2898  }
2899
2900  return false;
2901}
2902
2903static inline bool
2904FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2905  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2906          FTI.ArgInfo[0].Param &&
2907          FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2908}
2909
2910/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2911/// the well-formednes of the destructor declarator @p D with type @p
2912/// R. If there are any errors in the declarator, this routine will
2913/// emit diagnostics and set the declarator to invalid.  Even if this happens,
2914/// will be updated to reflect a well-formed type for the destructor and
2915/// returned.
2916QualType Sema::CheckDestructorDeclarator(Declarator &D,
2917                                         FunctionDecl::StorageClass& SC) {
2918  // C++ [class.dtor]p1:
2919  //   [...] A typedef-name that names a class is a class-name
2920  //   (7.1.3); however, a typedef-name that names a class shall not
2921  //   be used as the identifier in the declarator for a destructor
2922  //   declaration.
2923  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
2924  if (isa<TypedefType>(DeclaratorType)) {
2925    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
2926      << DeclaratorType;
2927    D.setInvalidType();
2928  }
2929
2930  // C++ [class.dtor]p2:
2931  //   A destructor is used to destroy objects of its class type. A
2932  //   destructor takes no parameters, and no return type can be
2933  //   specified for it (not even void). The address of a destructor
2934  //   shall not be taken. A destructor shall not be static. A
2935  //   destructor can be invoked for a const, volatile or const
2936  //   volatile object. A destructor shall not be declared const,
2937  //   volatile or const volatile (9.3.2).
2938  if (SC == FunctionDecl::Static) {
2939    if (!D.isInvalidType())
2940      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2941        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2942        << SourceRange(D.getIdentifierLoc());
2943    SC = FunctionDecl::None;
2944    D.setInvalidType();
2945  }
2946  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
2947    // Destructors don't have return types, but the parser will
2948    // happily parse something like:
2949    //
2950    //   class X {
2951    //     float ~X();
2952    //   };
2953    //
2954    // The return type will be eliminated later.
2955    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2956      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2957      << SourceRange(D.getIdentifierLoc());
2958  }
2959
2960  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2961  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
2962    if (FTI.TypeQuals & Qualifiers::Const)
2963      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2964        << "const" << SourceRange(D.getIdentifierLoc());
2965    if (FTI.TypeQuals & Qualifiers::Volatile)
2966      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2967        << "volatile" << SourceRange(D.getIdentifierLoc());
2968    if (FTI.TypeQuals & Qualifiers::Restrict)
2969      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2970        << "restrict" << SourceRange(D.getIdentifierLoc());
2971    D.setInvalidType();
2972  }
2973
2974  // Make sure we don't have any parameters.
2975  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
2976    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2977
2978    // Delete the parameters.
2979    FTI.freeArgs();
2980    D.setInvalidType();
2981  }
2982
2983  // Make sure the destructor isn't variadic.
2984  if (FTI.isVariadic) {
2985    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
2986    D.setInvalidType();
2987  }
2988
2989  // Rebuild the function type "R" without any type qualifiers or
2990  // parameters (in case any of the errors above fired) and with
2991  // "void" as the return type, since destructors don't have return
2992  // types. We *always* have to do this, because GetTypeForDeclarator
2993  // will put in a result type of "int" when none was specified.
2994  // FIXME: Exceptions!
2995  return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
2996                                 false, false, 0, 0, FunctionType::ExtInfo());
2997}
2998
2999/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3000/// well-formednes of the conversion function declarator @p D with
3001/// type @p R. If there are any errors in the declarator, this routine
3002/// will emit diagnostics and return true. Otherwise, it will return
3003/// false. Either way, the type @p R will be updated to reflect a
3004/// well-formed type for the conversion operator.
3005void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
3006                                     FunctionDecl::StorageClass& SC) {
3007  // C++ [class.conv.fct]p1:
3008  //   Neither parameter types nor return type can be specified. The
3009  //   type of a conversion function (8.3.5) is "function taking no
3010  //   parameter returning conversion-type-id."
3011  if (SC == FunctionDecl::Static) {
3012    if (!D.isInvalidType())
3013      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3014        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3015        << SourceRange(D.getIdentifierLoc());
3016    D.setInvalidType();
3017    SC = FunctionDecl::None;
3018  }
3019
3020  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3021
3022  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
3023    // Conversion functions don't have return types, but the parser will
3024    // happily parse something like:
3025    //
3026    //   class X {
3027    //     float operator bool();
3028    //   };
3029    //
3030    // The return type will be changed later anyway.
3031    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3032      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3033      << SourceRange(D.getIdentifierLoc());
3034    D.setInvalidType();
3035  }
3036
3037  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3038
3039  // Make sure we don't have any parameters.
3040  if (Proto->getNumArgs() > 0) {
3041    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3042
3043    // Delete the parameters.
3044    D.getTypeObject(0).Fun.freeArgs();
3045    D.setInvalidType();
3046  } else if (Proto->isVariadic()) {
3047    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
3048    D.setInvalidType();
3049  }
3050
3051  // Diagnose "&operator bool()" and other such nonsense.  This
3052  // is actually a gcc extension which we don't support.
3053  if (Proto->getResultType() != ConvType) {
3054    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3055      << Proto->getResultType();
3056    D.setInvalidType();
3057    ConvType = Proto->getResultType();
3058  }
3059
3060  // C++ [class.conv.fct]p4:
3061  //   The conversion-type-id shall not represent a function type nor
3062  //   an array type.
3063  if (ConvType->isArrayType()) {
3064    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3065    ConvType = Context.getPointerType(ConvType);
3066    D.setInvalidType();
3067  } else if (ConvType->isFunctionType()) {
3068    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3069    ConvType = Context.getPointerType(ConvType);
3070    D.setInvalidType();
3071  }
3072
3073  // Rebuild the function type "R" without any parameters (in case any
3074  // of the errors above fired) and with the conversion type as the
3075  // return type.
3076  if (D.isInvalidType()) {
3077    R = Context.getFunctionType(ConvType, 0, 0, false,
3078                                Proto->getTypeQuals(),
3079                                Proto->hasExceptionSpec(),
3080                                Proto->hasAnyExceptionSpec(),
3081                                Proto->getNumExceptions(),
3082                                Proto->exception_begin(),
3083                                Proto->getExtInfo());
3084  }
3085
3086  // C++0x explicit conversion operators.
3087  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
3088    Diag(D.getDeclSpec().getExplicitSpecLoc(),
3089         diag::warn_explicit_conversion_functions)
3090      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
3091}
3092
3093/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3094/// the declaration of the given C++ conversion function. This routine
3095/// is responsible for recording the conversion function in the C++
3096/// class, if possible.
3097Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
3098  assert(Conversion && "Expected to receive a conversion function declaration");
3099
3100  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
3101
3102  // Make sure we aren't redeclaring the conversion function.
3103  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
3104
3105  // C++ [class.conv.fct]p1:
3106  //   [...] A conversion function is never used to convert a
3107  //   (possibly cv-qualified) object to the (possibly cv-qualified)
3108  //   same object type (or a reference to it), to a (possibly
3109  //   cv-qualified) base class of that type (or a reference to it),
3110  //   or to (possibly cv-qualified) void.
3111  // FIXME: Suppress this warning if the conversion function ends up being a
3112  // virtual function that overrides a virtual function in a base class.
3113  QualType ClassType
3114    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
3115  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
3116    ConvType = ConvTypeRef->getPointeeType();
3117  if (ConvType->isRecordType()) {
3118    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3119    if (ConvType == ClassType)
3120      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
3121        << ClassType;
3122    else if (IsDerivedFrom(ClassType, ConvType))
3123      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
3124        <<  ClassType << ConvType;
3125  } else if (ConvType->isVoidType()) {
3126    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
3127      << ClassType << ConvType;
3128  }
3129
3130  if (Conversion->getPrimaryTemplate()) {
3131    // ignore specializations
3132  } else if (Conversion->getPreviousDeclaration()) {
3133    if (FunctionTemplateDecl *ConversionTemplate
3134                                  = Conversion->getDescribedFunctionTemplate()) {
3135      if (ClassDecl->replaceConversion(
3136                                   ConversionTemplate->getPreviousDeclaration(),
3137                                       ConversionTemplate))
3138        return DeclPtrTy::make(ConversionTemplate);
3139    } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3140                                            Conversion))
3141      return DeclPtrTy::make(Conversion);
3142    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
3143  } else if (FunctionTemplateDecl *ConversionTemplate
3144               = Conversion->getDescribedFunctionTemplate())
3145    ClassDecl->addConversionFunction(ConversionTemplate);
3146  else
3147    ClassDecl->addConversionFunction(Conversion);
3148
3149  return DeclPtrTy::make(Conversion);
3150}
3151
3152//===----------------------------------------------------------------------===//
3153// Namespace Handling
3154//===----------------------------------------------------------------------===//
3155
3156/// ActOnStartNamespaceDef - This is called at the start of a namespace
3157/// definition.
3158Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3159                                             SourceLocation IdentLoc,
3160                                             IdentifierInfo *II,
3161                                             SourceLocation LBrace,
3162                                             AttributeList *AttrList) {
3163  NamespaceDecl *Namespc =
3164      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3165  Namespc->setLBracLoc(LBrace);
3166
3167  Scope *DeclRegionScope = NamespcScope->getParent();
3168
3169  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3170
3171  if (II) {
3172    // C++ [namespace.def]p2:
3173    // The identifier in an original-namespace-definition shall not have been
3174    // previously defined in the declarative region in which the
3175    // original-namespace-definition appears. The identifier in an
3176    // original-namespace-definition is the name of the namespace. Subsequently
3177    // in that declarative region, it is treated as an original-namespace-name.
3178
3179    NamedDecl *PrevDecl
3180      = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
3181                         ForRedeclaration);
3182
3183    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3184      // This is an extended namespace definition.
3185      // Attach this namespace decl to the chain of extended namespace
3186      // definitions.
3187      OrigNS->setNextNamespace(Namespc);
3188      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
3189
3190      // Remove the previous declaration from the scope.
3191      if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
3192        IdResolver.RemoveDecl(OrigNS);
3193        DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
3194      }
3195    } else if (PrevDecl) {
3196      // This is an invalid name redefinition.
3197      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3198       << Namespc->getDeclName();
3199      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3200      Namespc->setInvalidDecl();
3201      // Continue on to push Namespc as current DeclContext and return it.
3202    } else if (II->isStr("std") &&
3203               CurContext->getLookupContext()->isTranslationUnit()) {
3204      // This is the first "real" definition of the namespace "std", so update
3205      // our cache of the "std" namespace to point at this definition.
3206      if (StdNamespace) {
3207        // We had already defined a dummy namespace "std". Link this new
3208        // namespace definition to the dummy namespace "std".
3209        StdNamespace->setNextNamespace(Namespc);
3210        StdNamespace->setLocation(IdentLoc);
3211        Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3212      }
3213
3214      // Make our StdNamespace cache point at the first real definition of the
3215      // "std" namespace.
3216      StdNamespace = Namespc;
3217    }
3218
3219    PushOnScopeChains(Namespc, DeclRegionScope);
3220  } else {
3221    // Anonymous namespaces.
3222    assert(Namespc->isAnonymousNamespace());
3223
3224    // Link the anonymous namespace into its parent.
3225    NamespaceDecl *PrevDecl;
3226    DeclContext *Parent = CurContext->getLookupContext();
3227    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3228      PrevDecl = TU->getAnonymousNamespace();
3229      TU->setAnonymousNamespace(Namespc);
3230    } else {
3231      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3232      PrevDecl = ND->getAnonymousNamespace();
3233      ND->setAnonymousNamespace(Namespc);
3234    }
3235
3236    // Link the anonymous namespace with its previous declaration.
3237    if (PrevDecl) {
3238      assert(PrevDecl->isAnonymousNamespace());
3239      assert(!PrevDecl->getNextNamespace());
3240      Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3241      PrevDecl->setNextNamespace(Namespc);
3242    }
3243
3244    CurContext->addDecl(Namespc);
3245
3246    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
3247    //   behaves as if it were replaced by
3248    //     namespace unique { /* empty body */ }
3249    //     using namespace unique;
3250    //     namespace unique { namespace-body }
3251    //   where all occurrences of 'unique' in a translation unit are
3252    //   replaced by the same identifier and this identifier differs
3253    //   from all other identifiers in the entire program.
3254
3255    // We just create the namespace with an empty name and then add an
3256    // implicit using declaration, just like the standard suggests.
3257    //
3258    // CodeGen enforces the "universally unique" aspect by giving all
3259    // declarations semantically contained within an anonymous
3260    // namespace internal linkage.
3261
3262    if (!PrevDecl) {
3263      UsingDirectiveDecl* UD
3264        = UsingDirectiveDecl::Create(Context, CurContext,
3265                                     /* 'using' */ LBrace,
3266                                     /* 'namespace' */ SourceLocation(),
3267                                     /* qualifier */ SourceRange(),
3268                                     /* NNS */ NULL,
3269                                     /* identifier */ SourceLocation(),
3270                                     Namespc,
3271                                     /* Ancestor */ CurContext);
3272      UD->setImplicit();
3273      CurContext->addDecl(UD);
3274    }
3275  }
3276
3277  // Although we could have an invalid decl (i.e. the namespace name is a
3278  // redefinition), push it as current DeclContext and try to continue parsing.
3279  // FIXME: We should be able to push Namespc here, so that the each DeclContext
3280  // for the namespace has the declarations that showed up in that particular
3281  // namespace definition.
3282  PushDeclContext(NamespcScope, Namespc);
3283  return DeclPtrTy::make(Namespc);
3284}
3285
3286/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3287/// is a namespace alias, returns the namespace it points to.
3288static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3289  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3290    return AD->getNamespace();
3291  return dyn_cast_or_null<NamespaceDecl>(D);
3292}
3293
3294/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3295/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3296void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3297  Decl *Dcl = D.getAs<Decl>();
3298  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3299  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3300  Namespc->setRBracLoc(RBrace);
3301  PopDeclContext();
3302}
3303
3304Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3305                                          SourceLocation UsingLoc,
3306                                          SourceLocation NamespcLoc,
3307                                          CXXScopeSpec &SS,
3308                                          SourceLocation IdentLoc,
3309                                          IdentifierInfo *NamespcName,
3310                                          AttributeList *AttrList) {
3311  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3312  assert(NamespcName && "Invalid NamespcName.");
3313  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
3314  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3315
3316  UsingDirectiveDecl *UDir = 0;
3317
3318  // Lookup namespace name.
3319  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3320  LookupParsedName(R, S, &SS);
3321  if (R.isAmbiguous())
3322    return DeclPtrTy();
3323
3324  if (!R.empty()) {
3325    NamedDecl *Named = R.getFoundDecl();
3326    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3327        && "expected namespace decl");
3328    // C++ [namespace.udir]p1:
3329    //   A using-directive specifies that the names in the nominated
3330    //   namespace can be used in the scope in which the
3331    //   using-directive appears after the using-directive. During
3332    //   unqualified name lookup (3.4.1), the names appear as if they
3333    //   were declared in the nearest enclosing namespace which
3334    //   contains both the using-directive and the nominated
3335    //   namespace. [Note: in this context, "contains" means "contains
3336    //   directly or indirectly". ]
3337
3338    // Find enclosing context containing both using-directive and
3339    // nominated namespace.
3340    NamespaceDecl *NS = getNamespaceDecl(Named);
3341    DeclContext *CommonAncestor = cast<DeclContext>(NS);
3342    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3343      CommonAncestor = CommonAncestor->getParent();
3344
3345    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
3346                                      SS.getRange(),
3347                                      (NestedNameSpecifier *)SS.getScopeRep(),
3348                                      IdentLoc, Named, CommonAncestor);
3349    PushUsingDirective(S, UDir);
3350  } else {
3351    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
3352  }
3353
3354  // FIXME: We ignore attributes for now.
3355  delete AttrList;
3356  return DeclPtrTy::make(UDir);
3357}
3358
3359void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3360  // If scope has associated entity, then using directive is at namespace
3361  // or translation unit scope. We add UsingDirectiveDecls, into
3362  // it's lookup structure.
3363  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
3364    Ctx->addDecl(UDir);
3365  else
3366    // Otherwise it is block-sope. using-directives will affect lookup
3367    // only to the end of scope.
3368    S->PushUsingDirective(DeclPtrTy::make(UDir));
3369}
3370
3371
3372Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
3373                                            AccessSpecifier AS,
3374                                            bool HasUsingKeyword,
3375                                            SourceLocation UsingLoc,
3376                                            CXXScopeSpec &SS,
3377                                            UnqualifiedId &Name,
3378                                            AttributeList *AttrList,
3379                                            bool IsTypeName,
3380                                            SourceLocation TypenameLoc) {
3381  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
3382
3383  switch (Name.getKind()) {
3384  case UnqualifiedId::IK_Identifier:
3385  case UnqualifiedId::IK_OperatorFunctionId:
3386  case UnqualifiedId::IK_LiteralOperatorId:
3387  case UnqualifiedId::IK_ConversionFunctionId:
3388    break;
3389
3390  case UnqualifiedId::IK_ConstructorName:
3391  case UnqualifiedId::IK_ConstructorTemplateId:
3392    // C++0x inherited constructors.
3393    if (getLangOptions().CPlusPlus0x) break;
3394
3395    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3396      << SS.getRange();
3397    return DeclPtrTy();
3398
3399  case UnqualifiedId::IK_DestructorName:
3400    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3401      << SS.getRange();
3402    return DeclPtrTy();
3403
3404  case UnqualifiedId::IK_TemplateId:
3405    Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3406      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3407    return DeclPtrTy();
3408  }
3409
3410  DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
3411  if (!TargetName)
3412    return DeclPtrTy();
3413
3414  // Warn about using declarations.
3415  // TODO: store that the declaration was written without 'using' and
3416  // talk about access decls instead of using decls in the
3417  // diagnostics.
3418  if (!HasUsingKeyword) {
3419    UsingLoc = Name.getSourceRange().getBegin();
3420
3421    Diag(UsingLoc, diag::warn_access_decl_deprecated)
3422      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
3423  }
3424
3425  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
3426                                        Name.getSourceRange().getBegin(),
3427                                        TargetName, AttrList,
3428                                        /* IsInstantiation */ false,
3429                                        IsTypeName, TypenameLoc);
3430  if (UD)
3431    PushOnScopeChains(UD, S, /*AddToContext*/ false);
3432
3433  return DeclPtrTy::make(UD);
3434}
3435
3436/// Determines whether to create a using shadow decl for a particular
3437/// decl, given the set of decls existing prior to this using lookup.
3438bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3439                                const LookupResult &Previous) {
3440  // Diagnose finding a decl which is not from a base class of the
3441  // current class.  We do this now because there are cases where this
3442  // function will silently decide not to build a shadow decl, which
3443  // will pre-empt further diagnostics.
3444  //
3445  // We don't need to do this in C++0x because we do the check once on
3446  // the qualifier.
3447  //
3448  // FIXME: diagnose the following if we care enough:
3449  //   struct A { int foo; };
3450  //   struct B : A { using A::foo; };
3451  //   template <class T> struct C : A {};
3452  //   template <class T> struct D : C<T> { using B::foo; } // <---
3453  // This is invalid (during instantiation) in C++03 because B::foo
3454  // resolves to the using decl in B, which is not a base class of D<T>.
3455  // We can't diagnose it immediately because C<T> is an unknown
3456  // specialization.  The UsingShadowDecl in D<T> then points directly
3457  // to A::foo, which will look well-formed when we instantiate.
3458  // The right solution is to not collapse the shadow-decl chain.
3459  if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3460    DeclContext *OrigDC = Orig->getDeclContext();
3461
3462    // Handle enums and anonymous structs.
3463    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3464    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3465    while (OrigRec->isAnonymousStructOrUnion())
3466      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3467
3468    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3469      if (OrigDC == CurContext) {
3470        Diag(Using->getLocation(),
3471             diag::err_using_decl_nested_name_specifier_is_current_class)
3472          << Using->getNestedNameRange();
3473        Diag(Orig->getLocation(), diag::note_using_decl_target);
3474        return true;
3475      }
3476
3477      Diag(Using->getNestedNameRange().getBegin(),
3478           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3479        << Using->getTargetNestedNameDecl()
3480        << cast<CXXRecordDecl>(CurContext)
3481        << Using->getNestedNameRange();
3482      Diag(Orig->getLocation(), diag::note_using_decl_target);
3483      return true;
3484    }
3485  }
3486
3487  if (Previous.empty()) return false;
3488
3489  NamedDecl *Target = Orig;
3490  if (isa<UsingShadowDecl>(Target))
3491    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3492
3493  // If the target happens to be one of the previous declarations, we
3494  // don't have a conflict.
3495  //
3496  // FIXME: but we might be increasing its access, in which case we
3497  // should redeclare it.
3498  NamedDecl *NonTag = 0, *Tag = 0;
3499  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3500         I != E; ++I) {
3501    NamedDecl *D = (*I)->getUnderlyingDecl();
3502    if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3503      return false;
3504
3505    (isa<TagDecl>(D) ? Tag : NonTag) = D;
3506  }
3507
3508  if (Target->isFunctionOrFunctionTemplate()) {
3509    FunctionDecl *FD;
3510    if (isa<FunctionTemplateDecl>(Target))
3511      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3512    else
3513      FD = cast<FunctionDecl>(Target);
3514
3515    NamedDecl *OldDecl = 0;
3516    switch (CheckOverload(FD, Previous, OldDecl)) {
3517    case Ovl_Overload:
3518      return false;
3519
3520    case Ovl_NonFunction:
3521      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3522      break;
3523
3524    // We found a decl with the exact signature.
3525    case Ovl_Match:
3526      if (isa<UsingShadowDecl>(OldDecl)) {
3527        // Silently ignore the possible conflict.
3528        return false;
3529      }
3530
3531      // If we're in a record, we want to hide the target, so we
3532      // return true (without a diagnostic) to tell the caller not to
3533      // build a shadow decl.
3534      if (CurContext->isRecord())
3535        return true;
3536
3537      // If we're not in a record, this is an error.
3538      Diag(Using->getLocation(), diag::err_using_decl_conflict);
3539      break;
3540    }
3541
3542    Diag(Target->getLocation(), diag::note_using_decl_target);
3543    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3544    return true;
3545  }
3546
3547  // Target is not a function.
3548
3549  if (isa<TagDecl>(Target)) {
3550    // No conflict between a tag and a non-tag.
3551    if (!Tag) return false;
3552
3553    Diag(Using->getLocation(), diag::err_using_decl_conflict);
3554    Diag(Target->getLocation(), diag::note_using_decl_target);
3555    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3556    return true;
3557  }
3558
3559  // No conflict between a tag and a non-tag.
3560  if (!NonTag) return false;
3561
3562  Diag(Using->getLocation(), diag::err_using_decl_conflict);
3563  Diag(Target->getLocation(), diag::note_using_decl_target);
3564  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3565  return true;
3566}
3567
3568/// Builds a shadow declaration corresponding to a 'using' declaration.
3569UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
3570                                            UsingDecl *UD,
3571                                            NamedDecl *Orig) {
3572
3573  // If we resolved to another shadow declaration, just coalesce them.
3574  NamedDecl *Target = Orig;
3575  if (isa<UsingShadowDecl>(Target)) {
3576    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3577    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
3578  }
3579
3580  UsingShadowDecl *Shadow
3581    = UsingShadowDecl::Create(Context, CurContext,
3582                              UD->getLocation(), UD, Target);
3583  UD->addShadowDecl(Shadow);
3584
3585  if (S)
3586    PushOnScopeChains(Shadow, S);
3587  else
3588    CurContext->addDecl(Shadow);
3589  Shadow->setAccess(UD->getAccess());
3590
3591  // Register it as a conversion if appropriate.
3592  if (Shadow->getDeclName().getNameKind()
3593        == DeclarationName::CXXConversionFunctionName)
3594    cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3595
3596  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3597    Shadow->setInvalidDecl();
3598
3599  return Shadow;
3600}
3601
3602/// Hides a using shadow declaration.  This is required by the current
3603/// using-decl implementation when a resolvable using declaration in a
3604/// class is followed by a declaration which would hide or override
3605/// one or more of the using decl's targets; for example:
3606///
3607///   struct Base { void foo(int); };
3608///   struct Derived : Base {
3609///     using Base::foo;
3610///     void foo(int);
3611///   };
3612///
3613/// The governing language is C++03 [namespace.udecl]p12:
3614///
3615///   When a using-declaration brings names from a base class into a
3616///   derived class scope, member functions in the derived class
3617///   override and/or hide member functions with the same name and
3618///   parameter types in a base class (rather than conflicting).
3619///
3620/// There are two ways to implement this:
3621///   (1) optimistically create shadow decls when they're not hidden
3622///       by existing declarations, or
3623///   (2) don't create any shadow decls (or at least don't make them
3624///       visible) until we've fully parsed/instantiated the class.
3625/// The problem with (1) is that we might have to retroactively remove
3626/// a shadow decl, which requires several O(n) operations because the
3627/// decl structures are (very reasonably) not designed for removal.
3628/// (2) avoids this but is very fiddly and phase-dependent.
3629void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
3630  if (Shadow->getDeclName().getNameKind() ==
3631        DeclarationName::CXXConversionFunctionName)
3632    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3633
3634  // Remove it from the DeclContext...
3635  Shadow->getDeclContext()->removeDecl(Shadow);
3636
3637  // ...and the scope, if applicable...
3638  if (S) {
3639    S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3640    IdResolver.RemoveDecl(Shadow);
3641  }
3642
3643  // ...and the using decl.
3644  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3645
3646  // TODO: complain somehow if Shadow was used.  It shouldn't
3647  // be possible for this to happen, because...?
3648}
3649
3650/// Builds a using declaration.
3651///
3652/// \param IsInstantiation - Whether this call arises from an
3653///   instantiation of an unresolved using declaration.  We treat
3654///   the lookup differently for these declarations.
3655NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3656                                       SourceLocation UsingLoc,
3657                                       CXXScopeSpec &SS,
3658                                       SourceLocation IdentLoc,
3659                                       DeclarationName Name,
3660                                       AttributeList *AttrList,
3661                                       bool IsInstantiation,
3662                                       bool IsTypeName,
3663                                       SourceLocation TypenameLoc) {
3664  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3665  assert(IdentLoc.isValid() && "Invalid TargetName location.");
3666
3667  // FIXME: We ignore attributes for now.
3668  delete AttrList;
3669
3670  if (SS.isEmpty()) {
3671    Diag(IdentLoc, diag::err_using_requires_qualname);
3672    return 0;
3673  }
3674
3675  // Do the redeclaration lookup in the current scope.
3676  LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3677                        ForRedeclaration);
3678  Previous.setHideTags(false);
3679  if (S) {
3680    LookupName(Previous, S);
3681
3682    // It is really dumb that we have to do this.
3683    LookupResult::Filter F = Previous.makeFilter();
3684    while (F.hasNext()) {
3685      NamedDecl *D = F.next();
3686      if (!isDeclInScope(D, CurContext, S))
3687        F.erase();
3688    }
3689    F.done();
3690  } else {
3691    assert(IsInstantiation && "no scope in non-instantiation");
3692    assert(CurContext->isRecord() && "scope not record in instantiation");
3693    LookupQualifiedName(Previous, CurContext);
3694  }
3695
3696  NestedNameSpecifier *NNS =
3697    static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3698
3699  // Check for invalid redeclarations.
3700  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3701    return 0;
3702
3703  // Check for bad qualifiers.
3704  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3705    return 0;
3706
3707  DeclContext *LookupContext = computeDeclContext(SS);
3708  NamedDecl *D;
3709  if (!LookupContext) {
3710    if (IsTypeName) {
3711      // FIXME: not all declaration name kinds are legal here
3712      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3713                                              UsingLoc, TypenameLoc,
3714                                              SS.getRange(), NNS,
3715                                              IdentLoc, Name);
3716    } else {
3717      D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3718                                           UsingLoc, SS.getRange(), NNS,
3719                                           IdentLoc, Name);
3720    }
3721  } else {
3722    D = UsingDecl::Create(Context, CurContext, IdentLoc,
3723                          SS.getRange(), UsingLoc, NNS, Name,
3724                          IsTypeName);
3725  }
3726  D->setAccess(AS);
3727  CurContext->addDecl(D);
3728
3729  if (!LookupContext) return D;
3730  UsingDecl *UD = cast<UsingDecl>(D);
3731
3732  if (RequireCompleteDeclContext(SS)) {
3733    UD->setInvalidDecl();
3734    return UD;
3735  }
3736
3737  // Look up the target name.
3738
3739  LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
3740
3741  // Unlike most lookups, we don't always want to hide tag
3742  // declarations: tag names are visible through the using declaration
3743  // even if hidden by ordinary names, *except* in a dependent context
3744  // where it's important for the sanity of two-phase lookup.
3745  if (!IsInstantiation)
3746    R.setHideTags(false);
3747
3748  LookupQualifiedName(R, LookupContext);
3749
3750  if (R.empty()) {
3751    Diag(IdentLoc, diag::err_no_member)
3752      << Name << LookupContext << SS.getRange();
3753    UD->setInvalidDecl();
3754    return UD;
3755  }
3756
3757  if (R.isAmbiguous()) {
3758    UD->setInvalidDecl();
3759    return UD;
3760  }
3761
3762  if (IsTypeName) {
3763    // If we asked for a typename and got a non-type decl, error out.
3764    if (!R.getAsSingle<TypeDecl>()) {
3765      Diag(IdentLoc, diag::err_using_typename_non_type);
3766      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3767        Diag((*I)->getUnderlyingDecl()->getLocation(),
3768             diag::note_using_decl_target);
3769      UD->setInvalidDecl();
3770      return UD;
3771    }
3772  } else {
3773    // If we asked for a non-typename and we got a type, error out,
3774    // but only if this is an instantiation of an unresolved using
3775    // decl.  Otherwise just silently find the type name.
3776    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
3777      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3778      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
3779      UD->setInvalidDecl();
3780      return UD;
3781    }
3782  }
3783
3784  // C++0x N2914 [namespace.udecl]p6:
3785  // A using-declaration shall not name a namespace.
3786  if (R.getAsSingle<NamespaceDecl>()) {
3787    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3788      << SS.getRange();
3789    UD->setInvalidDecl();
3790    return UD;
3791  }
3792
3793  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3794    if (!CheckUsingShadowDecl(UD, *I, Previous))
3795      BuildUsingShadowDecl(S, UD, *I);
3796  }
3797
3798  return UD;
3799}
3800
3801/// Checks that the given using declaration is not an invalid
3802/// redeclaration.  Note that this is checking only for the using decl
3803/// itself, not for any ill-formedness among the UsingShadowDecls.
3804bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3805                                       bool isTypeName,
3806                                       const CXXScopeSpec &SS,
3807                                       SourceLocation NameLoc,
3808                                       const LookupResult &Prev) {
3809  // C++03 [namespace.udecl]p8:
3810  // C++0x [namespace.udecl]p10:
3811  //   A using-declaration is a declaration and can therefore be used
3812  //   repeatedly where (and only where) multiple declarations are
3813  //   allowed.
3814  // That's only in file contexts.
3815  if (CurContext->getLookupContext()->isFileContext())
3816    return false;
3817
3818  NestedNameSpecifier *Qual
3819    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3820
3821  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3822    NamedDecl *D = *I;
3823
3824    bool DTypename;
3825    NestedNameSpecifier *DQual;
3826    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3827      DTypename = UD->isTypeName();
3828      DQual = UD->getTargetNestedNameDecl();
3829    } else if (UnresolvedUsingValueDecl *UD
3830                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3831      DTypename = false;
3832      DQual = UD->getTargetNestedNameSpecifier();
3833    } else if (UnresolvedUsingTypenameDecl *UD
3834                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3835      DTypename = true;
3836      DQual = UD->getTargetNestedNameSpecifier();
3837    } else continue;
3838
3839    // using decls differ if one says 'typename' and the other doesn't.
3840    // FIXME: non-dependent using decls?
3841    if (isTypeName != DTypename) continue;
3842
3843    // using decls differ if they name different scopes (but note that
3844    // template instantiation can cause this check to trigger when it
3845    // didn't before instantiation).
3846    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3847        Context.getCanonicalNestedNameSpecifier(DQual))
3848      continue;
3849
3850    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
3851    Diag(D->getLocation(), diag::note_using_decl) << 1;
3852    return true;
3853  }
3854
3855  return false;
3856}
3857
3858
3859/// Checks that the given nested-name qualifier used in a using decl
3860/// in the current context is appropriately related to the current
3861/// scope.  If an error is found, diagnoses it and returns true.
3862bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3863                                   const CXXScopeSpec &SS,
3864                                   SourceLocation NameLoc) {
3865  DeclContext *NamedContext = computeDeclContext(SS);
3866
3867  if (!CurContext->isRecord()) {
3868    // C++03 [namespace.udecl]p3:
3869    // C++0x [namespace.udecl]p8:
3870    //   A using-declaration for a class member shall be a member-declaration.
3871
3872    // If we weren't able to compute a valid scope, it must be a
3873    // dependent class scope.
3874    if (!NamedContext || NamedContext->isRecord()) {
3875      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3876        << SS.getRange();
3877      return true;
3878    }
3879
3880    // Otherwise, everything is known to be fine.
3881    return false;
3882  }
3883
3884  // The current scope is a record.
3885
3886  // If the named context is dependent, we can't decide much.
3887  if (!NamedContext) {
3888    // FIXME: in C++0x, we can diagnose if we can prove that the
3889    // nested-name-specifier does not refer to a base class, which is
3890    // still possible in some cases.
3891
3892    // Otherwise we have to conservatively report that things might be
3893    // okay.
3894    return false;
3895  }
3896
3897  if (!NamedContext->isRecord()) {
3898    // Ideally this would point at the last name in the specifier,
3899    // but we don't have that level of source info.
3900    Diag(SS.getRange().getBegin(),
3901         diag::err_using_decl_nested_name_specifier_is_not_class)
3902      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3903    return true;
3904  }
3905
3906  if (getLangOptions().CPlusPlus0x) {
3907    // C++0x [namespace.udecl]p3:
3908    //   In a using-declaration used as a member-declaration, the
3909    //   nested-name-specifier shall name a base class of the class
3910    //   being defined.
3911
3912    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3913                                 cast<CXXRecordDecl>(NamedContext))) {
3914      if (CurContext == NamedContext) {
3915        Diag(NameLoc,
3916             diag::err_using_decl_nested_name_specifier_is_current_class)
3917          << SS.getRange();
3918        return true;
3919      }
3920
3921      Diag(SS.getRange().getBegin(),
3922           diag::err_using_decl_nested_name_specifier_is_not_base_class)
3923        << (NestedNameSpecifier*) SS.getScopeRep()
3924        << cast<CXXRecordDecl>(CurContext)
3925        << SS.getRange();
3926      return true;
3927    }
3928
3929    return false;
3930  }
3931
3932  // C++03 [namespace.udecl]p4:
3933  //   A using-declaration used as a member-declaration shall refer
3934  //   to a member of a base class of the class being defined [etc.].
3935
3936  // Salient point: SS doesn't have to name a base class as long as
3937  // lookup only finds members from base classes.  Therefore we can
3938  // diagnose here only if we can prove that that can't happen,
3939  // i.e. if the class hierarchies provably don't intersect.
3940
3941  // TODO: it would be nice if "definitely valid" results were cached
3942  // in the UsingDecl and UsingShadowDecl so that these checks didn't
3943  // need to be repeated.
3944
3945  struct UserData {
3946    llvm::DenseSet<const CXXRecordDecl*> Bases;
3947
3948    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3949      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3950      Data->Bases.insert(Base);
3951      return true;
3952    }
3953
3954    bool hasDependentBases(const CXXRecordDecl *Class) {
3955      return !Class->forallBases(collect, this);
3956    }
3957
3958    /// Returns true if the base is dependent or is one of the
3959    /// accumulated base classes.
3960    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3961      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3962      return !Data->Bases.count(Base);
3963    }
3964
3965    bool mightShareBases(const CXXRecordDecl *Class) {
3966      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3967    }
3968  };
3969
3970  UserData Data;
3971
3972  // Returns false if we find a dependent base.
3973  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3974    return false;
3975
3976  // Returns false if the class has a dependent base or if it or one
3977  // of its bases is present in the base set of the current context.
3978  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3979    return false;
3980
3981  Diag(SS.getRange().getBegin(),
3982       diag::err_using_decl_nested_name_specifier_is_not_base_class)
3983    << (NestedNameSpecifier*) SS.getScopeRep()
3984    << cast<CXXRecordDecl>(CurContext)
3985    << SS.getRange();
3986
3987  return true;
3988}
3989
3990Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
3991                                             SourceLocation NamespaceLoc,
3992                                             SourceLocation AliasLoc,
3993                                             IdentifierInfo *Alias,
3994                                             CXXScopeSpec &SS,
3995                                             SourceLocation IdentLoc,
3996                                             IdentifierInfo *Ident) {
3997
3998  // Lookup the namespace name.
3999  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4000  LookupParsedName(R, S, &SS);
4001
4002  // Check if we have a previous declaration with the same name.
4003  if (NamedDecl *PrevDecl
4004        = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4005                           ForRedeclaration)) {
4006    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
4007      // We already have an alias with the same name that points to the same
4008      // namespace, so don't create a new one.
4009      // FIXME: At some point, we'll want to create the (redundant)
4010      // declaration to maintain better source information.
4011      if (!R.isAmbiguous() && !R.empty() &&
4012          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
4013        return DeclPtrTy();
4014    }
4015
4016    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4017      diag::err_redefinition_different_kind;
4018    Diag(AliasLoc, DiagID) << Alias;
4019    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4020    return DeclPtrTy();
4021  }
4022
4023  if (R.isAmbiguous())
4024    return DeclPtrTy();
4025
4026  if (R.empty()) {
4027    Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4028    return DeclPtrTy();
4029  }
4030
4031  NamespaceAliasDecl *AliasDecl =
4032    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4033                               Alias, SS.getRange(),
4034                               (NestedNameSpecifier *)SS.getScopeRep(),
4035                               IdentLoc, R.getFoundDecl());
4036
4037  PushOnScopeChains(AliasDecl, S);
4038  return DeclPtrTy::make(AliasDecl);
4039}
4040
4041void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4042                                            CXXConstructorDecl *Constructor) {
4043  assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4044          !Constructor->isUsed()) &&
4045    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
4046
4047  CXXRecordDecl *ClassDecl = Constructor->getParent();
4048  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
4049
4050  DeclContext *PreviousContext = CurContext;
4051  CurContext = Constructor;
4052  if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
4053    Diag(CurrentLocation, diag::note_member_synthesized_at)
4054      << CXXConstructor << Context.getTagDeclType(ClassDecl);
4055    Constructor->setInvalidDecl();
4056  } else {
4057    Constructor->setUsed();
4058  }
4059  CurContext = PreviousContext;
4060}
4061
4062void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
4063                                    CXXDestructorDecl *Destructor) {
4064  assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4065         "DefineImplicitDestructor - call it for implicit default dtor");
4066  CXXRecordDecl *ClassDecl = Destructor->getParent();
4067  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
4068
4069  DeclContext *PreviousContext = CurContext;
4070  CurContext = Destructor;
4071
4072  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4073                                         Destructor->getParent());
4074
4075  // FIXME: If CheckDestructor fails, we should emit a note about where the
4076  // implicit destructor was needed.
4077  if (CheckDestructor(Destructor)) {
4078    Diag(CurrentLocation, diag::note_member_synthesized_at)
4079      << CXXDestructor << Context.getTagDeclType(ClassDecl);
4080
4081    Destructor->setInvalidDecl();
4082    CurContext = PreviousContext;
4083
4084    return;
4085  }
4086  CurContext = PreviousContext;
4087
4088  Destructor->setUsed();
4089}
4090
4091void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
4092                                          CXXMethodDecl *MethodDecl) {
4093  assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
4094          MethodDecl->getOverloadedOperator() == OO_Equal &&
4095          !MethodDecl->isUsed()) &&
4096         "DefineImplicitOverloadedAssign - call it for implicit assignment op");
4097
4098  CXXRecordDecl *ClassDecl
4099    = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
4100
4101  DeclContext *PreviousContext = CurContext;
4102  CurContext = MethodDecl;
4103
4104  // C++[class.copy] p12
4105  // Before the implicitly-declared copy assignment operator for a class is
4106  // implicitly defined, all implicitly-declared copy assignment operators
4107  // for its direct base classes and its nonstatic data members shall have
4108  // been implicitly defined.
4109  bool err = false;
4110  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4111       E = ClassDecl->bases_end(); Base != E; ++Base) {
4112    CXXRecordDecl *BaseClassDecl
4113      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
4114    if (CXXMethodDecl *BaseAssignOpMethod =
4115          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
4116                                  BaseClassDecl)) {
4117      CheckDirectMemberAccess(Base->getSourceRange().getBegin(),
4118                              BaseAssignOpMethod,
4119                              PDiag(diag::err_access_assign_base)
4120                                << Base->getType());
4121
4122      MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
4123    }
4124  }
4125  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4126       E = ClassDecl->field_end(); Field != E; ++Field) {
4127    QualType FieldType = Context.getCanonicalType((*Field)->getType());
4128    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4129      FieldType = Array->getElementType();
4130    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4131      CXXRecordDecl *FieldClassDecl
4132        = cast<CXXRecordDecl>(FieldClassType->getDecl());
4133      if (CXXMethodDecl *FieldAssignOpMethod =
4134          getAssignOperatorMethod(CurrentLocation, MethodDecl->getParamDecl(0),
4135                                  FieldClassDecl)) {
4136        CheckDirectMemberAccess(Field->getLocation(),
4137                                FieldAssignOpMethod,
4138                                PDiag(diag::err_access_assign_field)
4139                                  << Field->getDeclName() << Field->getType());
4140
4141        MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
4142      }
4143    } else if (FieldType->isReferenceType()) {
4144      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4145      << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4146      Diag(Field->getLocation(), diag::note_declared_at);
4147      Diag(CurrentLocation, diag::note_first_required_here);
4148      err = true;
4149    } else if (FieldType.isConstQualified()) {
4150      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4151      << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4152      Diag(Field->getLocation(), diag::note_declared_at);
4153      Diag(CurrentLocation, diag::note_first_required_here);
4154      err = true;
4155    }
4156  }
4157  if (!err)
4158    MethodDecl->setUsed();
4159
4160  CurContext = PreviousContext;
4161}
4162
4163CXXMethodDecl *
4164Sema::getAssignOperatorMethod(SourceLocation CurrentLocation,
4165                              ParmVarDecl *ParmDecl,
4166                              CXXRecordDecl *ClassDecl) {
4167  QualType LHSType = Context.getTypeDeclType(ClassDecl);
4168  QualType RHSType(LHSType);
4169  // If class's assignment operator argument is const/volatile qualified,
4170  // look for operator = (const/volatile B&). Otherwise, look for
4171  // operator = (B&).
4172  RHSType = Context.getCVRQualifiedType(RHSType,
4173                                     ParmDecl->getType().getCVRQualifiers());
4174  ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
4175                                                           LHSType,
4176                                                           SourceLocation()));
4177  ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
4178                                                           RHSType,
4179                                                           CurrentLocation));
4180  Expr *Args[2] = { &*LHS, &*RHS };
4181  OverloadCandidateSet CandidateSet(CurrentLocation);
4182  AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
4183                              CandidateSet);
4184  OverloadCandidateSet::iterator Best;
4185  if (BestViableFunction(CandidateSet, CurrentLocation, Best) == OR_Success)
4186    return cast<CXXMethodDecl>(Best->Function);
4187  assert(false &&
4188         "getAssignOperatorMethod - copy assignment operator method not found");
4189  return 0;
4190}
4191
4192void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4193                                   CXXConstructorDecl *CopyConstructor,
4194                                   unsigned TypeQuals) {
4195  assert((CopyConstructor->isImplicit() &&
4196          CopyConstructor->isCopyConstructor(TypeQuals) &&
4197          !CopyConstructor->isUsed()) &&
4198         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
4199
4200  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
4201  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
4202
4203  DeclContext *PreviousContext = CurContext;
4204  CurContext = CopyConstructor;
4205
4206  if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4207    Diag(CurrentLocation, diag::note_member_synthesized_at)
4208    << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
4209    CopyConstructor->setInvalidDecl();
4210  } else {
4211    CopyConstructor->setUsed();
4212  }
4213
4214  // FIXME: Once we teach SetBaseOrMemberInitializers to copy fields, we can
4215  // get rid of this code.
4216  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4217                                  FieldEnd = ClassDecl->field_end();
4218       Field != FieldEnd; ++Field) {
4219    QualType FieldType = Context.getCanonicalType((*Field)->getType());
4220    if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4221      FieldType = Array->getElementType();
4222    if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4223      CXXRecordDecl *FieldClassDecl
4224        = cast<CXXRecordDecl>(FieldClassType->getDecl());
4225      if (CXXConstructorDecl *FieldCopyCtor =
4226          FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4227        CheckDirectMemberAccess(Field->getLocation(),
4228                                FieldCopyCtor,
4229                                PDiag(diag::err_access_copy_field)
4230                                  << Field->getDeclName() << Field->getType());
4231
4232        MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
4233      }
4234    }
4235  }
4236  CopyConstructor->setUsed();
4237
4238  CurContext = PreviousContext;
4239}
4240
4241Sema::OwningExprResult
4242Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4243                            CXXConstructorDecl *Constructor,
4244                            MultiExprArg ExprArgs,
4245                            bool RequiresZeroInit,
4246                            bool BaseInitialization) {
4247  bool Elidable = false;
4248
4249  // C++0x [class.copy]p34:
4250  //   When certain criteria are met, an implementation is allowed to
4251  //   omit the copy/move construction of a class object, even if the
4252  //   copy/move constructor and/or destructor for the object have
4253  //   side effects. [...]
4254  //     - when a temporary class object that has not been bound to a
4255  //       reference (12.2) would be copied/moved to a class object
4256  //       with the same cv-unqualified type, the copy/move operation
4257  //       can be omitted by constructing the temporary object
4258  //       directly into the target of the omitted copy/move
4259  if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4260    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4261    Elidable = SubExpr->isTemporaryObject() &&
4262      Context.hasSameUnqualifiedType(SubExpr->getType(),
4263                           Context.getTypeDeclType(Constructor->getParent()));
4264  }
4265
4266  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
4267                               Elidable, move(ExprArgs), RequiresZeroInit,
4268                               BaseInitialization);
4269}
4270
4271/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4272/// including handling of its default argument expressions.
4273Sema::OwningExprResult
4274Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4275                            CXXConstructorDecl *Constructor, bool Elidable,
4276                            MultiExprArg ExprArgs,
4277                            bool RequiresZeroInit,
4278                            bool BaseInitialization) {
4279  unsigned NumExprs = ExprArgs.size();
4280  Expr **Exprs = (Expr **)ExprArgs.release();
4281
4282  MarkDeclarationReferenced(ConstructLoc, Constructor);
4283  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
4284                                        Constructor, Elidable, Exprs, NumExprs,
4285                                        RequiresZeroInit, BaseInitialization));
4286}
4287
4288bool Sema::InitializeVarWithConstructor(VarDecl *VD,
4289                                        CXXConstructorDecl *Constructor,
4290                                        MultiExprArg Exprs) {
4291  OwningExprResult TempResult =
4292    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
4293                          move(Exprs));
4294  if (TempResult.isInvalid())
4295    return true;
4296
4297  Expr *Temp = TempResult.takeAs<Expr>();
4298  MarkDeclarationReferenced(VD->getLocation(), Constructor);
4299  Temp = MaybeCreateCXXExprWithTemporaries(Temp);
4300  VD->setInit(Temp);
4301
4302  return false;
4303}
4304
4305void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4306  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
4307  if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4308      !ClassDecl->hasTrivialDestructor()) {
4309    CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4310    MarkDeclarationReferenced(VD->getLocation(), Destructor);
4311    CheckDestructorAccess(VD->getLocation(), Destructor,
4312                          PDiag(diag::err_access_dtor_var)
4313                            << VD->getDeclName()
4314                            << VD->getType());
4315  }
4316}
4317
4318/// AddCXXDirectInitializerToDecl - This action is called immediately after
4319/// ActOnDeclarator, when a C++ direct initializer is present.
4320/// e.g: "int x(1);"
4321void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4322                                         SourceLocation LParenLoc,
4323                                         MultiExprArg Exprs,
4324                                         SourceLocation *CommaLocs,
4325                                         SourceLocation RParenLoc) {
4326  assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
4327  Decl *RealDecl = Dcl.getAs<Decl>();
4328
4329  // If there is no declaration, there was an error parsing it.  Just ignore
4330  // the initializer.
4331  if (RealDecl == 0)
4332    return;
4333
4334  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4335  if (!VDecl) {
4336    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4337    RealDecl->setInvalidDecl();
4338    return;
4339  }
4340
4341  // We will represent direct-initialization similarly to copy-initialization:
4342  //    int x(1);  -as-> int x = 1;
4343  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4344  //
4345  // Clients that want to distinguish between the two forms, can check for
4346  // direct initializer using VarDecl::hasCXXDirectInitializer().
4347  // A major benefit is that clients that don't particularly care about which
4348  // exactly form was it (like the CodeGen) can handle both cases without
4349  // special case code.
4350
4351  // C++ 8.5p11:
4352  // The form of initialization (using parentheses or '=') is generally
4353  // insignificant, but does matter when the entity being initialized has a
4354  // class type.
4355  QualType DeclInitType = VDecl->getType();
4356  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
4357    DeclInitType = Context.getBaseElementType(Array);
4358
4359  if (!VDecl->getType()->isDependentType() &&
4360      RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
4361                          diag::err_typecheck_decl_incomplete_type)) {
4362    VDecl->setInvalidDecl();
4363    return;
4364  }
4365
4366  // The variable can not have an abstract class type.
4367  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4368                             diag::err_abstract_type_in_decl,
4369                             AbstractVariableType))
4370    VDecl->setInvalidDecl();
4371
4372  const VarDecl *Def;
4373  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
4374    Diag(VDecl->getLocation(), diag::err_redefinition)
4375    << VDecl->getDeclName();
4376    Diag(Def->getLocation(), diag::note_previous_definition);
4377    VDecl->setInvalidDecl();
4378    return;
4379  }
4380
4381  // If either the declaration has a dependent type or if any of the
4382  // expressions is type-dependent, we represent the initialization
4383  // via a ParenListExpr for later use during template instantiation.
4384  if (VDecl->getType()->isDependentType() ||
4385      Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4386    // Let clients know that initialization was done with a direct initializer.
4387    VDecl->setCXXDirectInitializer(true);
4388
4389    // Store the initialization expressions as a ParenListExpr.
4390    unsigned NumExprs = Exprs.size();
4391    VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4392                                               (Expr **)Exprs.release(),
4393                                               NumExprs, RParenLoc));
4394    return;
4395  }
4396
4397  // Capture the variable that is being initialized and the style of
4398  // initialization.
4399  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4400
4401  // FIXME: Poor source location information.
4402  InitializationKind Kind
4403    = InitializationKind::CreateDirect(VDecl->getLocation(),
4404                                       LParenLoc, RParenLoc);
4405
4406  InitializationSequence InitSeq(*this, Entity, Kind,
4407                                 (Expr**)Exprs.get(), Exprs.size());
4408  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4409  if (Result.isInvalid()) {
4410    VDecl->setInvalidDecl();
4411    return;
4412  }
4413
4414  Result = MaybeCreateCXXExprWithTemporaries(move(Result));
4415  VDecl->setInit(Result.takeAs<Expr>());
4416  VDecl->setCXXDirectInitializer(true);
4417
4418  if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4419    FinalizeVarWithDestructor(VDecl, Record);
4420}
4421
4422/// \brief Given a constructor and the set of arguments provided for the
4423/// constructor, convert the arguments and add any required default arguments
4424/// to form a proper call to this constructor.
4425///
4426/// \returns true if an error occurred, false otherwise.
4427bool
4428Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4429                              MultiExprArg ArgsPtr,
4430                              SourceLocation Loc,
4431                     ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4432  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4433  unsigned NumArgs = ArgsPtr.size();
4434  Expr **Args = (Expr **)ArgsPtr.get();
4435
4436  const FunctionProtoType *Proto
4437    = Constructor->getType()->getAs<FunctionProtoType>();
4438  assert(Proto && "Constructor without a prototype?");
4439  unsigned NumArgsInProto = Proto->getNumArgs();
4440
4441  // If too few arguments are available, we'll fill in the rest with defaults.
4442  if (NumArgs < NumArgsInProto)
4443    ConvertedArgs.reserve(NumArgsInProto);
4444  else
4445    ConvertedArgs.reserve(NumArgs);
4446
4447  VariadicCallType CallType =
4448    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4449  llvm::SmallVector<Expr *, 8> AllArgs;
4450  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4451                                        Proto, 0, Args, NumArgs, AllArgs,
4452                                        CallType);
4453  for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4454    ConvertedArgs.push_back(AllArgs[i]);
4455  return Invalid;
4456}
4457
4458static inline bool
4459CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4460                                       const FunctionDecl *FnDecl) {
4461  const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4462  if (isa<NamespaceDecl>(DC)) {
4463    return SemaRef.Diag(FnDecl->getLocation(),
4464                        diag::err_operator_new_delete_declared_in_namespace)
4465      << FnDecl->getDeclName();
4466  }
4467
4468  if (isa<TranslationUnitDecl>(DC) &&
4469      FnDecl->getStorageClass() == FunctionDecl::Static) {
4470    return SemaRef.Diag(FnDecl->getLocation(),
4471                        diag::err_operator_new_delete_declared_static)
4472      << FnDecl->getDeclName();
4473  }
4474
4475  return false;
4476}
4477
4478static inline bool
4479CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4480                            CanQualType ExpectedResultType,
4481                            CanQualType ExpectedFirstParamType,
4482                            unsigned DependentParamTypeDiag,
4483                            unsigned InvalidParamTypeDiag) {
4484  QualType ResultType =
4485    FnDecl->getType()->getAs<FunctionType>()->getResultType();
4486
4487  // Check that the result type is not dependent.
4488  if (ResultType->isDependentType())
4489    return SemaRef.Diag(FnDecl->getLocation(),
4490                        diag::err_operator_new_delete_dependent_result_type)
4491    << FnDecl->getDeclName() << ExpectedResultType;
4492
4493  // Check that the result type is what we expect.
4494  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4495    return SemaRef.Diag(FnDecl->getLocation(),
4496                        diag::err_operator_new_delete_invalid_result_type)
4497    << FnDecl->getDeclName() << ExpectedResultType;
4498
4499  // A function template must have at least 2 parameters.
4500  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4501    return SemaRef.Diag(FnDecl->getLocation(),
4502                      diag::err_operator_new_delete_template_too_few_parameters)
4503        << FnDecl->getDeclName();
4504
4505  // The function decl must have at least 1 parameter.
4506  if (FnDecl->getNumParams() == 0)
4507    return SemaRef.Diag(FnDecl->getLocation(),
4508                        diag::err_operator_new_delete_too_few_parameters)
4509      << FnDecl->getDeclName();
4510
4511  // Check the the first parameter type is not dependent.
4512  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4513  if (FirstParamType->isDependentType())
4514    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4515      << FnDecl->getDeclName() << ExpectedFirstParamType;
4516
4517  // Check that the first parameter type is what we expect.
4518  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
4519      ExpectedFirstParamType)
4520    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4521    << FnDecl->getDeclName() << ExpectedFirstParamType;
4522
4523  return false;
4524}
4525
4526static bool
4527CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4528  // C++ [basic.stc.dynamic.allocation]p1:
4529  //   A program is ill-formed if an allocation function is declared in a
4530  //   namespace scope other than global scope or declared static in global
4531  //   scope.
4532  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4533    return true;
4534
4535  CanQualType SizeTy =
4536    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4537
4538  // C++ [basic.stc.dynamic.allocation]p1:
4539  //  The return type shall be void*. The first parameter shall have type
4540  //  std::size_t.
4541  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4542                                  SizeTy,
4543                                  diag::err_operator_new_dependent_param_type,
4544                                  diag::err_operator_new_param_type))
4545    return true;
4546
4547  // C++ [basic.stc.dynamic.allocation]p1:
4548  //  The first parameter shall not have an associated default argument.
4549  if (FnDecl->getParamDecl(0)->hasDefaultArg())
4550    return SemaRef.Diag(FnDecl->getLocation(),
4551                        diag::err_operator_new_default_arg)
4552      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4553
4554  return false;
4555}
4556
4557static bool
4558CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4559  // C++ [basic.stc.dynamic.deallocation]p1:
4560  //   A program is ill-formed if deallocation functions are declared in a
4561  //   namespace scope other than global scope or declared static in global
4562  //   scope.
4563  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4564    return true;
4565
4566  // C++ [basic.stc.dynamic.deallocation]p2:
4567  //   Each deallocation function shall return void and its first parameter
4568  //   shall be void*.
4569  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4570                                  SemaRef.Context.VoidPtrTy,
4571                                 diag::err_operator_delete_dependent_param_type,
4572                                 diag::err_operator_delete_param_type))
4573    return true;
4574
4575  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4576  if (FirstParamType->isDependentType())
4577    return SemaRef.Diag(FnDecl->getLocation(),
4578                        diag::err_operator_delete_dependent_param_type)
4579    << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4580
4581  if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4582      SemaRef.Context.VoidPtrTy)
4583    return SemaRef.Diag(FnDecl->getLocation(),
4584                        diag::err_operator_delete_param_type)
4585      << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4586
4587  return false;
4588}
4589
4590/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4591/// of this overloaded operator is well-formed. If so, returns false;
4592/// otherwise, emits appropriate diagnostics and returns true.
4593bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
4594  assert(FnDecl && FnDecl->isOverloadedOperator() &&
4595         "Expected an overloaded operator declaration");
4596
4597  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4598
4599  // C++ [over.oper]p5:
4600  //   The allocation and deallocation functions, operator new,
4601  //   operator new[], operator delete and operator delete[], are
4602  //   described completely in 3.7.3. The attributes and restrictions
4603  //   found in the rest of this subclause do not apply to them unless
4604  //   explicitly stated in 3.7.3.
4605  if (Op == OO_Delete || Op == OO_Array_Delete)
4606    return CheckOperatorDeleteDeclaration(*this, FnDecl);
4607
4608  if (Op == OO_New || Op == OO_Array_New)
4609    return CheckOperatorNewDeclaration(*this, FnDecl);
4610
4611  // C++ [over.oper]p6:
4612  //   An operator function shall either be a non-static member
4613  //   function or be a non-member function and have at least one
4614  //   parameter whose type is a class, a reference to a class, an
4615  //   enumeration, or a reference to an enumeration.
4616  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4617    if (MethodDecl->isStatic())
4618      return Diag(FnDecl->getLocation(),
4619                  diag::err_operator_overload_static) << FnDecl->getDeclName();
4620  } else {
4621    bool ClassOrEnumParam = false;
4622    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4623                                   ParamEnd = FnDecl->param_end();
4624         Param != ParamEnd; ++Param) {
4625      QualType ParamType = (*Param)->getType().getNonReferenceType();
4626      if (ParamType->isDependentType() || ParamType->isRecordType() ||
4627          ParamType->isEnumeralType()) {
4628        ClassOrEnumParam = true;
4629        break;
4630      }
4631    }
4632
4633    if (!ClassOrEnumParam)
4634      return Diag(FnDecl->getLocation(),
4635                  diag::err_operator_overload_needs_class_or_enum)
4636        << FnDecl->getDeclName();
4637  }
4638
4639  // C++ [over.oper]p8:
4640  //   An operator function cannot have default arguments (8.3.6),
4641  //   except where explicitly stated below.
4642  //
4643  // Only the function-call operator allows default arguments
4644  // (C++ [over.call]p1).
4645  if (Op != OO_Call) {
4646    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4647         Param != FnDecl->param_end(); ++Param) {
4648      if ((*Param)->hasDefaultArg())
4649        return Diag((*Param)->getLocation(),
4650                    diag::err_operator_overload_default_arg)
4651          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
4652    }
4653  }
4654
4655  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4656    { false, false, false }
4657#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4658    , { Unary, Binary, MemberOnly }
4659#include "clang/Basic/OperatorKinds.def"
4660  };
4661
4662  bool CanBeUnaryOperator = OperatorUses[Op][0];
4663  bool CanBeBinaryOperator = OperatorUses[Op][1];
4664  bool MustBeMemberOperator = OperatorUses[Op][2];
4665
4666  // C++ [over.oper]p8:
4667  //   [...] Operator functions cannot have more or fewer parameters
4668  //   than the number required for the corresponding operator, as
4669  //   described in the rest of this subclause.
4670  unsigned NumParams = FnDecl->getNumParams()
4671                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
4672  if (Op != OO_Call &&
4673      ((NumParams == 1 && !CanBeUnaryOperator) ||
4674       (NumParams == 2 && !CanBeBinaryOperator) ||
4675       (NumParams < 1) || (NumParams > 2))) {
4676    // We have the wrong number of parameters.
4677    unsigned ErrorKind;
4678    if (CanBeUnaryOperator && CanBeBinaryOperator) {
4679      ErrorKind = 2;  // 2 -> unary or binary.
4680    } else if (CanBeUnaryOperator) {
4681      ErrorKind = 0;  // 0 -> unary
4682    } else {
4683      assert(CanBeBinaryOperator &&
4684             "All non-call overloaded operators are unary or binary!");
4685      ErrorKind = 1;  // 1 -> binary
4686    }
4687
4688    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
4689      << FnDecl->getDeclName() << NumParams << ErrorKind;
4690  }
4691
4692  // Overloaded operators other than operator() cannot be variadic.
4693  if (Op != OO_Call &&
4694      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
4695    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
4696      << FnDecl->getDeclName();
4697  }
4698
4699  // Some operators must be non-static member functions.
4700  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
4701    return Diag(FnDecl->getLocation(),
4702                diag::err_operator_overload_must_be_member)
4703      << FnDecl->getDeclName();
4704  }
4705
4706  // C++ [over.inc]p1:
4707  //   The user-defined function called operator++ implements the
4708  //   prefix and postfix ++ operator. If this function is a member
4709  //   function with no parameters, or a non-member function with one
4710  //   parameter of class or enumeration type, it defines the prefix
4711  //   increment operator ++ for objects of that type. If the function
4712  //   is a member function with one parameter (which shall be of type
4713  //   int) or a non-member function with two parameters (the second
4714  //   of which shall be of type int), it defines the postfix
4715  //   increment operator ++ for objects of that type.
4716  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
4717    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
4718    bool ParamIsInt = false;
4719    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
4720      ParamIsInt = BT->getKind() == BuiltinType::Int;
4721
4722    if (!ParamIsInt)
4723      return Diag(LastParam->getLocation(),
4724                  diag::err_operator_overload_post_incdec_must_be_int)
4725        << LastParam->getType() << (Op == OO_MinusMinus);
4726  }
4727
4728  // Notify the class if it got an assignment operator.
4729  if (Op == OO_Equal) {
4730    // Would have returned earlier otherwise.
4731    assert(isa<CXXMethodDecl>(FnDecl) &&
4732      "Overloaded = not member, but not filtered.");
4733    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4734    Method->getParent()->addedAssignmentOperator(Context, Method);
4735  }
4736
4737  return false;
4738}
4739
4740/// CheckLiteralOperatorDeclaration - Check whether the declaration
4741/// of this literal operator function is well-formed. If so, returns
4742/// false; otherwise, emits appropriate diagnostics and returns true.
4743bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
4744  DeclContext *DC = FnDecl->getDeclContext();
4745  Decl::Kind Kind = DC->getDeclKind();
4746  if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
4747      Kind != Decl::LinkageSpec) {
4748    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
4749      << FnDecl->getDeclName();
4750    return true;
4751  }
4752
4753  bool Valid = false;
4754
4755  // template <char...> type operator "" name() is the only valid template
4756  // signature, and the only valid signature with no parameters.
4757  if (FnDecl->param_size() == 0) {
4758    if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
4759      // Must have only one template parameter
4760      TemplateParameterList *Params = TpDecl->getTemplateParameters();
4761      if (Params->size() == 1) {
4762        NonTypeTemplateParmDecl *PmDecl =
4763          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
4764
4765        // The template parameter must be a char parameter pack.
4766        // FIXME: This test will always fail because non-type parameter packs
4767        //   have not been implemented.
4768        if (PmDecl && PmDecl->isTemplateParameterPack() &&
4769            Context.hasSameType(PmDecl->getType(), Context.CharTy))
4770          Valid = true;
4771      }
4772    }
4773  } else {
4774    // Check the first parameter
4775    FunctionDecl::param_iterator Param = FnDecl->param_begin();
4776
4777    QualType T = (*Param)->getType();
4778
4779    // unsigned long long int, long double, and any character type are allowed
4780    // as the only parameters.
4781    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
4782        Context.hasSameType(T, Context.LongDoubleTy) ||
4783        Context.hasSameType(T, Context.CharTy) ||
4784        Context.hasSameType(T, Context.WCharTy) ||
4785        Context.hasSameType(T, Context.Char16Ty) ||
4786        Context.hasSameType(T, Context.Char32Ty)) {
4787      if (++Param == FnDecl->param_end())
4788        Valid = true;
4789      goto FinishedParams;
4790    }
4791
4792    // Otherwise it must be a pointer to const; let's strip those qualifiers.
4793    const PointerType *PT = T->getAs<PointerType>();
4794    if (!PT)
4795      goto FinishedParams;
4796    T = PT->getPointeeType();
4797    if (!T.isConstQualified())
4798      goto FinishedParams;
4799    T = T.getUnqualifiedType();
4800
4801    // Move on to the second parameter;
4802    ++Param;
4803
4804    // If there is no second parameter, the first must be a const char *
4805    if (Param == FnDecl->param_end()) {
4806      if (Context.hasSameType(T, Context.CharTy))
4807        Valid = true;
4808      goto FinishedParams;
4809    }
4810
4811    // const char *, const wchar_t*, const char16_t*, and const char32_t*
4812    // are allowed as the first parameter to a two-parameter function
4813    if (!(Context.hasSameType(T, Context.CharTy) ||
4814          Context.hasSameType(T, Context.WCharTy) ||
4815          Context.hasSameType(T, Context.Char16Ty) ||
4816          Context.hasSameType(T, Context.Char32Ty)))
4817      goto FinishedParams;
4818
4819    // The second and final parameter must be an std::size_t
4820    T = (*Param)->getType().getUnqualifiedType();
4821    if (Context.hasSameType(T, Context.getSizeType()) &&
4822        ++Param == FnDecl->param_end())
4823      Valid = true;
4824  }
4825
4826  // FIXME: This diagnostic is absolutely terrible.
4827FinishedParams:
4828  if (!Valid) {
4829    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
4830      << FnDecl->getDeclName();
4831    return true;
4832  }
4833
4834  return false;
4835}
4836
4837/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
4838/// linkage specification, including the language and (if present)
4839/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
4840/// the location of the language string literal, which is provided
4841/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
4842/// the '{' brace. Otherwise, this linkage specification does not
4843/// have any braces.
4844Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
4845                                                     SourceLocation ExternLoc,
4846                                                     SourceLocation LangLoc,
4847                                                     const char *Lang,
4848                                                     unsigned StrSize,
4849                                                     SourceLocation LBraceLoc) {
4850  LinkageSpecDecl::LanguageIDs Language;
4851  if (strncmp(Lang, "\"C\"", StrSize) == 0)
4852    Language = LinkageSpecDecl::lang_c;
4853  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
4854    Language = LinkageSpecDecl::lang_cxx;
4855  else {
4856    Diag(LangLoc, diag::err_bad_language);
4857    return DeclPtrTy();
4858  }
4859
4860  // FIXME: Add all the various semantics of linkage specifications
4861
4862  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
4863                                               LangLoc, Language,
4864                                               LBraceLoc.isValid());
4865  CurContext->addDecl(D);
4866  PushDeclContext(S, D);
4867  return DeclPtrTy::make(D);
4868}
4869
4870/// ActOnFinishLinkageSpecification - Completely the definition of
4871/// the C++ linkage specification LinkageSpec. If RBraceLoc is
4872/// valid, it's the position of the closing '}' brace in a linkage
4873/// specification that uses braces.
4874Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
4875                                                      DeclPtrTy LinkageSpec,
4876                                                      SourceLocation RBraceLoc) {
4877  if (LinkageSpec)
4878    PopDeclContext();
4879  return LinkageSpec;
4880}
4881
4882/// \brief Perform semantic analysis for the variable declaration that
4883/// occurs within a C++ catch clause, returning the newly-created
4884/// variable.
4885VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
4886                                         TypeSourceInfo *TInfo,
4887                                         IdentifierInfo *Name,
4888                                         SourceLocation Loc,
4889                                         SourceRange Range) {
4890  bool Invalid = false;
4891
4892  // Arrays and functions decay.
4893  if (ExDeclType->isArrayType())
4894    ExDeclType = Context.getArrayDecayedType(ExDeclType);
4895  else if (ExDeclType->isFunctionType())
4896    ExDeclType = Context.getPointerType(ExDeclType);
4897
4898  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
4899  // The exception-declaration shall not denote a pointer or reference to an
4900  // incomplete type, other than [cv] void*.
4901  // N2844 forbids rvalue references.
4902  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
4903    Diag(Loc, diag::err_catch_rvalue_ref) << Range;
4904    Invalid = true;
4905  }
4906
4907  // GCC allows catching pointers and references to incomplete types
4908  // as an extension; so do we, but we warn by default.
4909
4910  QualType BaseType = ExDeclType;
4911  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
4912  unsigned DK = diag::err_catch_incomplete;
4913  bool IncompleteCatchIsInvalid = true;
4914  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4915    BaseType = Ptr->getPointeeType();
4916    Mode = 1;
4917    DK = diag::ext_catch_incomplete_ptr;
4918    IncompleteCatchIsInvalid = false;
4919  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
4920    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
4921    BaseType = Ref->getPointeeType();
4922    Mode = 2;
4923    DK = diag::ext_catch_incomplete_ref;
4924    IncompleteCatchIsInvalid = false;
4925  }
4926  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
4927      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
4928      IncompleteCatchIsInvalid)
4929    Invalid = true;
4930
4931  if (!Invalid && !ExDeclType->isDependentType() &&
4932      RequireNonAbstractType(Loc, ExDeclType,
4933                             diag::err_abstract_type_in_decl,
4934                             AbstractVariableType))
4935    Invalid = true;
4936
4937  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
4938                                    Name, ExDeclType, TInfo, VarDecl::None,
4939                                    VarDecl::None);
4940
4941  if (!Invalid) {
4942    if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
4943      // C++ [except.handle]p16:
4944      //   The object declared in an exception-declaration or, if the
4945      //   exception-declaration does not specify a name, a temporary (12.2) is
4946      //   copy-initialized (8.5) from the exception object. [...]
4947      //   The object is destroyed when the handler exits, after the destruction
4948      //   of any automatic objects initialized within the handler.
4949      //
4950      // We just pretend to initialize the object with itself, then make sure
4951      // it can be destroyed later.
4952      InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
4953      Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
4954                                            Loc, ExDeclType, 0);
4955      InitializationKind Kind = InitializationKind::CreateCopy(Loc,
4956                                                               SourceLocation());
4957      InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
4958      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4959                                    MultiExprArg(*this, (void**)&ExDeclRef, 1));
4960      if (Result.isInvalid())
4961        Invalid = true;
4962      else
4963        FinalizeVarWithDestructor(ExDecl, RecordTy);
4964    }
4965  }
4966
4967  if (Invalid)
4968    ExDecl->setInvalidDecl();
4969
4970  return ExDecl;
4971}
4972
4973/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
4974/// handler.
4975Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
4976  TypeSourceInfo *TInfo = 0;
4977  QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
4978
4979  bool Invalid = D.isInvalidType();
4980  IdentifierInfo *II = D.getIdentifier();
4981  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
4982                                             LookupOrdinaryName,
4983                                             ForRedeclaration)) {
4984    // The scope should be freshly made just for us. There is just no way
4985    // it contains any previous declaration.
4986    assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
4987    if (PrevDecl->isTemplateParameter()) {
4988      // Maybe we will complain about the shadowed template parameter.
4989      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4990    }
4991  }
4992
4993  if (D.getCXXScopeSpec().isSet() && !Invalid) {
4994    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
4995      << D.getCXXScopeSpec().getRange();
4996    Invalid = true;
4997  }
4998
4999  VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
5000                                              D.getIdentifier(),
5001                                              D.getIdentifierLoc(),
5002                                            D.getDeclSpec().getSourceRange());
5003
5004  if (Invalid)
5005    ExDecl->setInvalidDecl();
5006
5007  // Add the exception declaration into this scope.
5008  if (II)
5009    PushOnScopeChains(ExDecl, S);
5010  else
5011    CurContext->addDecl(ExDecl);
5012
5013  ProcessDeclAttributes(S, ExDecl, D);
5014  return DeclPtrTy::make(ExDecl);
5015}
5016
5017Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
5018                                                   ExprArg assertexpr,
5019                                                   ExprArg assertmessageexpr) {
5020  Expr *AssertExpr = (Expr *)assertexpr.get();
5021  StringLiteral *AssertMessage =
5022    cast<StringLiteral>((Expr *)assertmessageexpr.get());
5023
5024  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5025    llvm::APSInt Value(32);
5026    if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5027      Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5028        AssertExpr->getSourceRange();
5029      return DeclPtrTy();
5030    }
5031
5032    if (Value == 0) {
5033      Diag(AssertLoc, diag::err_static_assert_failed)
5034        << AssertMessage->getString() << AssertExpr->getSourceRange();
5035    }
5036  }
5037
5038  assertexpr.release();
5039  assertmessageexpr.release();
5040  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
5041                                        AssertExpr, AssertMessage);
5042
5043  CurContext->addDecl(Decl);
5044  return DeclPtrTy::make(Decl);
5045}
5046
5047/// \brief Perform semantic analysis of the given friend type declaration.
5048///
5049/// \returns A friend declaration that.
5050FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5051                                      TypeSourceInfo *TSInfo) {
5052  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5053
5054  QualType T = TSInfo->getType();
5055  SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5056
5057  if (!getLangOptions().CPlusPlus0x) {
5058    // C++03 [class.friend]p2:
5059    //   An elaborated-type-specifier shall be used in a friend declaration
5060    //   for a class.*
5061    //
5062    //   * The class-key of the elaborated-type-specifier is required.
5063    if (!ActiveTemplateInstantiations.empty()) {
5064      // Do not complain about the form of friend template types during
5065      // template instantiation; we will already have complained when the
5066      // template was declared.
5067    } else if (!T->isElaboratedTypeSpecifier()) {
5068      // If we evaluated the type to a record type, suggest putting
5069      // a tag in front.
5070      if (const RecordType *RT = T->getAs<RecordType>()) {
5071        RecordDecl *RD = RT->getDecl();
5072
5073        std::string InsertionText = std::string(" ") + RD->getKindName();
5074
5075        Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5076          << (unsigned) RD->getTagKind()
5077          << T
5078          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5079                                        InsertionText);
5080      } else {
5081        Diag(FriendLoc, diag::ext_nonclass_type_friend)
5082          << T
5083          << SourceRange(FriendLoc, TypeRange.getEnd());
5084      }
5085    } else if (T->getAs<EnumType>()) {
5086      Diag(FriendLoc, diag::ext_enum_friend)
5087        << T
5088        << SourceRange(FriendLoc, TypeRange.getEnd());
5089    }
5090  }
5091
5092  // C++0x [class.friend]p3:
5093  //   If the type specifier in a friend declaration designates a (possibly
5094  //   cv-qualified) class type, that class is declared as a friend; otherwise,
5095  //   the friend declaration is ignored.
5096
5097  // FIXME: C++0x has some syntactic restrictions on friend type declarations
5098  // in [class.friend]p3 that we do not implement.
5099
5100  return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5101}
5102
5103/// Handle a friend type declaration.  This works in tandem with
5104/// ActOnTag.
5105///
5106/// Notes on friend class templates:
5107///
5108/// We generally treat friend class declarations as if they were
5109/// declaring a class.  So, for example, the elaborated type specifier
5110/// in a friend declaration is required to obey the restrictions of a
5111/// class-head (i.e. no typedefs in the scope chain), template
5112/// parameters are required to match up with simple template-ids, &c.
5113/// However, unlike when declaring a template specialization, it's
5114/// okay to refer to a template specialization without an empty
5115/// template parameter declaration, e.g.
5116///   friend class A<T>::B<unsigned>;
5117/// We permit this as a special case; if there are any template
5118/// parameters present at all, require proper matching, i.e.
5119///   template <> template <class T> friend class A<int>::B;
5120Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5121                                          MultiTemplateParamsArg TempParams) {
5122  SourceLocation Loc = DS.getSourceRange().getBegin();
5123
5124  assert(DS.isFriendSpecified());
5125  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5126
5127  // Try to convert the decl specifier to a type.  This works for
5128  // friend templates because ActOnTag never produces a ClassTemplateDecl
5129  // for a TUK_Friend.
5130  Declarator TheDeclarator(DS, Declarator::MemberContext);
5131  TypeSourceInfo *TSI;
5132  QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
5133  if (TheDeclarator.isInvalidType())
5134    return DeclPtrTy();
5135
5136  if (!TSI)
5137    TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5138
5139  // This is definitely an error in C++98.  It's probably meant to
5140  // be forbidden in C++0x, too, but the specification is just
5141  // poorly written.
5142  //
5143  // The problem is with declarations like the following:
5144  //   template <T> friend A<T>::foo;
5145  // where deciding whether a class C is a friend or not now hinges
5146  // on whether there exists an instantiation of A that causes
5147  // 'foo' to equal C.  There are restrictions on class-heads
5148  // (which we declare (by fiat) elaborated friend declarations to
5149  // be) that makes this tractable.
5150  //
5151  // FIXME: handle "template <> friend class A<T>;", which
5152  // is possibly well-formed?  Who even knows?
5153  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
5154    Diag(Loc, diag::err_tagless_friend_type_template)
5155      << DS.getSourceRange();
5156    return DeclPtrTy();
5157  }
5158
5159  // C++98 [class.friend]p1: A friend of a class is a function
5160  //   or class that is not a member of the class . . .
5161  // This is fixed in DR77, which just barely didn't make the C++03
5162  // deadline.  It's also a very silly restriction that seriously
5163  // affects inner classes and which nobody else seems to implement;
5164  // thus we never diagnose it, not even in -pedantic.
5165  //
5166  // But note that we could warn about it: it's always useless to
5167  // friend one of your own members (it's not, however, worthless to
5168  // friend a member of an arbitrary specialization of your template).
5169
5170  Decl *D;
5171  if (unsigned NumTempParamLists = TempParams.size())
5172    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
5173                                   NumTempParamLists,
5174                                 (TemplateParameterList**) TempParams.release(),
5175                                   TSI,
5176                                   DS.getFriendSpecLoc());
5177  else
5178    D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5179
5180  if (!D)
5181    return DeclPtrTy();
5182
5183  D->setAccess(AS_public);
5184  CurContext->addDecl(D);
5185
5186  return DeclPtrTy::make(D);
5187}
5188
5189Sema::DeclPtrTy
5190Sema::ActOnFriendFunctionDecl(Scope *S,
5191                              Declarator &D,
5192                              bool IsDefinition,
5193                              MultiTemplateParamsArg TemplateParams) {
5194  const DeclSpec &DS = D.getDeclSpec();
5195
5196  assert(DS.isFriendSpecified());
5197  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5198
5199  SourceLocation Loc = D.getIdentifierLoc();
5200  TypeSourceInfo *TInfo = 0;
5201  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5202
5203  // C++ [class.friend]p1
5204  //   A friend of a class is a function or class....
5205  // Note that this sees through typedefs, which is intended.
5206  // It *doesn't* see through dependent types, which is correct
5207  // according to [temp.arg.type]p3:
5208  //   If a declaration acquires a function type through a
5209  //   type dependent on a template-parameter and this causes
5210  //   a declaration that does not use the syntactic form of a
5211  //   function declarator to have a function type, the program
5212  //   is ill-formed.
5213  if (!T->isFunctionType()) {
5214    Diag(Loc, diag::err_unexpected_friend);
5215
5216    // It might be worthwhile to try to recover by creating an
5217    // appropriate declaration.
5218    return DeclPtrTy();
5219  }
5220
5221  // C++ [namespace.memdef]p3
5222  //  - If a friend declaration in a non-local class first declares a
5223  //    class or function, the friend class or function is a member
5224  //    of the innermost enclosing namespace.
5225  //  - The name of the friend is not found by simple name lookup
5226  //    until a matching declaration is provided in that namespace
5227  //    scope (either before or after the class declaration granting
5228  //    friendship).
5229  //  - If a friend function is called, its name may be found by the
5230  //    name lookup that considers functions from namespaces and
5231  //    classes associated with the types of the function arguments.
5232  //  - When looking for a prior declaration of a class or a function
5233  //    declared as a friend, scopes outside the innermost enclosing
5234  //    namespace scope are not considered.
5235
5236  CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5237  DeclarationName Name = GetNameForDeclarator(D);
5238  assert(Name);
5239
5240  // The context we found the declaration in, or in which we should
5241  // create the declaration.
5242  DeclContext *DC;
5243
5244  // FIXME: handle local classes
5245
5246  // Recover from invalid scope qualifiers as if they just weren't there.
5247  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5248                        ForRedeclaration);
5249  if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5250    // FIXME: RequireCompleteDeclContext
5251    DC = computeDeclContext(ScopeQual);
5252
5253    // FIXME: handle dependent contexts
5254    if (!DC) return DeclPtrTy();
5255
5256    LookupQualifiedName(Previous, DC);
5257
5258    // If searching in that context implicitly found a declaration in
5259    // a different context, treat it like it wasn't found at all.
5260    // TODO: better diagnostics for this case.  Suggesting the right
5261    // qualified scope would be nice...
5262    // FIXME: getRepresentativeDecl() is not right here at all
5263    if (Previous.empty() ||
5264        !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
5265      D.setInvalidType();
5266      Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5267      return DeclPtrTy();
5268    }
5269
5270    // C++ [class.friend]p1: A friend of a class is a function or
5271    //   class that is not a member of the class . . .
5272    if (DC->Equals(CurContext))
5273      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5274
5275  // Otherwise walk out to the nearest namespace scope looking for matches.
5276  } else {
5277    // TODO: handle local class contexts.
5278
5279    DC = CurContext;
5280    while (true) {
5281      // Skip class contexts.  If someone can cite chapter and verse
5282      // for this behavior, that would be nice --- it's what GCC and
5283      // EDG do, and it seems like a reasonable intent, but the spec
5284      // really only says that checks for unqualified existing
5285      // declarations should stop at the nearest enclosing namespace,
5286      // not that they should only consider the nearest enclosing
5287      // namespace.
5288      while (DC->isRecord())
5289        DC = DC->getParent();
5290
5291      LookupQualifiedName(Previous, DC);
5292
5293      // TODO: decide what we think about using declarations.
5294      if (!Previous.empty())
5295        break;
5296
5297      if (DC->isFileContext()) break;
5298      DC = DC->getParent();
5299    }
5300
5301    // C++ [class.friend]p1: A friend of a class is a function or
5302    //   class that is not a member of the class . . .
5303    // C++0x changes this for both friend types and functions.
5304    // Most C++ 98 compilers do seem to give an error here, so
5305    // we do, too.
5306    if (!Previous.empty() && DC->Equals(CurContext)
5307        && !getLangOptions().CPlusPlus0x)
5308      Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5309  }
5310
5311  if (DC->isFileContext()) {
5312    // This implies that it has to be an operator or function.
5313    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5314        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5315        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
5316      Diag(Loc, diag::err_introducing_special_friend) <<
5317        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5318         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
5319      return DeclPtrTy();
5320    }
5321  }
5322
5323  bool Redeclaration = false;
5324  NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
5325                                          move(TemplateParams),
5326                                          IsDefinition,
5327                                          Redeclaration);
5328  if (!ND) return DeclPtrTy();
5329
5330  assert(ND->getDeclContext() == DC);
5331  assert(ND->getLexicalDeclContext() == CurContext);
5332
5333  // Add the function declaration to the appropriate lookup tables,
5334  // adjusting the redeclarations list as necessary.  We don't
5335  // want to do this yet if the friending class is dependent.
5336  //
5337  // Also update the scope-based lookup if the target context's
5338  // lookup context is in lexical scope.
5339  if (!CurContext->isDependentContext()) {
5340    DC = DC->getLookupContext();
5341    DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
5342    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5343      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
5344  }
5345
5346  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
5347                                       D.getIdentifierLoc(), ND,
5348                                       DS.getFriendSpecLoc());
5349  FrD->setAccess(AS_public);
5350  CurContext->addDecl(FrD);
5351
5352  return DeclPtrTy::make(ND);
5353}
5354
5355void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
5356  AdjustDeclIfTemplate(dcl);
5357
5358  Decl *Dcl = dcl.getAs<Decl>();
5359  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5360  if (!Fn) {
5361    Diag(DelLoc, diag::err_deleted_non_function);
5362    return;
5363  }
5364  if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5365    Diag(DelLoc, diag::err_deleted_decl_not_first);
5366    Diag(Prev->getLocation(), diag::note_previous_declaration);
5367    // If the declaration wasn't the first, we delete the function anyway for
5368    // recovery.
5369  }
5370  Fn->setDeleted();
5371}
5372
5373static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5374  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5375       ++CI) {
5376    Stmt *SubStmt = *CI;
5377    if (!SubStmt)
5378      continue;
5379    if (isa<ReturnStmt>(SubStmt))
5380      Self.Diag(SubStmt->getSourceRange().getBegin(),
5381           diag::err_return_in_constructor_handler);
5382    if (!isa<Expr>(SubStmt))
5383      SearchForReturnInStmt(Self, SubStmt);
5384  }
5385}
5386
5387void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5388  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5389    CXXCatchStmt *Handler = TryBlock->getHandler(I);
5390    SearchForReturnInStmt(*this, Handler);
5391  }
5392}
5393
5394bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5395                                             const CXXMethodDecl *Old) {
5396  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5397  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
5398
5399  if (Context.hasSameType(NewTy, OldTy) ||
5400      NewTy->isDependentType() || OldTy->isDependentType())
5401    return false;
5402
5403  // Check if the return types are covariant
5404  QualType NewClassTy, OldClassTy;
5405
5406  /// Both types must be pointers or references to classes.
5407  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5408    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
5409      NewClassTy = NewPT->getPointeeType();
5410      OldClassTy = OldPT->getPointeeType();
5411    }
5412  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5413    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5414      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5415        NewClassTy = NewRT->getPointeeType();
5416        OldClassTy = OldRT->getPointeeType();
5417      }
5418    }
5419  }
5420
5421  // The return types aren't either both pointers or references to a class type.
5422  if (NewClassTy.isNull()) {
5423    Diag(New->getLocation(),
5424         diag::err_different_return_type_for_overriding_virtual_function)
5425      << New->getDeclName() << NewTy << OldTy;
5426    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5427
5428    return true;
5429  }
5430
5431  // C++ [class.virtual]p6:
5432  //   If the return type of D::f differs from the return type of B::f, the
5433  //   class type in the return type of D::f shall be complete at the point of
5434  //   declaration of D::f or shall be the class type D.
5435  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5436    if (!RT->isBeingDefined() &&
5437        RequireCompleteType(New->getLocation(), NewClassTy,
5438                            PDiag(diag::err_covariant_return_incomplete)
5439                              << New->getDeclName()))
5440    return true;
5441  }
5442
5443  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
5444    // Check if the new class derives from the old class.
5445    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5446      Diag(New->getLocation(),
5447           diag::err_covariant_return_not_derived)
5448      << New->getDeclName() << NewTy << OldTy;
5449      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5450      return true;
5451    }
5452
5453    // Check if we the conversion from derived to base is valid.
5454    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
5455                    diag::err_covariant_return_inaccessible_base,
5456                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
5457                    // FIXME: Should this point to the return type?
5458                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
5459      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5460      return true;
5461    }
5462  }
5463
5464  // The qualifiers of the return types must be the same.
5465  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
5466    Diag(New->getLocation(),
5467         diag::err_covariant_return_type_different_qualifications)
5468    << New->getDeclName() << NewTy << OldTy;
5469    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5470    return true;
5471  };
5472
5473
5474  // The new class type must have the same or less qualifiers as the old type.
5475  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5476    Diag(New->getLocation(),
5477         diag::err_covariant_return_type_class_type_more_qualified)
5478    << New->getDeclName() << NewTy << OldTy;
5479    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5480    return true;
5481  };
5482
5483  return false;
5484}
5485
5486bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5487                                             const CXXMethodDecl *Old)
5488{
5489  if (Old->hasAttr<FinalAttr>()) {
5490    Diag(New->getLocation(), diag::err_final_function_overridden)
5491      << New->getDeclName();
5492    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5493    return true;
5494  }
5495
5496  return false;
5497}
5498
5499/// \brief Mark the given method pure.
5500///
5501/// \param Method the method to be marked pure.
5502///
5503/// \param InitRange the source range that covers the "0" initializer.
5504bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5505  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5506    Method->setPure();
5507
5508    // A class is abstract if at least one function is pure virtual.
5509    Method->getParent()->setAbstract(true);
5510    return false;
5511  }
5512
5513  if (!Method->isInvalidDecl())
5514    Diag(Method->getLocation(), diag::err_non_virtual_pure)
5515      << Method->getDeclName() << InitRange;
5516  return true;
5517}
5518
5519/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5520/// an initializer for the out-of-line declaration 'Dcl'.  The scope
5521/// is a fresh scope pushed for just this purpose.
5522///
5523/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5524/// static data member of class X, names should be looked up in the scope of
5525/// class X.
5526void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5527  // If there is no declaration, there was an error parsing it.
5528  Decl *D = Dcl.getAs<Decl>();
5529  if (D == 0) return;
5530
5531  // We should only get called for declarations with scope specifiers, like:
5532  //   int foo::bar;
5533  assert(D->isOutOfLine());
5534  EnterDeclaratorContext(S, D->getDeclContext());
5535}
5536
5537/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5538/// initializer for the out-of-line declaration 'Dcl'.
5539void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
5540  // If there is no declaration, there was an error parsing it.
5541  Decl *D = Dcl.getAs<Decl>();
5542  if (D == 0) return;
5543
5544  assert(D->isOutOfLine());
5545  ExitDeclaratorContext(S);
5546}
5547
5548/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5549/// C++ if/switch/while/for statement.
5550/// e.g: "if (int x = f()) {...}"
5551Action::DeclResult
5552Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5553  // C++ 6.4p2:
5554  // The declarator shall not specify a function or an array.
5555  // The type-specifier-seq shall not contain typedef and shall not declare a
5556  // new class or enumeration.
5557  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5558         "Parser allowed 'typedef' as storage class of condition decl.");
5559
5560  TypeSourceInfo *TInfo = 0;
5561  TagDecl *OwnedTag = 0;
5562  QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
5563
5564  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5565                              // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5566                              // would be created and CXXConditionDeclExpr wants a VarDecl.
5567    Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5568      << D.getSourceRange();
5569    return DeclResult();
5570  } else if (OwnedTag && OwnedTag->isDefinition()) {
5571    // The type-specifier-seq shall not declare a new class or enumeration.
5572    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5573  }
5574
5575  DeclPtrTy Dcl = ActOnDeclarator(S, D);
5576  if (!Dcl)
5577    return DeclResult();
5578
5579  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5580  VD->setDeclaredInCondition(true);
5581  return Dcl;
5582}
5583
5584static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
5585  // Ignore dependent types.
5586  if (MD->isDependentContext())
5587    return false;
5588
5589  // Ignore declarations that are not definitions.
5590  if (!MD->isThisDeclarationADefinition())
5591    return false;
5592
5593  CXXRecordDecl *RD = MD->getParent();
5594
5595  // Ignore classes without a vtable.
5596  if (!RD->isDynamicClass())
5597    return false;
5598
5599  switch (MD->getParent()->getTemplateSpecializationKind()) {
5600  case TSK_Undeclared:
5601  case TSK_ExplicitSpecialization:
5602    // Classes that aren't instantiations of templates don't need their
5603    // virtual methods marked until we see the definition of the key
5604    // function.
5605    break;
5606
5607  case TSK_ImplicitInstantiation:
5608    // This is a constructor of a class template; mark all of the virtual
5609    // members as referenced to ensure that they get instantiatied.
5610    if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5611      return true;
5612    break;
5613
5614  case TSK_ExplicitInstantiationDeclaration:
5615    return false;
5616
5617  case TSK_ExplicitInstantiationDefinition:
5618    // This is method of a explicit instantiation; mark all of the virtual
5619    // members as referenced to ensure that they get instantiatied.
5620    return true;
5621  }
5622
5623  // Consider only out-of-line definitions of member functions. When we see
5624  // an inline definition, it's too early to compute the key function.
5625  if (!MD->isOutOfLine())
5626    return false;
5627
5628  const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5629
5630  // If there is no key function, we will need a copy of the vtable.
5631  if (!KeyFunction)
5632    return true;
5633
5634  // If this is the key function, we need to mark virtual members.
5635  if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5636    return true;
5637
5638  return false;
5639}
5640
5641void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5642                                             CXXMethodDecl *MD) {
5643  CXXRecordDecl *RD = MD->getParent();
5644
5645  // We will need to mark all of the virtual members as referenced to build the
5646  // vtable.
5647  if (!needsVTable(MD, Context))
5648    return;
5649
5650  TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5651  if (kind == TSK_ImplicitInstantiation)
5652    ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5653  else
5654    MarkVirtualMembersReferenced(Loc, RD);
5655}
5656
5657bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
5658  if (ClassesWithUnmarkedVirtualMembers.empty())
5659    return false;
5660
5661  while (!ClassesWithUnmarkedVirtualMembers.empty()) {
5662    CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
5663    SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
5664    ClassesWithUnmarkedVirtualMembers.pop_back();
5665    MarkVirtualMembersReferenced(Loc, RD);
5666  }
5667
5668  return true;
5669}
5670
5671void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
5672                                        const CXXRecordDecl *RD) {
5673  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
5674       e = RD->method_end(); i != e; ++i) {
5675    CXXMethodDecl *MD = *i;
5676
5677    // C++ [basic.def.odr]p2:
5678    //   [...] A virtual member function is used if it is not pure. [...]
5679    if (MD->isVirtual() && !MD->isPure())
5680      MarkDeclarationReferenced(Loc, MD);
5681  }
5682
5683  // Only classes that have virtual bases need a VTT.
5684  if (RD->getNumVBases() == 0)
5685    return;
5686
5687  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
5688           e = RD->bases_end(); i != e; ++i) {
5689    const CXXRecordDecl *Base =
5690        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
5691    if (i->isVirtual())
5692      continue;
5693    if (Base->getNumVBases() == 0)
5694      continue;
5695    MarkVirtualMembersReferenced(Loc, Base);
5696  }
5697}
5698