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