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