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