DeclCXX.cpp revision 256281
11590Srgrimes//===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
21590Srgrimes//
31590Srgrimes//                     The LLVM Compiler Infrastructure
41590Srgrimes//
51590Srgrimes// This file is distributed under the University of Illinois Open Source
61590Srgrimes// License. See LICENSE.TXT for details.
71590Srgrimes//
81590Srgrimes//===----------------------------------------------------------------------===//
91590Srgrimes//
101590Srgrimes// This file implements the C++ related Decl classes.
111590Srgrimes//
121590Srgrimes//===----------------------------------------------------------------------===//
131590Srgrimes
141590Srgrimes#include "clang/AST/DeclCXX.h"
151590Srgrimes#include "clang/AST/ASTContext.h"
161590Srgrimes#include "clang/AST/ASTMutationListener.h"
171590Srgrimes#include "clang/AST/CXXInheritance.h"
181590Srgrimes#include "clang/AST/DeclTemplate.h"
191590Srgrimes#include "clang/AST/Expr.h"
201590Srgrimes#include "clang/AST/ExprCXX.h"
211590Srgrimes#include "clang/AST/TypeLoc.h"
221590Srgrimes#include "clang/Basic/IdentifierTable.h"
231590Srgrimes#include "llvm/ADT/STLExtras.h"
241590Srgrimes#include "llvm/ADT/SmallPtrSet.h"
251590Srgrimesusing namespace clang;
261590Srgrimes
271590Srgrimes//===----------------------------------------------------------------------===//
281590Srgrimes// Decl Allocation/Deallocation Method Implementations
291590Srgrimes//===----------------------------------------------------------------------===//
301590Srgrimes
3127604Scharniervoid AccessSpecDecl::anchor() { }
321590Srgrimes
331590SrgrimesAccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
341590Srgrimes  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(AccessSpecDecl));
351590Srgrimes  return new (Mem) AccessSpecDecl(EmptyShell());
36146756Scharnier}
371590Srgrimes
381590SrgrimesCXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
39146756Scharnier  : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
4027604Scharnier    Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
41146756Scharnier    Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
4293525Sdwmalone    HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
4393525Sdwmalone    HasMutableFields(false), HasOnlyCMembers(true),
4493525Sdwmalone    HasInClassInitializer(false), HasUninitializedReferenceMember(false),
4563402Sdwmalone    NeedOverloadResolutionForMoveConstructor(false),
4663402Sdwmalone    NeedOverloadResolutionForMoveAssignment(false),
4763402Sdwmalone    NeedOverloadResolutionForDestructor(false),
4863402Sdwmalone    DefaultedMoveConstructorIsDeleted(false),
4927604Scharnier    DefaultedMoveAssignmentIsDeleted(false),
5027604Scharnier    DefaultedDestructorIsDeleted(false),
5163402Sdwmalone    HasTrivialSpecialMembers(SMF_All),
5227604Scharnier    DeclaredNonTrivialSpecialMembers(0),
531590Srgrimes    HasIrrelevantDestructor(true),
541590Srgrimes    HasConstexprNonCopyMoveConstructor(false),
5527604Scharnier    DefaultedDefaultConstructorIsConstexpr(true),
561590Srgrimes    HasConstexprDefaultConstructor(false),
571590Srgrimes    HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false),
581590Srgrimes    UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
591590Srgrimes    ImplicitCopyConstructorHasConstParam(true),
60227170Sed    ImplicitCopyAssignmentHasConstParam(true),
61227170Sed    HasDeclaredCopyConstructorWithConstParam(false),
62220448Sedwin    HasDeclaredCopyAssignmentWithConstParam(false),
63220448Sedwin    FailedImplicitMoveConstructor(false), FailedImplicitMoveAssignment(false),
6492920Simp    IsLambda(false), NumBases(0), NumVBases(0), Bases(), VBases(),
651590Srgrimes    Definition(D), FirstFriend(0) {
6670100Sume}
6770100Sume
6870100SumeCXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
6970100Sume  return Bases.get(Definition->getASTContext().getExternalSource());
7070100Sume}
7170100Sume
7270100SumeCXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
73227170Sed  return VBases.get(Definition->getASTContext().getExternalSource());
7470100Sume}
75227170Sed
7670100SumeCXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
77227170Sed                             SourceLocation StartLoc, SourceLocation IdLoc,
7870100Sume                             IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
791590Srgrimes  : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
801590Srgrimes    DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
811590Srgrimes    TemplateOrInstantiation() { }
821590Srgrimes
831590SrgrimesCXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
841590Srgrimes                                     DeclContext *DC, SourceLocation StartLoc,
851590Srgrimes                                     SourceLocation IdLoc, IdentifierInfo *Id,
86102944Sdwmalone                                     CXXRecordDecl* PrevDecl,
871590Srgrimes                                     bool DelayTypeCreation) {
881590Srgrimes  CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
89169344Sdwmalone                                           Id, PrevDecl);
90169344Sdwmalone  R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
911590Srgrimes
921590Srgrimes  // FIXME: DelayTypeCreation seems like such a hack
9363402Sdwmalone  if (!DelayTypeCreation)
94160917Sbms    C.getTypeDeclType(R, PrevDecl);
9583150Sru  return R;
961590Srgrimes}
9719075Sphk
98160917SbmsCXXRecordDecl *CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
991590Srgrimes                                           TypeSourceInfo *Info, SourceLocation Loc,
10070100Sume                                           bool Dependent) {
10170100Sume  CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TTK_Class, DC, Loc, Loc,
10270100Sume                                           0, 0);
10370100Sume  R->IsBeingDefined = true;
10470100Sume  R->DefinitionData = new (C) struct LambdaDefinitionData(R, Info, Dependent);
10570100Sume  R->MayHaveOutOfDateDef = false;
10670100Sume  C.getTypeDeclType(R, /*PrevDecl=*/0);
10770100Sume  return R;
10870100Sume}
10970100Sume
11070100SumeCXXRecordDecl *
1111590SrgrimesCXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
11227604Scharnier  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXRecordDecl));
11327604Scharnier  CXXRecordDecl *R = new (Mem) CXXRecordDecl(CXXRecord, TTK_Struct, 0,
114198702Smckusick                                             SourceLocation(), SourceLocation(),
1151590Srgrimes                                             0, 0);
11663402Sdwmalone  R->MayHaveOutOfDateDef = false;
11763402Sdwmalone  return R;
11863402Sdwmalone}
1191590Srgrimes
1201590Srgrimesvoid
1211590SrgrimesCXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
122160917Sbms                        unsigned NumBases) {
123160917Sbms  ASTContext &C = getASTContext();
124160917Sbms
1251590Srgrimes  if (!data().Bases.isOffset() && data().NumBases > 0)
1261590Srgrimes    C.Deallocate(data().getBases());
1271590Srgrimes
1281590Srgrimes  if (NumBases) {
1291590Srgrimes    // C++ [dcl.init.aggr]p1:
1301590Srgrimes    //   An aggregate is [...] a class with [...] no base classes [...].
1311590Srgrimes    data().Aggregate = false;
1321590Srgrimes
1331590Srgrimes    // C++ [class]p4:
1341590Srgrimes    //   A POD-struct is an aggregate class...
1351590Srgrimes    data().PlainOldData = false;
1361590Srgrimes  }
1371590Srgrimes
1381590Srgrimes  // The set of seen virtual base types.
1391590Srgrimes  llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
1401590Srgrimes
141220448Sedwin  // The virtual bases of this class.
142220448Sedwin  SmallVector<const CXXBaseSpecifier *, 8> VBases;
1431590Srgrimes
144220448Sedwin  data().Bases = new(C) CXXBaseSpecifier [NumBases];
145220448Sedwin  data().NumBases = NumBases;
1461590Srgrimes  for (unsigned i = 0; i < NumBases; ++i) {
1471590Srgrimes    data().getBases()[i] = *Bases[i];
1481590Srgrimes    // Keep track of inherited vbases for this base class.
1491590Srgrimes    const CXXBaseSpecifier *Base = Bases[i];
150102944Sdwmalone    QualType BaseType = Base->getType();
15193525Sdwmalone    // Skip dependent types; we can't do any checking on them now.
1521590Srgrimes    if (BaseType->isDependentType())
1531590Srgrimes      continue;
1541590Srgrimes    CXXRecordDecl *BaseClassDecl
1551590Srgrimes      = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
156220448Sedwin
1571590Srgrimes    // A class with a non-empty base class is not empty.
1581590Srgrimes    // FIXME: Standard ref?
1591590Srgrimes    if (!BaseClassDecl->isEmpty()) {
160220448Sedwin      if (!data().Empty) {
1611590Srgrimes        // C++0x [class]p7:
1621590Srgrimes        //   A standard-layout class is a class that:
1631590Srgrimes        //    [...]
1641590Srgrimes        //    -- either has no non-static data members in the most derived
1651590Srgrimes        //       class and at most one base class with non-static data members,
1661590Srgrimes        //       or has no base classes with non-static data members, and
1671590Srgrimes        // If this is the second non-empty base, then neither of these two
1681590Srgrimes        // clauses can be true.
169220448Sedwin        data().IsStandardLayout = false;
1701590Srgrimes      }
1711590Srgrimes
172220448Sedwin      data().Empty = false;
1731590Srgrimes      data().HasNoNonEmptyBases = false;
1741590Srgrimes    }
1751590Srgrimes
1761590Srgrimes    // C++ [class.virtual]p1:
17763402Sdwmalone    //   A class that declares or inherits a virtual function is called a
17863402Sdwmalone    //   polymorphic class.
179227170Sed    if (BaseClassDecl->isPolymorphic())
180220448Sedwin      data().Polymorphic = true;
181220448Sedwin
18263402Sdwmalone    // C++0x [class]p7:
18370100Sume    //   A standard-layout class is a class that: [...]
18470100Sume    //    -- has no non-standard-layout base classes
18570100Sume    if (!BaseClassDecl->isStandardLayout())
18663402Sdwmalone      data().IsStandardLayout = false;
18770100Sume
18863402Sdwmalone    // Record if this base is the first non-literal field or base.
18963402Sdwmalone    if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
19063402Sdwmalone      data().HasNonLiteralTypeFieldsOrBases = true;
19163402Sdwmalone
19263402Sdwmalone    // Now go through all virtual bases of this base and add them.
19363402Sdwmalone    for (CXXRecordDecl::base_class_iterator VBase =
19470100Sume          BaseClassDecl->vbases_begin(),
19570100Sume         E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
19670100Sume      // Add this base if it's not already in the list.
19770100Sume      if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType()))) {
19870100Sume        VBases.push_back(VBase);
199160917Sbms
20070100Sume        // C++11 [class.copy]p8:
201160917Sbms        //   The implicitly-declared copy constructor for a class X will have
20270100Sume        //   the form 'X::X(const X&)' if each [...] virtual base class B of X
20370100Sume        //   has a copy constructor whose first parameter is of type
20470100Sume        //   'const B&' or 'const volatile B&' [...]
20570100Sume        if (CXXRecordDecl *VBaseDecl = VBase->getType()->getAsCXXRecordDecl())
20670100Sume          if (!VBaseDecl->hasCopyConstructorWithConstParam())
20770100Sume            data().ImplicitCopyConstructorHasConstParam = false;
20870100Sume      }
20970100Sume    }
21070100Sume
21170100Sume    if (Base->isVirtual()) {
21270100Sume      // Add this base if it's not already in the list.
21370100Sume      if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
21470100Sume        VBases.push_back(Base);
21570100Sume
21670100Sume      // C++0x [meta.unary.prop] is_empty:
21770100Sume      //    T is a class type, but not a union type, with ... no virtual base
21870100Sume      //    classes
21970100Sume      data().Empty = false;
22070100Sume
22170100Sume      // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
22263402Sdwmalone      //   A [default constructor, copy/move constructor, or copy/move assignment
22363402Sdwmalone      //   operator for a class X] is trivial [...] if:
22463402Sdwmalone      //    -- class X has [...] no virtual base classes
225220448Sedwin      data().HasTrivialSpecialMembers &= SMF_Destructor;
22663402Sdwmalone
22763402Sdwmalone      // C++0x [class]p7:
228146756Scharnier      //   A standard-layout class is a class that: [...]
22970100Sume      //    -- has [...] no virtual base classes
23070100Sume      data().IsStandardLayout = false;
23170100Sume
23270100Sume      // C++11 [dcl.constexpr]p4:
23370100Sume      //   In the definition of a constexpr constructor [...]
23470100Sume      //    -- the class shall not have any virtual base classes
23570100Sume      data().DefaultedDefaultConstructorIsConstexpr = false;
23693525Sdwmalone    } else {
23791433Sfenner      // C++ [class.ctor]p5:
23891433Sfenner      //   A default constructor is trivial [...] if:
23991433Sfenner      //    -- all the direct base classes of its class have trivial default
24091433Sfenner      //       constructors.
24193525Sdwmalone      if (!BaseClassDecl->hasTrivialDefaultConstructor())
24263402Sdwmalone        data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
24363402Sdwmalone
24463402Sdwmalone      // C++0x [class.copy]p13:
24563402Sdwmalone      //   A copy/move constructor for class X is trivial if [...]
24663402Sdwmalone      //    [...]
2471590Srgrimes      //    -- the constructor selected to copy/move each direct base class
2481590Srgrimes      //       subobject is trivial, and
249227170Sed      if (!BaseClassDecl->hasTrivialCopyConstructor())
250102944Sdwmalone        data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
2511590Srgrimes      // If the base class doesn't have a simple move constructor, we'll eagerly
2521590Srgrimes      // declare it and perform overload resolution to determine which function
2531590Srgrimes      // it actually calls. If it does have a simple move constructor, this
2541590Srgrimes      // check is correct.
2551590Srgrimes      if (!BaseClassDecl->hasTrivialMoveConstructor())
2561590Srgrimes        data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
2571590Srgrimes
2581590Srgrimes      // C++0x [class.copy]p27:
25927604Scharnier      //   A copy/move assignment operator for class X is trivial if [...]
26027604Scharnier      //    [...]
2611590Srgrimes      //    -- the assignment operator selected to copy/move each direct base
2621590Srgrimes      //       class subobject is trivial, and
2631590Srgrimes      if (!BaseClassDecl->hasTrivialCopyAssignment())
2641590Srgrimes        data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
2651590Srgrimes      // If the base class doesn't have a simple move assignment, we'll eagerly
2661590Srgrimes      // declare it and perform overload resolution to determine which function
2671590Srgrimes      // it actually calls. If it does have a simple move assignment, this
26827604Scharnier      // check is correct.
26927604Scharnier      if (!BaseClassDecl->hasTrivialMoveAssignment())
2701590Srgrimes        data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
2711590Srgrimes
2721590Srgrimes      // C++11 [class.ctor]p6:
273227170Sed      //   If that user-written default constructor would satisfy the
274102944Sdwmalone      //   requirements of a constexpr constructor, the implicitly-defined
2751590Srgrimes      //   default constructor is constexpr.
276102944Sdwmalone      if (!BaseClassDecl->hasConstexprDefaultConstructor())
2771590Srgrimes        data().DefaultedDefaultConstructorIsConstexpr = false;
2781590Srgrimes    }
2791590Srgrimes
2801590Srgrimes    // C++ [class.ctor]p3:
2811590Srgrimes    //   A destructor is trivial if all the direct base classes of its class
2821590Srgrimes    //   have trivial destructors.
2831590Srgrimes    if (!BaseClassDecl->hasTrivialDestructor())
2841590Srgrimes      data().HasTrivialSpecialMembers &= ~SMF_Destructor;
2851590Srgrimes
2861590Srgrimes    if (!BaseClassDecl->hasIrrelevantDestructor())
2871590Srgrimes      data().HasIrrelevantDestructor = false;
28827604Scharnier
289102944Sdwmalone    // C++11 [class.copy]p18:
2901590Srgrimes    //   The implicitly-declared copy assignment oeprator for a class X will
29163402Sdwmalone    //   have the form 'X& X::operator=(const X&)' if each direct base class B
292160917Sbms    //   of X has a copy assignment operator whose parameter is of type 'const
293160917Sbms    //   B&', 'const volatile B&', or 'B' [...]
29463402Sdwmalone    if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
2951590Srgrimes      data().ImplicitCopyAssignmentHasConstParam = false;
2961590Srgrimes
297    // C++11 [class.copy]p8:
298    //   The implicitly-declared copy constructor for a class X will have
299    //   the form 'X::X(const X&)' if each direct [...] base class B of X
300    //   has a copy constructor whose first parameter is of type
301    //   'const B&' or 'const volatile B&' [...]
302    if (!BaseClassDecl->hasCopyConstructorWithConstParam())
303      data().ImplicitCopyConstructorHasConstParam = false;
304
305    // A class has an Objective-C object member if... or any of its bases
306    // has an Objective-C object member.
307    if (BaseClassDecl->hasObjectMember())
308      setHasObjectMember(true);
309
310    if (BaseClassDecl->hasVolatileMember())
311      setHasVolatileMember(true);
312
313    // Keep track of the presence of mutable fields.
314    if (BaseClassDecl->hasMutableFields())
315      data().HasMutableFields = true;
316
317    if (BaseClassDecl->hasUninitializedReferenceMember())
318      data().HasUninitializedReferenceMember = true;
319
320    addedClassSubobject(BaseClassDecl);
321  }
322
323  if (VBases.empty())
324    return;
325
326  // Create base specifier for any direct or indirect virtual bases.
327  data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
328  data().NumVBases = VBases.size();
329  for (int I = 0, E = VBases.size(); I != E; ++I) {
330    QualType Type = VBases[I]->getType();
331    if (!Type->isDependentType())
332      addedClassSubobject(Type->getAsCXXRecordDecl());
333    data().getVBases()[I] = *VBases[I];
334  }
335}
336
337void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
338  // C++11 [class.copy]p11:
339  //   A defaulted copy/move constructor for a class X is defined as
340  //   deleted if X has:
341  //    -- a direct or virtual base class B that cannot be copied/moved [...]
342  //    -- a non-static data member of class type M (or array thereof)
343  //       that cannot be copied or moved [...]
344  if (!Subobj->hasSimpleMoveConstructor())
345    data().NeedOverloadResolutionForMoveConstructor = true;
346
347  // C++11 [class.copy]p23:
348  //   A defaulted copy/move assignment operator for a class X is defined as
349  //   deleted if X has:
350  //    -- a direct or virtual base class B that cannot be copied/moved [...]
351  //    -- a non-static data member of class type M (or array thereof)
352  //        that cannot be copied or moved [...]
353  if (!Subobj->hasSimpleMoveAssignment())
354    data().NeedOverloadResolutionForMoveAssignment = true;
355
356  // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
357  //   A defaulted [ctor or dtor] for a class X is defined as
358  //   deleted if X has:
359  //    -- any direct or virtual base class [...] has a type with a destructor
360  //       that is deleted or inaccessible from the defaulted [ctor or dtor].
361  //    -- any non-static data member has a type with a destructor
362  //       that is deleted or inaccessible from the defaulted [ctor or dtor].
363  if (!Subobj->hasSimpleDestructor()) {
364    data().NeedOverloadResolutionForMoveConstructor = true;
365    data().NeedOverloadResolutionForDestructor = true;
366  }
367}
368
369/// Callback function for CXXRecordDecl::forallBases that acknowledges
370/// that it saw a base class.
371static bool SawBase(const CXXRecordDecl *, void *) {
372  return true;
373}
374
375bool CXXRecordDecl::hasAnyDependentBases() const {
376  if (!isDependentContext())
377    return false;
378
379  return !forallBases(SawBase, 0);
380}
381
382bool CXXRecordDecl::isTriviallyCopyable() const {
383  // C++0x [class]p5:
384  //   A trivially copyable class is a class that:
385  //   -- has no non-trivial copy constructors,
386  if (hasNonTrivialCopyConstructor()) return false;
387  //   -- has no non-trivial move constructors,
388  if (hasNonTrivialMoveConstructor()) return false;
389  //   -- has no non-trivial copy assignment operators,
390  if (hasNonTrivialCopyAssignment()) return false;
391  //   -- has no non-trivial move assignment operators, and
392  if (hasNonTrivialMoveAssignment()) return false;
393  //   -- has a trivial destructor.
394  if (!hasTrivialDestructor()) return false;
395
396  return true;
397}
398
399void CXXRecordDecl::markedVirtualFunctionPure() {
400  // C++ [class.abstract]p2:
401  //   A class is abstract if it has at least one pure virtual function.
402  data().Abstract = true;
403}
404
405void CXXRecordDecl::addedMember(Decl *D) {
406  if (!D->isImplicit() &&
407      !isa<FieldDecl>(D) &&
408      !isa<IndirectFieldDecl>(D) &&
409      (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class ||
410        cast<TagDecl>(D)->getTagKind() == TTK_Interface))
411    data().HasOnlyCMembers = false;
412
413  // Ignore friends and invalid declarations.
414  if (D->getFriendObjectKind() || D->isInvalidDecl())
415    return;
416
417  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
418  if (FunTmpl)
419    D = FunTmpl->getTemplatedDecl();
420
421  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
422    if (Method->isVirtual()) {
423      // C++ [dcl.init.aggr]p1:
424      //   An aggregate is an array or a class with [...] no virtual functions.
425      data().Aggregate = false;
426
427      // C++ [class]p4:
428      //   A POD-struct is an aggregate class...
429      data().PlainOldData = false;
430
431      // Virtual functions make the class non-empty.
432      // FIXME: Standard ref?
433      data().Empty = false;
434
435      // C++ [class.virtual]p1:
436      //   A class that declares or inherits a virtual function is called a
437      //   polymorphic class.
438      data().Polymorphic = true;
439
440      // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
441      //   A [default constructor, copy/move constructor, or copy/move
442      //   assignment operator for a class X] is trivial [...] if:
443      //    -- class X has no virtual functions [...]
444      data().HasTrivialSpecialMembers &= SMF_Destructor;
445
446      // C++0x [class]p7:
447      //   A standard-layout class is a class that: [...]
448      //    -- has no virtual functions
449      data().IsStandardLayout = false;
450    }
451  }
452
453  // Notify the listener if an implicit member was added after the definition
454  // was completed.
455  if (!isBeingDefined() && D->isImplicit())
456    if (ASTMutationListener *L = getASTMutationListener())
457      L->AddedCXXImplicitMember(data().Definition, D);
458
459  // The kind of special member this declaration is, if any.
460  unsigned SMKind = 0;
461
462  // Handle constructors.
463  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
464    if (!Constructor->isImplicit()) {
465      // Note that we have a user-declared constructor.
466      data().UserDeclaredConstructor = true;
467
468      // C++ [class]p4:
469      //   A POD-struct is an aggregate class [...]
470      // Since the POD bit is meant to be C++03 POD-ness, clear it even if the
471      // type is technically an aggregate in C++0x since it wouldn't be in 03.
472      data().PlainOldData = false;
473    }
474
475    // Technically, "user-provided" is only defined for special member
476    // functions, but the intent of the standard is clearly that it should apply
477    // to all functions.
478    bool UserProvided = Constructor->isUserProvided();
479
480    if (Constructor->isDefaultConstructor()) {
481      SMKind |= SMF_DefaultConstructor;
482
483      if (UserProvided)
484        data().UserProvidedDefaultConstructor = true;
485      if (Constructor->isConstexpr())
486        data().HasConstexprDefaultConstructor = true;
487    }
488
489    if (!FunTmpl) {
490      unsigned Quals;
491      if (Constructor->isCopyConstructor(Quals)) {
492        SMKind |= SMF_CopyConstructor;
493
494        if (Quals & Qualifiers::Const)
495          data().HasDeclaredCopyConstructorWithConstParam = true;
496      } else if (Constructor->isMoveConstructor())
497        SMKind |= SMF_MoveConstructor;
498    }
499
500    // Record if we see any constexpr constructors which are neither copy
501    // nor move constructors.
502    if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
503      data().HasConstexprNonCopyMoveConstructor = true;
504
505    // C++ [dcl.init.aggr]p1:
506    //   An aggregate is an array or a class with no user-declared
507    //   constructors [...].
508    // C++11 [dcl.init.aggr]p1:
509    //   An aggregate is an array or a class with no user-provided
510    //   constructors [...].
511    if (getASTContext().getLangOpts().CPlusPlus11
512          ? UserProvided : !Constructor->isImplicit())
513      data().Aggregate = false;
514  }
515
516  // Handle destructors.
517  if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) {
518    SMKind |= SMF_Destructor;
519
520    if (!DD->isImplicit())
521      data().HasIrrelevantDestructor = false;
522
523    // C++11 [class.dtor]p5:
524    //   A destructor is trivial if [...] the destructor is not virtual.
525    if (DD->isVirtual())
526      data().HasTrivialSpecialMembers &= ~SMF_Destructor;
527  }
528
529  // Handle member functions.
530  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
531    if (Method->isCopyAssignmentOperator()) {
532      SMKind |= SMF_CopyAssignment;
533
534      const ReferenceType *ParamTy =
535        Method->getParamDecl(0)->getType()->getAs<ReferenceType>();
536      if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
537        data().HasDeclaredCopyAssignmentWithConstParam = true;
538    }
539
540    if (Method->isMoveAssignmentOperator())
541      SMKind |= SMF_MoveAssignment;
542
543    // Keep the list of conversion functions up-to-date.
544    if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
545      // FIXME: We use the 'unsafe' accessor for the access specifier here,
546      // because Sema may not have set it yet. That's really just a misdesign
547      // in Sema. However, LLDB *will* have set the access specifier correctly,
548      // and adds declarations after the class is technically completed,
549      // so completeDefinition()'s overriding of the access specifiers doesn't
550      // work.
551      AccessSpecifier AS = Conversion->getAccessUnsafe();
552
553      if (Conversion->getPrimaryTemplate()) {
554        // We don't record specializations.
555      } else if (FunTmpl) {
556        if (FunTmpl->getPreviousDecl())
557          data().Conversions.replace(FunTmpl->getPreviousDecl(),
558                                     FunTmpl, AS);
559        else
560          data().Conversions.addDecl(getASTContext(), FunTmpl, AS);
561      } else {
562        if (Conversion->getPreviousDecl())
563          data().Conversions.replace(Conversion->getPreviousDecl(),
564                                     Conversion, AS);
565        else
566          data().Conversions.addDecl(getASTContext(), Conversion, AS);
567      }
568    }
569
570    if (SMKind) {
571      // If this is the first declaration of a special member, we no longer have
572      // an implicit trivial special member.
573      data().HasTrivialSpecialMembers &=
574        data().DeclaredSpecialMembers | ~SMKind;
575
576      if (!Method->isImplicit() && !Method->isUserProvided()) {
577        // This method is user-declared but not user-provided. We can't work out
578        // whether it's trivial yet (not until we get to the end of the class).
579        // We'll handle this method in finishedDefaultedOrDeletedMember.
580      } else if (Method->isTrivial())
581        data().HasTrivialSpecialMembers |= SMKind;
582      else
583        data().DeclaredNonTrivialSpecialMembers |= SMKind;
584
585      // Note when we have declared a declared special member, and suppress the
586      // implicit declaration of this special member.
587      data().DeclaredSpecialMembers |= SMKind;
588
589      if (!Method->isImplicit()) {
590        data().UserDeclaredSpecialMembers |= SMKind;
591
592        // C++03 [class]p4:
593        //   A POD-struct is an aggregate class that has [...] no user-defined
594        //   copy assignment operator and no user-defined destructor.
595        //
596        // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
597        // aggregates could not have any constructors, clear it even for an
598        // explicitly defaulted or deleted constructor.
599        // type is technically an aggregate in C++0x since it wouldn't be in 03.
600        //
601        // Also, a user-declared move assignment operator makes a class non-POD.
602        // This is an extension in C++03.
603        data().PlainOldData = false;
604      }
605    }
606
607    return;
608  }
609
610  // Handle non-static data members.
611  if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
612    // C++ [class.bit]p2:
613    //   A declaration for a bit-field that omits the identifier declares an
614    //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
615    //   initialized.
616    if (Field->isUnnamedBitfield())
617      return;
618
619    // C++ [dcl.init.aggr]p1:
620    //   An aggregate is an array or a class (clause 9) with [...] no
621    //   private or protected non-static data members (clause 11).
622    //
623    // A POD must be an aggregate.
624    if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
625      data().Aggregate = false;
626      data().PlainOldData = false;
627    }
628
629    // C++0x [class]p7:
630    //   A standard-layout class is a class that:
631    //    [...]
632    //    -- has the same access control for all non-static data members,
633    switch (D->getAccess()) {
634    case AS_private:    data().HasPrivateFields = true;   break;
635    case AS_protected:  data().HasProtectedFields = true; break;
636    case AS_public:     data().HasPublicFields = true;    break;
637    case AS_none:       llvm_unreachable("Invalid access specifier");
638    };
639    if ((data().HasPrivateFields + data().HasProtectedFields +
640         data().HasPublicFields) > 1)
641      data().IsStandardLayout = false;
642
643    // Keep track of the presence of mutable fields.
644    if (Field->isMutable())
645      data().HasMutableFields = true;
646
647    // C++0x [class]p9:
648    //   A POD struct is a class that is both a trivial class and a
649    //   standard-layout class, and has no non-static data members of type
650    //   non-POD struct, non-POD union (or array of such types).
651    //
652    // Automatic Reference Counting: the presence of a member of Objective-C pointer type
653    // that does not explicitly have no lifetime makes the class a non-POD.
654    // However, we delay setting PlainOldData to false in this case so that
655    // Sema has a chance to diagnostic causes where the same class will be
656    // non-POD with Automatic Reference Counting but a POD without ARC.
657    // In this case, the class will become a non-POD class when we complete
658    // the definition.
659    ASTContext &Context = getASTContext();
660    QualType T = Context.getBaseElementType(Field->getType());
661    if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
662      if (!Context.getLangOpts().ObjCAutoRefCount ||
663          T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)
664        setHasObjectMember(true);
665    } else if (!T.isPODType(Context))
666      data().PlainOldData = false;
667
668    if (T->isReferenceType()) {
669      if (!Field->hasInClassInitializer())
670        data().HasUninitializedReferenceMember = true;
671
672      // C++0x [class]p7:
673      //   A standard-layout class is a class that:
674      //    -- has no non-static data members of type [...] reference,
675      data().IsStandardLayout = false;
676    }
677
678    // Record if this field is the first non-literal or volatile field or base.
679    if (!T->isLiteralType(Context) || T.isVolatileQualified())
680      data().HasNonLiteralTypeFieldsOrBases = true;
681
682    if (Field->hasInClassInitializer()) {
683      data().HasInClassInitializer = true;
684
685      // C++11 [class]p5:
686      //   A default constructor is trivial if [...] no non-static data member
687      //   of its class has a brace-or-equal-initializer.
688      data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
689
690      // C++11 [dcl.init.aggr]p1:
691      //   An aggregate is a [...] class with [...] no
692      //   brace-or-equal-initializers for non-static data members.
693      //
694      // This rule was removed in C++1y.
695      if (!getASTContext().getLangOpts().CPlusPlus1y)
696        data().Aggregate = false;
697
698      // C++11 [class]p10:
699      //   A POD struct is [...] a trivial class.
700      data().PlainOldData = false;
701    }
702
703    // C++11 [class.copy]p23:
704    //   A defaulted copy/move assignment operator for a class X is defined
705    //   as deleted if X has:
706    //    -- a non-static data member of reference type
707    if (T->isReferenceType())
708      data().DefaultedMoveAssignmentIsDeleted = true;
709
710    if (const RecordType *RecordTy = T->getAs<RecordType>()) {
711      CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
712      if (FieldRec->getDefinition()) {
713        addedClassSubobject(FieldRec);
714
715        // C++11 [class.ctor]p5, C++11 [class.copy]p11:
716        //   A defaulted [special member] for a class X is defined as
717        //   deleted if:
718        //    -- X is a union-like class that has a variant member with a
719        //       non-trivial [corresponding special member]
720        if (isUnion()) {
721          if (FieldRec->hasNonTrivialMoveConstructor())
722            data().DefaultedMoveConstructorIsDeleted = true;
723          if (FieldRec->hasNonTrivialMoveAssignment())
724            data().DefaultedMoveAssignmentIsDeleted = true;
725          if (FieldRec->hasNonTrivialDestructor())
726            data().DefaultedDestructorIsDeleted = true;
727        }
728
729        // C++0x [class.ctor]p5:
730        //   A default constructor is trivial [...] if:
731        //    -- for all the non-static data members of its class that are of
732        //       class type (or array thereof), each such class has a trivial
733        //       default constructor.
734        if (!FieldRec->hasTrivialDefaultConstructor())
735          data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
736
737        // C++0x [class.copy]p13:
738        //   A copy/move constructor for class X is trivial if [...]
739        //    [...]
740        //    -- for each non-static data member of X that is of class type (or
741        //       an array thereof), the constructor selected to copy/move that
742        //       member is trivial;
743        if (!FieldRec->hasTrivialCopyConstructor())
744          data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
745        // If the field doesn't have a simple move constructor, we'll eagerly
746        // declare the move constructor for this class and we'll decide whether
747        // it's trivial then.
748        if (!FieldRec->hasTrivialMoveConstructor())
749          data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
750
751        // C++0x [class.copy]p27:
752        //   A copy/move assignment operator for class X is trivial if [...]
753        //    [...]
754        //    -- for each non-static data member of X that is of class type (or
755        //       an array thereof), the assignment operator selected to
756        //       copy/move that member is trivial;
757        if (!FieldRec->hasTrivialCopyAssignment())
758          data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
759        // If the field doesn't have a simple move assignment, we'll eagerly
760        // declare the move assignment for this class and we'll decide whether
761        // it's trivial then.
762        if (!FieldRec->hasTrivialMoveAssignment())
763          data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
764
765        if (!FieldRec->hasTrivialDestructor())
766          data().HasTrivialSpecialMembers &= ~SMF_Destructor;
767        if (!FieldRec->hasIrrelevantDestructor())
768          data().HasIrrelevantDestructor = false;
769        if (FieldRec->hasObjectMember())
770          setHasObjectMember(true);
771        if (FieldRec->hasVolatileMember())
772          setHasVolatileMember(true);
773
774        // C++0x [class]p7:
775        //   A standard-layout class is a class that:
776        //    -- has no non-static data members of type non-standard-layout
777        //       class (or array of such types) [...]
778        if (!FieldRec->isStandardLayout())
779          data().IsStandardLayout = false;
780
781        // C++0x [class]p7:
782        //   A standard-layout class is a class that:
783        //    [...]
784        //    -- has no base classes of the same type as the first non-static
785        //       data member.
786        // We don't want to expend bits in the state of the record decl
787        // tracking whether this is the first non-static data member so we
788        // cheat a bit and use some of the existing state: the empty bit.
789        // Virtual bases and virtual methods make a class non-empty, but they
790        // also make it non-standard-layout so we needn't check here.
791        // A non-empty base class may leave the class standard-layout, but not
792        // if we have arrived here, and have at least on non-static data
793        // member. If IsStandardLayout remains true, then the first non-static
794        // data member must come through here with Empty still true, and Empty
795        // will subsequently be set to false below.
796        if (data().IsStandardLayout && data().Empty) {
797          for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
798                                                        BE = bases_end();
799               BI != BE; ++BI) {
800            if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
801              data().IsStandardLayout = false;
802              break;
803            }
804          }
805        }
806
807        // Keep track of the presence of mutable fields.
808        if (FieldRec->hasMutableFields())
809          data().HasMutableFields = true;
810
811        // C++11 [class.copy]p13:
812        //   If the implicitly-defined constructor would satisfy the
813        //   requirements of a constexpr constructor, the implicitly-defined
814        //   constructor is constexpr.
815        // C++11 [dcl.constexpr]p4:
816        //    -- every constructor involved in initializing non-static data
817        //       members [...] shall be a constexpr constructor
818        if (!Field->hasInClassInitializer() &&
819            !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
820          // The standard requires any in-class initializer to be a constant
821          // expression. We consider this to be a defect.
822          data().DefaultedDefaultConstructorIsConstexpr = false;
823
824        // C++11 [class.copy]p8:
825        //   The implicitly-declared copy constructor for a class X will have
826        //   the form 'X::X(const X&)' if [...] for all the non-static data
827        //   members of X that are of a class type M (or array thereof), each
828        //   such class type has a copy constructor whose first parameter is
829        //   of type 'const M&' or 'const volatile M&'.
830        if (!FieldRec->hasCopyConstructorWithConstParam())
831          data().ImplicitCopyConstructorHasConstParam = false;
832
833        // C++11 [class.copy]p18:
834        //   The implicitly-declared copy assignment oeprator for a class X will
835        //   have the form 'X& X::operator=(const X&)' if [...] for all the
836        //   non-static data members of X that are of a class type M (or array
837        //   thereof), each such class type has a copy assignment operator whose
838        //   parameter is of type 'const M&', 'const volatile M&' or 'M'.
839        if (!FieldRec->hasCopyAssignmentWithConstParam())
840          data().ImplicitCopyAssignmentHasConstParam = false;
841
842        if (FieldRec->hasUninitializedReferenceMember() &&
843            !Field->hasInClassInitializer())
844          data().HasUninitializedReferenceMember = true;
845      }
846    } else {
847      // Base element type of field is a non-class type.
848      if (!T->isLiteralType(Context) ||
849          (!Field->hasInClassInitializer() && !isUnion()))
850        data().DefaultedDefaultConstructorIsConstexpr = false;
851
852      // C++11 [class.copy]p23:
853      //   A defaulted copy/move assignment operator for a class X is defined
854      //   as deleted if X has:
855      //    -- a non-static data member of const non-class type (or array
856      //       thereof)
857      if (T.isConstQualified())
858        data().DefaultedMoveAssignmentIsDeleted = true;
859    }
860
861    // C++0x [class]p7:
862    //   A standard-layout class is a class that:
863    //    [...]
864    //    -- either has no non-static data members in the most derived
865    //       class and at most one base class with non-static data members,
866    //       or has no base classes with non-static data members, and
867    // At this point we know that we have a non-static data member, so the last
868    // clause holds.
869    if (!data().HasNoNonEmptyBases)
870      data().IsStandardLayout = false;
871
872    // If this is not a zero-length bit-field, then the class is not empty.
873    if (data().Empty) {
874      if (!Field->isBitField() ||
875          (!Field->getBitWidth()->isTypeDependent() &&
876           !Field->getBitWidth()->isValueDependent() &&
877           Field->getBitWidthValue(Context) != 0))
878        data().Empty = false;
879    }
880  }
881
882  // Handle using declarations of conversion functions.
883  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
884    if (Shadow->getDeclName().getNameKind()
885          == DeclarationName::CXXConversionFunctionName)
886      data().Conversions.addDecl(getASTContext(), Shadow, Shadow->getAccess());
887}
888
889void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
890  assert(!D->isImplicit() && !D->isUserProvided());
891
892  // The kind of special member this declaration is, if any.
893  unsigned SMKind = 0;
894
895  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
896    if (Constructor->isDefaultConstructor()) {
897      SMKind |= SMF_DefaultConstructor;
898      if (Constructor->isConstexpr())
899        data().HasConstexprDefaultConstructor = true;
900    }
901    if (Constructor->isCopyConstructor())
902      SMKind |= SMF_CopyConstructor;
903    else if (Constructor->isMoveConstructor())
904      SMKind |= SMF_MoveConstructor;
905    else if (Constructor->isConstexpr())
906      // We may now know that the constructor is constexpr.
907      data().HasConstexprNonCopyMoveConstructor = true;
908  } else if (isa<CXXDestructorDecl>(D))
909    SMKind |= SMF_Destructor;
910  else if (D->isCopyAssignmentOperator())
911    SMKind |= SMF_CopyAssignment;
912  else if (D->isMoveAssignmentOperator())
913    SMKind |= SMF_MoveAssignment;
914
915  // Update which trivial / non-trivial special members we have.
916  // addedMember will have skipped this step for this member.
917  if (D->isTrivial())
918    data().HasTrivialSpecialMembers |= SMKind;
919  else
920    data().DeclaredNonTrivialSpecialMembers |= SMKind;
921}
922
923bool CXXRecordDecl::isCLike() const {
924  if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface ||
925      !TemplateOrInstantiation.isNull())
926    return false;
927  if (!hasDefinition())
928    return true;
929
930  return isPOD() && data().HasOnlyCMembers;
931}
932
933void CXXRecordDecl::getCaptureFields(
934       llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
935       FieldDecl *&ThisCapture) const {
936  Captures.clear();
937  ThisCapture = 0;
938
939  LambdaDefinitionData &Lambda = getLambdaData();
940  RecordDecl::field_iterator Field = field_begin();
941  for (LambdaExpr::Capture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
942       C != CEnd; ++C, ++Field) {
943    if (C->capturesThis()) {
944      ThisCapture = *Field;
945      continue;
946    }
947
948    Captures[C->getCapturedVar()] = *Field;
949  }
950}
951
952
953static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
954  QualType T;
955  if (isa<UsingShadowDecl>(Conv))
956    Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
957  if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
958    T = ConvTemp->getTemplatedDecl()->getResultType();
959  else
960    T = cast<CXXConversionDecl>(Conv)->getConversionType();
961  return Context.getCanonicalType(T);
962}
963
964/// Collect the visible conversions of a base class.
965///
966/// \param Record a base class of the class we're considering
967/// \param InVirtual whether this base class is a virtual base (or a base
968///   of a virtual base)
969/// \param Access the access along the inheritance path to this base
970/// \param ParentHiddenTypes the conversions provided by the inheritors
971///   of this base
972/// \param Output the set to which to add conversions from non-virtual bases
973/// \param VOutput the set to which to add conversions from virtual bases
974/// \param HiddenVBaseCs the set of conversions which were hidden in a
975///   virtual base along some inheritance path
976static void CollectVisibleConversions(ASTContext &Context,
977                                      CXXRecordDecl *Record,
978                                      bool InVirtual,
979                                      AccessSpecifier Access,
980                  const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
981                                      ASTUnresolvedSet &Output,
982                                      UnresolvedSetImpl &VOutput,
983                           llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
984  // The set of types which have conversions in this class or its
985  // subclasses.  As an optimization, we don't copy the derived set
986  // unless it might change.
987  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
988  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
989
990  // Collect the direct conversions and figure out which conversions
991  // will be hidden in the subclasses.
992  CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
993  CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
994  if (ConvI != ConvE) {
995    HiddenTypesBuffer = ParentHiddenTypes;
996    HiddenTypes = &HiddenTypesBuffer;
997
998    for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
999      CanQualType ConvType(GetConversionType(Context, I.getDecl()));
1000      bool Hidden = ParentHiddenTypes.count(ConvType);
1001      if (!Hidden)
1002        HiddenTypesBuffer.insert(ConvType);
1003
1004      // If this conversion is hidden and we're in a virtual base,
1005      // remember that it's hidden along some inheritance path.
1006      if (Hidden && InVirtual)
1007        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1008
1009      // If this conversion isn't hidden, add it to the appropriate output.
1010      else if (!Hidden) {
1011        AccessSpecifier IAccess
1012          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1013
1014        if (InVirtual)
1015          VOutput.addDecl(I.getDecl(), IAccess);
1016        else
1017          Output.addDecl(Context, I.getDecl(), IAccess);
1018      }
1019    }
1020  }
1021
1022  // Collect information recursively from any base classes.
1023  for (CXXRecordDecl::base_class_iterator
1024         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1025    const RecordType *RT = I->getType()->getAs<RecordType>();
1026    if (!RT) continue;
1027
1028    AccessSpecifier BaseAccess
1029      = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
1030    bool BaseInVirtual = InVirtual || I->isVirtual();
1031
1032    CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1033    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1034                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1035  }
1036}
1037
1038/// Collect the visible conversions of a class.
1039///
1040/// This would be extremely straightforward if it weren't for virtual
1041/// bases.  It might be worth special-casing that, really.
1042static void CollectVisibleConversions(ASTContext &Context,
1043                                      CXXRecordDecl *Record,
1044                                      ASTUnresolvedSet &Output) {
1045  // The collection of all conversions in virtual bases that we've
1046  // found.  These will be added to the output as long as they don't
1047  // appear in the hidden-conversions set.
1048  UnresolvedSet<8> VBaseCs;
1049
1050  // The set of conversions in virtual bases that we've determined to
1051  // be hidden.
1052  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1053
1054  // The set of types hidden by classes derived from this one.
1055  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1056
1057  // Go ahead and collect the direct conversions and add them to the
1058  // hidden-types set.
1059  CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1060  CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1061  Output.append(Context, ConvI, ConvE);
1062  for (; ConvI != ConvE; ++ConvI)
1063    HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
1064
1065  // Recursively collect conversions from base classes.
1066  for (CXXRecordDecl::base_class_iterator
1067         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1068    const RecordType *RT = I->getType()->getAs<RecordType>();
1069    if (!RT) continue;
1070
1071    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1072                              I->isVirtual(), I->getAccessSpecifier(),
1073                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1074  }
1075
1076  // Add any unhidden conversions provided by virtual bases.
1077  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1078         I != E; ++I) {
1079    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1080      Output.addDecl(Context, I.getDecl(), I.getAccess());
1081  }
1082}
1083
1084/// getVisibleConversionFunctions - get all conversion functions visible
1085/// in current class; including conversion function templates.
1086std::pair<CXXRecordDecl::conversion_iterator,CXXRecordDecl::conversion_iterator>
1087CXXRecordDecl::getVisibleConversionFunctions() {
1088  // If root class, all conversions are visible.
1089  if (bases_begin() == bases_end())
1090    return std::make_pair(data().Conversions.begin(), data().Conversions.end());
1091  // If visible conversion list is already evaluated, return it.
1092  if (!data().ComputedVisibleConversions) {
1093    CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
1094    data().ComputedVisibleConversions = true;
1095  }
1096  return std::make_pair(data().VisibleConversions.begin(),
1097                        data().VisibleConversions.end());
1098}
1099
1100void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1101  // This operation is O(N) but extremely rare.  Sema only uses it to
1102  // remove UsingShadowDecls in a class that were followed by a direct
1103  // declaration, e.g.:
1104  //   class A : B {
1105  //     using B::operator int;
1106  //     operator int();
1107  //   };
1108  // This is uncommon by itself and even more uncommon in conjunction
1109  // with sufficiently large numbers of directly-declared conversions
1110  // that asymptotic behavior matters.
1111
1112  ASTUnresolvedSet &Convs = data().Conversions;
1113  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1114    if (Convs[I].getDecl() == ConvDecl) {
1115      Convs.erase(I);
1116      assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
1117             && "conversion was found multiple times in unresolved set");
1118      return;
1119    }
1120  }
1121
1122  llvm_unreachable("conversion not found in set!");
1123}
1124
1125CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1126  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1127    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1128
1129  return 0;
1130}
1131
1132void
1133CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1134                                             TemplateSpecializationKind TSK) {
1135  assert(TemplateOrInstantiation.isNull() &&
1136         "Previous template or instantiation?");
1137  assert(!isa<ClassTemplateSpecializationDecl>(this));
1138  TemplateOrInstantiation
1139    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1140}
1141
1142TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1143  if (const ClassTemplateSpecializationDecl *Spec
1144        = dyn_cast<ClassTemplateSpecializationDecl>(this))
1145    return Spec->getSpecializationKind();
1146
1147  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1148    return MSInfo->getTemplateSpecializationKind();
1149
1150  return TSK_Undeclared;
1151}
1152
1153void
1154CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1155  if (ClassTemplateSpecializationDecl *Spec
1156      = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1157    Spec->setSpecializationKind(TSK);
1158    return;
1159  }
1160
1161  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1162    MSInfo->setTemplateSpecializationKind(TSK);
1163    return;
1164  }
1165
1166  llvm_unreachable("Not a class template or member class specialization");
1167}
1168
1169CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1170  ASTContext &Context = getASTContext();
1171  QualType ClassType = Context.getTypeDeclType(this);
1172
1173  DeclarationName Name
1174    = Context.DeclarationNames.getCXXDestructorName(
1175                                          Context.getCanonicalType(ClassType));
1176
1177  DeclContext::lookup_const_result R = lookup(Name);
1178  if (R.empty())
1179    return 0;
1180
1181  CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(R.front());
1182  return Dtor;
1183}
1184
1185void CXXRecordDecl::completeDefinition() {
1186  completeDefinition(0);
1187}
1188
1189void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1190  RecordDecl::completeDefinition();
1191
1192  if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount) {
1193    // Objective-C Automatic Reference Counting:
1194    //   If a class has a non-static data member of Objective-C pointer
1195    //   type (or array thereof), it is a non-POD type and its
1196    //   default constructor (if any), copy constructor, move constructor,
1197    //   copy assignment operator, move assignment operator, and destructor are
1198    //   non-trivial.
1199    struct DefinitionData &Data = data();
1200    Data.PlainOldData = false;
1201    Data.HasTrivialSpecialMembers = 0;
1202    Data.HasIrrelevantDestructor = false;
1203  }
1204
1205  // If the class may be abstract (but hasn't been marked as such), check for
1206  // any pure final overriders.
1207  if (mayBeAbstract()) {
1208    CXXFinalOverriderMap MyFinalOverriders;
1209    if (!FinalOverriders) {
1210      getFinalOverriders(MyFinalOverriders);
1211      FinalOverriders = &MyFinalOverriders;
1212    }
1213
1214    bool Done = false;
1215    for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1216                                     MEnd = FinalOverriders->end();
1217         M != MEnd && !Done; ++M) {
1218      for (OverridingMethods::iterator SO = M->second.begin(),
1219                                    SOEnd = M->second.end();
1220           SO != SOEnd && !Done; ++SO) {
1221        assert(SO->second.size() > 0 &&
1222               "All virtual functions have overridding virtual functions");
1223
1224        // C++ [class.abstract]p4:
1225        //   A class is abstract if it contains or inherits at least one
1226        //   pure virtual function for which the final overrider is pure
1227        //   virtual.
1228        if (SO->second.front().Method->isPure()) {
1229          data().Abstract = true;
1230          Done = true;
1231          break;
1232        }
1233      }
1234    }
1235  }
1236
1237  // Set access bits correctly on the directly-declared conversions.
1238  for (UnresolvedSetIterator I = data().Conversions.begin(),
1239                             E = data().Conversions.end();
1240       I != E; ++I)
1241    I.setAccess((*I)->getAccess());
1242}
1243
1244bool CXXRecordDecl::mayBeAbstract() const {
1245  if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1246      isDependentContext())
1247    return false;
1248
1249  for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1250                                             BEnd = bases_end();
1251       B != BEnd; ++B) {
1252    CXXRecordDecl *BaseDecl
1253      = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1254    if (BaseDecl->isAbstract())
1255      return true;
1256  }
1257
1258  return false;
1259}
1260
1261void CXXMethodDecl::anchor() { }
1262
1263bool CXXMethodDecl::isStatic() const {
1264  const CXXMethodDecl *MD = getCanonicalDecl();
1265
1266  if (MD->getStorageClass() == SC_Static)
1267    return true;
1268
1269  DeclarationName Name = getDeclName();
1270  // [class.free]p1:
1271  // Any allocation function for a class T is a static member
1272  // (even if not explicitly declared static).
1273  if (Name.getCXXOverloadedOperator() == OO_New ||
1274      Name.getCXXOverloadedOperator() == OO_Array_New)
1275    return true;
1276
1277  // [class.free]p6 Any deallocation function for a class X is a static member
1278  // (even if not explicitly declared static).
1279  if (Name.getCXXOverloadedOperator() == OO_Delete ||
1280      Name.getCXXOverloadedOperator() == OO_Array_Delete)
1281    return true;
1282
1283  return false;
1284}
1285
1286static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
1287                                 const CXXMethodDecl *BaseMD) {
1288  for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),
1289         E = DerivedMD->end_overridden_methods(); I != E; ++I) {
1290    const CXXMethodDecl *MD = *I;
1291    if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
1292      return true;
1293    if (recursivelyOverrides(MD, BaseMD))
1294      return true;
1295  }
1296  return false;
1297}
1298
1299CXXMethodDecl *
1300CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
1301                                             bool MayBeBase) {
1302  if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
1303    return this;
1304
1305  // Lookup doesn't work for destructors, so handle them separately.
1306  if (isa<CXXDestructorDecl>(this)) {
1307    CXXMethodDecl *MD = RD->getDestructor();
1308    if (MD) {
1309      if (recursivelyOverrides(MD, this))
1310        return MD;
1311      if (MayBeBase && recursivelyOverrides(this, MD))
1312        return MD;
1313    }
1314    return NULL;
1315  }
1316
1317  lookup_const_result Candidates = RD->lookup(getDeclName());
1318  for (NamedDecl * const * I = Candidates.begin(); I != Candidates.end(); ++I) {
1319    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I);
1320    if (!MD)
1321      continue;
1322    if (recursivelyOverrides(MD, this))
1323      return MD;
1324    if (MayBeBase && recursivelyOverrides(this, MD))
1325      return MD;
1326  }
1327
1328  for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1329         E = RD->bases_end(); I != E; ++I) {
1330    const RecordType *RT = I->getType()->getAs<RecordType>();
1331    if (!RT)
1332      continue;
1333    const CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1334    CXXMethodDecl *T = this->getCorrespondingMethodInClass(Base);
1335    if (T)
1336      return T;
1337  }
1338
1339  return NULL;
1340}
1341
1342CXXMethodDecl *
1343CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1344                      SourceLocation StartLoc,
1345                      const DeclarationNameInfo &NameInfo,
1346                      QualType T, TypeSourceInfo *TInfo,
1347                      StorageClass SC, bool isInline,
1348                      bool isConstexpr, SourceLocation EndLocation) {
1349  return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1350                               SC, isInline, isConstexpr,
1351                               EndLocation);
1352}
1353
1354CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1355  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXMethodDecl));
1356  return new (Mem) CXXMethodDecl(CXXMethod, 0, SourceLocation(),
1357                                 DeclarationNameInfo(), QualType(),
1358                                 0, SC_None, false, false,
1359                                 SourceLocation());
1360}
1361
1362bool CXXMethodDecl::isUsualDeallocationFunction() const {
1363  if (getOverloadedOperator() != OO_Delete &&
1364      getOverloadedOperator() != OO_Array_Delete)
1365    return false;
1366
1367  // C++ [basic.stc.dynamic.deallocation]p2:
1368  //   A template instance is never a usual deallocation function,
1369  //   regardless of its signature.
1370  if (getPrimaryTemplate())
1371    return false;
1372
1373  // C++ [basic.stc.dynamic.deallocation]p2:
1374  //   If a class T has a member deallocation function named operator delete
1375  //   with exactly one parameter, then that function is a usual (non-placement)
1376  //   deallocation function. [...]
1377  if (getNumParams() == 1)
1378    return true;
1379
1380  // C++ [basic.stc.dynamic.deallocation]p2:
1381  //   [...] If class T does not declare such an operator delete but does
1382  //   declare a member deallocation function named operator delete with
1383  //   exactly two parameters, the second of which has type std::size_t (18.1),
1384  //   then this function is a usual deallocation function.
1385  ASTContext &Context = getASTContext();
1386  if (getNumParams() != 2 ||
1387      !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1388                                      Context.getSizeType()))
1389    return false;
1390
1391  // This function is a usual deallocation function if there are no
1392  // single-parameter deallocation functions of the same kind.
1393  DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1394  for (DeclContext::lookup_const_result::iterator I = R.begin(), E = R.end();
1395       I != E; ++I) {
1396    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
1397      if (FD->getNumParams() == 1)
1398        return false;
1399  }
1400
1401  return true;
1402}
1403
1404bool CXXMethodDecl::isCopyAssignmentOperator() const {
1405  // C++0x [class.copy]p17:
1406  //  A user-declared copy assignment operator X::operator= is a non-static
1407  //  non-template member function of class X with exactly one parameter of
1408  //  type X, X&, const X&, volatile X& or const volatile X&.
1409  if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1410      /*non-static*/ isStatic() ||
1411      /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate())
1412    return false;
1413
1414  QualType ParamType = getParamDecl(0)->getType();
1415  if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1416    ParamType = Ref->getPointeeType();
1417
1418  ASTContext &Context = getASTContext();
1419  QualType ClassType
1420    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1421  return Context.hasSameUnqualifiedType(ClassType, ParamType);
1422}
1423
1424bool CXXMethodDecl::isMoveAssignmentOperator() const {
1425  // C++0x [class.copy]p19:
1426  //  A user-declared move assignment operator X::operator= is a non-static
1427  //  non-template member function of class X with exactly one parameter of type
1428  //  X&&, const X&&, volatile X&&, or const volatile X&&.
1429  if (getOverloadedOperator() != OO_Equal || isStatic() ||
1430      getPrimaryTemplate() || getDescribedFunctionTemplate())
1431    return false;
1432
1433  QualType ParamType = getParamDecl(0)->getType();
1434  if (!isa<RValueReferenceType>(ParamType))
1435    return false;
1436  ParamType = ParamType->getPointeeType();
1437
1438  ASTContext &Context = getASTContext();
1439  QualType ClassType
1440    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1441  return Context.hasSameUnqualifiedType(ClassType, ParamType);
1442}
1443
1444void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1445  assert(MD->isCanonicalDecl() && "Method is not canonical!");
1446  assert(!MD->getParent()->isDependentContext() &&
1447         "Can't add an overridden method to a class template!");
1448  assert(MD->isVirtual() && "Method is not virtual!");
1449
1450  getASTContext().addOverriddenMethod(this, MD);
1451}
1452
1453CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1454  if (isa<CXXConstructorDecl>(this)) return 0;
1455  return getASTContext().overridden_methods_begin(this);
1456}
1457
1458CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1459  if (isa<CXXConstructorDecl>(this)) return 0;
1460  return getASTContext().overridden_methods_end(this);
1461}
1462
1463unsigned CXXMethodDecl::size_overridden_methods() const {
1464  if (isa<CXXConstructorDecl>(this)) return 0;
1465  return getASTContext().overridden_methods_size(this);
1466}
1467
1468QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1469  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1470  // If the member function is declared const, the type of this is const X*,
1471  // if the member function is declared volatile, the type of this is
1472  // volatile X*, and if the member function is declared const volatile,
1473  // the type of this is const volatile X*.
1474
1475  assert(isInstance() && "No 'this' for static methods!");
1476
1477  QualType ClassTy = C.getTypeDeclType(getParent());
1478  ClassTy = C.getQualifiedType(ClassTy,
1479                               Qualifiers::fromCVRMask(getTypeQualifiers()));
1480  return C.getPointerType(ClassTy);
1481}
1482
1483bool CXXMethodDecl::hasInlineBody() const {
1484  // If this function is a template instantiation, look at the template from
1485  // which it was instantiated.
1486  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1487  if (!CheckFn)
1488    CheckFn = this;
1489
1490  const FunctionDecl *fn;
1491  return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1492}
1493
1494bool CXXMethodDecl::isLambdaStaticInvoker() const {
1495  return getParent()->isLambda() &&
1496         getIdentifier() && getIdentifier()->getName() == "__invoke";
1497}
1498
1499
1500CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1501                                       TypeSourceInfo *TInfo, bool IsVirtual,
1502                                       SourceLocation L, Expr *Init,
1503                                       SourceLocation R,
1504                                       SourceLocation EllipsisLoc)
1505  : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
1506    LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
1507    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1508{
1509}
1510
1511CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1512                                       FieldDecl *Member,
1513                                       SourceLocation MemberLoc,
1514                                       SourceLocation L, Expr *Init,
1515                                       SourceLocation R)
1516  : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1517    LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1518    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1519{
1520}
1521
1522CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1523                                       IndirectFieldDecl *Member,
1524                                       SourceLocation MemberLoc,
1525                                       SourceLocation L, Expr *Init,
1526                                       SourceLocation R)
1527  : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1528    LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1529    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1530{
1531}
1532
1533CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1534                                       TypeSourceInfo *TInfo,
1535                                       SourceLocation L, Expr *Init,
1536                                       SourceLocation R)
1537  : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init),
1538    LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false),
1539    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1540{
1541}
1542
1543CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1544                                       FieldDecl *Member,
1545                                       SourceLocation MemberLoc,
1546                                       SourceLocation L, Expr *Init,
1547                                       SourceLocation R,
1548                                       VarDecl **Indices,
1549                                       unsigned NumIndices)
1550  : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1551    LParenLoc(L), RParenLoc(R), IsVirtual(false),
1552    IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1553{
1554  VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1555  memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1556}
1557
1558CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1559                                               FieldDecl *Member,
1560                                               SourceLocation MemberLoc,
1561                                               SourceLocation L, Expr *Init,
1562                                               SourceLocation R,
1563                                               VarDecl **Indices,
1564                                               unsigned NumIndices) {
1565  void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1566                               sizeof(VarDecl *) * NumIndices,
1567                               llvm::alignOf<CXXCtorInitializer>());
1568  return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1569                                      Indices, NumIndices);
1570}
1571
1572TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1573  if (isBaseInitializer())
1574    return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1575  else
1576    return TypeLoc();
1577}
1578
1579const Type *CXXCtorInitializer::getBaseClass() const {
1580  if (isBaseInitializer())
1581    return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1582  else
1583    return 0;
1584}
1585
1586SourceLocation CXXCtorInitializer::getSourceLocation() const {
1587  if (isAnyMemberInitializer())
1588    return getMemberLocation();
1589
1590  if (isInClassMemberInitializer())
1591    return getAnyMember()->getLocation();
1592
1593  if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>())
1594    return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
1595
1596  return SourceLocation();
1597}
1598
1599SourceRange CXXCtorInitializer::getSourceRange() const {
1600  if (isInClassMemberInitializer()) {
1601    FieldDecl *D = getAnyMember();
1602    if (Expr *I = D->getInClassInitializer())
1603      return I->getSourceRange();
1604    return SourceRange();
1605  }
1606
1607  return SourceRange(getSourceLocation(), getRParenLoc());
1608}
1609
1610void CXXConstructorDecl::anchor() { }
1611
1612CXXConstructorDecl *
1613CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1614  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConstructorDecl));
1615  return new (Mem) CXXConstructorDecl(0, SourceLocation(),DeclarationNameInfo(),
1616                                      QualType(), 0, false, false, false,false);
1617}
1618
1619CXXConstructorDecl *
1620CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1621                           SourceLocation StartLoc,
1622                           const DeclarationNameInfo &NameInfo,
1623                           QualType T, TypeSourceInfo *TInfo,
1624                           bool isExplicit, bool isInline,
1625                           bool isImplicitlyDeclared, bool isConstexpr) {
1626  assert(NameInfo.getName().getNameKind()
1627         == DeclarationName::CXXConstructorName &&
1628         "Name must refer to a constructor");
1629  return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1630                                    isExplicit, isInline, isImplicitlyDeclared,
1631                                    isConstexpr);
1632}
1633
1634CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
1635  assert(isDelegatingConstructor() && "Not a delegating constructor!");
1636  Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
1637  if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(E))
1638    return Construct->getConstructor();
1639
1640  return 0;
1641}
1642
1643bool CXXConstructorDecl::isDefaultConstructor() const {
1644  // C++ [class.ctor]p5:
1645  //   A default constructor for a class X is a constructor of class
1646  //   X that can be called without an argument.
1647  return (getNumParams() == 0) ||
1648         (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1649}
1650
1651bool
1652CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1653  return isCopyOrMoveConstructor(TypeQuals) &&
1654         getParamDecl(0)->getType()->isLValueReferenceType();
1655}
1656
1657bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1658  return isCopyOrMoveConstructor(TypeQuals) &&
1659    getParamDecl(0)->getType()->isRValueReferenceType();
1660}
1661
1662/// \brief Determine whether this is a copy or move constructor.
1663bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1664  // C++ [class.copy]p2:
1665  //   A non-template constructor for class X is a copy constructor
1666  //   if its first parameter is of type X&, const X&, volatile X& or
1667  //   const volatile X&, and either there are no other parameters
1668  //   or else all other parameters have default arguments (8.3.6).
1669  // C++0x [class.copy]p3:
1670  //   A non-template constructor for class X is a move constructor if its
1671  //   first parameter is of type X&&, const X&&, volatile X&&, or
1672  //   const volatile X&&, and either there are no other parameters or else
1673  //   all other parameters have default arguments.
1674  if ((getNumParams() < 1) ||
1675      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1676      (getPrimaryTemplate() != 0) ||
1677      (getDescribedFunctionTemplate() != 0))
1678    return false;
1679
1680  const ParmVarDecl *Param = getParamDecl(0);
1681
1682  // Do we have a reference type?
1683  const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1684  if (!ParamRefType)
1685    return false;
1686
1687  // Is it a reference to our class type?
1688  ASTContext &Context = getASTContext();
1689
1690  CanQualType PointeeType
1691    = Context.getCanonicalType(ParamRefType->getPointeeType());
1692  CanQualType ClassTy
1693    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1694  if (PointeeType.getUnqualifiedType() != ClassTy)
1695    return false;
1696
1697  // FIXME: other qualifiers?
1698
1699  // We have a copy or move constructor.
1700  TypeQuals = PointeeType.getCVRQualifiers();
1701  return true;
1702}
1703
1704bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1705  // C++ [class.conv.ctor]p1:
1706  //   A constructor declared without the function-specifier explicit
1707  //   that can be called with a single parameter specifies a
1708  //   conversion from the type of its first parameter to the type of
1709  //   its class. Such a constructor is called a converting
1710  //   constructor.
1711  if (isExplicit() && !AllowExplicit)
1712    return false;
1713
1714  return (getNumParams() == 0 &&
1715          getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1716         (getNumParams() == 1) ||
1717         (getNumParams() > 1 &&
1718          (getParamDecl(1)->hasDefaultArg() ||
1719           getParamDecl(1)->isParameterPack()));
1720}
1721
1722bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1723  if ((getNumParams() < 1) ||
1724      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1725      (getPrimaryTemplate() == 0) ||
1726      (getDescribedFunctionTemplate() != 0))
1727    return false;
1728
1729  const ParmVarDecl *Param = getParamDecl(0);
1730
1731  ASTContext &Context = getASTContext();
1732  CanQualType ParamType = Context.getCanonicalType(Param->getType());
1733
1734  // Is it the same as our our class type?
1735  CanQualType ClassTy
1736    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1737  if (ParamType.getUnqualifiedType() != ClassTy)
1738    return false;
1739
1740  return true;
1741}
1742
1743const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1744  // Hack: we store the inherited constructor in the overridden method table
1745  method_iterator It = getASTContext().overridden_methods_begin(this);
1746  if (It == getASTContext().overridden_methods_end(this))
1747    return 0;
1748
1749  return cast<CXXConstructorDecl>(*It);
1750}
1751
1752void
1753CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1754  // Hack: we store the inherited constructor in the overridden method table
1755  assert(getASTContext().overridden_methods_size(this) == 0 &&
1756         "Base ctor already set.");
1757  getASTContext().addOverriddenMethod(this, BaseCtor);
1758}
1759
1760void CXXDestructorDecl::anchor() { }
1761
1762CXXDestructorDecl *
1763CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1764  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXDestructorDecl));
1765  return new (Mem) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1766                                   QualType(), 0, false, false);
1767}
1768
1769CXXDestructorDecl *
1770CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1771                          SourceLocation StartLoc,
1772                          const DeclarationNameInfo &NameInfo,
1773                          QualType T, TypeSourceInfo *TInfo,
1774                          bool isInline, bool isImplicitlyDeclared) {
1775  assert(NameInfo.getName().getNameKind()
1776         == DeclarationName::CXXDestructorName &&
1777         "Name must refer to a destructor");
1778  return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1779                                   isImplicitlyDeclared);
1780}
1781
1782void CXXConversionDecl::anchor() { }
1783
1784CXXConversionDecl *
1785CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1786  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConversionDecl));
1787  return new (Mem) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1788                                     QualType(), 0, false, false, false,
1789                                     SourceLocation());
1790}
1791
1792CXXConversionDecl *
1793CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1794                          SourceLocation StartLoc,
1795                          const DeclarationNameInfo &NameInfo,
1796                          QualType T, TypeSourceInfo *TInfo,
1797                          bool isInline, bool isExplicit,
1798                          bool isConstexpr, SourceLocation EndLocation) {
1799  assert(NameInfo.getName().getNameKind()
1800         == DeclarationName::CXXConversionFunctionName &&
1801         "Name must refer to a conversion function");
1802  return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1803                                   isInline, isExplicit, isConstexpr,
1804                                   EndLocation);
1805}
1806
1807bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
1808  return isImplicit() && getParent()->isLambda() &&
1809         getConversionType()->isBlockPointerType();
1810}
1811
1812void LinkageSpecDecl::anchor() { }
1813
1814LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1815                                         DeclContext *DC,
1816                                         SourceLocation ExternLoc,
1817                                         SourceLocation LangLoc,
1818                                         LanguageIDs Lang,
1819                                         bool HasBraces) {
1820  return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
1821}
1822
1823LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1824  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
1825  return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
1826                                   lang_c, false);
1827}
1828
1829void UsingDirectiveDecl::anchor() { }
1830
1831UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1832                                               SourceLocation L,
1833                                               SourceLocation NamespaceLoc,
1834                                           NestedNameSpecifierLoc QualifierLoc,
1835                                               SourceLocation IdentLoc,
1836                                               NamedDecl *Used,
1837                                               DeclContext *CommonAncestor) {
1838  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1839    Used = NS->getOriginalNamespace();
1840  return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1841                                    IdentLoc, Used, CommonAncestor);
1842}
1843
1844UsingDirectiveDecl *
1845UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1846  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDirectiveDecl));
1847  return new (Mem) UsingDirectiveDecl(0, SourceLocation(), SourceLocation(),
1848                                      NestedNameSpecifierLoc(),
1849                                      SourceLocation(), 0, 0);
1850}
1851
1852NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1853  if (NamespaceAliasDecl *NA =
1854        dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1855    return NA->getNamespace();
1856  return cast_or_null<NamespaceDecl>(NominatedNamespace);
1857}
1858
1859void NamespaceDecl::anchor() { }
1860
1861NamespaceDecl::NamespaceDecl(DeclContext *DC, bool Inline,
1862                             SourceLocation StartLoc,
1863                             SourceLocation IdLoc, IdentifierInfo *Id,
1864                             NamespaceDecl *PrevDecl)
1865  : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
1866    LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(0, Inline)
1867{
1868  setPreviousDeclaration(PrevDecl);
1869
1870  if (PrevDecl)
1871    AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
1872}
1873
1874NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1875                                     bool Inline, SourceLocation StartLoc,
1876                                     SourceLocation IdLoc, IdentifierInfo *Id,
1877                                     NamespaceDecl *PrevDecl) {
1878  return new (C) NamespaceDecl(DC, Inline, StartLoc, IdLoc, Id, PrevDecl);
1879}
1880
1881NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1882  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceDecl));
1883  return new (Mem) NamespaceDecl(0, false, SourceLocation(), SourceLocation(),
1884                                 0, 0);
1885}
1886
1887void NamespaceAliasDecl::anchor() { }
1888
1889NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1890                                               SourceLocation UsingLoc,
1891                                               SourceLocation AliasLoc,
1892                                               IdentifierInfo *Alias,
1893                                           NestedNameSpecifierLoc QualifierLoc,
1894                                               SourceLocation IdentLoc,
1895                                               NamedDecl *Namespace) {
1896  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1897    Namespace = NS->getOriginalNamespace();
1898  return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias,
1899                                    QualifierLoc, IdentLoc, Namespace);
1900}
1901
1902NamespaceAliasDecl *
1903NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1904  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceAliasDecl));
1905  return new (Mem) NamespaceAliasDecl(0, SourceLocation(), SourceLocation(), 0,
1906                                      NestedNameSpecifierLoc(),
1907                                      SourceLocation(), 0);
1908}
1909
1910void UsingShadowDecl::anchor() { }
1911
1912UsingShadowDecl *
1913UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1914  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingShadowDecl));
1915  return new (Mem) UsingShadowDecl(0, SourceLocation(), 0, 0);
1916}
1917
1918UsingDecl *UsingShadowDecl::getUsingDecl() const {
1919  const UsingShadowDecl *Shadow = this;
1920  while (const UsingShadowDecl *NextShadow =
1921         dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1922    Shadow = NextShadow;
1923  return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1924}
1925
1926void UsingDecl::anchor() { }
1927
1928void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1929  assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1930         "declaration already in set");
1931  assert(S->getUsingDecl() == this);
1932
1933  if (FirstUsingShadow.getPointer())
1934    S->UsingOrNextShadow = FirstUsingShadow.getPointer();
1935  FirstUsingShadow.setPointer(S);
1936}
1937
1938void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1939  assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1940         "declaration not in set");
1941  assert(S->getUsingDecl() == this);
1942
1943  // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1944
1945  if (FirstUsingShadow.getPointer() == S) {
1946    FirstUsingShadow.setPointer(
1947      dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
1948    S->UsingOrNextShadow = this;
1949    return;
1950  }
1951
1952  UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
1953  while (Prev->UsingOrNextShadow != S)
1954    Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1955  Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1956  S->UsingOrNextShadow = this;
1957}
1958
1959UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
1960                             NestedNameSpecifierLoc QualifierLoc,
1961                             const DeclarationNameInfo &NameInfo,
1962                             bool IsTypeNameArg) {
1963  return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
1964}
1965
1966UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1967  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDecl));
1968  return new (Mem) UsingDecl(0, SourceLocation(), NestedNameSpecifierLoc(),
1969                             DeclarationNameInfo(), false);
1970}
1971
1972void UnresolvedUsingValueDecl::anchor() { }
1973
1974UnresolvedUsingValueDecl *
1975UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1976                                 SourceLocation UsingLoc,
1977                                 NestedNameSpecifierLoc QualifierLoc,
1978                                 const DeclarationNameInfo &NameInfo) {
1979  return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1980                                          QualifierLoc, NameInfo);
1981}
1982
1983UnresolvedUsingValueDecl *
1984UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1985  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UnresolvedUsingValueDecl));
1986  return new (Mem) UnresolvedUsingValueDecl(0, QualType(), SourceLocation(),
1987                                            NestedNameSpecifierLoc(),
1988                                            DeclarationNameInfo());
1989}
1990
1991void UnresolvedUsingTypenameDecl::anchor() { }
1992
1993UnresolvedUsingTypenameDecl *
1994UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1995                                    SourceLocation UsingLoc,
1996                                    SourceLocation TypenameLoc,
1997                                    NestedNameSpecifierLoc QualifierLoc,
1998                                    SourceLocation TargetNameLoc,
1999                                    DeclarationName TargetName) {
2000  return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
2001                                             QualifierLoc, TargetNameLoc,
2002                                             TargetName.getAsIdentifierInfo());
2003}
2004
2005UnresolvedUsingTypenameDecl *
2006UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2007  void *Mem = AllocateDeserializedDecl(C, ID,
2008                                       sizeof(UnresolvedUsingTypenameDecl));
2009  return new (Mem) UnresolvedUsingTypenameDecl(0, SourceLocation(),
2010                                               SourceLocation(),
2011                                               NestedNameSpecifierLoc(),
2012                                               SourceLocation(),
2013                                               0);
2014}
2015
2016void StaticAssertDecl::anchor() { }
2017
2018StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
2019                                           SourceLocation StaticAssertLoc,
2020                                           Expr *AssertExpr,
2021                                           StringLiteral *Message,
2022                                           SourceLocation RParenLoc,
2023                                           bool Failed) {
2024  return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
2025                                  RParenLoc, Failed);
2026}
2027
2028StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
2029                                                       unsigned ID) {
2030  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(StaticAssertDecl));
2031  return new (Mem) StaticAssertDecl(0, SourceLocation(), 0, 0,
2032                                    SourceLocation(), false);
2033}
2034
2035static const char *getAccessName(AccessSpecifier AS) {
2036  switch (AS) {
2037    case AS_none:
2038      llvm_unreachable("Invalid access specifier!");
2039    case AS_public:
2040      return "public";
2041    case AS_private:
2042      return "private";
2043    case AS_protected:
2044      return "protected";
2045  }
2046  llvm_unreachable("Invalid access specifier!");
2047}
2048
2049const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
2050                                           AccessSpecifier AS) {
2051  return DB << getAccessName(AS);
2052}
2053
2054const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
2055                                           AccessSpecifier AS) {
2056  return DB << getAccessName(AS);
2057}
2058