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