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