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