xref: /llvm-project/clang/include/clang/AST/DeclCXX.h (revision abc8812df02599fc413d9ed77b992f8236ed2af9)
1 //===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Defines the C++ Decl subclasses, other than those for templates
11 /// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_AST_DECLCXX_H
16 #define LLVM_CLANG_AST_DECLCXX_H
17 
18 #include "clang/AST/ASTUnresolvedSet.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclarationName.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExternalASTSource.h"
24 #include "clang/AST/LambdaCapture.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/AST/Redeclarable.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/Type.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/AST/UnresolvedSet.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/Lambda.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/OperatorKinds.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/PointerIntPair.h"
40 #include "llvm/ADT/PointerUnion.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/TinyPtrVector.h"
43 #include "llvm/ADT/iterator_range.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/PointerLikeTypeTraits.h"
47 #include "llvm/Support/TrailingObjects.h"
48 #include <cassert>
49 #include <cstddef>
50 #include <iterator>
51 #include <memory>
52 #include <vector>
53 
54 namespace clang {
55 
56 class ASTContext;
57 class ClassTemplateDecl;
58 class ConstructorUsingShadowDecl;
59 class CXXBasePath;
60 class CXXBasePaths;
61 class CXXConstructorDecl;
62 class CXXDestructorDecl;
63 class CXXFinalOverriderMap;
64 class CXXIndirectPrimaryBaseSet;
65 class CXXMethodDecl;
66 class DecompositionDecl;
67 class FriendDecl;
68 class FunctionTemplateDecl;
69 class IdentifierInfo;
70 class MemberSpecializationInfo;
71 class BaseUsingDecl;
72 class TemplateDecl;
73 class TemplateParameterList;
74 class UsingDecl;
75 
76 /// Represents an access specifier followed by colon ':'.
77 ///
78 /// An objects of this class represents sugar for the syntactic occurrence
79 /// of an access specifier followed by a colon in the list of member
80 /// specifiers of a C++ class definition.
81 ///
82 /// Note that they do not represent other uses of access specifiers,
83 /// such as those occurring in a list of base specifiers.
84 /// Also note that this class has nothing to do with so-called
85 /// "access declarations" (C++98 11.3 [class.access.dcl]).
86 class AccessSpecDecl : public Decl {
87   /// The location of the ':'.
88   SourceLocation ColonLoc;
89 
90   AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
91                  SourceLocation ASLoc, SourceLocation ColonLoc)
92     : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
93     setAccess(AS);
94   }
95 
96   AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
97 
98   virtual void anchor();
99 
100 public:
101   /// The location of the access specifier.
102   SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
103 
104   /// Sets the location of the access specifier.
105   void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
106 
107   /// The location of the colon following the access specifier.
108   SourceLocation getColonLoc() const { return ColonLoc; }
109 
110   /// Sets the location of the colon.
111   void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
112 
113   SourceRange getSourceRange() const override LLVM_READONLY {
114     return SourceRange(getAccessSpecifierLoc(), getColonLoc());
115   }
116 
117   static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
118                                 DeclContext *DC, SourceLocation ASLoc,
119                                 SourceLocation ColonLoc) {
120     return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
121   }
122 
123   static AccessSpecDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
124 
125   // Implement isa/cast/dyncast/etc.
126   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
127   static bool classofKind(Kind K) { return K == AccessSpec; }
128 };
129 
130 /// Represents a base class of a C++ class.
131 ///
132 /// Each CXXBaseSpecifier represents a single, direct base class (or
133 /// struct) of a C++ class (or struct). It specifies the type of that
134 /// base class, whether it is a virtual or non-virtual base, and what
135 /// level of access (public, protected, private) is used for the
136 /// derivation. For example:
137 ///
138 /// \code
139 ///   class A { };
140 ///   class B { };
141 ///   class C : public virtual A, protected B { };
142 /// \endcode
143 ///
144 /// In this code, C will have two CXXBaseSpecifiers, one for "public
145 /// virtual A" and the other for "protected B".
146 class CXXBaseSpecifier {
147   /// The source code range that covers the full base
148   /// specifier, including the "virtual" (if present) and access
149   /// specifier (if present).
150   SourceRange Range;
151 
152   /// The source location of the ellipsis, if this is a pack
153   /// expansion.
154   SourceLocation EllipsisLoc;
155 
156   /// Whether this is a virtual base class or not.
157   LLVM_PREFERRED_TYPE(bool)
158   unsigned Virtual : 1;
159 
160   /// Whether this is the base of a class (true) or of a struct (false).
161   ///
162   /// This determines the mapping from the access specifier as written in the
163   /// source code to the access specifier used for semantic analysis.
164   LLVM_PREFERRED_TYPE(bool)
165   unsigned BaseOfClass : 1;
166 
167   /// Access specifier as written in the source code (may be AS_none).
168   ///
169   /// The actual type of data stored here is an AccessSpecifier, but we use
170   /// "unsigned" here to work around Microsoft ABI.
171   LLVM_PREFERRED_TYPE(AccessSpecifier)
172   unsigned Access : 2;
173 
174   /// Whether the class contains a using declaration
175   /// to inherit the named class's constructors.
176   LLVM_PREFERRED_TYPE(bool)
177   unsigned InheritConstructors : 1;
178 
179   /// The type of the base class.
180   ///
181   /// This will be a class or struct (or a typedef of such). The source code
182   /// range does not include the \c virtual or the access specifier.
183   TypeSourceInfo *BaseTypeInfo;
184 
185 public:
186   CXXBaseSpecifier() = default;
187   CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
188                    TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
189     : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
190       Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
191 
192   /// Retrieves the source range that contains the entire base specifier.
193   SourceRange getSourceRange() const LLVM_READONLY { return Range; }
194   SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
195   SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
196 
197   /// Get the location at which the base class type was written.
198   SourceLocation getBaseTypeLoc() const LLVM_READONLY {
199     return BaseTypeInfo->getTypeLoc().getBeginLoc();
200   }
201 
202   /// Determines whether the base class is a virtual base class (or not).
203   bool isVirtual() const { return Virtual; }
204 
205   /// Determine whether this base class is a base of a class declared
206   /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
207   bool isBaseOfClass() const { return BaseOfClass; }
208 
209   /// Determine whether this base specifier is a pack expansion.
210   bool isPackExpansion() const { return EllipsisLoc.isValid(); }
211 
212   /// Determine whether this base class's constructors get inherited.
213   bool getInheritConstructors() const { return InheritConstructors; }
214 
215   /// Set that this base class's constructors should be inherited.
216   void setInheritConstructors(bool Inherit = true) {
217     InheritConstructors = Inherit;
218   }
219 
220   /// For a pack expansion, determine the location of the ellipsis.
221   SourceLocation getEllipsisLoc() const {
222     return EllipsisLoc;
223   }
224 
225   /// Returns the access specifier for this base specifier.
226   ///
227   /// This is the actual base specifier as used for semantic analysis, so
228   /// the result can never be AS_none. To retrieve the access specifier as
229   /// written in the source code, use getAccessSpecifierAsWritten().
230   AccessSpecifier getAccessSpecifier() const {
231     if ((AccessSpecifier)Access == AS_none)
232       return BaseOfClass? AS_private : AS_public;
233     else
234       return (AccessSpecifier)Access;
235   }
236 
237   /// Retrieves the access specifier as written in the source code
238   /// (which may mean that no access specifier was explicitly written).
239   ///
240   /// Use getAccessSpecifier() to retrieve the access specifier for use in
241   /// semantic analysis.
242   AccessSpecifier getAccessSpecifierAsWritten() const {
243     return (AccessSpecifier)Access;
244   }
245 
246   /// Retrieves the type of the base class.
247   ///
248   /// This type will always be an unqualified class type.
249   QualType getType() const {
250     return BaseTypeInfo->getType().getUnqualifiedType();
251   }
252 
253   /// Retrieves the type and source location of the base class.
254   TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
255 };
256 
257 /// Represents a C++ struct/union/class.
258 class CXXRecordDecl : public RecordDecl {
259   friend class ASTDeclMerger;
260   friend class ASTDeclReader;
261   friend class ASTDeclWriter;
262   friend class ASTNodeImporter;
263   friend class ASTReader;
264   friend class ASTRecordWriter;
265   friend class ASTWriter;
266   friend class DeclContext;
267   friend class LambdaExpr;
268   friend class ODRDiagsEmitter;
269 
270   friend void FunctionDecl::setIsPureVirtual(bool);
271   friend void TagDecl::startDefinition();
272 
273   /// Values used in DefinitionData fields to represent special members.
274   enum SpecialMemberFlags {
275     SMF_DefaultConstructor = 0x1,
276     SMF_CopyConstructor = 0x2,
277     SMF_MoveConstructor = 0x4,
278     SMF_CopyAssignment = 0x8,
279     SMF_MoveAssignment = 0x10,
280     SMF_Destructor = 0x20,
281     SMF_All = 0x3f
282   };
283 
284 public:
285   enum LambdaDependencyKind {
286     LDK_Unknown = 0,
287     LDK_AlwaysDependent,
288     LDK_NeverDependent,
289   };
290 
291 private:
292   struct DefinitionData {
293     #define FIELD(Name, Width, Merge) \
294     unsigned Name : Width;
295     #include "CXXRecordDeclDefinitionBits.def"
296 
297     /// Whether this class describes a C++ lambda.
298     LLVM_PREFERRED_TYPE(bool)
299     unsigned IsLambda : 1;
300 
301     /// Whether we are currently parsing base specifiers.
302     LLVM_PREFERRED_TYPE(bool)
303     unsigned IsParsingBaseSpecifiers : 1;
304 
305     /// True when visible conversion functions are already computed
306     /// and are available.
307     LLVM_PREFERRED_TYPE(bool)
308     unsigned ComputedVisibleConversions : 1;
309 
310     LLVM_PREFERRED_TYPE(bool)
311     unsigned HasODRHash : 1;
312 
313     /// A hash of parts of the class to help in ODR checking.
314     unsigned ODRHash = 0;
315 
316     /// The number of base class specifiers in Bases.
317     unsigned NumBases = 0;
318 
319     /// The number of virtual base class specifiers in VBases.
320     unsigned NumVBases = 0;
321 
322     /// Base classes of this class.
323     ///
324     /// FIXME: This is wasted space for a union.
325     LazyCXXBaseSpecifiersPtr Bases;
326 
327     /// direct and indirect virtual base classes of this class.
328     LazyCXXBaseSpecifiersPtr VBases;
329 
330     /// The conversion functions of this C++ class (but not its
331     /// inherited conversion functions).
332     ///
333     /// Each of the entries in this overload set is a CXXConversionDecl.
334     LazyASTUnresolvedSet Conversions;
335 
336     /// The conversion functions of this C++ class and all those
337     /// inherited conversion functions that are visible in this class.
338     ///
339     /// Each of the entries in this overload set is a CXXConversionDecl or a
340     /// FunctionTemplateDecl.
341     LazyASTUnresolvedSet VisibleConversions;
342 
343     /// The declaration which defines this record.
344     CXXRecordDecl *Definition;
345 
346     /// The first friend declaration in this class, or null if there
347     /// aren't any.
348     ///
349     /// This is actually currently stored in reverse order.
350     LazyDeclPtr FirstFriend;
351 
352     DefinitionData(CXXRecordDecl *D);
353 
354     /// Retrieve the set of direct base classes.
355     CXXBaseSpecifier *getBases() const {
356       if (!Bases.isOffset())
357         return Bases.get(nullptr);
358       return getBasesSlowCase();
359     }
360 
361     /// Retrieve the set of virtual base classes.
362     CXXBaseSpecifier *getVBases() const {
363       if (!VBases.isOffset())
364         return VBases.get(nullptr);
365       return getVBasesSlowCase();
366     }
367 
368     ArrayRef<CXXBaseSpecifier> bases() const {
369       return llvm::ArrayRef(getBases(), NumBases);
370     }
371 
372     ArrayRef<CXXBaseSpecifier> vbases() const {
373       return llvm::ArrayRef(getVBases(), NumVBases);
374     }
375 
376   private:
377     CXXBaseSpecifier *getBasesSlowCase() const;
378     CXXBaseSpecifier *getVBasesSlowCase() const;
379   };
380 
381   struct DefinitionData *DefinitionData;
382 
383   /// Describes a C++ closure type (generated by a lambda expression).
384   struct LambdaDefinitionData : public DefinitionData {
385     using Capture = LambdaCapture;
386 
387     /// Whether this lambda is known to be dependent, even if its
388     /// context isn't dependent.
389     ///
390     /// A lambda with a non-dependent context can be dependent if it occurs
391     /// within the default argument of a function template, because the
392     /// lambda will have been created with the enclosing context as its
393     /// declaration context, rather than function. This is an unfortunate
394     /// artifact of having to parse the default arguments before.
395     LLVM_PREFERRED_TYPE(LambdaDependencyKind)
396     unsigned DependencyKind : 2;
397 
398     /// Whether this lambda is a generic lambda.
399     LLVM_PREFERRED_TYPE(bool)
400     unsigned IsGenericLambda : 1;
401 
402     /// The Default Capture.
403     LLVM_PREFERRED_TYPE(LambdaCaptureDefault)
404     unsigned CaptureDefault : 2;
405 
406     /// The number of captures in this lambda is limited 2^NumCaptures.
407     unsigned NumCaptures : 15;
408 
409     /// The number of explicit captures in this lambda.
410     unsigned NumExplicitCaptures : 12;
411 
412     /// Has known `internal` linkage.
413     LLVM_PREFERRED_TYPE(bool)
414     unsigned HasKnownInternalLinkage : 1;
415 
416     /// The number used to indicate this lambda expression for name
417     /// mangling in the Itanium C++ ABI.
418     unsigned ManglingNumber : 31;
419 
420     /// The index of this lambda within its context declaration. This is not in
421     /// general the same as the mangling number.
422     unsigned IndexInContext;
423 
424     /// The declaration that provides context for this lambda, if the
425     /// actual DeclContext does not suffice. This is used for lambdas that
426     /// occur within default arguments of function parameters within the class
427     /// or within a data member initializer.
428     LazyDeclPtr ContextDecl;
429 
430     /// The lists of captures, both explicit and implicit, for this
431     /// lambda. One list is provided for each merged copy of the lambda.
432     /// The first list corresponds to the canonical definition.
433     /// The destructor is registered by AddCaptureList when necessary.
434     llvm::TinyPtrVector<Capture*> Captures;
435 
436     /// The type of the call method.
437     TypeSourceInfo *MethodTyInfo;
438 
439     LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, unsigned DK,
440                          bool IsGeneric, LambdaCaptureDefault CaptureDefault)
441         : DefinitionData(D), DependencyKind(DK), IsGenericLambda(IsGeneric),
442           CaptureDefault(CaptureDefault), NumCaptures(0),
443           NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
444           IndexInContext(0), MethodTyInfo(Info) {
445       IsLambda = true;
446 
447       // C++1z [expr.prim.lambda]p4:
448       //   This class type is not an aggregate type.
449       Aggregate = false;
450       PlainOldData = false;
451     }
452 
453     // Add a list of captures.
454     void AddCaptureList(ASTContext &Ctx, Capture *CaptureList);
455   };
456 
457   struct DefinitionData *dataPtr() const {
458     // Complete the redecl chain (if necessary).
459     getMostRecentDecl();
460     return DefinitionData;
461   }
462 
463   struct DefinitionData &data() const {
464     auto *DD = dataPtr();
465     assert(DD && "queried property of class with no definition");
466     return *DD;
467   }
468 
469   struct LambdaDefinitionData &getLambdaData() const {
470     // No update required: a merged definition cannot change any lambda
471     // properties.
472     auto *DD = DefinitionData;
473     assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
474     return static_cast<LambdaDefinitionData&>(*DD);
475   }
476 
477   /// The template or declaration that this declaration
478   /// describes or was instantiated from, respectively.
479   ///
480   /// For non-templates, this value will be null. For record
481   /// declarations that describe a class template, this will be a
482   /// pointer to a ClassTemplateDecl. For member
483   /// classes of class template specializations, this will be the
484   /// MemberSpecializationInfo referring to the member class that was
485   /// instantiated or specialized.
486   llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
487       TemplateOrInstantiation;
488 
489   /// Called from setBases and addedMember to notify the class that a
490   /// direct or virtual base class or a member of class type has been added.
491   void addedClassSubobject(CXXRecordDecl *Base);
492 
493   /// Notify the class that member has been added.
494   ///
495   /// This routine helps maintain information about the class based on which
496   /// members have been added. It will be invoked by DeclContext::addDecl()
497   /// whenever a member is added to this record.
498   void addedMember(Decl *D);
499 
500   void markedVirtualFunctionPure();
501 
502   /// Get the head of our list of friend declarations, possibly
503   /// deserializing the friends from an external AST source.
504   FriendDecl *getFirstFriend() const;
505 
506   /// Determine whether this class has an empty base class subobject of type X
507   /// or of one of the types that might be at offset 0 within X (per the C++
508   /// "standard layout" rules).
509   bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
510                                                const CXXRecordDecl *X);
511 
512 protected:
513   CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
514                 SourceLocation StartLoc, SourceLocation IdLoc,
515                 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
516 
517 public:
518   /// Iterator that traverses the base classes of a class.
519   using base_class_iterator = CXXBaseSpecifier *;
520 
521   /// Iterator that traverses the base classes of a class.
522   using base_class_const_iterator = const CXXBaseSpecifier *;
523 
524   CXXRecordDecl *getCanonicalDecl() override {
525     return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
526   }
527 
528   const CXXRecordDecl *getCanonicalDecl() const {
529     return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
530   }
531 
532   CXXRecordDecl *getPreviousDecl() {
533     return cast_or_null<CXXRecordDecl>(
534             static_cast<RecordDecl *>(this)->getPreviousDecl());
535   }
536 
537   const CXXRecordDecl *getPreviousDecl() const {
538     return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
539   }
540 
541   CXXRecordDecl *getMostRecentDecl() {
542     return cast<CXXRecordDecl>(
543             static_cast<RecordDecl *>(this)->getMostRecentDecl());
544   }
545 
546   const CXXRecordDecl *getMostRecentDecl() const {
547     return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
548   }
549 
550   CXXRecordDecl *getMostRecentNonInjectedDecl() {
551     CXXRecordDecl *Recent =
552         static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
553     while (Recent->isInjectedClassName()) {
554       // FIXME: Does injected class name need to be in the redeclarations chain?
555       assert(Recent->getPreviousDecl());
556       Recent = Recent->getPreviousDecl();
557     }
558     return Recent;
559   }
560 
561   const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
562     return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
563   }
564 
565   CXXRecordDecl *getDefinition() const {
566     // We only need an update if we don't already know which
567     // declaration is the definition.
568     auto *DD = DefinitionData ? DefinitionData : dataPtr();
569     return DD ? DD->Definition : nullptr;
570   }
571 
572   bool hasDefinition() const { return DefinitionData || dataPtr(); }
573 
574   static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
575                                SourceLocation StartLoc, SourceLocation IdLoc,
576                                IdentifierInfo *Id,
577                                CXXRecordDecl *PrevDecl = nullptr,
578                                bool DelayTypeCreation = false);
579   static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
580                                      TypeSourceInfo *Info, SourceLocation Loc,
581                                      unsigned DependencyKind, bool IsGeneric,
582                                      LambdaCaptureDefault CaptureDefault);
583   static CXXRecordDecl *CreateDeserialized(const ASTContext &C,
584                                            GlobalDeclID ID);
585 
586   bool isDynamicClass() const {
587     return data().Polymorphic || data().NumVBases != 0;
588   }
589 
590   /// @returns true if class is dynamic or might be dynamic because the
591   /// definition is incomplete of dependent.
592   bool mayBeDynamicClass() const {
593     return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
594   }
595 
596   /// @returns true if class is non dynamic or might be non dynamic because the
597   /// definition is incomplete of dependent.
598   bool mayBeNonDynamicClass() const {
599     return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
600   }
601 
602   void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
603 
604   bool isParsingBaseSpecifiers() const {
605     return data().IsParsingBaseSpecifiers;
606   }
607 
608   unsigned getODRHash() const;
609 
610   /// Sets the base classes of this struct or class.
611   void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
612 
613   /// Retrieves the number of base classes of this class.
614   unsigned getNumBases() const { return data().NumBases; }
615 
616   using base_class_range = llvm::iterator_range<base_class_iterator>;
617   using base_class_const_range =
618       llvm::iterator_range<base_class_const_iterator>;
619 
620   base_class_range bases() {
621     return base_class_range(bases_begin(), bases_end());
622   }
623   base_class_const_range bases() const {
624     return base_class_const_range(bases_begin(), bases_end());
625   }
626 
627   base_class_iterator bases_begin() { return data().getBases(); }
628   base_class_const_iterator bases_begin() const { return data().getBases(); }
629   base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
630   base_class_const_iterator bases_end() const {
631     return bases_begin() + data().NumBases;
632   }
633 
634   /// Retrieves the number of virtual base classes of this class.
635   unsigned getNumVBases() const { return data().NumVBases; }
636 
637   base_class_range vbases() {
638     return base_class_range(vbases_begin(), vbases_end());
639   }
640   base_class_const_range vbases() const {
641     return base_class_const_range(vbases_begin(), vbases_end());
642   }
643 
644   base_class_iterator vbases_begin() { return data().getVBases(); }
645   base_class_const_iterator vbases_begin() const { return data().getVBases(); }
646   base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
647   base_class_const_iterator vbases_end() const {
648     return vbases_begin() + data().NumVBases;
649   }
650 
651   /// Determine whether this class has any dependent base classes which
652   /// are not the current instantiation.
653   bool hasAnyDependentBases() const;
654 
655   /// Iterator access to method members.  The method iterator visits
656   /// all method members of the class, including non-instance methods,
657   /// special methods, etc.
658   using method_iterator = specific_decl_iterator<CXXMethodDecl>;
659   using method_range =
660       llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
661 
662   method_range methods() const {
663     return method_range(method_begin(), method_end());
664   }
665 
666   /// Method begin iterator.  Iterates in the order the methods
667   /// were declared.
668   method_iterator method_begin() const {
669     return method_iterator(decls_begin());
670   }
671 
672   /// Method past-the-end iterator.
673   method_iterator method_end() const {
674     return method_iterator(decls_end());
675   }
676 
677   /// Iterator access to constructor members.
678   using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
679   using ctor_range =
680       llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
681 
682   ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
683 
684   ctor_iterator ctor_begin() const {
685     return ctor_iterator(decls_begin());
686   }
687 
688   ctor_iterator ctor_end() const {
689     return ctor_iterator(decls_end());
690   }
691 
692   /// An iterator over friend declarations.  All of these are defined
693   /// in DeclFriend.h.
694   class friend_iterator;
695   using friend_range = llvm::iterator_range<friend_iterator>;
696 
697   friend_range friends() const;
698   friend_iterator friend_begin() const;
699   friend_iterator friend_end() const;
700   void pushFriendDecl(FriendDecl *FD);
701 
702   /// Determines whether this record has any friends.
703   bool hasFriends() const {
704     return data().FirstFriend.isValid();
705   }
706 
707   /// \c true if a defaulted copy constructor for this class would be
708   /// deleted.
709   bool defaultedCopyConstructorIsDeleted() const {
710     assert((!needsOverloadResolutionForCopyConstructor() ||
711             (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
712            "this property has not yet been computed by Sema");
713     return data().DefaultedCopyConstructorIsDeleted;
714   }
715 
716   /// \c true if a defaulted move constructor for this class would be
717   /// deleted.
718   bool defaultedMoveConstructorIsDeleted() const {
719     assert((!needsOverloadResolutionForMoveConstructor() ||
720             (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
721            "this property has not yet been computed by Sema");
722     return data().DefaultedMoveConstructorIsDeleted;
723   }
724 
725   /// \c true if a defaulted destructor for this class would be deleted.
726   bool defaultedDestructorIsDeleted() const {
727     assert((!needsOverloadResolutionForDestructor() ||
728             (data().DeclaredSpecialMembers & SMF_Destructor)) &&
729            "this property has not yet been computed by Sema");
730     return data().DefaultedDestructorIsDeleted;
731   }
732 
733   /// \c true if we know for sure that this class has a single,
734   /// accessible, unambiguous copy constructor that is not deleted.
735   bool hasSimpleCopyConstructor() const {
736     return !hasUserDeclaredCopyConstructor() &&
737            !data().DefaultedCopyConstructorIsDeleted;
738   }
739 
740   /// \c true if we know for sure that this class has a single,
741   /// accessible, unambiguous move constructor that is not deleted.
742   bool hasSimpleMoveConstructor() const {
743     return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
744            !data().DefaultedMoveConstructorIsDeleted;
745   }
746 
747   /// \c true if we know for sure that this class has a single,
748   /// accessible, unambiguous copy assignment operator that is not deleted.
749   bool hasSimpleCopyAssignment() const {
750     return !hasUserDeclaredCopyAssignment() &&
751            !data().DefaultedCopyAssignmentIsDeleted;
752   }
753 
754   /// \c true if we know for sure that this class has a single,
755   /// accessible, unambiguous move assignment operator that is not deleted.
756   bool hasSimpleMoveAssignment() const {
757     return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
758            !data().DefaultedMoveAssignmentIsDeleted;
759   }
760 
761   /// \c true if we know for sure that this class has an accessible
762   /// destructor that is not deleted.
763   bool hasSimpleDestructor() const {
764     return !hasUserDeclaredDestructor() &&
765            !data().DefaultedDestructorIsDeleted;
766   }
767 
768   /// Determine whether this class has any default constructors.
769   bool hasDefaultConstructor() const {
770     return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
771            needsImplicitDefaultConstructor();
772   }
773 
774   /// Determine if we need to declare a default constructor for
775   /// this class.
776   ///
777   /// This value is used for lazy creation of default constructors.
778   bool needsImplicitDefaultConstructor() const {
779     return (!data().UserDeclaredConstructor &&
780             !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
781             (!isLambda() || lambdaIsDefaultConstructibleAndAssignable())) ||
782            // FIXME: Proposed fix to core wording issue: if a class inherits
783            // a default constructor and doesn't explicitly declare one, one
784            // is declared implicitly.
785            (data().HasInheritedDefaultConstructor &&
786             !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
787   }
788 
789   /// Determine whether this class has any user-declared constructors.
790   ///
791   /// When true, a default constructor will not be implicitly declared.
792   bool hasUserDeclaredConstructor() const {
793     return data().UserDeclaredConstructor;
794   }
795 
796   /// Whether this class has a user-provided default constructor
797   /// per C++11.
798   bool hasUserProvidedDefaultConstructor() const {
799     return data().UserProvidedDefaultConstructor;
800   }
801 
802   /// Determine whether this class has a user-declared copy constructor.
803   ///
804   /// When false, a copy constructor will be implicitly declared.
805   bool hasUserDeclaredCopyConstructor() const {
806     return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
807   }
808 
809   /// Determine whether this class needs an implicit copy
810   /// constructor to be lazily declared.
811   bool needsImplicitCopyConstructor() const {
812     return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
813   }
814 
815   /// Determine whether we need to eagerly declare a defaulted copy
816   /// constructor for this class.
817   bool needsOverloadResolutionForCopyConstructor() const {
818     // C++17 [class.copy.ctor]p6:
819     //   If the class definition declares a move constructor or move assignment
820     //   operator, the implicitly declared copy constructor is defined as
821     //   deleted.
822     // In MSVC mode, sometimes a declared move assignment does not delete an
823     // implicit copy constructor, so defer this choice to Sema.
824     if (data().UserDeclaredSpecialMembers &
825         (SMF_MoveConstructor | SMF_MoveAssignment))
826       return true;
827     return data().NeedOverloadResolutionForCopyConstructor;
828   }
829 
830   /// Determine whether an implicit copy constructor for this type
831   /// would have a parameter with a const-qualified reference type.
832   bool implicitCopyConstructorHasConstParam() const {
833     return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
834            (isAbstract() ||
835             data().ImplicitCopyConstructorCanHaveConstParamForVBase);
836   }
837 
838   /// Determine whether this class has a copy constructor with
839   /// a parameter type which is a reference to a const-qualified type.
840   bool hasCopyConstructorWithConstParam() const {
841     return data().HasDeclaredCopyConstructorWithConstParam ||
842            (needsImplicitCopyConstructor() &&
843             implicitCopyConstructorHasConstParam());
844   }
845 
846   /// Whether this class has a user-declared move constructor or
847   /// assignment operator.
848   ///
849   /// When false, a move constructor and assignment operator may be
850   /// implicitly declared.
851   bool hasUserDeclaredMoveOperation() const {
852     return data().UserDeclaredSpecialMembers &
853              (SMF_MoveConstructor | SMF_MoveAssignment);
854   }
855 
856   /// Determine whether this class has had a move constructor
857   /// declared by the user.
858   bool hasUserDeclaredMoveConstructor() const {
859     return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
860   }
861 
862   /// Determine whether this class has a move constructor.
863   bool hasMoveConstructor() const {
864     return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
865            needsImplicitMoveConstructor();
866   }
867 
868   /// Set that we attempted to declare an implicit copy
869   /// constructor, but overload resolution failed so we deleted it.
870   void setImplicitCopyConstructorIsDeleted() {
871     assert((data().DefaultedCopyConstructorIsDeleted ||
872             needsOverloadResolutionForCopyConstructor()) &&
873            "Copy constructor should not be deleted");
874     data().DefaultedCopyConstructorIsDeleted = true;
875   }
876 
877   /// Set that we attempted to declare an implicit move
878   /// constructor, but overload resolution failed so we deleted it.
879   void setImplicitMoveConstructorIsDeleted() {
880     assert((data().DefaultedMoveConstructorIsDeleted ||
881             needsOverloadResolutionForMoveConstructor()) &&
882            "move constructor should not be deleted");
883     data().DefaultedMoveConstructorIsDeleted = true;
884   }
885 
886   /// Set that we attempted to declare an implicit destructor,
887   /// but overload resolution failed so we deleted it.
888   void setImplicitDestructorIsDeleted() {
889     assert((data().DefaultedDestructorIsDeleted ||
890             needsOverloadResolutionForDestructor()) &&
891            "destructor should not be deleted");
892     data().DefaultedDestructorIsDeleted = true;
893     // C++23 [dcl.constexpr]p3.2:
894     //   if the function is a constructor or destructor, its class does not have
895     //   any virtual base classes.
896     // C++20 [dcl.constexpr]p5:
897     //   The definition of a constexpr destructor whose function-body is
898     //   not = delete shall additionally satisfy...
899     data().DefaultedDestructorIsConstexpr = data().NumVBases == 0;
900   }
901 
902   /// Determine whether this class should get an implicit move
903   /// constructor or if any existing special member function inhibits this.
904   bool needsImplicitMoveConstructor() const {
905     return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
906            !hasUserDeclaredCopyConstructor() &&
907            !hasUserDeclaredCopyAssignment() &&
908            !hasUserDeclaredMoveAssignment() &&
909            !hasUserDeclaredDestructor();
910   }
911 
912   /// Determine whether we need to eagerly declare a defaulted move
913   /// constructor for this class.
914   bool needsOverloadResolutionForMoveConstructor() const {
915     return data().NeedOverloadResolutionForMoveConstructor;
916   }
917 
918   /// Determine whether this class has a user-declared copy assignment
919   /// operator.
920   ///
921   /// When false, a copy assignment operator will be implicitly declared.
922   bool hasUserDeclaredCopyAssignment() const {
923     return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
924   }
925 
926   /// Set that we attempted to declare an implicit copy assignment
927   /// operator, but overload resolution failed so we deleted it.
928   void setImplicitCopyAssignmentIsDeleted() {
929     assert((data().DefaultedCopyAssignmentIsDeleted ||
930             needsOverloadResolutionForCopyAssignment()) &&
931            "copy assignment should not be deleted");
932     data().DefaultedCopyAssignmentIsDeleted = true;
933   }
934 
935   /// Determine whether this class needs an implicit copy
936   /// assignment operator to be lazily declared.
937   bool needsImplicitCopyAssignment() const {
938     return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
939   }
940 
941   /// Determine whether we need to eagerly declare a defaulted copy
942   /// assignment operator for this class.
943   bool needsOverloadResolutionForCopyAssignment() const {
944     // C++20 [class.copy.assign]p2:
945     //   If the class definition declares a move constructor or move assignment
946     //   operator, the implicitly declared copy assignment operator is defined
947     //   as deleted.
948     // In MSVC mode, sometimes a declared move constructor does not delete an
949     // implicit copy assignment, so defer this choice to Sema.
950     if (data().UserDeclaredSpecialMembers &
951         (SMF_MoveConstructor | SMF_MoveAssignment))
952       return true;
953     return data().NeedOverloadResolutionForCopyAssignment;
954   }
955 
956   /// Determine whether an implicit copy assignment operator for this
957   /// type would have a parameter with a const-qualified reference type.
958   bool implicitCopyAssignmentHasConstParam() const {
959     return data().ImplicitCopyAssignmentHasConstParam;
960   }
961 
962   /// Determine whether this class has a copy assignment operator with
963   /// a parameter type which is a reference to a const-qualified type or is not
964   /// a reference.
965   bool hasCopyAssignmentWithConstParam() const {
966     return data().HasDeclaredCopyAssignmentWithConstParam ||
967            (needsImplicitCopyAssignment() &&
968             implicitCopyAssignmentHasConstParam());
969   }
970 
971   /// Determine whether this class has had a move assignment
972   /// declared by the user.
973   bool hasUserDeclaredMoveAssignment() const {
974     return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
975   }
976 
977   /// Determine whether this class has a move assignment operator.
978   bool hasMoveAssignment() const {
979     return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
980            needsImplicitMoveAssignment();
981   }
982 
983   /// Set that we attempted to declare an implicit move assignment
984   /// operator, but overload resolution failed so we deleted it.
985   void setImplicitMoveAssignmentIsDeleted() {
986     assert((data().DefaultedMoveAssignmentIsDeleted ||
987             needsOverloadResolutionForMoveAssignment()) &&
988            "move assignment should not be deleted");
989     data().DefaultedMoveAssignmentIsDeleted = true;
990   }
991 
992   /// Determine whether this class should get an implicit move
993   /// assignment operator or if any existing special member function inhibits
994   /// this.
995   bool needsImplicitMoveAssignment() const {
996     return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
997            !hasUserDeclaredCopyConstructor() &&
998            !hasUserDeclaredCopyAssignment() &&
999            !hasUserDeclaredMoveConstructor() &&
1000            !hasUserDeclaredDestructor() &&
1001            (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
1002   }
1003 
1004   /// Determine whether we need to eagerly declare a move assignment
1005   /// operator for this class.
1006   bool needsOverloadResolutionForMoveAssignment() const {
1007     return data().NeedOverloadResolutionForMoveAssignment;
1008   }
1009 
1010   /// Determine whether this class has a user-declared destructor.
1011   ///
1012   /// When false, a destructor will be implicitly declared.
1013   bool hasUserDeclaredDestructor() const {
1014     return data().UserDeclaredSpecialMembers & SMF_Destructor;
1015   }
1016 
1017   /// Determine whether this class needs an implicit destructor to
1018   /// be lazily declared.
1019   bool needsImplicitDestructor() const {
1020     return !(data().DeclaredSpecialMembers & SMF_Destructor);
1021   }
1022 
1023   /// Determine whether we need to eagerly declare a destructor for this
1024   /// class.
1025   bool needsOverloadResolutionForDestructor() const {
1026     return data().NeedOverloadResolutionForDestructor;
1027   }
1028 
1029   /// Determine whether this class describes a lambda function object.
1030   bool isLambda() const {
1031     // An update record can't turn a non-lambda into a lambda.
1032     auto *DD = DefinitionData;
1033     return DD && DD->IsLambda;
1034   }
1035 
1036   /// Determine whether this class describes a generic
1037   /// lambda function object (i.e. function call operator is
1038   /// a template).
1039   bool isGenericLambda() const;
1040 
1041   /// Determine whether this lambda should have an implicit default constructor
1042   /// and copy and move assignment operators.
1043   bool lambdaIsDefaultConstructibleAndAssignable() const;
1044 
1045   /// Retrieve the lambda call operator of the closure type
1046   /// if this is a closure type.
1047   CXXMethodDecl *getLambdaCallOperator() const;
1048 
1049   /// Retrieve the dependent lambda call operator of the closure type
1050   /// if this is a templated closure type.
1051   FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1052 
1053   /// Retrieve the lambda static invoker, the address of which
1054   /// is returned by the conversion operator, and the body of which
1055   /// is forwarded to the lambda call operator. The version that does not
1056   /// take a calling convention uses the 'default' calling convention for free
1057   /// functions if the Lambda's calling convention was not modified via
1058   /// attribute. Otherwise, it will return the calling convention specified for
1059   /// the lambda.
1060   CXXMethodDecl *getLambdaStaticInvoker() const;
1061   CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1062 
1063   /// Retrieve the generic lambda's template parameter list.
1064   /// Returns null if the class does not represent a lambda or a generic
1065   /// lambda.
1066   TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1067 
1068   /// Retrieve the lambda template parameters that were specified explicitly.
1069   ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1070 
1071   LambdaCaptureDefault getLambdaCaptureDefault() const {
1072     assert(isLambda());
1073     return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1074   }
1075 
1076   bool isCapturelessLambda() const {
1077     if (!isLambda())
1078       return false;
1079     return getLambdaCaptureDefault() == LCD_None && capture_size() == 0;
1080   }
1081 
1082   /// Set the captures for this lambda closure type.
1083   void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1084 
1085   /// For a closure type, retrieve the mapping from captured
1086   /// variables and \c this to the non-static data members that store the
1087   /// values or references of the captures.
1088   ///
1089   /// \param Captures Will be populated with the mapping from captured
1090   /// variables to the corresponding fields.
1091   ///
1092   /// \param ThisCapture Will be set to the field declaration for the
1093   /// \c this capture.
1094   ///
1095   /// \note No entries will be added for init-captures, as they do not capture
1096   /// variables.
1097   ///
1098   /// \note If multiple versions of the lambda are merged together, they may
1099   /// have different variable declarations corresponding to the same capture.
1100   /// In that case, all of those variable declarations will be added to the
1101   /// Captures list, so it may have more than one variable listed per field.
1102   void
1103   getCaptureFields(llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,
1104                    FieldDecl *&ThisCapture) const;
1105 
1106   using capture_const_iterator = const LambdaCapture *;
1107   using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1108 
1109   capture_const_range captures() const {
1110     return capture_const_range(captures_begin(), captures_end());
1111   }
1112 
1113   capture_const_iterator captures_begin() const {
1114     if (!isLambda()) return nullptr;
1115     LambdaDefinitionData &LambdaData = getLambdaData();
1116     return LambdaData.Captures.empty() ? nullptr : LambdaData.Captures.front();
1117   }
1118 
1119   capture_const_iterator captures_end() const {
1120     return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1121                       : nullptr;
1122   }
1123 
1124   unsigned capture_size() const { return getLambdaData().NumCaptures; }
1125 
1126   const LambdaCapture *getCapture(unsigned I) const {
1127     assert(isLambda() && I < capture_size() && "invalid index for capture");
1128     return captures_begin() + I;
1129   }
1130 
1131   using conversion_iterator = UnresolvedSetIterator;
1132 
1133   conversion_iterator conversion_begin() const {
1134     return data().Conversions.get(getASTContext()).begin();
1135   }
1136 
1137   conversion_iterator conversion_end() const {
1138     return data().Conversions.get(getASTContext()).end();
1139   }
1140 
1141   /// Removes a conversion function from this class.  The conversion
1142   /// function must currently be a member of this class.  Furthermore,
1143   /// this class must currently be in the process of being defined.
1144   void removeConversion(const NamedDecl *Old);
1145 
1146   /// Get all conversion functions visible in current class,
1147   /// including conversion function templates.
1148   llvm::iterator_range<conversion_iterator>
1149   getVisibleConversionFunctions() const;
1150 
1151   /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1152   /// which is a class with no user-declared constructors, no private
1153   /// or protected non-static data members, no base classes, and no virtual
1154   /// functions (C++ [dcl.init.aggr]p1).
1155   bool isAggregate() const { return data().Aggregate; }
1156 
1157   /// Whether this class has any in-class initializers
1158   /// for non-static data members (including those in anonymous unions or
1159   /// structs).
1160   bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1161 
1162   /// Whether this class or any of its subobjects has any members of
1163   /// reference type which would make value-initialization ill-formed.
1164   ///
1165   /// Per C++03 [dcl.init]p5:
1166   ///  - if T is a non-union class type without a user-declared constructor,
1167   ///    then every non-static data member and base-class component of T is
1168   ///    value-initialized [...] A program that calls for [...]
1169   ///    value-initialization of an entity of reference type is ill-formed.
1170   bool hasUninitializedReferenceMember() const {
1171     return !isUnion() && !hasUserDeclaredConstructor() &&
1172            data().HasUninitializedReferenceMember;
1173   }
1174 
1175   /// Whether this class is a POD-type (C++ [class]p4)
1176   ///
1177   /// For purposes of this function a class is POD if it is an aggregate
1178   /// that has no non-static non-POD data members, no reference data
1179   /// members, no user-defined copy assignment operator and no
1180   /// user-defined destructor.
1181   ///
1182   /// Note that this is the C++ TR1 definition of POD.
1183   bool isPOD() const { return data().PlainOldData; }
1184 
1185   /// True if this class is C-like, without C++-specific features, e.g.
1186   /// it contains only public fields, no bases, tag kind is not 'class', etc.
1187   bool isCLike() const;
1188 
1189   /// Determine whether this is an empty class in the sense of
1190   /// (C++11 [meta.unary.prop]).
1191   ///
1192   /// The CXXRecordDecl is a class type, but not a union type,
1193   /// with no non-static data members other than bit-fields of length 0,
1194   /// no virtual member functions, no virtual base classes,
1195   /// and no base class B for which is_empty<B>::value is false.
1196   ///
1197   /// \note This does NOT include a check for union-ness.
1198   bool isEmpty() const { return data().Empty; }
1199 
1200   void setInitMethod(bool Val) { data().HasInitMethod = Val; }
1201   bool hasInitMethod() const { return data().HasInitMethod; }
1202 
1203   bool hasPrivateFields() const {
1204     return data().HasPrivateFields;
1205   }
1206 
1207   bool hasProtectedFields() const {
1208     return data().HasProtectedFields;
1209   }
1210 
1211   /// Determine whether this class has direct non-static data members.
1212   bool hasDirectFields() const {
1213     auto &D = data();
1214     return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1215   }
1216 
1217   /// If this is a standard-layout class or union, any and all data members will
1218   /// be declared in the same type.
1219   ///
1220   /// This retrieves the type where any fields are declared,
1221   /// or the current class if there is no class with fields.
1222   const CXXRecordDecl *getStandardLayoutBaseWithFields() const;
1223 
1224   /// Whether this class is polymorphic (C++ [class.virtual]),
1225   /// which means that the class contains or inherits a virtual function.
1226   bool isPolymorphic() const { return data().Polymorphic; }
1227 
1228   /// Determine whether this class has a pure virtual function.
1229   ///
1230   /// The class is abstract per (C++ [class.abstract]p2) if it declares
1231   /// a pure virtual function or inherits a pure virtual function that is
1232   /// not overridden.
1233   bool isAbstract() const { return data().Abstract; }
1234 
1235   /// Determine whether this class is standard-layout per
1236   /// C++ [class]p7.
1237   bool isStandardLayout() const { return data().IsStandardLayout; }
1238 
1239   /// Determine whether this class was standard-layout per
1240   /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1241   bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1242 
1243   /// Determine whether this class, or any of its class subobjects,
1244   /// contains a mutable field.
1245   bool hasMutableFields() const { return data().HasMutableFields; }
1246 
1247   /// Determine whether this class has any variant members.
1248   bool hasVariantMembers() const { return data().HasVariantMembers; }
1249 
1250   /// Determine whether this class has a trivial default constructor
1251   /// (C++11 [class.ctor]p5).
1252   bool hasTrivialDefaultConstructor() const {
1253     return hasDefaultConstructor() &&
1254            (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1255   }
1256 
1257   /// Determine whether this class has a non-trivial default constructor
1258   /// (C++11 [class.ctor]p5).
1259   bool hasNonTrivialDefaultConstructor() const {
1260     return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1261            (needsImplicitDefaultConstructor() &&
1262             !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1263   }
1264 
1265   /// Determine whether this class has at least one constexpr constructor
1266   /// other than the copy or move constructors.
1267   bool hasConstexprNonCopyMoveConstructor() const {
1268     return data().HasConstexprNonCopyMoveConstructor ||
1269            (needsImplicitDefaultConstructor() &&
1270             defaultedDefaultConstructorIsConstexpr());
1271   }
1272 
1273   /// Determine whether a defaulted default constructor for this class
1274   /// would be constexpr.
1275   bool defaultedDefaultConstructorIsConstexpr() const {
1276     return data().DefaultedDefaultConstructorIsConstexpr &&
1277            (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1278             getLangOpts().CPlusPlus20);
1279   }
1280 
1281   /// Determine whether this class has a constexpr default constructor.
1282   bool hasConstexprDefaultConstructor() const {
1283     return data().HasConstexprDefaultConstructor ||
1284            (needsImplicitDefaultConstructor() &&
1285             defaultedDefaultConstructorIsConstexpr());
1286   }
1287 
1288   /// Determine whether this class has a trivial copy constructor
1289   /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1290   bool hasTrivialCopyConstructor() const {
1291     return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1292   }
1293 
1294   bool hasTrivialCopyConstructorForCall() const {
1295     return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1296   }
1297 
1298   /// Determine whether this class has a non-trivial copy constructor
1299   /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1300   bool hasNonTrivialCopyConstructor() const {
1301     return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1302            !hasTrivialCopyConstructor();
1303   }
1304 
1305   bool hasNonTrivialCopyConstructorForCall() const {
1306     return (data().DeclaredNonTrivialSpecialMembersForCall &
1307             SMF_CopyConstructor) ||
1308            !hasTrivialCopyConstructorForCall();
1309   }
1310 
1311   /// Determine whether this class has a trivial move constructor
1312   /// (C++11 [class.copy]p12)
1313   bool hasTrivialMoveConstructor() const {
1314     return hasMoveConstructor() &&
1315            (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1316   }
1317 
1318   bool hasTrivialMoveConstructorForCall() const {
1319     return hasMoveConstructor() &&
1320            (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1321   }
1322 
1323   /// Determine whether this class has a non-trivial move constructor
1324   /// (C++11 [class.copy]p12)
1325   bool hasNonTrivialMoveConstructor() const {
1326     return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1327            (needsImplicitMoveConstructor() &&
1328             !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1329   }
1330 
1331   bool hasNonTrivialMoveConstructorForCall() const {
1332     return (data().DeclaredNonTrivialSpecialMembersForCall &
1333             SMF_MoveConstructor) ||
1334            (needsImplicitMoveConstructor() &&
1335             !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1336   }
1337 
1338   /// Determine whether this class has a trivial copy assignment operator
1339   /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1340   bool hasTrivialCopyAssignment() const {
1341     return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1342   }
1343 
1344   /// Determine whether this class has a non-trivial copy assignment
1345   /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1346   bool hasNonTrivialCopyAssignment() const {
1347     return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1348            !hasTrivialCopyAssignment();
1349   }
1350 
1351   /// Determine whether this class has a trivial move assignment operator
1352   /// (C++11 [class.copy]p25)
1353   bool hasTrivialMoveAssignment() const {
1354     return hasMoveAssignment() &&
1355            (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1356   }
1357 
1358   /// Determine whether this class has a non-trivial move assignment
1359   /// operator (C++11 [class.copy]p25)
1360   bool hasNonTrivialMoveAssignment() const {
1361     return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1362            (needsImplicitMoveAssignment() &&
1363             !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1364   }
1365 
1366   /// Determine whether a defaulted default constructor for this class
1367   /// would be constexpr.
1368   bool defaultedDestructorIsConstexpr() const {
1369     return data().DefaultedDestructorIsConstexpr &&
1370            getLangOpts().CPlusPlus20;
1371   }
1372 
1373   /// Determine whether this class has a constexpr destructor.
1374   bool hasConstexprDestructor() const;
1375 
1376   /// Determine whether this class has a trivial destructor
1377   /// (C++ [class.dtor]p3)
1378   bool hasTrivialDestructor() const {
1379     return data().HasTrivialSpecialMembers & SMF_Destructor;
1380   }
1381 
1382   bool hasTrivialDestructorForCall() const {
1383     return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1384   }
1385 
1386   /// Determine whether this class has a non-trivial destructor
1387   /// (C++ [class.dtor]p3)
1388   bool hasNonTrivialDestructor() const {
1389     return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1390   }
1391 
1392   bool hasNonTrivialDestructorForCall() const {
1393     return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1394   }
1395 
1396   void setHasTrivialSpecialMemberForCall() {
1397     data().HasTrivialSpecialMembersForCall =
1398         (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1399   }
1400 
1401   /// Determine whether declaring a const variable with this type is ok
1402   /// per core issue 253.
1403   bool allowConstDefaultInit() const {
1404     return !data().HasUninitializedFields ||
1405            !(data().HasDefaultedDefaultConstructor ||
1406              needsImplicitDefaultConstructor());
1407   }
1408 
1409   /// Determine whether this class has a destructor which has no
1410   /// semantic effect.
1411   ///
1412   /// Any such destructor will be trivial, public, defaulted and not deleted,
1413   /// and will call only irrelevant destructors.
1414   bool hasIrrelevantDestructor() const {
1415     return data().HasIrrelevantDestructor;
1416   }
1417 
1418   /// Determine whether this class has a non-literal or/ volatile type
1419   /// non-static data member or base class.
1420   bool hasNonLiteralTypeFieldsOrBases() const {
1421     return data().HasNonLiteralTypeFieldsOrBases;
1422   }
1423 
1424   /// Determine whether this class has a using-declaration that names
1425   /// a user-declared base class constructor.
1426   bool hasInheritedConstructor() const {
1427     return data().HasInheritedConstructor;
1428   }
1429 
1430   /// Determine whether this class has a using-declaration that names
1431   /// a base class assignment operator.
1432   bool hasInheritedAssignment() const {
1433     return data().HasInheritedAssignment;
1434   }
1435 
1436   /// Determine whether this class is considered trivially copyable per
1437   /// (C++11 [class]p6).
1438   bool isTriviallyCopyable() const;
1439 
1440   /// Determine whether this class is considered trivially copyable per
1441   bool isTriviallyCopyConstructible() const;
1442 
1443   /// Determine whether this class is considered trivial.
1444   ///
1445   /// C++11 [class]p6:
1446   ///    "A trivial class is a class that has a trivial default constructor and
1447   ///    is trivially copyable."
1448   bool isTrivial() const {
1449     return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1450   }
1451 
1452   /// Determine whether this class is a literal type.
1453   ///
1454   /// C++20 [basic.types]p10:
1455   ///   A class type that has all the following properties:
1456   ///     - it has a constexpr destructor
1457   ///     - all of its non-static non-variant data members and base classes
1458   ///       are of non-volatile literal types, and it:
1459   ///        - is a closure type
1460   ///        - is an aggregate union type that has either no variant members
1461   ///          or at least one variant member of non-volatile literal type
1462   ///        - is a non-union aggregate type for which each of its anonymous
1463   ///          union members satisfies the above requirements for an aggregate
1464   ///          union type, or
1465   ///        - has at least one constexpr constructor or constructor template
1466   ///          that is not a copy or move constructor.
1467   bool isLiteral() const;
1468 
1469   /// Determine whether this is a structural type.
1470   bool isStructural() const {
1471     return isLiteral() && data().StructuralIfLiteral;
1472   }
1473 
1474   /// Notify the class that this destructor is now selected.
1475   ///
1476   /// Important properties of the class depend on destructor properties. Since
1477   /// C++20, it is possible to have multiple destructor declarations in a class
1478   /// out of which one will be selected at the end.
1479   /// This is called separately from addedMember because it has to be deferred
1480   /// to the completion of the class.
1481   void addedSelectedDestructor(CXXDestructorDecl *DD);
1482 
1483   /// Notify the class that an eligible SMF has been added.
1484   /// This updates triviality and destructor based properties of the class accordingly.
1485   void addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD, unsigned SMKind);
1486 
1487   /// If this record is an instantiation of a member class,
1488   /// retrieves the member class from which it was instantiated.
1489   ///
1490   /// This routine will return non-null for (non-templated) member
1491   /// classes of class templates. For example, given:
1492   ///
1493   /// \code
1494   /// template<typename T>
1495   /// struct X {
1496   ///   struct A { };
1497   /// };
1498   /// \endcode
1499   ///
1500   /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1501   /// whose parent is the class template specialization X<int>. For
1502   /// this declaration, getInstantiatedFromMemberClass() will return
1503   /// the CXXRecordDecl X<T>::A. When a complete definition of
1504   /// X<int>::A is required, it will be instantiated from the
1505   /// declaration returned by getInstantiatedFromMemberClass().
1506   CXXRecordDecl *getInstantiatedFromMemberClass() const;
1507 
1508   /// If this class is an instantiation of a member class of a
1509   /// class template specialization, retrieves the member specialization
1510   /// information.
1511   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1512 
1513   /// Specify that this record is an instantiation of the
1514   /// member class \p RD.
1515   void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1516                                      TemplateSpecializationKind TSK);
1517 
1518   /// Retrieves the class template that is described by this
1519   /// class declaration.
1520   ///
1521   /// Every class template is represented as a ClassTemplateDecl and a
1522   /// CXXRecordDecl. The former contains template properties (such as
1523   /// the template parameter lists) while the latter contains the
1524   /// actual description of the template's
1525   /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1526   /// CXXRecordDecl that from a ClassTemplateDecl, while
1527   /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1528   /// a CXXRecordDecl.
1529   ClassTemplateDecl *getDescribedClassTemplate() const;
1530 
1531   void setDescribedClassTemplate(ClassTemplateDecl *Template);
1532 
1533   /// Determine whether this particular class is a specialization or
1534   /// instantiation of a class template or member class of a class template,
1535   /// and how it was instantiated or specialized.
1536   TemplateSpecializationKind getTemplateSpecializationKind() const;
1537 
1538   /// Set the kind of specialization or template instantiation this is.
1539   void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1540 
1541   /// Retrieve the record declaration from which this record could be
1542   /// instantiated. Returns null if this class is not a template instantiation.
1543   const CXXRecordDecl *getTemplateInstantiationPattern() const;
1544 
1545   CXXRecordDecl *getTemplateInstantiationPattern() {
1546     return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1547                                            ->getTemplateInstantiationPattern());
1548   }
1549 
1550   /// Returns the destructor decl for this class.
1551   CXXDestructorDecl *getDestructor() const;
1552 
1553   /// Returns true if the class destructor, or any implicitly invoked
1554   /// destructors are marked noreturn.
1555   bool isAnyDestructorNoReturn() const { return data().IsAnyDestructorNoReturn; }
1556 
1557   /// Returns true if the class contains HLSL intangible type, either as
1558   /// a field or in base class.
1559   bool isHLSLIntangible() const { return data().IsHLSLIntangible; }
1560 
1561   /// If the class is a local class [class.local], returns
1562   /// the enclosing function declaration.
1563   const FunctionDecl *isLocalClass() const {
1564     if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1565       return RD->isLocalClass();
1566 
1567     return dyn_cast<FunctionDecl>(getDeclContext());
1568   }
1569 
1570   FunctionDecl *isLocalClass() {
1571     return const_cast<FunctionDecl*>(
1572         const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1573   }
1574 
1575   /// Determine whether this dependent class is a current instantiation,
1576   /// when viewed from within the given context.
1577   bool isCurrentInstantiation(const DeclContext *CurContext) const;
1578 
1579   /// Determine whether this class is derived from the class \p Base.
1580   ///
1581   /// This routine only determines whether this class is derived from \p Base,
1582   /// but does not account for factors that may make a Derived -> Base class
1583   /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1584   /// base class subobjects.
1585   ///
1586   /// \param Base the base class we are searching for.
1587   ///
1588   /// \returns true if this class is derived from Base, false otherwise.
1589   bool isDerivedFrom(const CXXRecordDecl *Base) const;
1590 
1591   /// Determine whether this class is derived from the type \p Base.
1592   ///
1593   /// This routine only determines whether this class is derived from \p Base,
1594   /// but does not account for factors that may make a Derived -> Base class
1595   /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1596   /// base class subobjects.
1597   ///
1598   /// \param Base the base class we are searching for.
1599   ///
1600   /// \param Paths will contain the paths taken from the current class to the
1601   /// given \p Base class.
1602   ///
1603   /// \returns true if this class is derived from \p Base, false otherwise.
1604   ///
1605   /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1606   /// tangling input and output in \p Paths
1607   bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1608 
1609   /// Determine whether this class is virtually derived from
1610   /// the class \p Base.
1611   ///
1612   /// This routine only determines whether this class is virtually
1613   /// derived from \p Base, but does not account for factors that may
1614   /// make a Derived -> Base class ill-formed, such as
1615   /// private/protected inheritance or multiple, ambiguous base class
1616   /// subobjects.
1617   ///
1618   /// \param Base the base class we are searching for.
1619   ///
1620   /// \returns true if this class is virtually derived from Base,
1621   /// false otherwise.
1622   bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1623 
1624   /// Determine whether this class is provably not derived from
1625   /// the type \p Base.
1626   bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1627 
1628   /// Function type used by forallBases() as a callback.
1629   ///
1630   /// \param BaseDefinition the definition of the base class
1631   ///
1632   /// \returns true if this base matched the search criteria
1633   using ForallBasesCallback =
1634       llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1635 
1636   /// Determines if the given callback holds for all the direct
1637   /// or indirect base classes of this type.
1638   ///
1639   /// The class itself does not count as a base class.  This routine
1640   /// returns false if the class has non-computable base classes.
1641   ///
1642   /// \param BaseMatches Callback invoked for each (direct or indirect) base
1643   /// class of this type until a call returns false.
1644   bool forallBases(ForallBasesCallback BaseMatches) const;
1645 
1646   /// Function type used by lookupInBases() to determine whether a
1647   /// specific base class subobject matches the lookup criteria.
1648   ///
1649   /// \param Specifier the base-class specifier that describes the inheritance
1650   /// from the base class we are trying to match.
1651   ///
1652   /// \param Path the current path, from the most-derived class down to the
1653   /// base named by the \p Specifier.
1654   ///
1655   /// \returns true if this base matched the search criteria, false otherwise.
1656   using BaseMatchesCallback =
1657       llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1658                               CXXBasePath &Path)>;
1659 
1660   /// Look for entities within the base classes of this C++ class,
1661   /// transitively searching all base class subobjects.
1662   ///
1663   /// This routine uses the callback function \p BaseMatches to find base
1664   /// classes meeting some search criteria, walking all base class subobjects
1665   /// and populating the given \p Paths structure with the paths through the
1666   /// inheritance hierarchy that resulted in a match. On a successful search,
1667   /// the \p Paths structure can be queried to retrieve the matching paths and
1668   /// to determine if there were any ambiguities.
1669   ///
1670   /// \param BaseMatches callback function used to determine whether a given
1671   /// base matches the user-defined search criteria.
1672   ///
1673   /// \param Paths used to record the paths from this class to its base class
1674   /// subobjects that match the search criteria.
1675   ///
1676   /// \param LookupInDependent can be set to true to extend the search to
1677   /// dependent base classes.
1678   ///
1679   /// \returns true if there exists any path from this class to a base class
1680   /// subobject that matches the search criteria.
1681   bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1682                      bool LookupInDependent = false) const;
1683 
1684   /// Base-class lookup callback that determines whether the given
1685   /// base class specifier refers to a specific class declaration.
1686   ///
1687   /// This callback can be used with \c lookupInBases() to determine whether
1688   /// a given derived class has is a base class subobject of a particular type.
1689   /// The base record pointer should refer to the canonical CXXRecordDecl of the
1690   /// base class that we are searching for.
1691   static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1692                             CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1693 
1694   /// Base-class lookup callback that determines whether the
1695   /// given base class specifier refers to a specific class
1696   /// declaration and describes virtual derivation.
1697   ///
1698   /// This callback can be used with \c lookupInBases() to determine
1699   /// whether a given derived class has is a virtual base class
1700   /// subobject of a particular type.  The base record pointer should
1701   /// refer to the canonical CXXRecordDecl of the base class that we
1702   /// are searching for.
1703   static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1704                                    CXXBasePath &Path,
1705                                    const CXXRecordDecl *BaseRecord);
1706 
1707   /// Retrieve the final overriders for each virtual member
1708   /// function in the class hierarchy where this class is the
1709   /// most-derived class in the class hierarchy.
1710   void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1711 
1712   /// Get the indirect primary bases for this class.
1713   void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1714 
1715   /// Determine whether this class has a member with the given name, possibly
1716   /// in a non-dependent base class.
1717   ///
1718   /// No check for ambiguity is performed, so this should never be used when
1719   /// implementing language semantics, but it may be appropriate for warnings,
1720   /// static analysis, or similar.
1721   bool hasMemberName(DeclarationName N) const;
1722 
1723   /// Performs an imprecise lookup of a dependent name in this class.
1724   ///
1725   /// This function does not follow strict semantic rules and should be used
1726   /// only when lookup rules can be relaxed, e.g. indexing.
1727   std::vector<const NamedDecl *>
1728   lookupDependentName(DeclarationName Name,
1729                       llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1730 
1731   /// Renders and displays an inheritance diagram
1732   /// for this C++ class and all of its base classes (transitively) using
1733   /// GraphViz.
1734   void viewInheritance(ASTContext& Context) const;
1735 
1736   /// Calculates the access of a decl that is reached
1737   /// along a path.
1738   static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1739                                      AccessSpecifier DeclAccess) {
1740     assert(DeclAccess != AS_none);
1741     if (DeclAccess == AS_private) return AS_none;
1742     return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1743   }
1744 
1745   /// Indicates that the declaration of a defaulted or deleted special
1746   /// member function is now complete.
1747   void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1748 
1749   void setTrivialForCallFlags(CXXMethodDecl *MD);
1750 
1751   /// Indicates that the definition of this class is now complete.
1752   void completeDefinition() override;
1753 
1754   /// Indicates that the definition of this class is now complete,
1755   /// and provides a final overrider map to help determine
1756   ///
1757   /// \param FinalOverriders The final overrider map for this class, which can
1758   /// be provided as an optimization for abstract-class checking. If NULL,
1759   /// final overriders will be computed if they are needed to complete the
1760   /// definition.
1761   void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1762 
1763   /// Determine whether this class may end up being abstract, even though
1764   /// it is not yet known to be abstract.
1765   ///
1766   /// \returns true if this class is not known to be abstract but has any
1767   /// base classes that are abstract. In this case, \c completeDefinition()
1768   /// will need to compute final overriders to determine whether the class is
1769   /// actually abstract.
1770   bool mayBeAbstract() const;
1771 
1772   /// Determine whether it's impossible for a class to be derived from this
1773   /// class. This is best-effort, and may conservatively return false.
1774   bool isEffectivelyFinal() const;
1775 
1776   /// If this is the closure type of a lambda expression, retrieve the
1777   /// number to be used for name mangling in the Itanium C++ ABI.
1778   ///
1779   /// Zero indicates that this closure type has internal linkage, so the
1780   /// mangling number does not matter, while a non-zero value indicates which
1781   /// lambda expression this is in this particular context.
1782   unsigned getLambdaManglingNumber() const {
1783     assert(isLambda() && "Not a lambda closure type!");
1784     return getLambdaData().ManglingNumber;
1785   }
1786 
1787   /// The lambda is known to has internal linkage no matter whether it has name
1788   /// mangling number.
1789   bool hasKnownLambdaInternalLinkage() const {
1790     assert(isLambda() && "Not a lambda closure type!");
1791     return getLambdaData().HasKnownInternalLinkage;
1792   }
1793 
1794   /// Retrieve the declaration that provides additional context for a
1795   /// lambda, when the normal declaration context is not specific enough.
1796   ///
1797   /// Certain contexts (default arguments of in-class function parameters and
1798   /// the initializers of data members) have separate name mangling rules for
1799   /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1800   /// the declaration in which the lambda occurs, e.g., the function parameter
1801   /// or the non-static data member. Otherwise, it returns NULL to imply that
1802   /// the declaration context suffices.
1803   Decl *getLambdaContextDecl() const;
1804 
1805   /// Retrieve the index of this lambda within the context declaration returned
1806   /// by getLambdaContextDecl().
1807   unsigned getLambdaIndexInContext() const {
1808     assert(isLambda() && "Not a lambda closure type!");
1809     return getLambdaData().IndexInContext;
1810   }
1811 
1812   /// Information about how a lambda is numbered within its context.
1813   struct LambdaNumbering {
1814     Decl *ContextDecl = nullptr;
1815     unsigned IndexInContext = 0;
1816     unsigned ManglingNumber = 0;
1817     unsigned DeviceManglingNumber = 0;
1818     bool HasKnownInternalLinkage = false;
1819   };
1820 
1821   /// Set the mangling numbers and context declaration for a lambda class.
1822   void setLambdaNumbering(LambdaNumbering Numbering);
1823 
1824   // Get the mangling numbers and context declaration for a lambda class.
1825   LambdaNumbering getLambdaNumbering() const {
1826     return {getLambdaContextDecl(), getLambdaIndexInContext(),
1827             getLambdaManglingNumber(), getDeviceLambdaManglingNumber(),
1828             hasKnownLambdaInternalLinkage()};
1829   }
1830 
1831   /// Retrieve the device side mangling number.
1832   unsigned getDeviceLambdaManglingNumber() const;
1833 
1834   /// Returns the inheritance model used for this record.
1835   MSInheritanceModel getMSInheritanceModel() const;
1836 
1837   /// Calculate what the inheritance model would be for this class.
1838   MSInheritanceModel calculateInheritanceModel() const;
1839 
1840   /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1841   /// member pointer if we can guarantee that zero is not a valid field offset,
1842   /// or if the member pointer has multiple fields.  Polymorphic classes have a
1843   /// vfptr at offset zero, so we can use zero for null.  If there are multiple
1844   /// fields, we can use zero even if it is a valid field offset because
1845   /// null-ness testing will check the other fields.
1846   bool nullFieldOffsetIsZero() const;
1847 
1848   /// Controls when vtordisps will be emitted if this record is used as a
1849   /// virtual base.
1850   MSVtorDispMode getMSVtorDispMode() const;
1851 
1852   /// Determine whether this lambda expression was known to be dependent
1853   /// at the time it was created, even if its context does not appear to be
1854   /// dependent.
1855   ///
1856   /// This flag is a workaround for an issue with parsing, where default
1857   /// arguments are parsed before their enclosing function declarations have
1858   /// been created. This means that any lambda expressions within those
1859   /// default arguments will have as their DeclContext the context enclosing
1860   /// the function declaration, which may be non-dependent even when the
1861   /// function declaration itself is dependent. This flag indicates when we
1862   /// know that the lambda is dependent despite that.
1863   bool isDependentLambda() const {
1864     return isLambda() && getLambdaData().DependencyKind == LDK_AlwaysDependent;
1865   }
1866 
1867   bool isNeverDependentLambda() const {
1868     return isLambda() && getLambdaData().DependencyKind == LDK_NeverDependent;
1869   }
1870 
1871   unsigned getLambdaDependencyKind() const {
1872     if (!isLambda())
1873       return LDK_Unknown;
1874     return getLambdaData().DependencyKind;
1875   }
1876 
1877   TypeSourceInfo *getLambdaTypeInfo() const {
1878     return getLambdaData().MethodTyInfo;
1879   }
1880 
1881   void setLambdaTypeInfo(TypeSourceInfo *TS) {
1882     assert(DefinitionData && DefinitionData->IsLambda &&
1883            "setting lambda property of non-lambda class");
1884     auto &DL = static_cast<LambdaDefinitionData &>(*DefinitionData);
1885     DL.MethodTyInfo = TS;
1886   }
1887 
1888   void setLambdaDependencyKind(unsigned Kind) {
1889     getLambdaData().DependencyKind = Kind;
1890   }
1891 
1892   void setLambdaIsGeneric(bool IsGeneric) {
1893     assert(DefinitionData && DefinitionData->IsLambda &&
1894            "setting lambda property of non-lambda class");
1895     auto &DL = static_cast<LambdaDefinitionData &>(*DefinitionData);
1896     DL.IsGenericLambda = IsGeneric;
1897   }
1898 
1899   // Determine whether this type is an Interface Like type for
1900   // __interface inheritance purposes.
1901   bool isInterfaceLike() const;
1902 
1903   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1904   static bool classofKind(Kind K) {
1905     return K >= firstCXXRecord && K <= lastCXXRecord;
1906   }
1907   void markAbstract() { data().Abstract = true; }
1908 };
1909 
1910 /// Store information needed for an explicit specifier.
1911 /// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1912 class ExplicitSpecifier {
1913   llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1914       nullptr, ExplicitSpecKind::ResolvedFalse};
1915 
1916 public:
1917   ExplicitSpecifier() = default;
1918   ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1919       : ExplicitSpec(Expression, Kind) {}
1920   ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1921   const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1922   Expr *getExpr() { return ExplicitSpec.getPointer(); }
1923 
1924   /// Determine if the declaration had an explicit specifier of any kind.
1925   bool isSpecified() const {
1926     return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1927            ExplicitSpec.getPointer();
1928   }
1929 
1930   /// Check for equivalence of explicit specifiers.
1931   /// \return true if the explicit specifier are equivalent, false otherwise.
1932   bool isEquivalent(const ExplicitSpecifier Other) const;
1933   /// Determine whether this specifier is known to correspond to an explicit
1934   /// declaration. Returns false if the specifier is absent or has an
1935   /// expression that is value-dependent or evaluates to false.
1936   bool isExplicit() const {
1937     return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1938   }
1939   /// Determine if the explicit specifier is invalid.
1940   /// This state occurs after a substitution failures.
1941   bool isInvalid() const {
1942     return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1943            !ExplicitSpec.getPointer();
1944   }
1945   void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1946   void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1947   // Retrieve the explicit specifier in the given declaration, if any.
1948   static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1949   static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1950     return getFromDecl(const_cast<FunctionDecl *>(Function));
1951   }
1952   static ExplicitSpecifier Invalid() {
1953     return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1954   }
1955 };
1956 
1957 /// Represents a C++ deduction guide declaration.
1958 ///
1959 /// \code
1960 /// template<typename T> struct A { A(); A(T); };
1961 /// A() -> A<int>;
1962 /// \endcode
1963 ///
1964 /// In this example, there will be an explicit deduction guide from the
1965 /// second line, and implicit deduction guide templates synthesized from
1966 /// the constructors of \c A.
1967 class CXXDeductionGuideDecl : public FunctionDecl {
1968   void anchor() override;
1969 
1970 public:
1971   // Represents the relationship between this deduction guide and the
1972   // deduction guide that it was generated from (or lack thereof).
1973   // See the SourceDeductionGuide member for more details.
1974   enum class SourceDeductionGuideKind : uint8_t {
1975     None,
1976     Alias,
1977   };
1978 
1979 private:
1980   CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1981                         ExplicitSpecifier ES,
1982                         const DeclarationNameInfo &NameInfo, QualType T,
1983                         TypeSourceInfo *TInfo, SourceLocation EndLocation,
1984                         CXXConstructorDecl *Ctor, DeductionCandidate Kind,
1985                         Expr *TrailingRequiresClause,
1986                         const CXXDeductionGuideDecl *GeneratedFrom,
1987                         SourceDeductionGuideKind SourceKind)
1988       : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1989                      SC_None, false, false, ConstexprSpecKind::Unspecified,
1990                      TrailingRequiresClause),
1991         Ctor(Ctor), ExplicitSpec(ES),
1992         SourceDeductionGuide(GeneratedFrom, SourceKind) {
1993     if (EndLocation.isValid())
1994       setRangeEnd(EndLocation);
1995     setDeductionCandidateKind(Kind);
1996   }
1997 
1998   CXXConstructorDecl *Ctor;
1999   ExplicitSpecifier ExplicitSpec;
2000   // The deduction guide, if any, that this deduction guide was generated from,
2001   // in the case of alias template deduction. The SourceDeductionGuideKind
2002   // member indicates which of these sources applies, or is None otherwise.
2003   llvm::PointerIntPair<const CXXDeductionGuideDecl *, 2,
2004                        SourceDeductionGuideKind>
2005       SourceDeductionGuide;
2006   void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2007 
2008 public:
2009   friend class ASTDeclReader;
2010   friend class ASTDeclWriter;
2011 
2012   static CXXDeductionGuideDecl *
2013   Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2014          ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2015          TypeSourceInfo *TInfo, SourceLocation EndLocation,
2016          CXXConstructorDecl *Ctor = nullptr,
2017          DeductionCandidate Kind = DeductionCandidate::Normal,
2018          Expr *TrailingRequiresClause = nullptr,
2019          const CXXDeductionGuideDecl *SourceDG = nullptr,
2020          SourceDeductionGuideKind SK = SourceDeductionGuideKind::None);
2021 
2022   static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C,
2023                                                    GlobalDeclID ID);
2024 
2025   ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
2026   const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
2027 
2028   /// Return true if the declaration is already resolved to be explicit.
2029   bool isExplicit() const { return ExplicitSpec.isExplicit(); }
2030 
2031   /// Get the template for which this guide performs deduction.
2032   TemplateDecl *getDeducedTemplate() const {
2033     return getDeclName().getCXXDeductionGuideTemplate();
2034   }
2035 
2036   /// Get the constructor from which this deduction guide was generated, if
2037   /// this is an implicit deduction guide.
2038   CXXConstructorDecl *getCorrespondingConstructor() const { return Ctor; }
2039 
2040   /// Get the deduction guide from which this deduction guide was generated,
2041   /// if it was generated as part of alias template deduction or from an
2042   /// inherited constructor.
2043   const CXXDeductionGuideDecl *getSourceDeductionGuide() const {
2044     return SourceDeductionGuide.getPointer();
2045   }
2046 
2047   void setSourceDeductionGuide(CXXDeductionGuideDecl *DG) {
2048     SourceDeductionGuide.setPointer(DG);
2049   }
2050 
2051   SourceDeductionGuideKind getSourceDeductionGuideKind() const {
2052     return SourceDeductionGuide.getInt();
2053   }
2054 
2055   void setSourceDeductionGuideKind(SourceDeductionGuideKind SK) {
2056     SourceDeductionGuide.setInt(SK);
2057   }
2058 
2059   void setDeductionCandidateKind(DeductionCandidate K) {
2060     FunctionDeclBits.DeductionCandidateKind = static_cast<unsigned char>(K);
2061   }
2062 
2063   DeductionCandidate getDeductionCandidateKind() const {
2064     return static_cast<DeductionCandidate>(
2065         FunctionDeclBits.DeductionCandidateKind);
2066   }
2067 
2068   // Implement isa/cast/dyncast/etc.
2069   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2070   static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
2071 };
2072 
2073 /// \brief Represents the body of a requires-expression.
2074 ///
2075 /// This decl exists merely to serve as the DeclContext for the local
2076 /// parameters of the requires expression as well as other declarations inside
2077 /// it.
2078 ///
2079 /// \code
2080 /// template<typename T> requires requires (T t) { {t++} -> regular; }
2081 /// \endcode
2082 ///
2083 /// In this example, a RequiresExpr object will be generated for the expression,
2084 /// and a RequiresExprBodyDecl will be created to hold the parameter t and the
2085 /// template argument list imposed by the compound requirement.
2086 class RequiresExprBodyDecl : public Decl, public DeclContext {
2087   RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
2088       : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
2089 
2090 public:
2091   friend class ASTDeclReader;
2092   friend class ASTDeclWriter;
2093 
2094   static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
2095                                       SourceLocation StartLoc);
2096 
2097   static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C,
2098                                                   GlobalDeclID ID);
2099 
2100   // Implement isa/cast/dyncast/etc.
2101   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2102   static bool classofKind(Kind K) { return K == RequiresExprBody; }
2103 
2104   static DeclContext *castToDeclContext(const RequiresExprBodyDecl *D) {
2105     return static_cast<DeclContext *>(const_cast<RequiresExprBodyDecl *>(D));
2106   }
2107 
2108   static RequiresExprBodyDecl *castFromDeclContext(const DeclContext *DC) {
2109     return static_cast<RequiresExprBodyDecl *>(const_cast<DeclContext *>(DC));
2110   }
2111 };
2112 
2113 /// Represents a static or instance method of a struct/union/class.
2114 ///
2115 /// In the terminology of the C++ Standard, these are the (static and
2116 /// non-static) member functions, whether virtual or not.
2117 class CXXMethodDecl : public FunctionDecl {
2118   void anchor() override;
2119 
2120 protected:
2121   CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2122                 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2123                 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
2124                 bool UsesFPIntrin, bool isInline,
2125                 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2126                 Expr *TrailingRequiresClause = nullptr)
2127       : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
2128                      isInline, ConstexprKind, TrailingRequiresClause) {
2129     if (EndLocation.isValid())
2130       setRangeEnd(EndLocation);
2131   }
2132 
2133 public:
2134   static CXXMethodDecl *
2135   Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2136          const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2137          StorageClass SC, bool UsesFPIntrin, bool isInline,
2138          ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2139          Expr *TrailingRequiresClause = nullptr);
2140 
2141   static CXXMethodDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2142 
2143   bool isStatic() const;
2144   bool isInstance() const { return !isStatic(); }
2145 
2146   /// [C++2b][dcl.fct]/p7
2147   /// An explicit object member function is a non-static
2148   /// member function with an explicit object parameter. e.g.,
2149   ///   void func(this SomeType);
2150   bool isExplicitObjectMemberFunction() const;
2151 
2152   /// [C++2b][dcl.fct]/p7
2153   /// An implicit object member function is a non-static
2154   /// member function without an explicit object parameter.
2155   bool isImplicitObjectMemberFunction() const;
2156 
2157   /// Returns true if the given operator is implicitly static in a record
2158   /// context.
2159   static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2160     // [class.free]p1:
2161     // Any allocation function for a class T is a static member
2162     // (even if not explicitly declared static).
2163     // [class.free]p6 Any deallocation function for a class X is a static member
2164     // (even if not explicitly declared static).
2165     return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2166            OOK == OO_Array_Delete;
2167   }
2168 
2169   bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2170   bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2171 
2172   bool isVirtual() const {
2173     CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2174 
2175     // Member function is virtual if it is marked explicitly so, or if it is
2176     // declared in __interface -- then it is automatically pure virtual.
2177     if (CD->isVirtualAsWritten() || CD->isPureVirtual())
2178       return true;
2179 
2180     return CD->size_overridden_methods() != 0;
2181   }
2182 
2183   /// If it's possible to devirtualize a call to this method, return the called
2184   /// function. Otherwise, return null.
2185 
2186   /// \param Base The object on which this virtual function is called.
2187   /// \param IsAppleKext True if we are compiling for Apple kext.
2188   CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2189 
2190   const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2191                                               bool IsAppleKext) const {
2192     return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2193         Base, IsAppleKext);
2194   }
2195 
2196   /// Determine whether this is a usual deallocation function (C++
2197   /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2198   /// delete[] operator with a particular signature. Populates \p PreventedBy
2199   /// with the declarations of the functions of the same kind if they were the
2200   /// reason for this function returning false. This is used by
2201   /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2202   /// context.
2203   bool isUsualDeallocationFunction(
2204       SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2205 
2206   /// Determine whether this is a copy-assignment operator, regardless
2207   /// of whether it was declared implicitly or explicitly.
2208   bool isCopyAssignmentOperator() const;
2209 
2210   /// Determine whether this is a move assignment operator.
2211   bool isMoveAssignmentOperator() const;
2212 
2213   CXXMethodDecl *getCanonicalDecl() override {
2214     return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2215   }
2216   const CXXMethodDecl *getCanonicalDecl() const {
2217     return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2218   }
2219 
2220   CXXMethodDecl *getMostRecentDecl() {
2221     return cast<CXXMethodDecl>(
2222             static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2223   }
2224   const CXXMethodDecl *getMostRecentDecl() const {
2225     return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2226   }
2227 
2228   void addOverriddenMethod(const CXXMethodDecl *MD);
2229 
2230   using method_iterator = const CXXMethodDecl *const *;
2231 
2232   method_iterator begin_overridden_methods() const;
2233   method_iterator end_overridden_methods() const;
2234   unsigned size_overridden_methods() const;
2235 
2236   using overridden_method_range = llvm::iterator_range<
2237       llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2238 
2239   overridden_method_range overridden_methods() const;
2240 
2241   /// Return the parent of this method declaration, which
2242   /// is the class in which this method is defined.
2243   const CXXRecordDecl *getParent() const {
2244     return cast<CXXRecordDecl>(FunctionDecl::getParent());
2245   }
2246 
2247   /// Return the parent of this method declaration, which
2248   /// is the class in which this method is defined.
2249   CXXRecordDecl *getParent() {
2250     return const_cast<CXXRecordDecl *>(
2251              cast<CXXRecordDecl>(FunctionDecl::getParent()));
2252   }
2253 
2254   /// Return the type of the \c this pointer.
2255   ///
2256   /// Should only be called for instance (i.e., non-static) methods. Note
2257   /// that for the call operator of a lambda closure type, this returns the
2258   /// desugared 'this' type (a pointer to the closure type), not the captured
2259   /// 'this' type.
2260   QualType getThisType() const;
2261 
2262   /// Return the type of the object pointed by \c this.
2263   ///
2264   /// See getThisType() for usage restriction.
2265 
2266   QualType getFunctionObjectParameterReferenceType() const;
2267   QualType getFunctionObjectParameterType() const {
2268     return getFunctionObjectParameterReferenceType().getNonReferenceType();
2269   }
2270 
2271   unsigned getNumExplicitParams() const {
2272     return getNumParams() - (isExplicitObjectMemberFunction() ? 1 : 0);
2273   }
2274 
2275   static QualType getThisType(const FunctionProtoType *FPT,
2276                               const CXXRecordDecl *Decl);
2277 
2278   Qualifiers getMethodQualifiers() const {
2279     return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2280   }
2281 
2282   /// Retrieve the ref-qualifier associated with this method.
2283   ///
2284   /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2285   /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2286   /// @code
2287   /// struct X {
2288   ///   void f() &;
2289   ///   void g() &&;
2290   ///   void h();
2291   /// };
2292   /// @endcode
2293   RefQualifierKind getRefQualifier() const {
2294     return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2295   }
2296 
2297   bool hasInlineBody() const;
2298 
2299   /// Determine whether this is a lambda closure type's static member
2300   /// function that is used for the result of the lambda's conversion to
2301   /// function pointer (for a lambda with no captures).
2302   ///
2303   /// The function itself, if used, will have a placeholder body that will be
2304   /// supplied by IR generation to either forward to the function call operator
2305   /// or clone the function call operator.
2306   bool isLambdaStaticInvoker() const;
2307 
2308   /// Find the method in \p RD that corresponds to this one.
2309   ///
2310   /// Find if \p RD or one of the classes it inherits from override this method.
2311   /// If so, return it. \p RD is assumed to be a subclass of the class defining
2312   /// this method (or be the class itself), unless \p MayBeBase is set to true.
2313   CXXMethodDecl *
2314   getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2315                                 bool MayBeBase = false);
2316 
2317   const CXXMethodDecl *
2318   getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2319                                 bool MayBeBase = false) const {
2320     return const_cast<CXXMethodDecl *>(this)
2321               ->getCorrespondingMethodInClass(RD, MayBeBase);
2322   }
2323 
2324   /// Find if \p RD declares a function that overrides this function, and if so,
2325   /// return it. Does not search base classes.
2326   CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2327                                                        bool MayBeBase = false);
2328   const CXXMethodDecl *
2329   getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2330                                         bool MayBeBase = false) const {
2331     return const_cast<CXXMethodDecl *>(this)
2332         ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2333   }
2334 
2335   // Implement isa/cast/dyncast/etc.
2336   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2337   static bool classofKind(Kind K) {
2338     return K >= firstCXXMethod && K <= lastCXXMethod;
2339   }
2340 };
2341 
2342 /// Represents a C++ base or member initializer.
2343 ///
2344 /// This is part of a constructor initializer that
2345 /// initializes one non-static member variable or one base class. For
2346 /// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2347 /// initializers:
2348 ///
2349 /// \code
2350 /// class A { };
2351 /// class B : public A {
2352 ///   float f;
2353 /// public:
2354 ///   B(A& a) : A(a), f(3.14159) { }
2355 /// };
2356 /// \endcode
2357 class CXXCtorInitializer final {
2358   /// Either the base class name/delegating constructor type (stored as
2359   /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2360   /// (IndirectFieldDecl*) being initialized.
2361   llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2362       Initializee;
2363 
2364   /// The argument used to initialize the base or member, which may
2365   /// end up constructing an object (when multiple arguments are involved).
2366   Stmt *Init;
2367 
2368   /// The source location for the field name or, for a base initializer
2369   /// pack expansion, the location of the ellipsis.
2370   ///
2371   /// In the case of a delegating
2372   /// constructor, it will still include the type's source location as the
2373   /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2374   SourceLocation MemberOrEllipsisLocation;
2375 
2376   /// Location of the left paren of the ctor-initializer.
2377   SourceLocation LParenLoc;
2378 
2379   /// Location of the right paren of the ctor-initializer.
2380   SourceLocation RParenLoc;
2381 
2382   /// If the initializee is a type, whether that type makes this
2383   /// a delegating initialization.
2384   LLVM_PREFERRED_TYPE(bool)
2385   unsigned IsDelegating : 1;
2386 
2387   /// If the initializer is a base initializer, this keeps track
2388   /// of whether the base is virtual or not.
2389   LLVM_PREFERRED_TYPE(bool)
2390   unsigned IsVirtual : 1;
2391 
2392   /// Whether or not the initializer is explicitly written
2393   /// in the sources.
2394   LLVM_PREFERRED_TYPE(bool)
2395   unsigned IsWritten : 1;
2396 
2397   /// If IsWritten is true, then this number keeps track of the textual order
2398   /// of this initializer in the original sources, counting from 0.
2399   unsigned SourceOrder : 13;
2400 
2401 public:
2402   /// Creates a new base-class initializer.
2403   explicit
2404   CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2405                      SourceLocation L, Expr *Init, SourceLocation R,
2406                      SourceLocation EllipsisLoc);
2407 
2408   /// Creates a new member initializer.
2409   explicit
2410   CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2411                      SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2412                      SourceLocation R);
2413 
2414   /// Creates a new anonymous field initializer.
2415   explicit
2416   CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2417                      SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2418                      SourceLocation R);
2419 
2420   /// Creates a new delegating initializer.
2421   explicit
2422   CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2423                      SourceLocation L, Expr *Init, SourceLocation R);
2424 
2425   /// \return Unique reproducible object identifier.
2426   int64_t getID(const ASTContext &Context) const;
2427 
2428   /// Determine whether this initializer is initializing a base class.
2429   bool isBaseInitializer() const {
2430     return isa<TypeSourceInfo *>(Initializee) && !IsDelegating;
2431   }
2432 
2433   /// Determine whether this initializer is initializing a non-static
2434   /// data member.
2435   bool isMemberInitializer() const { return isa<FieldDecl *>(Initializee); }
2436 
2437   bool isAnyMemberInitializer() const {
2438     return isMemberInitializer() || isIndirectMemberInitializer();
2439   }
2440 
2441   bool isIndirectMemberInitializer() const {
2442     return isa<IndirectFieldDecl *>(Initializee);
2443   }
2444 
2445   /// Determine whether this initializer is an implicit initializer
2446   /// generated for a field with an initializer defined on the member
2447   /// declaration.
2448   ///
2449   /// In-class member initializers (also known as "non-static data member
2450   /// initializations", NSDMIs) were introduced in C++11.
2451   bool isInClassMemberInitializer() const {
2452     return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2453   }
2454 
2455   /// Determine whether this initializer is creating a delegating
2456   /// constructor.
2457   bool isDelegatingInitializer() const {
2458     return isa<TypeSourceInfo *>(Initializee) && IsDelegating;
2459   }
2460 
2461   /// Determine whether this initializer is a pack expansion.
2462   bool isPackExpansion() const {
2463     return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2464   }
2465 
2466   // For a pack expansion, returns the location of the ellipsis.
2467   SourceLocation getEllipsisLoc() const {
2468     if (!isPackExpansion())
2469       return {};
2470     return MemberOrEllipsisLocation;
2471   }
2472 
2473   /// If this is a base class initializer, returns the type of the
2474   /// base class with location information. Otherwise, returns an NULL
2475   /// type location.
2476   TypeLoc getBaseClassLoc() const;
2477 
2478   /// If this is a base class initializer, returns the type of the base class.
2479   /// Otherwise, returns null.
2480   const Type *getBaseClass() const;
2481 
2482   /// Returns whether the base is virtual or not.
2483   bool isBaseVirtual() const {
2484     assert(isBaseInitializer() && "Must call this on base initializer!");
2485 
2486     return IsVirtual;
2487   }
2488 
2489   /// Returns the declarator information for a base class or delegating
2490   /// initializer.
2491   TypeSourceInfo *getTypeSourceInfo() const {
2492     return Initializee.dyn_cast<TypeSourceInfo *>();
2493   }
2494 
2495   /// If this is a member initializer, returns the declaration of the
2496   /// non-static data member being initialized. Otherwise, returns null.
2497   FieldDecl *getMember() const {
2498     if (isMemberInitializer())
2499       return cast<FieldDecl *>(Initializee);
2500     return nullptr;
2501   }
2502 
2503   FieldDecl *getAnyMember() const {
2504     if (isMemberInitializer())
2505       return cast<FieldDecl *>(Initializee);
2506     if (isIndirectMemberInitializer())
2507       return cast<IndirectFieldDecl *>(Initializee)->getAnonField();
2508     return nullptr;
2509   }
2510 
2511   IndirectFieldDecl *getIndirectMember() const {
2512     if (isIndirectMemberInitializer())
2513       return cast<IndirectFieldDecl *>(Initializee);
2514     return nullptr;
2515   }
2516 
2517   SourceLocation getMemberLocation() const {
2518     return MemberOrEllipsisLocation;
2519   }
2520 
2521   /// Determine the source location of the initializer.
2522   SourceLocation getSourceLocation() const;
2523 
2524   /// Determine the source range covering the entire initializer.
2525   SourceRange getSourceRange() const LLVM_READONLY;
2526 
2527   /// Determine whether this initializer is explicitly written
2528   /// in the source code.
2529   bool isWritten() const { return IsWritten; }
2530 
2531   /// Return the source position of the initializer, counting from 0.
2532   /// If the initializer was implicit, -1 is returned.
2533   int getSourceOrder() const {
2534     return IsWritten ? static_cast<int>(SourceOrder) : -1;
2535   }
2536 
2537   /// Set the source order of this initializer.
2538   ///
2539   /// This can only be called once for each initializer; it cannot be called
2540   /// on an initializer having a positive number of (implicit) array indices.
2541   ///
2542   /// This assumes that the initializer was written in the source code, and
2543   /// ensures that isWritten() returns true.
2544   void setSourceOrder(int Pos) {
2545     assert(!IsWritten &&
2546            "setSourceOrder() used on implicit initializer");
2547     assert(SourceOrder == 0 &&
2548            "calling twice setSourceOrder() on the same initializer");
2549     assert(Pos >= 0 &&
2550            "setSourceOrder() used to make an initializer implicit");
2551     IsWritten = true;
2552     SourceOrder = static_cast<unsigned>(Pos);
2553   }
2554 
2555   SourceLocation getLParenLoc() const { return LParenLoc; }
2556   SourceLocation getRParenLoc() const { return RParenLoc; }
2557 
2558   /// Get the initializer.
2559   Expr *getInit() const { return static_cast<Expr *>(Init); }
2560 };
2561 
2562 /// Description of a constructor that was inherited from a base class.
2563 class InheritedConstructor {
2564   ConstructorUsingShadowDecl *Shadow = nullptr;
2565   CXXConstructorDecl *BaseCtor = nullptr;
2566 
2567 public:
2568   InheritedConstructor() = default;
2569   InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2570                        CXXConstructorDecl *BaseCtor)
2571       : Shadow(Shadow), BaseCtor(BaseCtor) {}
2572 
2573   explicit operator bool() const { return Shadow; }
2574 
2575   ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2576   CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2577 };
2578 
2579 /// Represents a C++ constructor within a class.
2580 ///
2581 /// For example:
2582 ///
2583 /// \code
2584 /// class X {
2585 /// public:
2586 ///   explicit X(int); // represented by a CXXConstructorDecl.
2587 /// };
2588 /// \endcode
2589 class CXXConstructorDecl final
2590     : public CXXMethodDecl,
2591       private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2592                                     ExplicitSpecifier> {
2593   // This class stores some data in DeclContext::CXXConstructorDeclBits
2594   // to save some space. Use the provided accessors to access it.
2595 
2596   /// \name Support for base and member initializers.
2597   /// \{
2598   /// The arguments used to initialize the base or member.
2599   LazyCXXCtorInitializersPtr CtorInitializers;
2600 
2601   CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2602                      const DeclarationNameInfo &NameInfo, QualType T,
2603                      TypeSourceInfo *TInfo, ExplicitSpecifier ES,
2604                      bool UsesFPIntrin, bool isInline,
2605                      bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2606                      InheritedConstructor Inherited,
2607                      Expr *TrailingRequiresClause);
2608 
2609   void anchor() override;
2610 
2611   size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2612     return CXXConstructorDeclBits.IsInheritingConstructor;
2613   }
2614   size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2615     return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2616   }
2617 
2618   ExplicitSpecifier getExplicitSpecifierInternal() const {
2619     if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2620       return *getTrailingObjects<ExplicitSpecifier>();
2621     return ExplicitSpecifier(
2622         nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2623                      ? ExplicitSpecKind::ResolvedTrue
2624                      : ExplicitSpecKind::ResolvedFalse);
2625   }
2626 
2627   enum TrailingAllocKind {
2628     TAKInheritsConstructor = 1,
2629     TAKHasTailExplicit = 1 << 1,
2630   };
2631 
2632   uint64_t getTrailingAllocKind() const {
2633     return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2634            (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2635   }
2636 
2637 public:
2638   friend class ASTDeclReader;
2639   friend class ASTDeclWriter;
2640   friend TrailingObjects;
2641 
2642   static CXXConstructorDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID,
2643                                                 uint64_t AllocKind);
2644   static CXXConstructorDecl *
2645   Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2646          const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2647          ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2648          bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2649          InheritedConstructor Inherited = InheritedConstructor(),
2650          Expr *TrailingRequiresClause = nullptr);
2651 
2652   void setExplicitSpecifier(ExplicitSpecifier ES) {
2653     assert((!ES.getExpr() ||
2654             CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&
2655            "cannot set this explicit specifier. no trail-allocated space for "
2656            "explicit");
2657     if (ES.getExpr())
2658       *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2659     else
2660       CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2661   }
2662 
2663   ExplicitSpecifier getExplicitSpecifier() {
2664     return getCanonicalDecl()->getExplicitSpecifierInternal();
2665   }
2666   const ExplicitSpecifier getExplicitSpecifier() const {
2667     return getCanonicalDecl()->getExplicitSpecifierInternal();
2668   }
2669 
2670   /// Return true if the declaration is already resolved to be explicit.
2671   bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2672 
2673   /// Iterates through the member/base initializer list.
2674   using init_iterator = CXXCtorInitializer **;
2675 
2676   /// Iterates through the member/base initializer list.
2677   using init_const_iterator = CXXCtorInitializer *const *;
2678 
2679   using init_range = llvm::iterator_range<init_iterator>;
2680   using init_const_range = llvm::iterator_range<init_const_iterator>;
2681 
2682   init_range inits() { return init_range(init_begin(), init_end()); }
2683   init_const_range inits() const {
2684     return init_const_range(init_begin(), init_end());
2685   }
2686 
2687   /// Retrieve an iterator to the first initializer.
2688   init_iterator init_begin() {
2689     const auto *ConstThis = this;
2690     return const_cast<init_iterator>(ConstThis->init_begin());
2691   }
2692 
2693   /// Retrieve an iterator to the first initializer.
2694   init_const_iterator init_begin() const;
2695 
2696   /// Retrieve an iterator past the last initializer.
2697   init_iterator       init_end()       {
2698     return init_begin() + getNumCtorInitializers();
2699   }
2700 
2701   /// Retrieve an iterator past the last initializer.
2702   init_const_iterator init_end() const {
2703     return init_begin() + getNumCtorInitializers();
2704   }
2705 
2706   using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2707   using init_const_reverse_iterator =
2708       std::reverse_iterator<init_const_iterator>;
2709 
2710   init_reverse_iterator init_rbegin() {
2711     return init_reverse_iterator(init_end());
2712   }
2713   init_const_reverse_iterator init_rbegin() const {
2714     return init_const_reverse_iterator(init_end());
2715   }
2716 
2717   init_reverse_iterator init_rend() {
2718     return init_reverse_iterator(init_begin());
2719   }
2720   init_const_reverse_iterator init_rend() const {
2721     return init_const_reverse_iterator(init_begin());
2722   }
2723 
2724   /// Determine the number of arguments used to initialize the member
2725   /// or base.
2726   unsigned getNumCtorInitializers() const {
2727       return CXXConstructorDeclBits.NumCtorInitializers;
2728   }
2729 
2730   void setNumCtorInitializers(unsigned numCtorInitializers) {
2731     CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2732     // This assert added because NumCtorInitializers is stored
2733     // in CXXConstructorDeclBits as a bitfield and its width has
2734     // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2735     assert(CXXConstructorDeclBits.NumCtorInitializers ==
2736            numCtorInitializers && "NumCtorInitializers overflow!");
2737   }
2738 
2739   void setCtorInitializers(CXXCtorInitializer **Initializers) {
2740     CtorInitializers = Initializers;
2741   }
2742 
2743   /// Determine whether this constructor is a delegating constructor.
2744   bool isDelegatingConstructor() const {
2745     return (getNumCtorInitializers() == 1) &&
2746            init_begin()[0]->isDelegatingInitializer();
2747   }
2748 
2749   /// When this constructor delegates to another, retrieve the target.
2750   CXXConstructorDecl *getTargetConstructor() const;
2751 
2752   /// Whether this constructor is a default
2753   /// constructor (C++ [class.ctor]p5), which can be used to
2754   /// default-initialize a class of this type.
2755   bool isDefaultConstructor() const;
2756 
2757   /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2758   /// which can be used to copy the class.
2759   ///
2760   /// \p TypeQuals will be set to the qualifiers on the
2761   /// argument type. For example, \p TypeQuals would be set to \c
2762   /// Qualifiers::Const for the following copy constructor:
2763   ///
2764   /// \code
2765   /// class X {
2766   /// public:
2767   ///   X(const X&);
2768   /// };
2769   /// \endcode
2770   bool isCopyConstructor(unsigned &TypeQuals) const;
2771 
2772   /// Whether this constructor is a copy
2773   /// constructor (C++ [class.copy]p2, which can be used to copy the
2774   /// class.
2775   bool isCopyConstructor() const {
2776     unsigned TypeQuals = 0;
2777     return isCopyConstructor(TypeQuals);
2778   }
2779 
2780   /// Determine whether this constructor is a move constructor
2781   /// (C++11 [class.copy]p3), which can be used to move values of the class.
2782   ///
2783   /// \param TypeQuals If this constructor is a move constructor, will be set
2784   /// to the type qualifiers on the referent of the first parameter's type.
2785   bool isMoveConstructor(unsigned &TypeQuals) const;
2786 
2787   /// Determine whether this constructor is a move constructor
2788   /// (C++11 [class.copy]p3), which can be used to move values of the class.
2789   bool isMoveConstructor() const {
2790     unsigned TypeQuals = 0;
2791     return isMoveConstructor(TypeQuals);
2792   }
2793 
2794   /// Determine whether this is a copy or move constructor.
2795   ///
2796   /// \param TypeQuals Will be set to the type qualifiers on the reference
2797   /// parameter, if in fact this is a copy or move constructor.
2798   bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2799 
2800   /// Determine whether this a copy or move constructor.
2801   bool isCopyOrMoveConstructor() const {
2802     unsigned Quals;
2803     return isCopyOrMoveConstructor(Quals);
2804   }
2805 
2806   /// Whether this constructor is a
2807   /// converting constructor (C++ [class.conv.ctor]), which can be
2808   /// used for user-defined conversions.
2809   bool isConvertingConstructor(bool AllowExplicit) const;
2810 
2811   /// Determine whether this is a member template specialization that
2812   /// would copy the object to itself. Such constructors are never used to copy
2813   /// an object.
2814   bool isSpecializationCopyingObject() const;
2815 
2816   /// Determine whether this is an implicit constructor synthesized to
2817   /// model a call to a constructor inherited from a base class.
2818   bool isInheritingConstructor() const {
2819     return CXXConstructorDeclBits.IsInheritingConstructor;
2820   }
2821 
2822   /// State that this is an implicit constructor synthesized to
2823   /// model a call to a constructor inherited from a base class.
2824   void setInheritingConstructor(bool isIC = true) {
2825     CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2826   }
2827 
2828   /// Get the constructor that this inheriting constructor is based on.
2829   InheritedConstructor getInheritedConstructor() const {
2830     return isInheritingConstructor() ?
2831       *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2832   }
2833 
2834   CXXConstructorDecl *getCanonicalDecl() override {
2835     return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2836   }
2837   const CXXConstructorDecl *getCanonicalDecl() const {
2838     return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2839   }
2840 
2841   // Implement isa/cast/dyncast/etc.
2842   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2843   static bool classofKind(Kind K) { return K == CXXConstructor; }
2844 };
2845 
2846 /// Represents a C++ destructor within a class.
2847 ///
2848 /// For example:
2849 ///
2850 /// \code
2851 /// class X {
2852 /// public:
2853 ///   ~X(); // represented by a CXXDestructorDecl.
2854 /// };
2855 /// \endcode
2856 class CXXDestructorDecl : public CXXMethodDecl {
2857   friend class ASTDeclReader;
2858   friend class ASTDeclWriter;
2859 
2860   // FIXME: Don't allocate storage for these except in the first declaration
2861   // of a virtual destructor.
2862   FunctionDecl *OperatorDelete = nullptr;
2863   Expr *OperatorDeleteThisArg = nullptr;
2864 
2865   CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2866                     const DeclarationNameInfo &NameInfo, QualType T,
2867                     TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline,
2868                     bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2869                     Expr *TrailingRequiresClause = nullptr)
2870       : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2871                       SC_None, UsesFPIntrin, isInline, ConstexprKind,
2872                       SourceLocation(), TrailingRequiresClause) {
2873     setImplicit(isImplicitlyDeclared);
2874   }
2875 
2876   void anchor() override;
2877 
2878 public:
2879   static CXXDestructorDecl *
2880   Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2881          const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2882          bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
2883          ConstexprSpecKind ConstexprKind,
2884          Expr *TrailingRequiresClause = nullptr);
2885   static CXXDestructorDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2886 
2887   void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2888 
2889   const FunctionDecl *getOperatorDelete() const {
2890     return getCanonicalDecl()->OperatorDelete;
2891   }
2892 
2893   Expr *getOperatorDeleteThisArg() const {
2894     return getCanonicalDecl()->OperatorDeleteThisArg;
2895   }
2896 
2897   /// Will this destructor ever be called when considering which deallocation
2898   /// function is associated with the destructor? Can optionally be passed an
2899   /// 'operator delete' function declaration to test against specifically.
2900   bool isCalledByDelete(const FunctionDecl *OpDel = nullptr) const;
2901 
2902   CXXDestructorDecl *getCanonicalDecl() override {
2903     return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2904   }
2905   const CXXDestructorDecl *getCanonicalDecl() const {
2906     return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2907   }
2908 
2909   // Implement isa/cast/dyncast/etc.
2910   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2911   static bool classofKind(Kind K) { return K == CXXDestructor; }
2912 };
2913 
2914 /// Represents a C++ conversion function within a class.
2915 ///
2916 /// For example:
2917 ///
2918 /// \code
2919 /// class X {
2920 /// public:
2921 ///   operator bool();
2922 /// };
2923 /// \endcode
2924 class CXXConversionDecl : public CXXMethodDecl {
2925   CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2926                     const DeclarationNameInfo &NameInfo, QualType T,
2927                     TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline,
2928                     ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2929                     SourceLocation EndLocation,
2930                     Expr *TrailingRequiresClause = nullptr)
2931       : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2932                       SC_None, UsesFPIntrin, isInline, ConstexprKind,
2933                       EndLocation, TrailingRequiresClause),
2934         ExplicitSpec(ES) {}
2935   void anchor() override;
2936 
2937   ExplicitSpecifier ExplicitSpec;
2938 
2939 public:
2940   friend class ASTDeclReader;
2941   friend class ASTDeclWriter;
2942 
2943   static CXXConversionDecl *
2944   Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2945          const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2946          bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
2947          ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2948          Expr *TrailingRequiresClause = nullptr);
2949   static CXXConversionDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
2950 
2951   ExplicitSpecifier getExplicitSpecifier() {
2952     return getCanonicalDecl()->ExplicitSpec;
2953   }
2954 
2955   const ExplicitSpecifier getExplicitSpecifier() const {
2956     return getCanonicalDecl()->ExplicitSpec;
2957   }
2958 
2959   /// Return true if the declaration is already resolved to be explicit.
2960   bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2961   void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2962 
2963   /// Returns the type that this conversion function is converting to.
2964   QualType getConversionType() const {
2965     return getType()->castAs<FunctionType>()->getReturnType();
2966   }
2967 
2968   /// Determine whether this conversion function is a conversion from
2969   /// a lambda closure type to a block pointer.
2970   bool isLambdaToBlockPointerConversion() const;
2971 
2972   CXXConversionDecl *getCanonicalDecl() override {
2973     return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2974   }
2975   const CXXConversionDecl *getCanonicalDecl() const {
2976     return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2977   }
2978 
2979   // Implement isa/cast/dyncast/etc.
2980   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2981   static bool classofKind(Kind K) { return K == CXXConversion; }
2982 };
2983 
2984 /// Represents the language in a linkage specification.
2985 ///
2986 /// The values are part of the serialization ABI for
2987 /// ASTs and cannot be changed without altering that ABI.
2988 enum class LinkageSpecLanguageIDs { C = 1, CXX = 2 };
2989 
2990 /// Represents a linkage specification.
2991 ///
2992 /// For example:
2993 /// \code
2994 ///   extern "C" void foo();
2995 /// \endcode
2996 class LinkageSpecDecl : public Decl, public DeclContext {
2997   virtual void anchor();
2998   // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2999   // some space. Use the provided accessors to access it.
3000 
3001   /// The source location for the extern keyword.
3002   SourceLocation ExternLoc;
3003 
3004   /// The source location for the right brace (if valid).
3005   SourceLocation RBraceLoc;
3006 
3007   LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
3008                   SourceLocation LangLoc, LinkageSpecLanguageIDs lang,
3009                   bool HasBraces);
3010 
3011 public:
3012   static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
3013                                  SourceLocation ExternLoc,
3014                                  SourceLocation LangLoc,
3015                                  LinkageSpecLanguageIDs Lang, bool HasBraces);
3016   static LinkageSpecDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3017 
3018   /// Return the language specified by this linkage specification.
3019   LinkageSpecLanguageIDs getLanguage() const {
3020     return static_cast<LinkageSpecLanguageIDs>(LinkageSpecDeclBits.Language);
3021   }
3022 
3023   /// Set the language specified by this linkage specification.
3024   void setLanguage(LinkageSpecLanguageIDs L) {
3025     LinkageSpecDeclBits.Language = llvm::to_underlying(L);
3026   }
3027 
3028   /// Determines whether this linkage specification had braces in
3029   /// its syntactic form.
3030   bool hasBraces() const {
3031     assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces);
3032     return LinkageSpecDeclBits.HasBraces;
3033   }
3034 
3035   SourceLocation getExternLoc() const { return ExternLoc; }
3036   SourceLocation getRBraceLoc() const { return RBraceLoc; }
3037   void setExternLoc(SourceLocation L) { ExternLoc = L; }
3038   void setRBraceLoc(SourceLocation L) {
3039     RBraceLoc = L;
3040     LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
3041   }
3042 
3043   SourceLocation getEndLoc() const LLVM_READONLY {
3044     if (hasBraces())
3045       return getRBraceLoc();
3046     // No braces: get the end location of the (only) declaration in context
3047     // (if present).
3048     return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
3049   }
3050 
3051   SourceRange getSourceRange() const override LLVM_READONLY {
3052     return SourceRange(ExternLoc, getEndLoc());
3053   }
3054 
3055   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3056   static bool classofKind(Kind K) { return K == LinkageSpec; }
3057 
3058   static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
3059     return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
3060   }
3061 
3062   static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
3063     return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
3064   }
3065 };
3066 
3067 /// Represents C++ using-directive.
3068 ///
3069 /// For example:
3070 /// \code
3071 ///    using namespace std;
3072 /// \endcode
3073 ///
3074 /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
3075 /// artificial names for all using-directives in order to store
3076 /// them in DeclContext effectively.
3077 class UsingDirectiveDecl : public NamedDecl {
3078   /// The location of the \c using keyword.
3079   SourceLocation UsingLoc;
3080 
3081   /// The location of the \c namespace keyword.
3082   SourceLocation NamespaceLoc;
3083 
3084   /// The nested-name-specifier that precedes the namespace.
3085   NestedNameSpecifierLoc QualifierLoc;
3086 
3087   /// The namespace nominated by this using-directive.
3088   NamedDecl *NominatedNamespace;
3089 
3090   /// Enclosing context containing both using-directive and nominated
3091   /// namespace.
3092   DeclContext *CommonAncestor;
3093 
3094   UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
3095                      SourceLocation NamespcLoc,
3096                      NestedNameSpecifierLoc QualifierLoc,
3097                      SourceLocation IdentLoc,
3098                      NamedDecl *Nominated,
3099                      DeclContext *CommonAncestor)
3100       : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
3101         NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
3102         NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
3103 
3104   /// Returns special DeclarationName used by using-directives.
3105   ///
3106   /// This is only used by DeclContext for storing UsingDirectiveDecls in
3107   /// its lookup structure.
3108   static DeclarationName getName() {
3109     return DeclarationName::getUsingDirectiveName();
3110   }
3111 
3112   void anchor() override;
3113 
3114 public:
3115   friend class ASTDeclReader;
3116 
3117   // Friend for getUsingDirectiveName.
3118   friend class DeclContext;
3119 
3120   /// Retrieve the nested-name-specifier that qualifies the
3121   /// name of the namespace, with source-location information.
3122   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3123 
3124   /// Retrieve the nested-name-specifier that qualifies the
3125   /// name of the namespace.
3126   NestedNameSpecifier *getQualifier() const {
3127     return QualifierLoc.getNestedNameSpecifier();
3128   }
3129 
3130   NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
3131   const NamedDecl *getNominatedNamespaceAsWritten() const {
3132     return NominatedNamespace;
3133   }
3134 
3135   /// Returns the namespace nominated by this using-directive.
3136   NamespaceDecl *getNominatedNamespace();
3137 
3138   const NamespaceDecl *getNominatedNamespace() const {
3139     return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
3140   }
3141 
3142   /// Returns the common ancestor context of this using-directive and
3143   /// its nominated namespace.
3144   DeclContext *getCommonAncestor() { return CommonAncestor; }
3145   const DeclContext *getCommonAncestor() const { return CommonAncestor; }
3146 
3147   /// Return the location of the \c using keyword.
3148   SourceLocation getUsingLoc() const { return UsingLoc; }
3149 
3150   // FIXME: Could omit 'Key' in name.
3151   /// Returns the location of the \c namespace keyword.
3152   SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
3153 
3154   /// Returns the location of this using declaration's identifier.
3155   SourceLocation getIdentLocation() const { return getLocation(); }
3156 
3157   static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
3158                                     SourceLocation UsingLoc,
3159                                     SourceLocation NamespaceLoc,
3160                                     NestedNameSpecifierLoc QualifierLoc,
3161                                     SourceLocation IdentLoc,
3162                                     NamedDecl *Nominated,
3163                                     DeclContext *CommonAncestor);
3164   static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3165 
3166   SourceRange getSourceRange() const override LLVM_READONLY {
3167     return SourceRange(UsingLoc, getLocation());
3168   }
3169 
3170   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3171   static bool classofKind(Kind K) { return K == UsingDirective; }
3172 };
3173 
3174 /// Represents a C++ namespace alias.
3175 ///
3176 /// For example:
3177 ///
3178 /// \code
3179 /// namespace Foo = Bar;
3180 /// \endcode
3181 class NamespaceAliasDecl : public NamedDecl,
3182                            public Redeclarable<NamespaceAliasDecl> {
3183   friend class ASTDeclReader;
3184 
3185   /// The location of the \c namespace keyword.
3186   SourceLocation NamespaceLoc;
3187 
3188   /// The location of the namespace's identifier.
3189   ///
3190   /// This is accessed by TargetNameLoc.
3191   SourceLocation IdentLoc;
3192 
3193   /// The nested-name-specifier that precedes the namespace.
3194   NestedNameSpecifierLoc QualifierLoc;
3195 
3196   /// The Decl that this alias points to, either a NamespaceDecl or
3197   /// a NamespaceAliasDecl.
3198   NamedDecl *Namespace;
3199 
3200   NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3201                      SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3202                      IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3203                      SourceLocation IdentLoc, NamedDecl *Namespace)
3204       : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3205         NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3206         QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3207 
3208   void anchor() override;
3209 
3210   using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3211 
3212   NamespaceAliasDecl *getNextRedeclarationImpl() override;
3213   NamespaceAliasDecl *getPreviousDeclImpl() override;
3214   NamespaceAliasDecl *getMostRecentDeclImpl() override;
3215 
3216 public:
3217   static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3218                                     SourceLocation NamespaceLoc,
3219                                     SourceLocation AliasLoc,
3220                                     IdentifierInfo *Alias,
3221                                     NestedNameSpecifierLoc QualifierLoc,
3222                                     SourceLocation IdentLoc,
3223                                     NamedDecl *Namespace);
3224 
3225   static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3226 
3227   using redecl_range = redeclarable_base::redecl_range;
3228   using redecl_iterator = redeclarable_base::redecl_iterator;
3229 
3230   using redeclarable_base::redecls_begin;
3231   using redeclarable_base::redecls_end;
3232   using redeclarable_base::redecls;
3233   using redeclarable_base::getPreviousDecl;
3234   using redeclarable_base::getMostRecentDecl;
3235 
3236   NamespaceAliasDecl *getCanonicalDecl() override {
3237     return getFirstDecl();
3238   }
3239   const NamespaceAliasDecl *getCanonicalDecl() const {
3240     return getFirstDecl();
3241   }
3242 
3243   /// Retrieve the nested-name-specifier that qualifies the
3244   /// name of the namespace, with source-location information.
3245   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3246 
3247   /// Retrieve the nested-name-specifier that qualifies the
3248   /// name of the namespace.
3249   NestedNameSpecifier *getQualifier() const {
3250     return QualifierLoc.getNestedNameSpecifier();
3251   }
3252 
3253   /// Retrieve the namespace declaration aliased by this directive.
3254   NamespaceDecl *getNamespace() {
3255     if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3256       return AD->getNamespace();
3257 
3258     return cast<NamespaceDecl>(Namespace);
3259   }
3260 
3261   const NamespaceDecl *getNamespace() const {
3262     return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3263   }
3264 
3265   /// Returns the location of the alias name, i.e. 'foo' in
3266   /// "namespace foo = ns::bar;".
3267   SourceLocation getAliasLoc() const { return getLocation(); }
3268 
3269   /// Returns the location of the \c namespace keyword.
3270   SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3271 
3272   /// Returns the location of the identifier in the named namespace.
3273   SourceLocation getTargetNameLoc() const { return IdentLoc; }
3274 
3275   /// Retrieve the namespace that this alias refers to, which
3276   /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3277   NamedDecl *getAliasedNamespace() const { return Namespace; }
3278 
3279   SourceRange getSourceRange() const override LLVM_READONLY {
3280     return SourceRange(NamespaceLoc, IdentLoc);
3281   }
3282 
3283   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3284   static bool classofKind(Kind K) { return K == NamespaceAlias; }
3285 };
3286 
3287 /// Implicit declaration of a temporary that was materialized by
3288 /// a MaterializeTemporaryExpr and lifetime-extended by a declaration
3289 class LifetimeExtendedTemporaryDecl final
3290     : public Decl,
3291       public Mergeable<LifetimeExtendedTemporaryDecl> {
3292   friend class MaterializeTemporaryExpr;
3293   friend class ASTDeclReader;
3294 
3295   Stmt *ExprWithTemporary = nullptr;
3296 
3297   /// The declaration which lifetime-extended this reference, if any.
3298   /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3299   ValueDecl *ExtendingDecl = nullptr;
3300   unsigned ManglingNumber;
3301 
3302   mutable APValue *Value = nullptr;
3303 
3304   virtual void anchor();
3305 
3306   LifetimeExtendedTemporaryDecl(Expr *Temp, ValueDecl *EDecl, unsigned Mangling)
3307       : Decl(Decl::LifetimeExtendedTemporary, EDecl->getDeclContext(),
3308              EDecl->getLocation()),
3309         ExprWithTemporary(Temp), ExtendingDecl(EDecl),
3310         ManglingNumber(Mangling) {}
3311 
3312   LifetimeExtendedTemporaryDecl(EmptyShell)
3313       : Decl(Decl::LifetimeExtendedTemporary, EmptyShell{}) {}
3314 
3315 public:
3316   static LifetimeExtendedTemporaryDecl *Create(Expr *Temp, ValueDecl *EDec,
3317                                                unsigned Mangling) {
3318     return new (EDec->getASTContext(), EDec->getDeclContext())
3319         LifetimeExtendedTemporaryDecl(Temp, EDec, Mangling);
3320   }
3321   static LifetimeExtendedTemporaryDecl *CreateDeserialized(ASTContext &C,
3322                                                            GlobalDeclID ID) {
3323     return new (C, ID) LifetimeExtendedTemporaryDecl(EmptyShell{});
3324   }
3325 
3326   ValueDecl *getExtendingDecl() { return ExtendingDecl; }
3327   const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3328 
3329   /// Retrieve the storage duration for the materialized temporary.
3330   StorageDuration getStorageDuration() const;
3331 
3332   /// Retrieve the expression to which the temporary materialization conversion
3333   /// was applied. This isn't necessarily the initializer of the temporary due
3334   /// to the C++98 delayed materialization rules, but
3335   /// skipRValueSubobjectAdjustments can be used to find said initializer within
3336   /// the subexpression.
3337   Expr *getTemporaryExpr() { return cast<Expr>(ExprWithTemporary); }
3338   const Expr *getTemporaryExpr() const { return cast<Expr>(ExprWithTemporary); }
3339 
3340   unsigned getManglingNumber() const { return ManglingNumber; }
3341 
3342   /// Get the storage for the constant value of a materialized temporary
3343   /// of static storage duration.
3344   APValue *getOrCreateValue(bool MayCreate) const;
3345 
3346   APValue *getValue() const { return Value; }
3347 
3348   // Iterators
3349   Stmt::child_range childrenExpr() {
3350     return Stmt::child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3351   }
3352 
3353   Stmt::const_child_range childrenExpr() const {
3354     return Stmt::const_child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3355   }
3356 
3357   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3358   static bool classofKind(Kind K) {
3359     return K == Decl::LifetimeExtendedTemporary;
3360   }
3361 };
3362 
3363 /// Represents a shadow declaration implicitly introduced into a scope by a
3364 /// (resolved) using-declaration or using-enum-declaration to achieve
3365 /// the desired lookup semantics.
3366 ///
3367 /// For example:
3368 /// \code
3369 /// namespace A {
3370 ///   void foo();
3371 ///   void foo(int);
3372 ///   struct foo {};
3373 ///   enum bar { bar1, bar2 };
3374 /// }
3375 /// namespace B {
3376 ///   // add a UsingDecl and three UsingShadowDecls (named foo) to B.
3377 ///   using A::foo;
3378 ///   // adds UsingEnumDecl and two UsingShadowDecls (named bar1 and bar2) to B.
3379 ///   using enum A::bar;
3380 /// }
3381 /// \endcode
3382 class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3383   friend class BaseUsingDecl;
3384 
3385   /// The referenced declaration.
3386   NamedDecl *Underlying = nullptr;
3387 
3388   /// The using declaration which introduced this decl or the next using
3389   /// shadow declaration contained in the aforementioned using declaration.
3390   NamedDecl *UsingOrNextShadow = nullptr;
3391 
3392   void anchor() override;
3393 
3394   using redeclarable_base = Redeclarable<UsingShadowDecl>;
3395 
3396   UsingShadowDecl *getNextRedeclarationImpl() override {
3397     return getNextRedeclaration();
3398   }
3399 
3400   UsingShadowDecl *getPreviousDeclImpl() override {
3401     return getPreviousDecl();
3402   }
3403 
3404   UsingShadowDecl *getMostRecentDeclImpl() override {
3405     return getMostRecentDecl();
3406   }
3407 
3408 protected:
3409   UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3410                   DeclarationName Name, BaseUsingDecl *Introducer,
3411                   NamedDecl *Target);
3412   UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3413 
3414 public:
3415   friend class ASTDeclReader;
3416   friend class ASTDeclWriter;
3417 
3418   static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3419                                  SourceLocation Loc, DeclarationName Name,
3420                                  BaseUsingDecl *Introducer, NamedDecl *Target) {
3421     return new (C, DC)
3422         UsingShadowDecl(UsingShadow, C, DC, Loc, Name, Introducer, Target);
3423   }
3424 
3425   static UsingShadowDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3426 
3427   using redecl_range = redeclarable_base::redecl_range;
3428   using redecl_iterator = redeclarable_base::redecl_iterator;
3429 
3430   using redeclarable_base::redecls_begin;
3431   using redeclarable_base::redecls_end;
3432   using redeclarable_base::redecls;
3433   using redeclarable_base::getPreviousDecl;
3434   using redeclarable_base::getMostRecentDecl;
3435   using redeclarable_base::isFirstDecl;
3436 
3437   UsingShadowDecl *getCanonicalDecl() override {
3438     return getFirstDecl();
3439   }
3440   const UsingShadowDecl *getCanonicalDecl() const {
3441     return getFirstDecl();
3442   }
3443 
3444   /// Gets the underlying declaration which has been brought into the
3445   /// local scope.
3446   NamedDecl *getTargetDecl() const { return Underlying; }
3447 
3448   /// Sets the underlying declaration which has been brought into the
3449   /// local scope.
3450   void setTargetDecl(NamedDecl *ND) {
3451     assert(ND && "Target decl is null!");
3452     Underlying = ND;
3453     // A UsingShadowDecl is never a friend or local extern declaration, even
3454     // if it is a shadow declaration for one.
3455     IdentifierNamespace =
3456         ND->getIdentifierNamespace() &
3457         ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3458   }
3459 
3460   /// Gets the (written or instantiated) using declaration that introduced this
3461   /// declaration.
3462   BaseUsingDecl *getIntroducer() const;
3463 
3464   /// The next using shadow declaration contained in the shadow decl
3465   /// chain of the using declaration which introduced this decl.
3466   UsingShadowDecl *getNextUsingShadowDecl() const {
3467     return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3468   }
3469 
3470   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3471   static bool classofKind(Kind K) {
3472     return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3473   }
3474 };
3475 
3476 /// Represents a C++ declaration that introduces decls from somewhere else. It
3477 /// provides a set of the shadow decls so introduced.
3478 
3479 class BaseUsingDecl : public NamedDecl {
3480   /// The first shadow declaration of the shadow decl chain associated
3481   /// with this using declaration.
3482   ///
3483   /// The bool member of the pair is a bool flag a derived type may use
3484   /// (UsingDecl makes use of it).
3485   llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3486 
3487 protected:
3488   BaseUsingDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
3489       : NamedDecl(DK, DC, L, N), FirstUsingShadow(nullptr, false) {}
3490 
3491 private:
3492   void anchor() override;
3493 
3494 protected:
3495   /// A bool flag for use by a derived type
3496   bool getShadowFlag() const { return FirstUsingShadow.getInt(); }
3497 
3498   /// A bool flag a derived type may set
3499   void setShadowFlag(bool V) { FirstUsingShadow.setInt(V); }
3500 
3501 public:
3502   friend class ASTDeclReader;
3503   friend class ASTDeclWriter;
3504 
3505   /// Iterates through the using shadow declarations associated with
3506   /// this using declaration.
3507   class shadow_iterator {
3508     /// The current using shadow declaration.
3509     UsingShadowDecl *Current = nullptr;
3510 
3511   public:
3512     using value_type = UsingShadowDecl *;
3513     using reference = UsingShadowDecl *;
3514     using pointer = UsingShadowDecl *;
3515     using iterator_category = std::forward_iterator_tag;
3516     using difference_type = std::ptrdiff_t;
3517 
3518     shadow_iterator() = default;
3519     explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3520 
3521     reference operator*() const { return Current; }
3522     pointer operator->() const { return Current; }
3523 
3524     shadow_iterator &operator++() {
3525       Current = Current->getNextUsingShadowDecl();
3526       return *this;
3527     }
3528 
3529     shadow_iterator operator++(int) {
3530       shadow_iterator tmp(*this);
3531       ++(*this);
3532       return tmp;
3533     }
3534 
3535     friend bool operator==(shadow_iterator x, shadow_iterator y) {
3536       return x.Current == y.Current;
3537     }
3538     friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3539       return x.Current != y.Current;
3540     }
3541   };
3542 
3543   using shadow_range = llvm::iterator_range<shadow_iterator>;
3544 
3545   shadow_range shadows() const {
3546     return shadow_range(shadow_begin(), shadow_end());
3547   }
3548 
3549   shadow_iterator shadow_begin() const {
3550     return shadow_iterator(FirstUsingShadow.getPointer());
3551   }
3552 
3553   shadow_iterator shadow_end() const { return shadow_iterator(); }
3554 
3555   /// Return the number of shadowed declarations associated with this
3556   /// using declaration.
3557   unsigned shadow_size() const {
3558     return std::distance(shadow_begin(), shadow_end());
3559   }
3560 
3561   void addShadowDecl(UsingShadowDecl *S);
3562   void removeShadowDecl(UsingShadowDecl *S);
3563 
3564   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3565   static bool classofKind(Kind K) { return K == Using || K == UsingEnum; }
3566 };
3567 
3568 /// Represents a C++ using-declaration.
3569 ///
3570 /// For example:
3571 /// \code
3572 ///    using someNameSpace::someIdentifier;
3573 /// \endcode
3574 class UsingDecl : public BaseUsingDecl, public Mergeable<UsingDecl> {
3575   /// The source location of the 'using' keyword itself.
3576   SourceLocation UsingLocation;
3577 
3578   /// The nested-name-specifier that precedes the name.
3579   NestedNameSpecifierLoc QualifierLoc;
3580 
3581   /// Provides source/type location info for the declaration name
3582   /// embedded in the ValueDecl base class.
3583   DeclarationNameLoc DNLoc;
3584 
3585   UsingDecl(DeclContext *DC, SourceLocation UL,
3586             NestedNameSpecifierLoc QualifierLoc,
3587             const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3588       : BaseUsingDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3589         UsingLocation(UL), QualifierLoc(QualifierLoc),
3590         DNLoc(NameInfo.getInfo()) {
3591     setShadowFlag(HasTypenameKeyword);
3592   }
3593 
3594   void anchor() override;
3595 
3596 public:
3597   friend class ASTDeclReader;
3598   friend class ASTDeclWriter;
3599 
3600   /// Return the source location of the 'using' keyword.
3601   SourceLocation getUsingLoc() const { return UsingLocation; }
3602 
3603   /// Set the source location of the 'using' keyword.
3604   void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3605 
3606   /// Retrieve the nested-name-specifier that qualifies the name,
3607   /// with source-location information.
3608   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3609 
3610   /// Retrieve the nested-name-specifier that qualifies the name.
3611   NestedNameSpecifier *getQualifier() const {
3612     return QualifierLoc.getNestedNameSpecifier();
3613   }
3614 
3615   DeclarationNameInfo getNameInfo() const {
3616     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3617   }
3618 
3619   /// Return true if it is a C++03 access declaration (no 'using').
3620   bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3621 
3622   /// Return true if the using declaration has 'typename'.
3623   bool hasTypename() const { return getShadowFlag(); }
3624 
3625   /// Sets whether the using declaration has 'typename'.
3626   void setTypename(bool TN) { setShadowFlag(TN); }
3627 
3628   static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3629                            SourceLocation UsingL,
3630                            NestedNameSpecifierLoc QualifierLoc,
3631                            const DeclarationNameInfo &NameInfo,
3632                            bool HasTypenameKeyword);
3633 
3634   static UsingDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3635 
3636   SourceRange getSourceRange() const override LLVM_READONLY;
3637 
3638   /// Retrieves the canonical declaration of this declaration.
3639   UsingDecl *getCanonicalDecl() override {
3640     return cast<UsingDecl>(getFirstDecl());
3641   }
3642   const UsingDecl *getCanonicalDecl() const {
3643     return cast<UsingDecl>(getFirstDecl());
3644   }
3645 
3646   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3647   static bool classofKind(Kind K) { return K == Using; }
3648 };
3649 
3650 /// Represents a shadow constructor declaration introduced into a
3651 /// class by a C++11 using-declaration that names a constructor.
3652 ///
3653 /// For example:
3654 /// \code
3655 /// struct Base { Base(int); };
3656 /// struct Derived {
3657 ///    using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3658 /// };
3659 /// \endcode
3660 class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3661   /// If this constructor using declaration inherted the constructor
3662   /// from an indirect base class, this is the ConstructorUsingShadowDecl
3663   /// in the named direct base class from which the declaration was inherited.
3664   ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3665 
3666   /// If this constructor using declaration inherted the constructor
3667   /// from an indirect base class, this is the ConstructorUsingShadowDecl
3668   /// that will be used to construct the unique direct or virtual base class
3669   /// that receives the constructor arguments.
3670   ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3671 
3672   /// \c true if the constructor ultimately named by this using shadow
3673   /// declaration is within a virtual base class subobject of the class that
3674   /// contains this declaration.
3675   LLVM_PREFERRED_TYPE(bool)
3676   unsigned IsVirtual : 1;
3677 
3678   ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3679                              UsingDecl *Using, NamedDecl *Target,
3680                              bool TargetInVirtualBase)
3681       : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc,
3682                         Using->getDeclName(), Using,
3683                         Target->getUnderlyingDecl()),
3684         NominatedBaseClassShadowDecl(
3685             dyn_cast<ConstructorUsingShadowDecl>(Target)),
3686         ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3687         IsVirtual(TargetInVirtualBase) {
3688     // If we found a constructor that chains to a constructor for a virtual
3689     // base, we should directly call that virtual base constructor instead.
3690     // FIXME: This logic belongs in Sema.
3691     if (NominatedBaseClassShadowDecl &&
3692         NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3693       ConstructedBaseClassShadowDecl =
3694           NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3695       IsVirtual = true;
3696     }
3697   }
3698 
3699   ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3700       : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3701 
3702   void anchor() override;
3703 
3704 public:
3705   friend class ASTDeclReader;
3706   friend class ASTDeclWriter;
3707 
3708   static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3709                                             SourceLocation Loc,
3710                                             UsingDecl *Using, NamedDecl *Target,
3711                                             bool IsVirtual);
3712   static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3713                                                         GlobalDeclID ID);
3714 
3715   /// Override the UsingShadowDecl's getIntroducer, returning the UsingDecl that
3716   /// introduced this.
3717   UsingDecl *getIntroducer() const {
3718     return cast<UsingDecl>(UsingShadowDecl::getIntroducer());
3719   }
3720 
3721   /// Returns the parent of this using shadow declaration, which
3722   /// is the class in which this is declared.
3723   //@{
3724   const CXXRecordDecl *getParent() const {
3725     return cast<CXXRecordDecl>(getDeclContext());
3726   }
3727   CXXRecordDecl *getParent() {
3728     return cast<CXXRecordDecl>(getDeclContext());
3729   }
3730   //@}
3731 
3732   /// Get the inheriting constructor declaration for the direct base
3733   /// class from which this using shadow declaration was inherited, if there is
3734   /// one. This can be different for each redeclaration of the same shadow decl.
3735   ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3736     return NominatedBaseClassShadowDecl;
3737   }
3738 
3739   /// Get the inheriting constructor declaration for the base class
3740   /// for which we don't have an explicit initializer, if there is one.
3741   ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3742     return ConstructedBaseClassShadowDecl;
3743   }
3744 
3745   /// Get the base class that was named in the using declaration. This
3746   /// can be different for each redeclaration of this same shadow decl.
3747   CXXRecordDecl *getNominatedBaseClass() const;
3748 
3749   /// Get the base class whose constructor or constructor shadow
3750   /// declaration is passed the constructor arguments.
3751   CXXRecordDecl *getConstructedBaseClass() const {
3752     return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3753                                     ? ConstructedBaseClassShadowDecl
3754                                     : getTargetDecl())
3755                                    ->getDeclContext());
3756   }
3757 
3758   /// Returns \c true if the constructed base class is a virtual base
3759   /// class subobject of this declaration's class.
3760   bool constructsVirtualBase() const {
3761     return IsVirtual;
3762   }
3763 
3764   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3765   static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3766 };
3767 
3768 /// Represents a C++ using-enum-declaration.
3769 ///
3770 /// For example:
3771 /// \code
3772 ///    using enum SomeEnumTag ;
3773 /// \endcode
3774 
3775 class UsingEnumDecl : public BaseUsingDecl, public Mergeable<UsingEnumDecl> {
3776   /// The source location of the 'using' keyword itself.
3777   SourceLocation UsingLocation;
3778   /// The source location of the 'enum' keyword.
3779   SourceLocation EnumLocation;
3780   /// 'qual::SomeEnum' as an EnumType, possibly with Elaborated/Typedef sugar.
3781   TypeSourceInfo *EnumType;
3782 
3783   UsingEnumDecl(DeclContext *DC, DeclarationName DN, SourceLocation UL,
3784                 SourceLocation EL, SourceLocation NL, TypeSourceInfo *EnumType)
3785       : BaseUsingDecl(UsingEnum, DC, NL, DN), UsingLocation(UL), EnumLocation(EL),
3786         EnumType(EnumType){}
3787 
3788   void anchor() override;
3789 
3790 public:
3791   friend class ASTDeclReader;
3792   friend class ASTDeclWriter;
3793 
3794   /// The source location of the 'using' keyword.
3795   SourceLocation getUsingLoc() const { return UsingLocation; }
3796   void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3797 
3798   /// The source location of the 'enum' keyword.
3799   SourceLocation getEnumLoc() const { return EnumLocation; }
3800   void setEnumLoc(SourceLocation L) { EnumLocation = L; }
3801   NestedNameSpecifier *getQualifier() const {
3802     return getQualifierLoc().getNestedNameSpecifier();
3803   }
3804   NestedNameSpecifierLoc getQualifierLoc() const {
3805     if (auto ETL = EnumType->getTypeLoc().getAs<ElaboratedTypeLoc>())
3806       return ETL.getQualifierLoc();
3807     return NestedNameSpecifierLoc();
3808   }
3809   // Returns the "qualifier::Name" part as a TypeLoc.
3810   TypeLoc getEnumTypeLoc() const {
3811     return EnumType->getTypeLoc();
3812   }
3813   TypeSourceInfo *getEnumType() const {
3814     return EnumType;
3815   }
3816   void setEnumType(TypeSourceInfo *TSI) { EnumType = TSI; }
3817 
3818 public:
3819   EnumDecl *getEnumDecl() const { return cast<EnumDecl>(EnumType->getType()->getAsTagDecl()); }
3820 
3821   static UsingEnumDecl *Create(ASTContext &C, DeclContext *DC,
3822                                SourceLocation UsingL, SourceLocation EnumL,
3823                                SourceLocation NameL, TypeSourceInfo *EnumType);
3824 
3825   static UsingEnumDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
3826 
3827   SourceRange getSourceRange() const override LLVM_READONLY;
3828 
3829   /// Retrieves the canonical declaration of this declaration.
3830   UsingEnumDecl *getCanonicalDecl() override {
3831     return cast<UsingEnumDecl>(getFirstDecl());
3832   }
3833   const UsingEnumDecl *getCanonicalDecl() const {
3834     return cast<UsingEnumDecl>(getFirstDecl());
3835   }
3836 
3837   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3838   static bool classofKind(Kind K) { return K == UsingEnum; }
3839 };
3840 
3841 /// Represents a pack of using declarations that a single
3842 /// using-declarator pack-expanded into.
3843 ///
3844 /// \code
3845 /// template<typename ...T> struct X : T... {
3846 ///   using T::operator()...;
3847 ///   using T::operator T...;
3848 /// };
3849 /// \endcode
3850 ///
3851 /// In the second case above, the UsingPackDecl will have the name
3852 /// 'operator T' (which contains an unexpanded pack), but the individual
3853 /// UsingDecls and UsingShadowDecls will have more reasonable names.
3854 class UsingPackDecl final
3855     : public NamedDecl, public Mergeable<UsingPackDecl>,
3856       private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3857   /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3858   /// which this waas instantiated.
3859   NamedDecl *InstantiatedFrom;
3860 
3861   /// The number of using-declarations created by this pack expansion.
3862   unsigned NumExpansions;
3863 
3864   UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3865                 ArrayRef<NamedDecl *> UsingDecls)
3866       : NamedDecl(UsingPack, DC,
3867                   InstantiatedFrom ? InstantiatedFrom->getLocation()
3868                                    : SourceLocation(),
3869                   InstantiatedFrom ? InstantiatedFrom->getDeclName()
3870                                    : DeclarationName()),
3871         InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3872     std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3873                             getTrailingObjects<NamedDecl *>());
3874   }
3875 
3876   void anchor() override;
3877 
3878 public:
3879   friend class ASTDeclReader;
3880   friend class ASTDeclWriter;
3881   friend TrailingObjects;
3882 
3883   /// Get the using declaration from which this was instantiated. This will
3884   /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3885   /// that is a pack expansion.
3886   NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3887 
3888   /// Get the set of using declarations that this pack expanded into. Note that
3889   /// some of these may still be unresolved.
3890   ArrayRef<NamedDecl *> expansions() const {
3891     return llvm::ArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3892   }
3893 
3894   static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3895                                NamedDecl *InstantiatedFrom,
3896                                ArrayRef<NamedDecl *> UsingDecls);
3897 
3898   static UsingPackDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID,
3899                                            unsigned NumExpansions);
3900 
3901   SourceRange getSourceRange() const override LLVM_READONLY {
3902     return InstantiatedFrom->getSourceRange();
3903   }
3904 
3905   UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3906   const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3907 
3908   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3909   static bool classofKind(Kind K) { return K == UsingPack; }
3910 };
3911 
3912 /// Represents a dependent using declaration which was not marked with
3913 /// \c typename.
3914 ///
3915 /// Unlike non-dependent using declarations, these *only* bring through
3916 /// non-types; otherwise they would break two-phase lookup.
3917 ///
3918 /// \code
3919 /// template \<class T> class A : public Base<T> {
3920 ///   using Base<T>::foo;
3921 /// };
3922 /// \endcode
3923 class UnresolvedUsingValueDecl : public ValueDecl,
3924                                  public Mergeable<UnresolvedUsingValueDecl> {
3925   /// The source location of the 'using' keyword
3926   SourceLocation UsingLocation;
3927 
3928   /// If this is a pack expansion, the location of the '...'.
3929   SourceLocation EllipsisLoc;
3930 
3931   /// The nested-name-specifier that precedes the name.
3932   NestedNameSpecifierLoc QualifierLoc;
3933 
3934   /// Provides source/type location info for the declaration name
3935   /// embedded in the ValueDecl base class.
3936   DeclarationNameLoc DNLoc;
3937 
3938   UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3939                            SourceLocation UsingLoc,
3940                            NestedNameSpecifierLoc QualifierLoc,
3941                            const DeclarationNameInfo &NameInfo,
3942                            SourceLocation EllipsisLoc)
3943       : ValueDecl(UnresolvedUsingValue, DC,
3944                   NameInfo.getLoc(), NameInfo.getName(), Ty),
3945         UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3946         QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3947 
3948   void anchor() override;
3949 
3950 public:
3951   friend class ASTDeclReader;
3952   friend class ASTDeclWriter;
3953 
3954   /// Returns the source location of the 'using' keyword.
3955   SourceLocation getUsingLoc() const { return UsingLocation; }
3956 
3957   /// Set the source location of the 'using' keyword.
3958   void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3959 
3960   /// Return true if it is a C++03 access declaration (no 'using').
3961   bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3962 
3963   /// Retrieve the nested-name-specifier that qualifies the name,
3964   /// with source-location information.
3965   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3966 
3967   /// Retrieve the nested-name-specifier that qualifies the name.
3968   NestedNameSpecifier *getQualifier() const {
3969     return QualifierLoc.getNestedNameSpecifier();
3970   }
3971 
3972   DeclarationNameInfo getNameInfo() const {
3973     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3974   }
3975 
3976   /// Determine whether this is a pack expansion.
3977   bool isPackExpansion() const {
3978     return EllipsisLoc.isValid();
3979   }
3980 
3981   /// Get the location of the ellipsis if this is a pack expansion.
3982   SourceLocation getEllipsisLoc() const {
3983     return EllipsisLoc;
3984   }
3985 
3986   static UnresolvedUsingValueDecl *
3987     Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3988            NestedNameSpecifierLoc QualifierLoc,
3989            const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3990 
3991   static UnresolvedUsingValueDecl *CreateDeserialized(ASTContext &C,
3992                                                       GlobalDeclID ID);
3993 
3994   SourceRange getSourceRange() const override LLVM_READONLY;
3995 
3996   /// Retrieves the canonical declaration of this declaration.
3997   UnresolvedUsingValueDecl *getCanonicalDecl() override {
3998     return getFirstDecl();
3999   }
4000   const UnresolvedUsingValueDecl *getCanonicalDecl() const {
4001     return getFirstDecl();
4002   }
4003 
4004   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4005   static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
4006 };
4007 
4008 /// Represents a dependent using declaration which was marked with
4009 /// \c typename.
4010 ///
4011 /// \code
4012 /// template \<class T> class A : public Base<T> {
4013 ///   using typename Base<T>::foo;
4014 /// };
4015 /// \endcode
4016 ///
4017 /// The type associated with an unresolved using typename decl is
4018 /// currently always a typename type.
4019 class UnresolvedUsingTypenameDecl
4020     : public TypeDecl,
4021       public Mergeable<UnresolvedUsingTypenameDecl> {
4022   friend class ASTDeclReader;
4023 
4024   /// The source location of the 'typename' keyword
4025   SourceLocation TypenameLocation;
4026 
4027   /// If this is a pack expansion, the location of the '...'.
4028   SourceLocation EllipsisLoc;
4029 
4030   /// The nested-name-specifier that precedes the name.
4031   NestedNameSpecifierLoc QualifierLoc;
4032 
4033   UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
4034                               SourceLocation TypenameLoc,
4035                               NestedNameSpecifierLoc QualifierLoc,
4036                               SourceLocation TargetNameLoc,
4037                               IdentifierInfo *TargetName,
4038                               SourceLocation EllipsisLoc)
4039     : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
4040                UsingLoc),
4041       TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
4042       QualifierLoc(QualifierLoc) {}
4043 
4044   void anchor() override;
4045 
4046 public:
4047   /// Returns the source location of the 'using' keyword.
4048   SourceLocation getUsingLoc() const { return getBeginLoc(); }
4049 
4050   /// Returns the source location of the 'typename' keyword.
4051   SourceLocation getTypenameLoc() const { return TypenameLocation; }
4052 
4053   /// Retrieve the nested-name-specifier that qualifies the name,
4054   /// with source-location information.
4055   NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
4056 
4057   /// Retrieve the nested-name-specifier that qualifies the name.
4058   NestedNameSpecifier *getQualifier() const {
4059     return QualifierLoc.getNestedNameSpecifier();
4060   }
4061 
4062   DeclarationNameInfo getNameInfo() const {
4063     return DeclarationNameInfo(getDeclName(), getLocation());
4064   }
4065 
4066   /// Determine whether this is a pack expansion.
4067   bool isPackExpansion() const {
4068     return EllipsisLoc.isValid();
4069   }
4070 
4071   /// Get the location of the ellipsis if this is a pack expansion.
4072   SourceLocation getEllipsisLoc() const {
4073     return EllipsisLoc;
4074   }
4075 
4076   static UnresolvedUsingTypenameDecl *
4077     Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
4078            SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
4079            SourceLocation TargetNameLoc, DeclarationName TargetName,
4080            SourceLocation EllipsisLoc);
4081 
4082   static UnresolvedUsingTypenameDecl *CreateDeserialized(ASTContext &C,
4083                                                          GlobalDeclID ID);
4084 
4085   /// Retrieves the canonical declaration of this declaration.
4086   UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
4087     return getFirstDecl();
4088   }
4089   const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
4090     return getFirstDecl();
4091   }
4092 
4093   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4094   static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
4095 };
4096 
4097 /// This node is generated when a using-declaration that was annotated with
4098 /// __attribute__((using_if_exists)) failed to resolve to a known declaration.
4099 /// In that case, Sema builds a UsingShadowDecl whose target is an instance of
4100 /// this declaration, adding it to the current scope. Referring to this
4101 /// declaration in any way is an error.
4102 class UnresolvedUsingIfExistsDecl final : public NamedDecl {
4103   UnresolvedUsingIfExistsDecl(DeclContext *DC, SourceLocation Loc,
4104                               DeclarationName Name);
4105 
4106   void anchor() override;
4107 
4108 public:
4109   static UnresolvedUsingIfExistsDecl *Create(ASTContext &Ctx, DeclContext *DC,
4110                                              SourceLocation Loc,
4111                                              DeclarationName Name);
4112   static UnresolvedUsingIfExistsDecl *CreateDeserialized(ASTContext &Ctx,
4113                                                          GlobalDeclID ID);
4114 
4115   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4116   static bool classofKind(Kind K) { return K == Decl::UnresolvedUsingIfExists; }
4117 };
4118 
4119 /// Represents a C++11 static_assert declaration.
4120 class StaticAssertDecl : public Decl {
4121   llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
4122   Expr *Message;
4123   SourceLocation RParenLoc;
4124 
4125   StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
4126                    Expr *AssertExpr, Expr *Message, SourceLocation RParenLoc,
4127                    bool Failed)
4128       : Decl(StaticAssert, DC, StaticAssertLoc),
4129         AssertExprAndFailed(AssertExpr, Failed), Message(Message),
4130         RParenLoc(RParenLoc) {}
4131 
4132   virtual void anchor();
4133 
4134 public:
4135   friend class ASTDeclReader;
4136 
4137   static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
4138                                   SourceLocation StaticAssertLoc,
4139                                   Expr *AssertExpr, Expr *Message,
4140                                   SourceLocation RParenLoc, bool Failed);
4141   static StaticAssertDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
4142 
4143   Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
4144   const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
4145 
4146   Expr *getMessage() { return Message; }
4147   const Expr *getMessage() const { return Message; }
4148 
4149   bool isFailed() const { return AssertExprAndFailed.getInt(); }
4150 
4151   SourceLocation getRParenLoc() const { return RParenLoc; }
4152 
4153   SourceRange getSourceRange() const override LLVM_READONLY {
4154     return SourceRange(getLocation(), getRParenLoc());
4155   }
4156 
4157   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4158   static bool classofKind(Kind K) { return K == StaticAssert; }
4159 };
4160 
4161 /// A binding in a decomposition declaration. For instance, given:
4162 ///
4163 ///   int n[3];
4164 ///   auto &[a, b, c] = n;
4165 ///
4166 /// a, b, and c are BindingDecls, whose bindings are the expressions
4167 /// x[0], x[1], and x[2] respectively, where x is the implicit
4168 /// DecompositionDecl of type 'int (&)[3]'.
4169 class BindingDecl : public ValueDecl {
4170   /// The declaration that this binding binds to part of.
4171   ValueDecl *Decomp;
4172   /// The binding represented by this declaration. References to this
4173   /// declaration are effectively equivalent to this expression (except
4174   /// that it is only evaluated once at the point of declaration of the
4175   /// binding).
4176   Expr *Binding = nullptr;
4177 
4178   BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id,
4179               QualType T)
4180       : ValueDecl(Decl::Binding, DC, IdLoc, Id, T) {}
4181 
4182   void anchor() override;
4183 
4184 public:
4185   friend class ASTDeclReader;
4186 
4187   static BindingDecl *Create(ASTContext &C, DeclContext *DC,
4188                              SourceLocation IdLoc, IdentifierInfo *Id,
4189                              QualType T);
4190   static BindingDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
4191 
4192   /// Get the expression to which this declaration is bound. This may be null
4193   /// in two different cases: while parsing the initializer for the
4194   /// decomposition declaration, and when the initializer is type-dependent.
4195   Expr *getBinding() const { return Binding; }
4196 
4197   // Get the array of Exprs when the binding represents a pack.
4198   llvm::ArrayRef<Expr *> getBindingPackExprs() const;
4199 
4200   /// Get the decomposition declaration that this binding represents a
4201   /// decomposition of.
4202   ValueDecl *getDecomposedDecl() const { return Decomp; }
4203 
4204   /// Set the binding for this BindingDecl, along with its declared type (which
4205   /// should be a possibly-cv-qualified form of the type of the binding, or a
4206   /// reference to such a type).
4207   void setBinding(QualType DeclaredType, Expr *Binding) {
4208     setType(DeclaredType);
4209     this->Binding = Binding;
4210   }
4211 
4212   /// Set the decomposed variable for this BindingDecl.
4213   void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
4214 
4215   /// Get the variable (if any) that holds the value of evaluating the binding.
4216   /// Only present for user-defined bindings for tuple-like types.
4217   VarDecl *getHoldingVar() const;
4218 
4219   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4220   static bool classofKind(Kind K) { return K == Decl::Binding; }
4221 };
4222 
4223 /// A decomposition declaration. For instance, given:
4224 ///
4225 ///   int n[3];
4226 ///   auto &[a, b, c] = n;
4227 ///
4228 /// the second line declares a DecompositionDecl of type 'int (&)[3]', and
4229 /// three BindingDecls (named a, b, and c). An instance of this class is always
4230 /// unnamed, but behaves in almost all other respects like a VarDecl.
4231 class DecompositionDecl final
4232     : public VarDecl,
4233       private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
4234   /// The number of BindingDecl*s following this object.
4235   unsigned NumBindings;
4236 
4237   DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4238                     SourceLocation LSquareLoc, QualType T,
4239                     TypeSourceInfo *TInfo, StorageClass SC,
4240                     ArrayRef<BindingDecl *> Bindings)
4241       : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
4242                 SC),
4243         NumBindings(Bindings.size()) {
4244     std::uninitialized_copy(Bindings.begin(), Bindings.end(),
4245                             getTrailingObjects<BindingDecl *>());
4246     for (auto *B : Bindings) {
4247       B->setDecomposedDecl(this);
4248       if (B->isParameterPack() && B->getBinding()) {
4249         for (Expr *E : B->getBindingPackExprs()) {
4250           auto *DRE = cast<DeclRefExpr>(E);
4251           auto *NestedB = cast<BindingDecl>(DRE->getDecl());
4252           NestedB->setDecomposedDecl(this);
4253         }
4254       }
4255     }
4256   }
4257 
4258   void anchor() override;
4259 
4260 public:
4261   friend class ASTDeclReader;
4262   friend TrailingObjects;
4263 
4264   static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
4265                                    SourceLocation StartLoc,
4266                                    SourceLocation LSquareLoc,
4267                                    QualType T, TypeSourceInfo *TInfo,
4268                                    StorageClass S,
4269                                    ArrayRef<BindingDecl *> Bindings);
4270   static DecompositionDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID,
4271                                                unsigned NumBindings);
4272 
4273   // Provide the range of bindings which may have a nested pack.
4274   llvm::ArrayRef<BindingDecl *> bindings() const {
4275     return {getTrailingObjects<BindingDecl *>(), NumBindings};
4276   }
4277 
4278   // Provide a flattened range to visit each binding.
4279   auto flat_bindings() const {
4280     llvm::ArrayRef<BindingDecl *> Bindings = bindings();
4281     llvm::ArrayRef<Expr *> PackExprs;
4282 
4283     // Split the bindings into subranges split by the pack.
4284     auto S1 = Bindings.take_until(
4285         [](BindingDecl *BD) { return BD->isParameterPack(); });
4286 
4287     Bindings = Bindings.drop_front(S1.size());
4288     if (!Bindings.empty()) {
4289       PackExprs = Bindings.front()->getBindingPackExprs();
4290       Bindings = Bindings.drop_front();
4291     }
4292 
4293     auto S2 = llvm::map_range(PackExprs, [](Expr *E) {
4294       auto *DRE = cast<DeclRefExpr>(E);
4295       return cast<BindingDecl>(DRE->getDecl());
4296     });
4297 
4298     return llvm::concat<BindingDecl *>(std::move(S1), std::move(S2),
4299                                        std::move(Bindings));
4300   }
4301 
4302   void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
4303 
4304   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4305   static bool classofKind(Kind K) { return K == Decomposition; }
4306 };
4307 
4308 /// An instance of this class represents the declaration of a property
4309 /// member.  This is a Microsoft extension to C++, first introduced in
4310 /// Visual Studio .NET 2003 as a parallel to similar features in C#
4311 /// and Managed C++.
4312 ///
4313 /// A property must always be a non-static class member.
4314 ///
4315 /// A property member superficially resembles a non-static data
4316 /// member, except preceded by a property attribute:
4317 ///   __declspec(property(get=GetX, put=PutX)) int x;
4318 /// Either (but not both) of the 'get' and 'put' names may be omitted.
4319 ///
4320 /// A reference to a property is always an lvalue.  If the lvalue
4321 /// undergoes lvalue-to-rvalue conversion, then a getter name is
4322 /// required, and that member is called with no arguments.
4323 /// If the lvalue is assigned into, then a setter name is required,
4324 /// and that member is called with one argument, the value assigned.
4325 /// Both operations are potentially overloaded.  Compound assignments
4326 /// are permitted, as are the increment and decrement operators.
4327 ///
4328 /// The getter and putter methods are permitted to be overloaded,
4329 /// although their return and parameter types are subject to certain
4330 /// restrictions according to the type of the property.
4331 ///
4332 /// A property declared using an incomplete array type may
4333 /// additionally be subscripted, adding extra parameters to the getter
4334 /// and putter methods.
4335 class MSPropertyDecl : public DeclaratorDecl {
4336   IdentifierInfo *GetterId, *SetterId;
4337 
4338   MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
4339                  QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
4340                  IdentifierInfo *Getter, IdentifierInfo *Setter)
4341       : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
4342         GetterId(Getter), SetterId(Setter) {}
4343 
4344   void anchor() override;
4345 public:
4346   friend class ASTDeclReader;
4347 
4348   static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
4349                                 SourceLocation L, DeclarationName N, QualType T,
4350                                 TypeSourceInfo *TInfo, SourceLocation StartL,
4351                                 IdentifierInfo *Getter, IdentifierInfo *Setter);
4352   static MSPropertyDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
4353 
4354   static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
4355 
4356   bool hasGetter() const { return GetterId != nullptr; }
4357   IdentifierInfo* getGetterId() const { return GetterId; }
4358   bool hasSetter() const { return SetterId != nullptr; }
4359   IdentifierInfo* getSetterId() const { return SetterId; }
4360 };
4361 
4362 /// Parts of a decomposed MSGuidDecl. Factored out to avoid unnecessary
4363 /// dependencies on DeclCXX.h.
4364 struct MSGuidDeclParts {
4365   /// {01234567-...
4366   uint32_t Part1;
4367   /// ...-89ab-...
4368   uint16_t Part2;
4369   /// ...-cdef-...
4370   uint16_t Part3;
4371   /// ...-0123-456789abcdef}
4372   uint8_t Part4And5[8];
4373 
4374   uint64_t getPart4And5AsUint64() const {
4375     uint64_t Val;
4376     memcpy(&Val, &Part4And5, sizeof(Part4And5));
4377     return Val;
4378   }
4379 };
4380 
4381 /// A global _GUID constant. These are implicitly created by UuidAttrs.
4382 ///
4383 ///   struct _declspec(uuid("01234567-89ab-cdef-0123-456789abcdef")) X{};
4384 ///
4385 /// X is a CXXRecordDecl that contains a UuidAttr that references the (unique)
4386 /// MSGuidDecl for the specified UUID.
4387 class MSGuidDecl : public ValueDecl,
4388                    public Mergeable<MSGuidDecl>,
4389                    public llvm::FoldingSetNode {
4390 public:
4391   using Parts = MSGuidDeclParts;
4392 
4393 private:
4394   /// The decomposed form of the UUID.
4395   Parts PartVal;
4396 
4397   /// The resolved value of the UUID as an APValue. Computed on demand and
4398   /// cached.
4399   mutable APValue APVal;
4400 
4401   void anchor() override;
4402 
4403   MSGuidDecl(DeclContext *DC, QualType T, Parts P);
4404 
4405   static MSGuidDecl *Create(const ASTContext &C, QualType T, Parts P);
4406   static MSGuidDecl *CreateDeserialized(ASTContext &C, GlobalDeclID ID);
4407 
4408   // Only ASTContext::getMSGuidDecl and deserialization create these.
4409   friend class ASTContext;
4410   friend class ASTReader;
4411   friend class ASTDeclReader;
4412 
4413 public:
4414   /// Print this UUID in a human-readable format.
4415   void printName(llvm::raw_ostream &OS,
4416                  const PrintingPolicy &Policy) const override;
4417 
4418   /// Get the decomposed parts of this declaration.
4419   Parts getParts() const { return PartVal; }
4420 
4421   /// Get the value of this MSGuidDecl as an APValue. This may fail and return
4422   /// an absent APValue if the type of the declaration is not of the expected
4423   /// shape.
4424   APValue &getAsAPValue() const;
4425 
4426   static void Profile(llvm::FoldingSetNodeID &ID, Parts P) {
4427     ID.AddInteger(P.Part1);
4428     ID.AddInteger(P.Part2);
4429     ID.AddInteger(P.Part3);
4430     ID.AddInteger(P.getPart4And5AsUint64());
4431   }
4432   void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, PartVal); }
4433 
4434   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4435   static bool classofKind(Kind K) { return K == Decl::MSGuid; }
4436 };
4437 
4438 /// An artificial decl, representing a global anonymous constant value which is
4439 /// uniquified by value within a translation unit.
4440 ///
4441 /// These is currently only used to back the LValue returned by
4442 /// __builtin_source_location, but could potentially be used for other similar
4443 /// situations in the future.
4444 class UnnamedGlobalConstantDecl : public ValueDecl,
4445                                   public Mergeable<UnnamedGlobalConstantDecl>,
4446                                   public llvm::FoldingSetNode {
4447 
4448   // The constant value of this global.
4449   APValue Value;
4450 
4451   void anchor() override;
4452 
4453   UnnamedGlobalConstantDecl(const ASTContext &C, DeclContext *DC, QualType T,
4454                             const APValue &Val);
4455 
4456   static UnnamedGlobalConstantDecl *Create(const ASTContext &C, QualType T,
4457                                            const APValue &APVal);
4458   static UnnamedGlobalConstantDecl *CreateDeserialized(ASTContext &C,
4459                                                        GlobalDeclID ID);
4460 
4461   // Only ASTContext::getUnnamedGlobalConstantDecl and deserialization create
4462   // these.
4463   friend class ASTContext;
4464   friend class ASTReader;
4465   friend class ASTDeclReader;
4466 
4467 public:
4468   /// Print this in a human-readable format.
4469   void printName(llvm::raw_ostream &OS,
4470                  const PrintingPolicy &Policy) const override;
4471 
4472   const APValue &getValue() const { return Value; }
4473 
4474   static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty,
4475                       const APValue &APVal) {
4476     Ty.Profile(ID);
4477     APVal.Profile(ID);
4478   }
4479   void Profile(llvm::FoldingSetNodeID &ID) {
4480     Profile(ID, getType(), getValue());
4481   }
4482 
4483   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4484   static bool classofKind(Kind K) { return K == Decl::UnnamedGlobalConstant; }
4485 };
4486 
4487 /// Insertion operator for diagnostics.  This allows sending an AccessSpecifier
4488 /// into a diagnostic with <<.
4489 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
4490                                       AccessSpecifier AS);
4491 
4492 } // namespace clang
4493 
4494 #endif // LLVM_CLANG_AST_DECLCXX_H
4495