1 //===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the C++ related Decl classes.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Basic/IdentifierTable.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 using namespace clang;
26 
27 //===----------------------------------------------------------------------===//
28 // Decl Allocation/Deallocation Method Implementations
29 //===----------------------------------------------------------------------===//
30 
31 void AccessSpecDecl::anchor() { }
32 
33 AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
34   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(AccessSpecDecl));
35   return new (Mem) AccessSpecDecl(EmptyShell());
36 }
37 
38 void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
39   ExternalASTSource *Source = C.getExternalSource();
40   assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");
41   assert(Source && "getFromExternalSource with no external source");
42 
43   for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)
44     I.setDecl(cast<NamedDecl>(Source->GetExternalDecl(
45         reinterpret_cast<uintptr_t>(I.getDecl()) >> 2)));
46   Impl.Decls.setLazy(false);
47 }
48 
49 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
50   : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
51     Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
52     Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
53     HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
54     HasMutableFields(false), HasOnlyCMembers(true),
55     HasInClassInitializer(false), HasUninitializedReferenceMember(false),
56     NeedOverloadResolutionForMoveConstructor(false),
57     NeedOverloadResolutionForMoveAssignment(false),
58     NeedOverloadResolutionForDestructor(false),
59     DefaultedMoveConstructorIsDeleted(false),
60     DefaultedMoveAssignmentIsDeleted(false),
61     DefaultedDestructorIsDeleted(false),
62     HasTrivialSpecialMembers(SMF_All),
63     DeclaredNonTrivialSpecialMembers(0),
64     HasIrrelevantDestructor(true),
65     HasConstexprNonCopyMoveConstructor(false),
66     DefaultedDefaultConstructorIsConstexpr(true),
67     HasConstexprDefaultConstructor(false),
68     HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false),
69     UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
70     ImplicitCopyConstructorHasConstParam(true),
71     ImplicitCopyAssignmentHasConstParam(true),
72     HasDeclaredCopyConstructorWithConstParam(false),
73     HasDeclaredCopyAssignmentWithConstParam(false),
74     FailedImplicitMoveConstructor(false), FailedImplicitMoveAssignment(false),
75     IsLambda(false), NumBases(0), NumVBases(0), Bases(), VBases(),
76     Definition(D), FirstFriend() {
77 }
78 
79 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
80   return Bases.get(Definition->getASTContext().getExternalSource());
81 }
82 
83 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
84   return VBases.get(Definition->getASTContext().getExternalSource());
85 }
86 
87 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
88                              SourceLocation StartLoc, SourceLocation IdLoc,
89                              IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
90   : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
91     DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
92     TemplateOrInstantiation() { }
93 
94 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
95                                      DeclContext *DC, SourceLocation StartLoc,
96                                      SourceLocation IdLoc, IdentifierInfo *Id,
97                                      CXXRecordDecl* PrevDecl,
98                                      bool DelayTypeCreation) {
99   CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
100                                            Id, PrevDecl);
101   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
102 
103   // FIXME: DelayTypeCreation seems like such a hack
104   if (!DelayTypeCreation)
105     C.getTypeDeclType(R, PrevDecl);
106   return R;
107 }
108 
109 CXXRecordDecl *CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
110                                            TypeSourceInfo *Info, SourceLocation Loc,
111                                            bool Dependent, bool IsGeneric,
112                                            LambdaCaptureDefault CaptureDefault) {
113   CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TTK_Class, DC, Loc, Loc,
114                                            0, 0);
115   R->IsBeingDefined = true;
116   R->DefinitionData = new (C) struct LambdaDefinitionData(R, Info,
117                                                           Dependent,
118                                                           IsGeneric,
119                                                           CaptureDefault);
120   R->MayHaveOutOfDateDef = false;
121   R->setImplicit(true);
122   C.getTypeDeclType(R, /*PrevDecl=*/0);
123   return R;
124 }
125 
126 CXXRecordDecl *
127 CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
128   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXRecordDecl));
129   CXXRecordDecl *R = new (Mem) CXXRecordDecl(CXXRecord, TTK_Struct, 0,
130                                              SourceLocation(), SourceLocation(),
131                                              0, 0);
132   R->MayHaveOutOfDateDef = false;
133   return R;
134 }
135 
136 void
137 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
138                         unsigned NumBases) {
139   ASTContext &C = getASTContext();
140 
141   if (!data().Bases.isOffset() && data().NumBases > 0)
142     C.Deallocate(data().getBases());
143 
144   if (NumBases) {
145     // C++ [dcl.init.aggr]p1:
146     //   An aggregate is [...] a class with [...] no base classes [...].
147     data().Aggregate = false;
148 
149     // C++ [class]p4:
150     //   A POD-struct is an aggregate class...
151     data().PlainOldData = false;
152   }
153 
154   // The set of seen virtual base types.
155   llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
156 
157   // The virtual bases of this class.
158   SmallVector<const CXXBaseSpecifier *, 8> VBases;
159 
160   data().Bases = new(C) CXXBaseSpecifier [NumBases];
161   data().NumBases = NumBases;
162   for (unsigned i = 0; i < NumBases; ++i) {
163     data().getBases()[i] = *Bases[i];
164     // Keep track of inherited vbases for this base class.
165     const CXXBaseSpecifier *Base = Bases[i];
166     QualType BaseType = Base->getType();
167     // Skip dependent types; we can't do any checking on them now.
168     if (BaseType->isDependentType())
169       continue;
170     CXXRecordDecl *BaseClassDecl
171       = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
172 
173     // A class with a non-empty base class is not empty.
174     // FIXME: Standard ref?
175     if (!BaseClassDecl->isEmpty()) {
176       if (!data().Empty) {
177         // C++0x [class]p7:
178         //   A standard-layout class is a class that:
179         //    [...]
180         //    -- either has no non-static data members in the most derived
181         //       class and at most one base class with non-static data members,
182         //       or has no base classes with non-static data members, and
183         // If this is the second non-empty base, then neither of these two
184         // clauses can be true.
185         data().IsStandardLayout = false;
186       }
187 
188       data().Empty = false;
189       data().HasNoNonEmptyBases = false;
190     }
191 
192     // C++ [class.virtual]p1:
193     //   A class that declares or inherits a virtual function is called a
194     //   polymorphic class.
195     if (BaseClassDecl->isPolymorphic())
196       data().Polymorphic = true;
197 
198     // C++0x [class]p7:
199     //   A standard-layout class is a class that: [...]
200     //    -- has no non-standard-layout base classes
201     if (!BaseClassDecl->isStandardLayout())
202       data().IsStandardLayout = false;
203 
204     // Record if this base is the first non-literal field or base.
205     if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
206       data().HasNonLiteralTypeFieldsOrBases = true;
207 
208     // Now go through all virtual bases of this base and add them.
209     for (CXXRecordDecl::base_class_iterator VBase =
210           BaseClassDecl->vbases_begin(),
211          E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
212       // Add this base if it's not already in the list.
213       if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType()))) {
214         VBases.push_back(VBase);
215 
216         // C++11 [class.copy]p8:
217         //   The implicitly-declared copy constructor for a class X will have
218         //   the form 'X::X(const X&)' if each [...] virtual base class B of X
219         //   has a copy constructor whose first parameter is of type
220         //   'const B&' or 'const volatile B&' [...]
221         if (CXXRecordDecl *VBaseDecl = VBase->getType()->getAsCXXRecordDecl())
222           if (!VBaseDecl->hasCopyConstructorWithConstParam())
223             data().ImplicitCopyConstructorHasConstParam = false;
224       }
225     }
226 
227     if (Base->isVirtual()) {
228       // Add this base if it's not already in the list.
229       if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
230         VBases.push_back(Base);
231 
232       // C++0x [meta.unary.prop] is_empty:
233       //    T is a class type, but not a union type, with ... no virtual base
234       //    classes
235       data().Empty = false;
236 
237       // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
238       //   A [default constructor, copy/move constructor, or copy/move assignment
239       //   operator for a class X] is trivial [...] if:
240       //    -- class X has [...] no virtual base classes
241       data().HasTrivialSpecialMembers &= SMF_Destructor;
242 
243       // C++0x [class]p7:
244       //   A standard-layout class is a class that: [...]
245       //    -- has [...] no virtual base classes
246       data().IsStandardLayout = false;
247 
248       // C++11 [dcl.constexpr]p4:
249       //   In the definition of a constexpr constructor [...]
250       //    -- the class shall not have any virtual base classes
251       data().DefaultedDefaultConstructorIsConstexpr = false;
252     } else {
253       // C++ [class.ctor]p5:
254       //   A default constructor is trivial [...] if:
255       //    -- all the direct base classes of its class have trivial default
256       //       constructors.
257       if (!BaseClassDecl->hasTrivialDefaultConstructor())
258         data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
259 
260       // C++0x [class.copy]p13:
261       //   A copy/move constructor for class X is trivial if [...]
262       //    [...]
263       //    -- the constructor selected to copy/move each direct base class
264       //       subobject is trivial, and
265       if (!BaseClassDecl->hasTrivialCopyConstructor())
266         data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
267       // If the base class doesn't have a simple move constructor, we'll eagerly
268       // declare it and perform overload resolution to determine which function
269       // it actually calls. If it does have a simple move constructor, this
270       // check is correct.
271       if (!BaseClassDecl->hasTrivialMoveConstructor())
272         data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
273 
274       // C++0x [class.copy]p27:
275       //   A copy/move assignment operator for class X is trivial if [...]
276       //    [...]
277       //    -- the assignment operator selected to copy/move each direct base
278       //       class subobject is trivial, and
279       if (!BaseClassDecl->hasTrivialCopyAssignment())
280         data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
281       // If the base class doesn't have a simple move assignment, we'll eagerly
282       // declare it and perform overload resolution to determine which function
283       // it actually calls. If it does have a simple move assignment, this
284       // check is correct.
285       if (!BaseClassDecl->hasTrivialMoveAssignment())
286         data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
287 
288       // C++11 [class.ctor]p6:
289       //   If that user-written default constructor would satisfy the
290       //   requirements of a constexpr constructor, the implicitly-defined
291       //   default constructor is constexpr.
292       if (!BaseClassDecl->hasConstexprDefaultConstructor())
293         data().DefaultedDefaultConstructorIsConstexpr = false;
294     }
295 
296     // C++ [class.ctor]p3:
297     //   A destructor is trivial if all the direct base classes of its class
298     //   have trivial destructors.
299     if (!BaseClassDecl->hasTrivialDestructor())
300       data().HasTrivialSpecialMembers &= ~SMF_Destructor;
301 
302     if (!BaseClassDecl->hasIrrelevantDestructor())
303       data().HasIrrelevantDestructor = false;
304 
305     // C++11 [class.copy]p18:
306     //   The implicitly-declared copy assignment oeprator for a class X will
307     //   have the form 'X& X::operator=(const X&)' if each direct base class B
308     //   of X has a copy assignment operator whose parameter is of type 'const
309     //   B&', 'const volatile B&', or 'B' [...]
310     if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
311       data().ImplicitCopyAssignmentHasConstParam = false;
312 
313     // C++11 [class.copy]p8:
314     //   The implicitly-declared copy constructor for a class X will have
315     //   the form 'X::X(const X&)' if each direct [...] base class B of X
316     //   has a copy constructor whose first parameter is of type
317     //   'const B&' or 'const volatile B&' [...]
318     if (!BaseClassDecl->hasCopyConstructorWithConstParam())
319       data().ImplicitCopyConstructorHasConstParam = false;
320 
321     // A class has an Objective-C object member if... or any of its bases
322     // has an Objective-C object member.
323     if (BaseClassDecl->hasObjectMember())
324       setHasObjectMember(true);
325 
326     if (BaseClassDecl->hasVolatileMember())
327       setHasVolatileMember(true);
328 
329     // Keep track of the presence of mutable fields.
330     if (BaseClassDecl->hasMutableFields())
331       data().HasMutableFields = true;
332 
333     if (BaseClassDecl->hasUninitializedReferenceMember())
334       data().HasUninitializedReferenceMember = true;
335 
336     addedClassSubobject(BaseClassDecl);
337   }
338 
339   if (VBases.empty())
340     return;
341 
342   // Create base specifier for any direct or indirect virtual bases.
343   data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
344   data().NumVBases = VBases.size();
345   for (int I = 0, E = VBases.size(); I != E; ++I) {
346     QualType Type = VBases[I]->getType();
347     if (!Type->isDependentType())
348       addedClassSubobject(Type->getAsCXXRecordDecl());
349     data().getVBases()[I] = *VBases[I];
350   }
351 }
352 
353 void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
354   // C++11 [class.copy]p11:
355   //   A defaulted copy/move constructor for a class X is defined as
356   //   deleted if X has:
357   //    -- a direct or virtual base class B that cannot be copied/moved [...]
358   //    -- a non-static data member of class type M (or array thereof)
359   //       that cannot be copied or moved [...]
360   if (!Subobj->hasSimpleMoveConstructor())
361     data().NeedOverloadResolutionForMoveConstructor = true;
362 
363   // C++11 [class.copy]p23:
364   //   A defaulted copy/move assignment operator for a class X is defined as
365   //   deleted if X has:
366   //    -- a direct or virtual base class B that cannot be copied/moved [...]
367   //    -- a non-static data member of class type M (or array thereof)
368   //        that cannot be copied or moved [...]
369   if (!Subobj->hasSimpleMoveAssignment())
370     data().NeedOverloadResolutionForMoveAssignment = true;
371 
372   // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
373   //   A defaulted [ctor or dtor] for a class X is defined as
374   //   deleted if X has:
375   //    -- any direct or virtual base class [...] has a type with a destructor
376   //       that is deleted or inaccessible from the defaulted [ctor or dtor].
377   //    -- any non-static data member has a type with a destructor
378   //       that is deleted or inaccessible from the defaulted [ctor or dtor].
379   if (!Subobj->hasSimpleDestructor()) {
380     data().NeedOverloadResolutionForMoveConstructor = true;
381     data().NeedOverloadResolutionForDestructor = true;
382   }
383 }
384 
385 /// Callback function for CXXRecordDecl::forallBases that acknowledges
386 /// that it saw a base class.
387 static bool SawBase(const CXXRecordDecl *, void *) {
388   return true;
389 }
390 
391 bool CXXRecordDecl::hasAnyDependentBases() const {
392   if (!isDependentContext())
393     return false;
394 
395   return !forallBases(SawBase, 0);
396 }
397 
398 bool CXXRecordDecl::isTriviallyCopyable() const {
399   // C++0x [class]p5:
400   //   A trivially copyable class is a class that:
401   //   -- has no non-trivial copy constructors,
402   if (hasNonTrivialCopyConstructor()) return false;
403   //   -- has no non-trivial move constructors,
404   if (hasNonTrivialMoveConstructor()) return false;
405   //   -- has no non-trivial copy assignment operators,
406   if (hasNonTrivialCopyAssignment()) return false;
407   //   -- has no non-trivial move assignment operators, and
408   if (hasNonTrivialMoveAssignment()) return false;
409   //   -- has a trivial destructor.
410   if (!hasTrivialDestructor()) return false;
411 
412   return true;
413 }
414 
415 void CXXRecordDecl::markedVirtualFunctionPure() {
416   // C++ [class.abstract]p2:
417   //   A class is abstract if it has at least one pure virtual function.
418   data().Abstract = true;
419 }
420 
421 void CXXRecordDecl::addedMember(Decl *D) {
422   if (!D->isImplicit() &&
423       !isa<FieldDecl>(D) &&
424       !isa<IndirectFieldDecl>(D) &&
425       (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class ||
426         cast<TagDecl>(D)->getTagKind() == TTK_Interface))
427     data().HasOnlyCMembers = false;
428 
429   // Ignore friends and invalid declarations.
430   if (D->getFriendObjectKind() || D->isInvalidDecl())
431     return;
432 
433   FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
434   if (FunTmpl)
435     D = FunTmpl->getTemplatedDecl();
436 
437   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
438     if (Method->isVirtual()) {
439       // C++ [dcl.init.aggr]p1:
440       //   An aggregate is an array or a class with [...] no virtual functions.
441       data().Aggregate = false;
442 
443       // C++ [class]p4:
444       //   A POD-struct is an aggregate class...
445       data().PlainOldData = false;
446 
447       // Virtual functions make the class non-empty.
448       // FIXME: Standard ref?
449       data().Empty = false;
450 
451       // C++ [class.virtual]p1:
452       //   A class that declares or inherits a virtual function is called a
453       //   polymorphic class.
454       data().Polymorphic = true;
455 
456       // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
457       //   A [default constructor, copy/move constructor, or copy/move
458       //   assignment operator for a class X] is trivial [...] if:
459       //    -- class X has no virtual functions [...]
460       data().HasTrivialSpecialMembers &= SMF_Destructor;
461 
462       // C++0x [class]p7:
463       //   A standard-layout class is a class that: [...]
464       //    -- has no virtual functions
465       data().IsStandardLayout = false;
466     }
467   }
468 
469   // Notify the listener if an implicit member was added after the definition
470   // was completed.
471   if (!isBeingDefined() && D->isImplicit())
472     if (ASTMutationListener *L = getASTMutationListener())
473       L->AddedCXXImplicitMember(data().Definition, D);
474 
475   // The kind of special member this declaration is, if any.
476   unsigned SMKind = 0;
477 
478   // Handle constructors.
479   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
480     if (!Constructor->isImplicit()) {
481       // Note that we have a user-declared constructor.
482       data().UserDeclaredConstructor = true;
483 
484       // C++ [class]p4:
485       //   A POD-struct is an aggregate class [...]
486       // Since the POD bit is meant to be C++03 POD-ness, clear it even if the
487       // type is technically an aggregate in C++0x since it wouldn't be in 03.
488       data().PlainOldData = false;
489     }
490 
491     // Technically, "user-provided" is only defined for special member
492     // functions, but the intent of the standard is clearly that it should apply
493     // to all functions.
494     bool UserProvided = Constructor->isUserProvided();
495 
496     if (Constructor->isDefaultConstructor()) {
497       SMKind |= SMF_DefaultConstructor;
498 
499       if (UserProvided)
500         data().UserProvidedDefaultConstructor = true;
501       if (Constructor->isConstexpr())
502         data().HasConstexprDefaultConstructor = true;
503     }
504 
505     if (!FunTmpl) {
506       unsigned Quals;
507       if (Constructor->isCopyConstructor(Quals)) {
508         SMKind |= SMF_CopyConstructor;
509 
510         if (Quals & Qualifiers::Const)
511           data().HasDeclaredCopyConstructorWithConstParam = true;
512       } else if (Constructor->isMoveConstructor())
513         SMKind |= SMF_MoveConstructor;
514     }
515 
516     // Record if we see any constexpr constructors which are neither copy
517     // nor move constructors.
518     if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
519       data().HasConstexprNonCopyMoveConstructor = true;
520 
521     // C++ [dcl.init.aggr]p1:
522     //   An aggregate is an array or a class with no user-declared
523     //   constructors [...].
524     // C++11 [dcl.init.aggr]p1:
525     //   An aggregate is an array or a class with no user-provided
526     //   constructors [...].
527     if (getASTContext().getLangOpts().CPlusPlus11
528           ? UserProvided : !Constructor->isImplicit())
529       data().Aggregate = false;
530   }
531 
532   // Handle destructors.
533   if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) {
534     SMKind |= SMF_Destructor;
535 
536     if (!DD->isImplicit())
537       data().HasIrrelevantDestructor = false;
538 
539     // C++11 [class.dtor]p5:
540     //   A destructor is trivial if [...] the destructor is not virtual.
541     if (DD->isVirtual())
542       data().HasTrivialSpecialMembers &= ~SMF_Destructor;
543   }
544 
545   // Handle member functions.
546   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
547     if (Method->isCopyAssignmentOperator()) {
548       SMKind |= SMF_CopyAssignment;
549 
550       const ReferenceType *ParamTy =
551         Method->getParamDecl(0)->getType()->getAs<ReferenceType>();
552       if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
553         data().HasDeclaredCopyAssignmentWithConstParam = true;
554     }
555 
556     if (Method->isMoveAssignmentOperator())
557       SMKind |= SMF_MoveAssignment;
558 
559     // Keep the list of conversion functions up-to-date.
560     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
561       // FIXME: We use the 'unsafe' accessor for the access specifier here,
562       // because Sema may not have set it yet. That's really just a misdesign
563       // in Sema. However, LLDB *will* have set the access specifier correctly,
564       // and adds declarations after the class is technically completed,
565       // so completeDefinition()'s overriding of the access specifiers doesn't
566       // work.
567       AccessSpecifier AS = Conversion->getAccessUnsafe();
568 
569       if (Conversion->getPrimaryTemplate()) {
570         // We don't record specializations.
571       } else {
572         ASTContext &Ctx = getASTContext();
573         ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);
574         NamedDecl *Primary =
575             FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);
576         if (Primary->getPreviousDecl())
577           Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),
578                               Primary, AS);
579         else
580           Conversions.addDecl(Ctx, Primary, AS);
581       }
582     }
583 
584     if (SMKind) {
585       // If this is the first declaration of a special member, we no longer have
586       // an implicit trivial special member.
587       data().HasTrivialSpecialMembers &=
588         data().DeclaredSpecialMembers | ~SMKind;
589 
590       if (!Method->isImplicit() && !Method->isUserProvided()) {
591         // This method is user-declared but not user-provided. We can't work out
592         // whether it's trivial yet (not until we get to the end of the class).
593         // We'll handle this method in finishedDefaultedOrDeletedMember.
594       } else if (Method->isTrivial())
595         data().HasTrivialSpecialMembers |= SMKind;
596       else
597         data().DeclaredNonTrivialSpecialMembers |= SMKind;
598 
599       // Note when we have declared a declared special member, and suppress the
600       // implicit declaration of this special member.
601       data().DeclaredSpecialMembers |= SMKind;
602 
603       if (!Method->isImplicit()) {
604         data().UserDeclaredSpecialMembers |= SMKind;
605 
606         // C++03 [class]p4:
607         //   A POD-struct is an aggregate class that has [...] no user-defined
608         //   copy assignment operator and no user-defined destructor.
609         //
610         // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
611         // aggregates could not have any constructors, clear it even for an
612         // explicitly defaulted or deleted constructor.
613         // type is technically an aggregate in C++0x since it wouldn't be in 03.
614         //
615         // Also, a user-declared move assignment operator makes a class non-POD.
616         // This is an extension in C++03.
617         data().PlainOldData = false;
618       }
619     }
620 
621     return;
622   }
623 
624   // Handle non-static data members.
625   if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
626     // C++ [class.bit]p2:
627     //   A declaration for a bit-field that omits the identifier declares an
628     //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
629     //   initialized.
630     if (Field->isUnnamedBitfield())
631       return;
632 
633     // C++ [dcl.init.aggr]p1:
634     //   An aggregate is an array or a class (clause 9) with [...] no
635     //   private or protected non-static data members (clause 11).
636     //
637     // A POD must be an aggregate.
638     if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
639       data().Aggregate = false;
640       data().PlainOldData = false;
641     }
642 
643     // C++0x [class]p7:
644     //   A standard-layout class is a class that:
645     //    [...]
646     //    -- has the same access control for all non-static data members,
647     switch (D->getAccess()) {
648     case AS_private:    data().HasPrivateFields = true;   break;
649     case AS_protected:  data().HasProtectedFields = true; break;
650     case AS_public:     data().HasPublicFields = true;    break;
651     case AS_none:       llvm_unreachable("Invalid access specifier");
652     };
653     if ((data().HasPrivateFields + data().HasProtectedFields +
654          data().HasPublicFields) > 1)
655       data().IsStandardLayout = false;
656 
657     // Keep track of the presence of mutable fields.
658     if (Field->isMutable())
659       data().HasMutableFields = true;
660 
661     // C++0x [class]p9:
662     //   A POD struct is a class that is both a trivial class and a
663     //   standard-layout class, and has no non-static data members of type
664     //   non-POD struct, non-POD union (or array of such types).
665     //
666     // Automatic Reference Counting: the presence of a member of Objective-C pointer type
667     // that does not explicitly have no lifetime makes the class a non-POD.
668     // However, we delay setting PlainOldData to false in this case so that
669     // Sema has a chance to diagnostic causes where the same class will be
670     // non-POD with Automatic Reference Counting but a POD without ARC.
671     // In this case, the class will become a non-POD class when we complete
672     // the definition.
673     ASTContext &Context = getASTContext();
674     QualType T = Context.getBaseElementType(Field->getType());
675     if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
676       if (!Context.getLangOpts().ObjCAutoRefCount ||
677           T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)
678         setHasObjectMember(true);
679     } else if (!T.isCXX98PODType(Context))
680       data().PlainOldData = false;
681 
682     if (T->isReferenceType()) {
683       if (!Field->hasInClassInitializer())
684         data().HasUninitializedReferenceMember = true;
685 
686       // C++0x [class]p7:
687       //   A standard-layout class is a class that:
688       //    -- has no non-static data members of type [...] reference,
689       data().IsStandardLayout = false;
690     }
691 
692     // Record if this field is the first non-literal or volatile field or base.
693     if (!T->isLiteralType(Context) || T.isVolatileQualified())
694       data().HasNonLiteralTypeFieldsOrBases = true;
695 
696     if (Field->hasInClassInitializer()) {
697       data().HasInClassInitializer = true;
698 
699       // C++11 [class]p5:
700       //   A default constructor is trivial if [...] no non-static data member
701       //   of its class has a brace-or-equal-initializer.
702       data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
703 
704       // C++11 [dcl.init.aggr]p1:
705       //   An aggregate is a [...] class with [...] no
706       //   brace-or-equal-initializers for non-static data members.
707       //
708       // This rule was removed in C++1y.
709       if (!getASTContext().getLangOpts().CPlusPlus1y)
710         data().Aggregate = false;
711 
712       // C++11 [class]p10:
713       //   A POD struct is [...] a trivial class.
714       data().PlainOldData = false;
715     }
716 
717     // C++11 [class.copy]p23:
718     //   A defaulted copy/move assignment operator for a class X is defined
719     //   as deleted if X has:
720     //    -- a non-static data member of reference type
721     if (T->isReferenceType())
722       data().DefaultedMoveAssignmentIsDeleted = true;
723 
724     if (const RecordType *RecordTy = T->getAs<RecordType>()) {
725       CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
726       if (FieldRec->getDefinition()) {
727         addedClassSubobject(FieldRec);
728 
729         // C++11 [class.ctor]p5, C++11 [class.copy]p11:
730         //   A defaulted [special member] for a class X is defined as
731         //   deleted if:
732         //    -- X is a union-like class that has a variant member with a
733         //       non-trivial [corresponding special member]
734         if (isUnion()) {
735           if (FieldRec->hasNonTrivialMoveConstructor())
736             data().DefaultedMoveConstructorIsDeleted = true;
737           if (FieldRec->hasNonTrivialMoveAssignment())
738             data().DefaultedMoveAssignmentIsDeleted = true;
739           if (FieldRec->hasNonTrivialDestructor())
740             data().DefaultedDestructorIsDeleted = true;
741         }
742 
743         // C++0x [class.ctor]p5:
744         //   A default constructor is trivial [...] if:
745         //    -- for all the non-static data members of its class that are of
746         //       class type (or array thereof), each such class has a trivial
747         //       default constructor.
748         if (!FieldRec->hasTrivialDefaultConstructor())
749           data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
750 
751         // C++0x [class.copy]p13:
752         //   A copy/move constructor 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 constructor selected to copy/move that
756         //       member is trivial;
757         if (!FieldRec->hasTrivialCopyConstructor())
758           data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
759         // If the field doesn't have a simple move constructor, we'll eagerly
760         // declare the move constructor for this class and we'll decide whether
761         // it's trivial then.
762         if (!FieldRec->hasTrivialMoveConstructor())
763           data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
764 
765         // C++0x [class.copy]p27:
766         //   A copy/move assignment operator for class X is trivial if [...]
767         //    [...]
768         //    -- for each non-static data member of X that is of class type (or
769         //       an array thereof), the assignment operator selected to
770         //       copy/move that member is trivial;
771         if (!FieldRec->hasTrivialCopyAssignment())
772           data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
773         // If the field doesn't have a simple move assignment, we'll eagerly
774         // declare the move assignment for this class and we'll decide whether
775         // it's trivial then.
776         if (!FieldRec->hasTrivialMoveAssignment())
777           data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
778 
779         if (!FieldRec->hasTrivialDestructor())
780           data().HasTrivialSpecialMembers &= ~SMF_Destructor;
781         if (!FieldRec->hasIrrelevantDestructor())
782           data().HasIrrelevantDestructor = false;
783         if (FieldRec->hasObjectMember())
784           setHasObjectMember(true);
785         if (FieldRec->hasVolatileMember())
786           setHasVolatileMember(true);
787 
788         // C++0x [class]p7:
789         //   A standard-layout class is a class that:
790         //    -- has no non-static data members of type non-standard-layout
791         //       class (or array of such types) [...]
792         if (!FieldRec->isStandardLayout())
793           data().IsStandardLayout = false;
794 
795         // C++0x [class]p7:
796         //   A standard-layout class is a class that:
797         //    [...]
798         //    -- has no base classes of the same type as the first non-static
799         //       data member.
800         // We don't want to expend bits in the state of the record decl
801         // tracking whether this is the first non-static data member so we
802         // cheat a bit and use some of the existing state: the empty bit.
803         // Virtual bases and virtual methods make a class non-empty, but they
804         // also make it non-standard-layout so we needn't check here.
805         // A non-empty base class may leave the class standard-layout, but not
806         // if we have arrived here, and have at least on non-static data
807         // member. If IsStandardLayout remains true, then the first non-static
808         // data member must come through here with Empty still true, and Empty
809         // will subsequently be set to false below.
810         if (data().IsStandardLayout && data().Empty) {
811           for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
812                                                         BE = bases_end();
813                BI != BE; ++BI) {
814             if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
815               data().IsStandardLayout = false;
816               break;
817             }
818           }
819         }
820 
821         // Keep track of the presence of mutable fields.
822         if (FieldRec->hasMutableFields())
823           data().HasMutableFields = true;
824 
825         // C++11 [class.copy]p13:
826         //   If the implicitly-defined constructor would satisfy the
827         //   requirements of a constexpr constructor, the implicitly-defined
828         //   constructor is constexpr.
829         // C++11 [dcl.constexpr]p4:
830         //    -- every constructor involved in initializing non-static data
831         //       members [...] shall be a constexpr constructor
832         if (!Field->hasInClassInitializer() &&
833             !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
834           // The standard requires any in-class initializer to be a constant
835           // expression. We consider this to be a defect.
836           data().DefaultedDefaultConstructorIsConstexpr = false;
837 
838         // C++11 [class.copy]p8:
839         //   The implicitly-declared copy constructor for a class X will have
840         //   the form 'X::X(const X&)' if [...] for all the non-static data
841         //   members of X that are of a class type M (or array thereof), each
842         //   such class type has a copy constructor whose first parameter is
843         //   of type 'const M&' or 'const volatile M&'.
844         if (!FieldRec->hasCopyConstructorWithConstParam())
845           data().ImplicitCopyConstructorHasConstParam = false;
846 
847         // C++11 [class.copy]p18:
848         //   The implicitly-declared copy assignment oeprator for a class X will
849         //   have the form 'X& X::operator=(const X&)' if [...] for all the
850         //   non-static data members of X that are of a class type M (or array
851         //   thereof), each such class type has a copy assignment operator whose
852         //   parameter is of type 'const M&', 'const volatile M&' or 'M'.
853         if (!FieldRec->hasCopyAssignmentWithConstParam())
854           data().ImplicitCopyAssignmentHasConstParam = false;
855 
856         if (FieldRec->hasUninitializedReferenceMember() &&
857             !Field->hasInClassInitializer())
858           data().HasUninitializedReferenceMember = true;
859       }
860     } else {
861       // Base element type of field is a non-class type.
862       if (!T->isLiteralType(Context) ||
863           (!Field->hasInClassInitializer() && !isUnion()))
864         data().DefaultedDefaultConstructorIsConstexpr = false;
865 
866       // C++11 [class.copy]p23:
867       //   A defaulted copy/move assignment operator for a class X is defined
868       //   as deleted if X has:
869       //    -- a non-static data member of const non-class type (or array
870       //       thereof)
871       if (T.isConstQualified())
872         data().DefaultedMoveAssignmentIsDeleted = true;
873     }
874 
875     // C++0x [class]p7:
876     //   A standard-layout class is a class that:
877     //    [...]
878     //    -- either has no non-static data members in the most derived
879     //       class and at most one base class with non-static data members,
880     //       or has no base classes with non-static data members, and
881     // At this point we know that we have a non-static data member, so the last
882     // clause holds.
883     if (!data().HasNoNonEmptyBases)
884       data().IsStandardLayout = false;
885 
886     // If this is not a zero-length bit-field, then the class is not empty.
887     if (data().Empty) {
888       if (!Field->isBitField() ||
889           (!Field->getBitWidth()->isTypeDependent() &&
890            !Field->getBitWidth()->isValueDependent() &&
891            Field->getBitWidthValue(Context) != 0))
892         data().Empty = false;
893     }
894   }
895 
896   // Handle using declarations of conversion functions.
897   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D)) {
898     if (Shadow->getDeclName().getNameKind()
899           == DeclarationName::CXXConversionFunctionName) {
900       ASTContext &Ctx = getASTContext();
901       data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());
902     }
903   }
904 }
905 
906 void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
907   assert(!D->isImplicit() && !D->isUserProvided());
908 
909   // The kind of special member this declaration is, if any.
910   unsigned SMKind = 0;
911 
912   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
913     if (Constructor->isDefaultConstructor()) {
914       SMKind |= SMF_DefaultConstructor;
915       if (Constructor->isConstexpr())
916         data().HasConstexprDefaultConstructor = true;
917     }
918     if (Constructor->isCopyConstructor())
919       SMKind |= SMF_CopyConstructor;
920     else if (Constructor->isMoveConstructor())
921       SMKind |= SMF_MoveConstructor;
922     else if (Constructor->isConstexpr())
923       // We may now know that the constructor is constexpr.
924       data().HasConstexprNonCopyMoveConstructor = true;
925   } else if (isa<CXXDestructorDecl>(D))
926     SMKind |= SMF_Destructor;
927   else if (D->isCopyAssignmentOperator())
928     SMKind |= SMF_CopyAssignment;
929   else if (D->isMoveAssignmentOperator())
930     SMKind |= SMF_MoveAssignment;
931 
932   // Update which trivial / non-trivial special members we have.
933   // addedMember will have skipped this step for this member.
934   if (D->isTrivial())
935     data().HasTrivialSpecialMembers |= SMKind;
936   else
937     data().DeclaredNonTrivialSpecialMembers |= SMKind;
938 }
939 
940 bool CXXRecordDecl::isCLike() const {
941   if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface ||
942       !TemplateOrInstantiation.isNull())
943     return false;
944   if (!hasDefinition())
945     return true;
946 
947   return isPOD() && data().HasOnlyCMembers;
948 }
949 
950 bool CXXRecordDecl::isGenericLambda() const {
951   if (!isLambda()) return false;
952   return getLambdaData().IsGenericLambda;
953 }
954 
955 CXXMethodDecl* CXXRecordDecl::getLambdaCallOperator() const {
956   if (!isLambda()) return 0;
957   DeclarationName Name =
958     getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
959   DeclContext::lookup_const_result Calls = lookup(Name);
960 
961   assert(!Calls.empty() && "Missing lambda call operator!");
962   assert(Calls.size() == 1 && "More than one lambda call operator!");
963 
964   NamedDecl *CallOp = Calls.front();
965   if (FunctionTemplateDecl *CallOpTmpl =
966                     dyn_cast<FunctionTemplateDecl>(CallOp))
967     return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());
968 
969   return cast<CXXMethodDecl>(CallOp);
970 }
971 
972 CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
973   if (!isLambda()) return 0;
974   DeclarationName Name =
975     &getASTContext().Idents.get(getLambdaStaticInvokerName());
976   DeclContext::lookup_const_result Invoker = lookup(Name);
977   if (Invoker.empty()) return 0;
978   assert(Invoker.size() == 1 && "More than one static invoker operator!");
979   NamedDecl *InvokerFun = Invoker.front();
980   if (FunctionTemplateDecl *InvokerTemplate =
981                   dyn_cast<FunctionTemplateDecl>(InvokerFun))
982     return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());
983 
984   return cast<CXXMethodDecl>(InvokerFun);
985 }
986 
987 void CXXRecordDecl::getCaptureFields(
988        llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
989        FieldDecl *&ThisCapture) const {
990   Captures.clear();
991   ThisCapture = 0;
992 
993   LambdaDefinitionData &Lambda = getLambdaData();
994   RecordDecl::field_iterator Field = field_begin();
995   for (LambdaExpr::Capture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
996        C != CEnd; ++C, ++Field) {
997     if (C->capturesThis())
998       ThisCapture = *Field;
999     else if (C->capturesVariable())
1000       Captures[C->getCapturedVar()] = *Field;
1001   }
1002   assert(Field == field_end());
1003 }
1004 
1005 TemplateParameterList *
1006 CXXRecordDecl::getGenericLambdaTemplateParameterList() const {
1007   if (!isLambda()) return 0;
1008   CXXMethodDecl *CallOp = getLambdaCallOperator();
1009   if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())
1010     return Tmpl->getTemplateParameters();
1011   return 0;
1012 }
1013 
1014 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
1015   QualType T;
1016   if (isa<UsingShadowDecl>(Conv))
1017     Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
1018   if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
1019     T = ConvTemp->getTemplatedDecl()->getResultType();
1020   else
1021     T = cast<CXXConversionDecl>(Conv)->getConversionType();
1022   return Context.getCanonicalType(T);
1023 }
1024 
1025 /// Collect the visible conversions of a base class.
1026 ///
1027 /// \param Record a base class of the class we're considering
1028 /// \param InVirtual whether this base class is a virtual base (or a base
1029 ///   of a virtual base)
1030 /// \param Access the access along the inheritance path to this base
1031 /// \param ParentHiddenTypes the conversions provided by the inheritors
1032 ///   of this base
1033 /// \param Output the set to which to add conversions from non-virtual bases
1034 /// \param VOutput the set to which to add conversions from virtual bases
1035 /// \param HiddenVBaseCs the set of conversions which were hidden in a
1036 ///   virtual base along some inheritance path
1037 static void CollectVisibleConversions(ASTContext &Context,
1038                                       CXXRecordDecl *Record,
1039                                       bool InVirtual,
1040                                       AccessSpecifier Access,
1041                   const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
1042                                       ASTUnresolvedSet &Output,
1043                                       UnresolvedSetImpl &VOutput,
1044                            llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
1045   // The set of types which have conversions in this class or its
1046   // subclasses.  As an optimization, we don't copy the derived set
1047   // unless it might change.
1048   const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1049   llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1050 
1051   // Collect the direct conversions and figure out which conversions
1052   // will be hidden in the subclasses.
1053   CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1054   CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1055   if (ConvI != ConvE) {
1056     HiddenTypesBuffer = ParentHiddenTypes;
1057     HiddenTypes = &HiddenTypesBuffer;
1058 
1059     for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
1060       CanQualType ConvType(GetConversionType(Context, I.getDecl()));
1061       bool Hidden = ParentHiddenTypes.count(ConvType);
1062       if (!Hidden)
1063         HiddenTypesBuffer.insert(ConvType);
1064 
1065       // If this conversion is hidden and we're in a virtual base,
1066       // remember that it's hidden along some inheritance path.
1067       if (Hidden && InVirtual)
1068         HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1069 
1070       // If this conversion isn't hidden, add it to the appropriate output.
1071       else if (!Hidden) {
1072         AccessSpecifier IAccess
1073           = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1074 
1075         if (InVirtual)
1076           VOutput.addDecl(I.getDecl(), IAccess);
1077         else
1078           Output.addDecl(Context, I.getDecl(), IAccess);
1079       }
1080     }
1081   }
1082 
1083   // Collect information recursively from any base classes.
1084   for (CXXRecordDecl::base_class_iterator
1085          I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1086     const RecordType *RT = I->getType()->getAs<RecordType>();
1087     if (!RT) continue;
1088 
1089     AccessSpecifier BaseAccess
1090       = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
1091     bool BaseInVirtual = InVirtual || I->isVirtual();
1092 
1093     CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1094     CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1095                               *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1096   }
1097 }
1098 
1099 /// Collect the visible conversions of a class.
1100 ///
1101 /// This would be extremely straightforward if it weren't for virtual
1102 /// bases.  It might be worth special-casing that, really.
1103 static void CollectVisibleConversions(ASTContext &Context,
1104                                       CXXRecordDecl *Record,
1105                                       ASTUnresolvedSet &Output) {
1106   // The collection of all conversions in virtual bases that we've
1107   // found.  These will be added to the output as long as they don't
1108   // appear in the hidden-conversions set.
1109   UnresolvedSet<8> VBaseCs;
1110 
1111   // The set of conversions in virtual bases that we've determined to
1112   // be hidden.
1113   llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1114 
1115   // The set of types hidden by classes derived from this one.
1116   llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1117 
1118   // Go ahead and collect the direct conversions and add them to the
1119   // hidden-types set.
1120   CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1121   CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1122   Output.append(Context, ConvI, ConvE);
1123   for (; ConvI != ConvE; ++ConvI)
1124     HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
1125 
1126   // Recursively collect conversions from base classes.
1127   for (CXXRecordDecl::base_class_iterator
1128          I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1129     const RecordType *RT = I->getType()->getAs<RecordType>();
1130     if (!RT) continue;
1131 
1132     CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1133                               I->isVirtual(), I->getAccessSpecifier(),
1134                               HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1135   }
1136 
1137   // Add any unhidden conversions provided by virtual bases.
1138   for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1139          I != E; ++I) {
1140     if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1141       Output.addDecl(Context, I.getDecl(), I.getAccess());
1142   }
1143 }
1144 
1145 /// getVisibleConversionFunctions - get all conversion functions visible
1146 /// in current class; including conversion function templates.
1147 std::pair<CXXRecordDecl::conversion_iterator,CXXRecordDecl::conversion_iterator>
1148 CXXRecordDecl::getVisibleConversionFunctions() {
1149   ASTContext &Ctx = getASTContext();
1150 
1151   ASTUnresolvedSet *Set;
1152   if (bases_begin() == bases_end()) {
1153     // If root class, all conversions are visible.
1154     Set = &data().Conversions.get(Ctx);
1155   } else {
1156     Set = &data().VisibleConversions.get(Ctx);
1157     // If visible conversion list is not evaluated, evaluate it.
1158     if (!data().ComputedVisibleConversions) {
1159       CollectVisibleConversions(Ctx, this, *Set);
1160       data().ComputedVisibleConversions = true;
1161     }
1162   }
1163   return std::make_pair(Set->begin(), Set->end());
1164 }
1165 
1166 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1167   // This operation is O(N) but extremely rare.  Sema only uses it to
1168   // remove UsingShadowDecls in a class that were followed by a direct
1169   // declaration, e.g.:
1170   //   class A : B {
1171   //     using B::operator int;
1172   //     operator int();
1173   //   };
1174   // This is uncommon by itself and even more uncommon in conjunction
1175   // with sufficiently large numbers of directly-declared conversions
1176   // that asymptotic behavior matters.
1177 
1178   ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());
1179   for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1180     if (Convs[I].getDecl() == ConvDecl) {
1181       Convs.erase(I);
1182       assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
1183              && "conversion was found multiple times in unresolved set");
1184       return;
1185     }
1186   }
1187 
1188   llvm_unreachable("conversion not found in set!");
1189 }
1190 
1191 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1192   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1193     return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1194 
1195   return 0;
1196 }
1197 
1198 void
1199 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1200                                              TemplateSpecializationKind TSK) {
1201   assert(TemplateOrInstantiation.isNull() &&
1202          "Previous template or instantiation?");
1203   assert(!isa<ClassTemplateSpecializationDecl>(this));
1204   TemplateOrInstantiation
1205     = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1206 }
1207 
1208 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1209   if (const ClassTemplateSpecializationDecl *Spec
1210         = dyn_cast<ClassTemplateSpecializationDecl>(this))
1211     return Spec->getSpecializationKind();
1212 
1213   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1214     return MSInfo->getTemplateSpecializationKind();
1215 
1216   return TSK_Undeclared;
1217 }
1218 
1219 void
1220 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1221   if (ClassTemplateSpecializationDecl *Spec
1222       = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1223     Spec->setSpecializationKind(TSK);
1224     return;
1225   }
1226 
1227   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1228     MSInfo->setTemplateSpecializationKind(TSK);
1229     return;
1230   }
1231 
1232   llvm_unreachable("Not a class template or member class specialization");
1233 }
1234 
1235 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1236   ASTContext &Context = getASTContext();
1237   QualType ClassType = Context.getTypeDeclType(this);
1238 
1239   DeclarationName Name
1240     = Context.DeclarationNames.getCXXDestructorName(
1241                                           Context.getCanonicalType(ClassType));
1242 
1243   DeclContext::lookup_const_result R = lookup(Name);
1244   if (R.empty())
1245     return 0;
1246 
1247   CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(R.front());
1248   return Dtor;
1249 }
1250 
1251 void CXXRecordDecl::completeDefinition() {
1252   completeDefinition(0);
1253 }
1254 
1255 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1256   RecordDecl::completeDefinition();
1257 
1258   if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount) {
1259     // Objective-C Automatic Reference Counting:
1260     //   If a class has a non-static data member of Objective-C pointer
1261     //   type (or array thereof), it is a non-POD type and its
1262     //   default constructor (if any), copy constructor, move constructor,
1263     //   copy assignment operator, move assignment operator, and destructor are
1264     //   non-trivial.
1265     struct DefinitionData &Data = data();
1266     Data.PlainOldData = false;
1267     Data.HasTrivialSpecialMembers = 0;
1268     Data.HasIrrelevantDestructor = false;
1269   }
1270 
1271   // If the class may be abstract (but hasn't been marked as such), check for
1272   // any pure final overriders.
1273   if (mayBeAbstract()) {
1274     CXXFinalOverriderMap MyFinalOverriders;
1275     if (!FinalOverriders) {
1276       getFinalOverriders(MyFinalOverriders);
1277       FinalOverriders = &MyFinalOverriders;
1278     }
1279 
1280     bool Done = false;
1281     for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1282                                      MEnd = FinalOverriders->end();
1283          M != MEnd && !Done; ++M) {
1284       for (OverridingMethods::iterator SO = M->second.begin(),
1285                                     SOEnd = M->second.end();
1286            SO != SOEnd && !Done; ++SO) {
1287         assert(SO->second.size() > 0 &&
1288                "All virtual functions have overridding virtual functions");
1289 
1290         // C++ [class.abstract]p4:
1291         //   A class is abstract if it contains or inherits at least one
1292         //   pure virtual function for which the final overrider is pure
1293         //   virtual.
1294         if (SO->second.front().Method->isPure()) {
1295           data().Abstract = true;
1296           Done = true;
1297           break;
1298         }
1299       }
1300     }
1301   }
1302 
1303   // Set access bits correctly on the directly-declared conversions.
1304   for (conversion_iterator I = conversion_begin(), E = conversion_end();
1305        I != E; ++I)
1306     I.setAccess((*I)->getAccess());
1307 }
1308 
1309 bool CXXRecordDecl::mayBeAbstract() const {
1310   if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1311       isDependentContext())
1312     return false;
1313 
1314   for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1315                                              BEnd = bases_end();
1316        B != BEnd; ++B) {
1317     CXXRecordDecl *BaseDecl
1318       = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1319     if (BaseDecl->isAbstract())
1320       return true;
1321   }
1322 
1323   return false;
1324 }
1325 
1326 void CXXMethodDecl::anchor() { }
1327 
1328 bool CXXMethodDecl::isStatic() const {
1329   const CXXMethodDecl *MD = getCanonicalDecl();
1330 
1331   if (MD->getStorageClass() == SC_Static)
1332     return true;
1333 
1334   OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();
1335   return isStaticOverloadedOperator(OOK);
1336 }
1337 
1338 static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
1339                                  const CXXMethodDecl *BaseMD) {
1340   for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),
1341          E = DerivedMD->end_overridden_methods(); I != E; ++I) {
1342     const CXXMethodDecl *MD = *I;
1343     if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
1344       return true;
1345     if (recursivelyOverrides(MD, BaseMD))
1346       return true;
1347   }
1348   return false;
1349 }
1350 
1351 CXXMethodDecl *
1352 CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
1353                                              bool MayBeBase) {
1354   if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
1355     return this;
1356 
1357   // Lookup doesn't work for destructors, so handle them separately.
1358   if (isa<CXXDestructorDecl>(this)) {
1359     CXXMethodDecl *MD = RD->getDestructor();
1360     if (MD) {
1361       if (recursivelyOverrides(MD, this))
1362         return MD;
1363       if (MayBeBase && recursivelyOverrides(this, MD))
1364         return MD;
1365     }
1366     return NULL;
1367   }
1368 
1369   lookup_const_result Candidates = RD->lookup(getDeclName());
1370   for (NamedDecl * const * I = Candidates.begin(); I != Candidates.end(); ++I) {
1371     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I);
1372     if (!MD)
1373       continue;
1374     if (recursivelyOverrides(MD, this))
1375       return MD;
1376     if (MayBeBase && recursivelyOverrides(this, MD))
1377       return MD;
1378   }
1379 
1380   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1381          E = RD->bases_end(); I != E; ++I) {
1382     const RecordType *RT = I->getType()->getAs<RecordType>();
1383     if (!RT)
1384       continue;
1385     const CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1386     CXXMethodDecl *T = this->getCorrespondingMethodInClass(Base);
1387     if (T)
1388       return T;
1389   }
1390 
1391   return NULL;
1392 }
1393 
1394 CXXMethodDecl *
1395 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1396                       SourceLocation StartLoc,
1397                       const DeclarationNameInfo &NameInfo,
1398                       QualType T, TypeSourceInfo *TInfo,
1399                       StorageClass SC, bool isInline,
1400                       bool isConstexpr, SourceLocation EndLocation) {
1401   return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1402                                SC, isInline, isConstexpr,
1403                                EndLocation);
1404 }
1405 
1406 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1407   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXMethodDecl));
1408   return new (Mem) CXXMethodDecl(CXXMethod, 0, SourceLocation(),
1409                                  DeclarationNameInfo(), QualType(),
1410                                  0, SC_None, false, false,
1411                                  SourceLocation());
1412 }
1413 
1414 bool CXXMethodDecl::isUsualDeallocationFunction() const {
1415   if (getOverloadedOperator() != OO_Delete &&
1416       getOverloadedOperator() != OO_Array_Delete)
1417     return false;
1418 
1419   // C++ [basic.stc.dynamic.deallocation]p2:
1420   //   A template instance is never a usual deallocation function,
1421   //   regardless of its signature.
1422   if (getPrimaryTemplate())
1423     return false;
1424 
1425   // C++ [basic.stc.dynamic.deallocation]p2:
1426   //   If a class T has a member deallocation function named operator delete
1427   //   with exactly one parameter, then that function is a usual (non-placement)
1428   //   deallocation function. [...]
1429   if (getNumParams() == 1)
1430     return true;
1431 
1432   // C++ [basic.stc.dynamic.deallocation]p2:
1433   //   [...] If class T does not declare such an operator delete but does
1434   //   declare a member deallocation function named operator delete with
1435   //   exactly two parameters, the second of which has type std::size_t (18.1),
1436   //   then this function is a usual deallocation function.
1437   ASTContext &Context = getASTContext();
1438   if (getNumParams() != 2 ||
1439       !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1440                                       Context.getSizeType()))
1441     return false;
1442 
1443   // This function is a usual deallocation function if there are no
1444   // single-parameter deallocation functions of the same kind.
1445   DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1446   for (DeclContext::lookup_const_result::iterator I = R.begin(), E = R.end();
1447        I != E; ++I) {
1448     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
1449       if (FD->getNumParams() == 1)
1450         return false;
1451   }
1452 
1453   return true;
1454 }
1455 
1456 bool CXXMethodDecl::isCopyAssignmentOperator() const {
1457   // C++0x [class.copy]p17:
1458   //  A user-declared copy assignment operator X::operator= is a non-static
1459   //  non-template member function of class X with exactly one parameter of
1460   //  type X, X&, const X&, volatile X& or const volatile X&.
1461   if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1462       /*non-static*/ isStatic() ||
1463       /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
1464       getNumParams() != 1)
1465     return false;
1466 
1467   QualType ParamType = getParamDecl(0)->getType();
1468   if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1469     ParamType = Ref->getPointeeType();
1470 
1471   ASTContext &Context = getASTContext();
1472   QualType ClassType
1473     = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1474   return Context.hasSameUnqualifiedType(ClassType, ParamType);
1475 }
1476 
1477 bool CXXMethodDecl::isMoveAssignmentOperator() const {
1478   // C++0x [class.copy]p19:
1479   //  A user-declared move assignment operator X::operator= is a non-static
1480   //  non-template member function of class X with exactly one parameter of type
1481   //  X&&, const X&&, volatile X&&, or const volatile X&&.
1482   if (getOverloadedOperator() != OO_Equal || isStatic() ||
1483       getPrimaryTemplate() || getDescribedFunctionTemplate() ||
1484       getNumParams() != 1)
1485     return false;
1486 
1487   QualType ParamType = getParamDecl(0)->getType();
1488   if (!isa<RValueReferenceType>(ParamType))
1489     return false;
1490   ParamType = ParamType->getPointeeType();
1491 
1492   ASTContext &Context = getASTContext();
1493   QualType ClassType
1494     = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1495   return Context.hasSameUnqualifiedType(ClassType, ParamType);
1496 }
1497 
1498 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1499   assert(MD->isCanonicalDecl() && "Method is not canonical!");
1500   assert(!MD->getParent()->isDependentContext() &&
1501          "Can't add an overridden method to a class template!");
1502   assert(MD->isVirtual() && "Method is not virtual!");
1503 
1504   getASTContext().addOverriddenMethod(this, MD);
1505 }
1506 
1507 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1508   if (isa<CXXConstructorDecl>(this)) return 0;
1509   return getASTContext().overridden_methods_begin(this);
1510 }
1511 
1512 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1513   if (isa<CXXConstructorDecl>(this)) return 0;
1514   return getASTContext().overridden_methods_end(this);
1515 }
1516 
1517 unsigned CXXMethodDecl::size_overridden_methods() const {
1518   if (isa<CXXConstructorDecl>(this)) return 0;
1519   return getASTContext().overridden_methods_size(this);
1520 }
1521 
1522 QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1523   // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1524   // If the member function is declared const, the type of this is const X*,
1525   // if the member function is declared volatile, the type of this is
1526   // volatile X*, and if the member function is declared const volatile,
1527   // the type of this is const volatile X*.
1528 
1529   assert(isInstance() && "No 'this' for static methods!");
1530 
1531   QualType ClassTy = C.getTypeDeclType(getParent());
1532   ClassTy = C.getQualifiedType(ClassTy,
1533                                Qualifiers::fromCVRMask(getTypeQualifiers()));
1534   return C.getPointerType(ClassTy);
1535 }
1536 
1537 bool CXXMethodDecl::hasInlineBody() const {
1538   // If this function is a template instantiation, look at the template from
1539   // which it was instantiated.
1540   const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1541   if (!CheckFn)
1542     CheckFn = this;
1543 
1544   const FunctionDecl *fn;
1545   return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1546 }
1547 
1548 bool CXXMethodDecl::isLambdaStaticInvoker() const {
1549   const CXXRecordDecl *P = getParent();
1550   if (P->isLambda()) {
1551     if (const CXXMethodDecl *StaticInvoker = P->getLambdaStaticInvoker()) {
1552       if (StaticInvoker == this) return true;
1553       if (P->isGenericLambda() && this->isFunctionTemplateSpecialization())
1554         return StaticInvoker == this->getPrimaryTemplate()->getTemplatedDecl();
1555     }
1556   }
1557   return false;
1558 }
1559 
1560 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1561                                        TypeSourceInfo *TInfo, bool IsVirtual,
1562                                        SourceLocation L, Expr *Init,
1563                                        SourceLocation R,
1564                                        SourceLocation EllipsisLoc)
1565   : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
1566     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
1567     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1568 {
1569 }
1570 
1571 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1572                                        FieldDecl *Member,
1573                                        SourceLocation MemberLoc,
1574                                        SourceLocation L, Expr *Init,
1575                                        SourceLocation R)
1576   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1577     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1578     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1579 {
1580 }
1581 
1582 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1583                                        IndirectFieldDecl *Member,
1584                                        SourceLocation MemberLoc,
1585                                        SourceLocation L, Expr *Init,
1586                                        SourceLocation R)
1587   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1588     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1589     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1590 {
1591 }
1592 
1593 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1594                                        TypeSourceInfo *TInfo,
1595                                        SourceLocation L, Expr *Init,
1596                                        SourceLocation R)
1597   : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init),
1598     LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false),
1599     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1600 {
1601 }
1602 
1603 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1604                                        FieldDecl *Member,
1605                                        SourceLocation MemberLoc,
1606                                        SourceLocation L, Expr *Init,
1607                                        SourceLocation R,
1608                                        VarDecl **Indices,
1609                                        unsigned NumIndices)
1610   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1611     LParenLoc(L), RParenLoc(R), IsVirtual(false),
1612     IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1613 {
1614   VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1615   memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1616 }
1617 
1618 CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1619                                                FieldDecl *Member,
1620                                                SourceLocation MemberLoc,
1621                                                SourceLocation L, Expr *Init,
1622                                                SourceLocation R,
1623                                                VarDecl **Indices,
1624                                                unsigned NumIndices) {
1625   void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1626                                sizeof(VarDecl *) * NumIndices,
1627                                llvm::alignOf<CXXCtorInitializer>());
1628   return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1629                                       Indices, NumIndices);
1630 }
1631 
1632 TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1633   if (isBaseInitializer())
1634     return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1635   else
1636     return TypeLoc();
1637 }
1638 
1639 const Type *CXXCtorInitializer::getBaseClass() const {
1640   if (isBaseInitializer())
1641     return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1642   else
1643     return 0;
1644 }
1645 
1646 SourceLocation CXXCtorInitializer::getSourceLocation() const {
1647   if (isAnyMemberInitializer())
1648     return getMemberLocation();
1649 
1650   if (isInClassMemberInitializer())
1651     return getAnyMember()->getLocation();
1652 
1653   if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>())
1654     return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
1655 
1656   return SourceLocation();
1657 }
1658 
1659 SourceRange CXXCtorInitializer::getSourceRange() const {
1660   if (isInClassMemberInitializer()) {
1661     FieldDecl *D = getAnyMember();
1662     if (Expr *I = D->getInClassInitializer())
1663       return I->getSourceRange();
1664     return SourceRange();
1665   }
1666 
1667   return SourceRange(getSourceLocation(), getRParenLoc());
1668 }
1669 
1670 void CXXConstructorDecl::anchor() { }
1671 
1672 CXXConstructorDecl *
1673 CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1674   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConstructorDecl));
1675   return new (Mem) CXXConstructorDecl(0, SourceLocation(),DeclarationNameInfo(),
1676                                       QualType(), 0, false, false, false,false);
1677 }
1678 
1679 CXXConstructorDecl *
1680 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1681                            SourceLocation StartLoc,
1682                            const DeclarationNameInfo &NameInfo,
1683                            QualType T, TypeSourceInfo *TInfo,
1684                            bool isExplicit, bool isInline,
1685                            bool isImplicitlyDeclared, bool isConstexpr) {
1686   assert(NameInfo.getName().getNameKind()
1687          == DeclarationName::CXXConstructorName &&
1688          "Name must refer to a constructor");
1689   return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1690                                     isExplicit, isInline, isImplicitlyDeclared,
1691                                     isConstexpr);
1692 }
1693 
1694 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
1695   assert(isDelegatingConstructor() && "Not a delegating constructor!");
1696   Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
1697   if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(E))
1698     return Construct->getConstructor();
1699 
1700   return 0;
1701 }
1702 
1703 bool CXXConstructorDecl::isDefaultConstructor() const {
1704   // C++ [class.ctor]p5:
1705   //   A default constructor for a class X is a constructor of class
1706   //   X that can be called without an argument.
1707   return (getNumParams() == 0) ||
1708          (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1709 }
1710 
1711 bool
1712 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1713   return isCopyOrMoveConstructor(TypeQuals) &&
1714          getParamDecl(0)->getType()->isLValueReferenceType();
1715 }
1716 
1717 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1718   return isCopyOrMoveConstructor(TypeQuals) &&
1719     getParamDecl(0)->getType()->isRValueReferenceType();
1720 }
1721 
1722 /// \brief Determine whether this is a copy or move constructor.
1723 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1724   // C++ [class.copy]p2:
1725   //   A non-template constructor for class X is a copy constructor
1726   //   if its first parameter is of type X&, const X&, volatile X& or
1727   //   const volatile X&, and either there are no other parameters
1728   //   or else all other parameters have default arguments (8.3.6).
1729   // C++0x [class.copy]p3:
1730   //   A non-template constructor for class X is a move constructor if its
1731   //   first parameter is of type X&&, const X&&, volatile X&&, or
1732   //   const volatile X&&, and either there are no other parameters or else
1733   //   all other parameters have default arguments.
1734   if ((getNumParams() < 1) ||
1735       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1736       (getPrimaryTemplate() != 0) ||
1737       (getDescribedFunctionTemplate() != 0))
1738     return false;
1739 
1740   const ParmVarDecl *Param = getParamDecl(0);
1741 
1742   // Do we have a reference type?
1743   const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1744   if (!ParamRefType)
1745     return false;
1746 
1747   // Is it a reference to our class type?
1748   ASTContext &Context = getASTContext();
1749 
1750   CanQualType PointeeType
1751     = Context.getCanonicalType(ParamRefType->getPointeeType());
1752   CanQualType ClassTy
1753     = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1754   if (PointeeType.getUnqualifiedType() != ClassTy)
1755     return false;
1756 
1757   // FIXME: other qualifiers?
1758 
1759   // We have a copy or move constructor.
1760   TypeQuals = PointeeType.getCVRQualifiers();
1761   return true;
1762 }
1763 
1764 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1765   // C++ [class.conv.ctor]p1:
1766   //   A constructor declared without the function-specifier explicit
1767   //   that can be called with a single parameter specifies a
1768   //   conversion from the type of its first parameter to the type of
1769   //   its class. Such a constructor is called a converting
1770   //   constructor.
1771   if (isExplicit() && !AllowExplicit)
1772     return false;
1773 
1774   return (getNumParams() == 0 &&
1775           getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1776          (getNumParams() == 1) ||
1777          (getNumParams() > 1 &&
1778           (getParamDecl(1)->hasDefaultArg() ||
1779            getParamDecl(1)->isParameterPack()));
1780 }
1781 
1782 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1783   if ((getNumParams() < 1) ||
1784       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1785       (getPrimaryTemplate() == 0) ||
1786       (getDescribedFunctionTemplate() != 0))
1787     return false;
1788 
1789   const ParmVarDecl *Param = getParamDecl(0);
1790 
1791   ASTContext &Context = getASTContext();
1792   CanQualType ParamType = Context.getCanonicalType(Param->getType());
1793 
1794   // Is it the same as our our class type?
1795   CanQualType ClassTy
1796     = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1797   if (ParamType.getUnqualifiedType() != ClassTy)
1798     return false;
1799 
1800   return true;
1801 }
1802 
1803 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1804   // Hack: we store the inherited constructor in the overridden method table
1805   method_iterator It = getASTContext().overridden_methods_begin(this);
1806   if (It == getASTContext().overridden_methods_end(this))
1807     return 0;
1808 
1809   return cast<CXXConstructorDecl>(*It);
1810 }
1811 
1812 void
1813 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1814   // Hack: we store the inherited constructor in the overridden method table
1815   assert(getASTContext().overridden_methods_size(this) == 0 &&
1816          "Base ctor already set.");
1817   getASTContext().addOverriddenMethod(this, BaseCtor);
1818 }
1819 
1820 void CXXDestructorDecl::anchor() { }
1821 
1822 CXXDestructorDecl *
1823 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1824   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXDestructorDecl));
1825   return new (Mem) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1826                                    QualType(), 0, false, false);
1827 }
1828 
1829 CXXDestructorDecl *
1830 CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1831                           SourceLocation StartLoc,
1832                           const DeclarationNameInfo &NameInfo,
1833                           QualType T, TypeSourceInfo *TInfo,
1834                           bool isInline, bool isImplicitlyDeclared) {
1835   assert(NameInfo.getName().getNameKind()
1836          == DeclarationName::CXXDestructorName &&
1837          "Name must refer to a destructor");
1838   return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1839                                    isImplicitlyDeclared);
1840 }
1841 
1842 void CXXConversionDecl::anchor() { }
1843 
1844 CXXConversionDecl *
1845 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1846   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConversionDecl));
1847   return new (Mem) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1848                                      QualType(), 0, false, false, false,
1849                                      SourceLocation());
1850 }
1851 
1852 CXXConversionDecl *
1853 CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1854                           SourceLocation StartLoc,
1855                           const DeclarationNameInfo &NameInfo,
1856                           QualType T, TypeSourceInfo *TInfo,
1857                           bool isInline, bool isExplicit,
1858                           bool isConstexpr, SourceLocation EndLocation) {
1859   assert(NameInfo.getName().getNameKind()
1860          == DeclarationName::CXXConversionFunctionName &&
1861          "Name must refer to a conversion function");
1862   return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1863                                    isInline, isExplicit, isConstexpr,
1864                                    EndLocation);
1865 }
1866 
1867 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
1868   return isImplicit() && getParent()->isLambda() &&
1869          getConversionType()->isBlockPointerType();
1870 }
1871 
1872 void LinkageSpecDecl::anchor() { }
1873 
1874 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1875                                          DeclContext *DC,
1876                                          SourceLocation ExternLoc,
1877                                          SourceLocation LangLoc,
1878                                          LanguageIDs Lang,
1879                                          bool HasBraces) {
1880   return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
1881 }
1882 
1883 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1884   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
1885   return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
1886                                    lang_c, false);
1887 }
1888 
1889 void UsingDirectiveDecl::anchor() { }
1890 
1891 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1892                                                SourceLocation L,
1893                                                SourceLocation NamespaceLoc,
1894                                            NestedNameSpecifierLoc QualifierLoc,
1895                                                SourceLocation IdentLoc,
1896                                                NamedDecl *Used,
1897                                                DeclContext *CommonAncestor) {
1898   if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1899     Used = NS->getOriginalNamespace();
1900   return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1901                                     IdentLoc, Used, CommonAncestor);
1902 }
1903 
1904 UsingDirectiveDecl *
1905 UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1906   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDirectiveDecl));
1907   return new (Mem) UsingDirectiveDecl(0, SourceLocation(), SourceLocation(),
1908                                       NestedNameSpecifierLoc(),
1909                                       SourceLocation(), 0, 0);
1910 }
1911 
1912 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1913   if (NamespaceAliasDecl *NA =
1914         dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1915     return NA->getNamespace();
1916   return cast_or_null<NamespaceDecl>(NominatedNamespace);
1917 }
1918 
1919 void NamespaceDecl::anchor() { }
1920 
1921 NamespaceDecl::NamespaceDecl(DeclContext *DC, bool Inline,
1922                              SourceLocation StartLoc,
1923                              SourceLocation IdLoc, IdentifierInfo *Id,
1924                              NamespaceDecl *PrevDecl)
1925   : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
1926     LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(0, Inline)
1927 {
1928   setPreviousDecl(PrevDecl);
1929 
1930   if (PrevDecl)
1931     AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
1932 }
1933 
1934 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1935                                      bool Inline, SourceLocation StartLoc,
1936                                      SourceLocation IdLoc, IdentifierInfo *Id,
1937                                      NamespaceDecl *PrevDecl) {
1938   return new (C) NamespaceDecl(DC, Inline, StartLoc, IdLoc, Id, PrevDecl);
1939 }
1940 
1941 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1942   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceDecl));
1943   return new (Mem) NamespaceDecl(0, false, SourceLocation(), SourceLocation(),
1944                                  0, 0);
1945 }
1946 
1947 void NamespaceAliasDecl::anchor() { }
1948 
1949 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1950                                                SourceLocation UsingLoc,
1951                                                SourceLocation AliasLoc,
1952                                                IdentifierInfo *Alias,
1953                                            NestedNameSpecifierLoc QualifierLoc,
1954                                                SourceLocation IdentLoc,
1955                                                NamedDecl *Namespace) {
1956   if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1957     Namespace = NS->getOriginalNamespace();
1958   return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias,
1959                                     QualifierLoc, IdentLoc, Namespace);
1960 }
1961 
1962 NamespaceAliasDecl *
1963 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1964   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceAliasDecl));
1965   return new (Mem) NamespaceAliasDecl(0, SourceLocation(), SourceLocation(), 0,
1966                                       NestedNameSpecifierLoc(),
1967                                       SourceLocation(), 0);
1968 }
1969 
1970 void UsingShadowDecl::anchor() { }
1971 
1972 UsingShadowDecl *
1973 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1974   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingShadowDecl));
1975   return new (Mem) UsingShadowDecl(0, SourceLocation(), 0, 0);
1976 }
1977 
1978 UsingDecl *UsingShadowDecl::getUsingDecl() const {
1979   const UsingShadowDecl *Shadow = this;
1980   while (const UsingShadowDecl *NextShadow =
1981          dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1982     Shadow = NextShadow;
1983   return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1984 }
1985 
1986 void UsingDecl::anchor() { }
1987 
1988 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1989   assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1990          "declaration already in set");
1991   assert(S->getUsingDecl() == this);
1992 
1993   if (FirstUsingShadow.getPointer())
1994     S->UsingOrNextShadow = FirstUsingShadow.getPointer();
1995   FirstUsingShadow.setPointer(S);
1996 }
1997 
1998 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1999   assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
2000          "declaration not in set");
2001   assert(S->getUsingDecl() == this);
2002 
2003   // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
2004 
2005   if (FirstUsingShadow.getPointer() == S) {
2006     FirstUsingShadow.setPointer(
2007       dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
2008     S->UsingOrNextShadow = this;
2009     return;
2010   }
2011 
2012   UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
2013   while (Prev->UsingOrNextShadow != S)
2014     Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
2015   Prev->UsingOrNextShadow = S->UsingOrNextShadow;
2016   S->UsingOrNextShadow = this;
2017 }
2018 
2019 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
2020                              NestedNameSpecifierLoc QualifierLoc,
2021                              const DeclarationNameInfo &NameInfo,
2022                              bool HasTypename) {
2023   return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
2024 }
2025 
2026 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2027   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDecl));
2028   return new (Mem) UsingDecl(0, SourceLocation(), NestedNameSpecifierLoc(),
2029                              DeclarationNameInfo(), false);
2030 }
2031 
2032 SourceRange UsingDecl::getSourceRange() const {
2033   SourceLocation Begin = isAccessDeclaration()
2034     ? getQualifierLoc().getBeginLoc() : UsingLocation;
2035   return SourceRange(Begin, getNameInfo().getEndLoc());
2036 }
2037 
2038 void UnresolvedUsingValueDecl::anchor() { }
2039 
2040 UnresolvedUsingValueDecl *
2041 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
2042                                  SourceLocation UsingLoc,
2043                                  NestedNameSpecifierLoc QualifierLoc,
2044                                  const DeclarationNameInfo &NameInfo) {
2045   return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
2046                                           QualifierLoc, NameInfo);
2047 }
2048 
2049 UnresolvedUsingValueDecl *
2050 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2051   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UnresolvedUsingValueDecl));
2052   return new (Mem) UnresolvedUsingValueDecl(0, QualType(), SourceLocation(),
2053                                             NestedNameSpecifierLoc(),
2054                                             DeclarationNameInfo());
2055 }
2056 
2057 SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
2058   SourceLocation Begin = isAccessDeclaration()
2059     ? getQualifierLoc().getBeginLoc() : UsingLocation;
2060   return SourceRange(Begin, getNameInfo().getEndLoc());
2061 }
2062 
2063 void UnresolvedUsingTypenameDecl::anchor() { }
2064 
2065 UnresolvedUsingTypenameDecl *
2066 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
2067                                     SourceLocation UsingLoc,
2068                                     SourceLocation TypenameLoc,
2069                                     NestedNameSpecifierLoc QualifierLoc,
2070                                     SourceLocation TargetNameLoc,
2071                                     DeclarationName TargetName) {
2072   return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
2073                                              QualifierLoc, TargetNameLoc,
2074                                              TargetName.getAsIdentifierInfo());
2075 }
2076 
2077 UnresolvedUsingTypenameDecl *
2078 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2079   void *Mem = AllocateDeserializedDecl(C, ID,
2080                                        sizeof(UnresolvedUsingTypenameDecl));
2081   return new (Mem) UnresolvedUsingTypenameDecl(0, SourceLocation(),
2082                                                SourceLocation(),
2083                                                NestedNameSpecifierLoc(),
2084                                                SourceLocation(),
2085                                                0);
2086 }
2087 
2088 void StaticAssertDecl::anchor() { }
2089 
2090 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
2091                                            SourceLocation StaticAssertLoc,
2092                                            Expr *AssertExpr,
2093                                            StringLiteral *Message,
2094                                            SourceLocation RParenLoc,
2095                                            bool Failed) {
2096   return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
2097                                   RParenLoc, Failed);
2098 }
2099 
2100 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
2101                                                        unsigned ID) {
2102   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(StaticAssertDecl));
2103   return new (Mem) StaticAssertDecl(0, SourceLocation(), 0, 0,
2104                                     SourceLocation(), false);
2105 }
2106 
2107 static const char *getAccessName(AccessSpecifier AS) {
2108   switch (AS) {
2109     case AS_none:
2110       llvm_unreachable("Invalid access specifier!");
2111     case AS_public:
2112       return "public";
2113     case AS_private:
2114       return "private";
2115     case AS_protected:
2116       return "protected";
2117   }
2118   llvm_unreachable("Invalid access specifier!");
2119 }
2120 
2121 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
2122                                            AccessSpecifier AS) {
2123   return DB << getAccessName(AS);
2124 }
2125 
2126 const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
2127                                            AccessSpecifier AS) {
2128   return DB << getAccessName(AS);
2129 }
2130