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