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