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