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