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