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