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