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