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