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