1 //===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Defines the C++ Decl subclasses, other than those for templates
12 /// (found in DeclTemplate.h) and friends (in DeclFriend.h).
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_AST_DECLCXX_H
17 #define LLVM_CLANG_AST_DECLCXX_H
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/Attr.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/LambdaCapture.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/Redeclarable.h"
30 #include "clang/AST/Stmt.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/UnresolvedSet.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/Lambda.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/SourceLocation.h"
39 #include "clang/Basic/Specifiers.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/PointerIntPair.h"
43 #include "llvm/ADT/PointerUnion.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/iterator_range.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/PointerLikeTypeTraits.h"
49 #include "llvm/Support/TrailingObjects.h"
58 class ClassTemplateDecl;
59 class ConstructorUsingShadowDecl;
62 class CXXConstructorDecl;
63 class CXXDestructorDecl;
64 class CXXFinalOverriderMap;
65 class CXXIndirectPrimaryBaseSet;
67 class DiagnosticBuilder;
69 class FunctionTemplateDecl;
71 class MemberSpecializationInfo;
73 class TemplateParameterList;
76 /// Represents any kind of function declaration, whether it is a
77 /// concrete function or a function template.
78 class AnyFunctionDecl {
81 AnyFunctionDecl(NamedDecl *ND) : Function(ND) {}
84 AnyFunctionDecl(FunctionDecl *FD) : Function(FD) {}
85 AnyFunctionDecl(FunctionTemplateDecl *FTD);
87 /// Implicily converts any function or function template into a
88 /// named declaration.
89 operator NamedDecl *() const { return Function; }
91 /// Retrieve the underlying function or function template.
92 NamedDecl *get() const { return Function; }
94 static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) {
95 return AnyFunctionDecl(ND);
103 // Provide PointerLikeTypeTraits for non-cvr pointers.
105 struct PointerLikeTypeTraits< ::clang::AnyFunctionDecl> {
106 static void *getAsVoidPointer(::clang::AnyFunctionDecl F) {
110 static ::clang::AnyFunctionDecl getFromVoidPointer(void *P) {
111 return ::clang::AnyFunctionDecl::getFromNamedDecl(
112 static_cast< ::clang::NamedDecl*>(P));
115 enum { NumLowBitsAvailable = 2 };
122 /// Represents an access specifier followed by colon ':'.
124 /// An objects of this class represents sugar for the syntactic occurrence
125 /// of an access specifier followed by a colon in the list of member
126 /// specifiers of a C++ class definition.
128 /// Note that they do not represent other uses of access specifiers,
129 /// such as those occurring in a list of base specifiers.
130 /// Also note that this class has nothing to do with so-called
131 /// "access declarations" (C++98 11.3 [class.access.dcl]).
132 class AccessSpecDecl : public Decl {
133 /// The location of the ':'.
134 SourceLocation ColonLoc;
136 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
137 SourceLocation ASLoc, SourceLocation ColonLoc)
138 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
142 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
144 virtual void anchor();
147 /// The location of the access specifier.
148 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
150 /// Sets the location of the access specifier.
151 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
153 /// The location of the colon following the access specifier.
154 SourceLocation getColonLoc() const { return ColonLoc; }
156 /// Sets the location of the colon.
157 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
159 SourceRange getSourceRange() const override LLVM_READONLY {
160 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
163 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
164 DeclContext *DC, SourceLocation ASLoc,
165 SourceLocation ColonLoc) {
166 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
169 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
171 // Implement isa/cast/dyncast/etc.
172 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
173 static bool classofKind(Kind K) { return K == AccessSpec; }
176 /// Represents a base class of a C++ class.
178 /// Each CXXBaseSpecifier represents a single, direct base class (or
179 /// struct) of a C++ class (or struct). It specifies the type of that
180 /// base class, whether it is a virtual or non-virtual base, and what
181 /// level of access (public, protected, private) is used for the
182 /// derivation. For example:
187 /// class C : public virtual A, protected B { };
190 /// In this code, C will have two CXXBaseSpecifiers, one for "public
191 /// virtual A" and the other for "protected B".
192 class CXXBaseSpecifier {
193 /// The source code range that covers the full base
194 /// specifier, including the "virtual" (if present) and access
195 /// specifier (if present).
198 /// The source location of the ellipsis, if this is a pack
200 SourceLocation EllipsisLoc;
202 /// Whether this is a virtual base class or not.
203 unsigned Virtual : 1;
205 /// Whether this is the base of a class (true) or of a struct (false).
207 /// This determines the mapping from the access specifier as written in the
208 /// source code to the access specifier used for semantic analysis.
209 unsigned BaseOfClass : 1;
211 /// Access specifier as written in the source code (may be AS_none).
213 /// The actual type of data stored here is an AccessSpecifier, but we use
214 /// "unsigned" here to work around a VC++ bug.
217 /// Whether the class contains a using declaration
218 /// to inherit the named class's constructors.
219 unsigned InheritConstructors : 1;
221 /// The type of the base class.
223 /// This will be a class or struct (or a typedef of such). The source code
224 /// range does not include the \c virtual or the access specifier.
225 TypeSourceInfo *BaseTypeInfo;
228 CXXBaseSpecifier() = default;
229 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
230 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
231 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
232 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
234 /// Retrieves the source range that contains the entire base specifier.
235 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
236 SourceLocation getLocStart() const LLVM_READONLY { return getBeginLoc(); }
237 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
238 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
239 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
241 /// Get the location at which the base class type was written.
242 SourceLocation getBaseTypeLoc() const LLVM_READONLY {
243 return BaseTypeInfo->getTypeLoc().getLocStart();
246 /// Determines whether the base class is a virtual base class (or not).
247 bool isVirtual() const { return Virtual; }
249 /// Determine whether this base class is a base of a class declared
250 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
251 bool isBaseOfClass() const { return BaseOfClass; }
253 /// Determine whether this base specifier is a pack expansion.
254 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
256 /// Determine whether this base class's constructors get inherited.
257 bool getInheritConstructors() const { return InheritConstructors; }
259 /// Set that this base class's constructors should be inherited.
260 void setInheritConstructors(bool Inherit = true) {
261 InheritConstructors = Inherit;
264 /// For a pack expansion, determine the location of the ellipsis.
265 SourceLocation getEllipsisLoc() const {
269 /// Returns the access specifier for this base specifier.
271 /// This is the actual base specifier as used for semantic analysis, so
272 /// the result can never be AS_none. To retrieve the access specifier as
273 /// written in the source code, use getAccessSpecifierAsWritten().
274 AccessSpecifier getAccessSpecifier() const {
275 if ((AccessSpecifier)Access == AS_none)
276 return BaseOfClass? AS_private : AS_public;
278 return (AccessSpecifier)Access;
281 /// Retrieves the access specifier as written in the source code
282 /// (which may mean that no access specifier was explicitly written).
284 /// Use getAccessSpecifier() to retrieve the access specifier for use in
285 /// semantic analysis.
286 AccessSpecifier getAccessSpecifierAsWritten() const {
287 return (AccessSpecifier)Access;
290 /// Retrieves the type of the base class.
292 /// This type will always be an unqualified class type.
293 QualType getType() const {
294 return BaseTypeInfo->getType().getUnqualifiedType();
297 /// Retrieves the type and source location of the base class.
298 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
301 /// Represents a C++ struct/union/class.
302 class CXXRecordDecl : public RecordDecl {
303 friend class ASTDeclReader;
304 friend class ASTDeclWriter;
305 friend class ASTNodeImporter;
306 friend class ASTReader;
307 friend class ASTRecordWriter;
308 friend class ASTWriter;
309 friend class DeclContext;
310 friend class LambdaExpr;
312 friend void FunctionDecl::setPure(bool);
313 friend void TagDecl::startDefinition();
315 /// Values used in DefinitionData fields to represent special members.
316 enum SpecialMemberFlags {
317 SMF_DefaultConstructor = 0x1,
318 SMF_CopyConstructor = 0x2,
319 SMF_MoveConstructor = 0x4,
320 SMF_CopyAssignment = 0x8,
321 SMF_MoveAssignment = 0x10,
322 SMF_Destructor = 0x20,
326 struct DefinitionData {
327 /// True if this class has any user-declared constructors.
328 unsigned UserDeclaredConstructor : 1;
330 /// The user-declared special members which this class has.
331 unsigned UserDeclaredSpecialMembers : 6;
333 /// True when this class is an aggregate.
334 unsigned Aggregate : 1;
336 /// True when this class is a POD-type.
337 unsigned PlainOldData : 1;
339 /// true when this class is empty for traits purposes,
340 /// i.e. has no data members other than 0-width bit-fields, has no
341 /// virtual function/base, and doesn't inherit from a non-empty
342 /// class. Doesn't take union-ness into account.
345 /// True when this class is polymorphic, i.e., has at
346 /// least one virtual member or derives from a polymorphic class.
347 unsigned Polymorphic : 1;
349 /// True when this class is abstract, i.e., has at least
350 /// one pure virtual function, (that can come from a base class).
351 unsigned Abstract : 1;
353 /// True when this class is standard-layout, per the applicable
354 /// language rules (including DRs).
355 unsigned IsStandardLayout : 1;
357 /// True when this class was standard-layout under the C++11
360 /// C++11 [class]p7. A standard-layout class is a class that:
361 /// * has no non-static data members of type non-standard-layout class (or
362 /// array of such types) or reference,
363 /// * has no virtual functions (10.3) and no virtual base classes (10.1),
364 /// * has the same access control (Clause 11) for all non-static data
366 /// * has no non-standard-layout base classes,
367 /// * either has no non-static data members in the most derived class and at
368 /// most one base class with non-static data members, or has no base
369 /// classes with non-static data members, and
370 /// * has no base classes of the same type as the first non-static data
372 unsigned IsCXX11StandardLayout : 1;
374 /// True when any base class has any declared non-static data
375 /// members or bit-fields.
376 /// This is a helper bit of state used to implement IsStandardLayout more
378 unsigned HasBasesWithFields : 1;
380 /// True when any base class has any declared non-static data
382 /// This is a helper bit of state used to implement IsCXX11StandardLayout
383 /// more efficiently.
384 unsigned HasBasesWithNonStaticDataMembers : 1;
386 /// True when there are private non-static data members.
387 unsigned HasPrivateFields : 1;
389 /// True when there are protected non-static data members.
390 unsigned HasProtectedFields : 1;
392 /// True when there are private non-static data members.
393 unsigned HasPublicFields : 1;
395 /// True if this class (or any subobject) has mutable fields.
396 unsigned HasMutableFields : 1;
398 /// True if this class (or any nested anonymous struct or union)
399 /// has variant members.
400 unsigned HasVariantMembers : 1;
402 /// True if there no non-field members declared by the user.
403 unsigned HasOnlyCMembers : 1;
405 /// True if any field has an in-class initializer, including those
406 /// within anonymous unions or structs.
407 unsigned HasInClassInitializer : 1;
409 /// True if any field is of reference type, and does not have an
410 /// in-class initializer.
412 /// In this case, value-initialization of this class is illegal in C++98
413 /// even if the class has a trivial default constructor.
414 unsigned HasUninitializedReferenceMember : 1;
416 /// True if any non-mutable field whose type doesn't have a user-
417 /// provided default ctor also doesn't have an in-class initializer.
418 unsigned HasUninitializedFields : 1;
420 /// True if there are any member using-declarations that inherit
421 /// constructors from a base class.
422 unsigned HasInheritedConstructor : 1;
424 /// True if there are any member using-declarations named
426 unsigned HasInheritedAssignment : 1;
428 /// These flags are \c true if a defaulted corresponding special
429 /// member can't be fully analyzed without performing overload resolution.
431 unsigned NeedOverloadResolutionForCopyConstructor : 1;
432 unsigned NeedOverloadResolutionForMoveConstructor : 1;
433 unsigned NeedOverloadResolutionForMoveAssignment : 1;
434 unsigned NeedOverloadResolutionForDestructor : 1;
437 /// These flags are \c true if an implicit defaulted corresponding
438 /// special member would be defined as deleted.
440 unsigned DefaultedCopyConstructorIsDeleted : 1;
441 unsigned DefaultedMoveConstructorIsDeleted : 1;
442 unsigned DefaultedMoveAssignmentIsDeleted : 1;
443 unsigned DefaultedDestructorIsDeleted : 1;
446 /// The trivial special members which this class has, per
447 /// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25,
448 /// C++11 [class.dtor]p5, or would have if the member were not suppressed.
450 /// This excludes any user-declared but not user-provided special members
451 /// which have been declared but not yet defined.
452 unsigned HasTrivialSpecialMembers : 6;
454 /// These bits keep track of the triviality of special functions for the
455 /// purpose of calls. Only the bits corresponding to SMF_CopyConstructor,
456 /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
457 unsigned HasTrivialSpecialMembersForCall : 6;
459 /// The declared special members of this class which are known to be
462 /// This excludes any user-declared but not user-provided special members
463 /// which have been declared but not yet defined, and any implicit special
464 /// members which have not yet been declared.
465 unsigned DeclaredNonTrivialSpecialMembers : 6;
467 /// These bits keep track of the declared special members that are
468 /// non-trivial for the purpose of calls.
469 /// Only the bits corresponding to SMF_CopyConstructor,
470 /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
471 unsigned DeclaredNonTrivialSpecialMembersForCall : 6;
473 /// True when this class has a destructor with no semantic effect.
474 unsigned HasIrrelevantDestructor : 1;
476 /// True when this class has at least one user-declared constexpr
477 /// constructor which is neither the copy nor move constructor.
478 unsigned HasConstexprNonCopyMoveConstructor : 1;
480 /// True if this class has a (possibly implicit) defaulted default
482 unsigned HasDefaultedDefaultConstructor : 1;
484 /// True if a defaulted default constructor for this class would
486 unsigned DefaultedDefaultConstructorIsConstexpr : 1;
488 /// True if this class has a constexpr default constructor.
490 /// This is true for either a user-declared constexpr default constructor
491 /// or an implicitly declared constexpr default constructor.
492 unsigned HasConstexprDefaultConstructor : 1;
494 /// True when this class contains at least one non-static data
495 /// member or base class of non-literal or volatile type.
496 unsigned HasNonLiteralTypeFieldsOrBases : 1;
498 /// True when visible conversion functions are already computed
499 /// and are available.
500 unsigned ComputedVisibleConversions : 1;
502 /// Whether we have a C++11 user-provided default constructor (not
503 /// explicitly deleted or defaulted).
504 unsigned UserProvidedDefaultConstructor : 1;
506 /// The special members which have been declared for this class,
507 /// either by the user or implicitly.
508 unsigned DeclaredSpecialMembers : 6;
510 /// Whether an implicit copy constructor could have a const-qualified
511 /// parameter, for initializing virtual bases and for other subobjects.
512 unsigned ImplicitCopyConstructorCanHaveConstParamForVBase : 1;
513 unsigned ImplicitCopyConstructorCanHaveConstParamForNonVBase : 1;
515 /// Whether an implicit copy assignment operator would have a
516 /// const-qualified parameter.
517 unsigned ImplicitCopyAssignmentHasConstParam : 1;
519 /// Whether any declared copy constructor has a const-qualified
521 unsigned HasDeclaredCopyConstructorWithConstParam : 1;
523 /// Whether any declared copy assignment operator has either a
524 /// const-qualified reference parameter or a non-reference parameter.
525 unsigned HasDeclaredCopyAssignmentWithConstParam : 1;
527 /// Whether this class describes a C++ lambda.
528 unsigned IsLambda : 1;
530 /// Whether we are currently parsing base specifiers.
531 unsigned IsParsingBaseSpecifiers : 1;
533 unsigned HasODRHash : 1;
535 /// A hash of parts of the class to help in ODR checking.
536 unsigned ODRHash = 0;
538 /// The number of base class specifiers in Bases.
539 unsigned NumBases = 0;
541 /// The number of virtual base class specifiers in VBases.
542 unsigned NumVBases = 0;
544 /// Base classes of this class.
546 /// FIXME: This is wasted space for a union.
547 LazyCXXBaseSpecifiersPtr Bases;
549 /// direct and indirect virtual base classes of this class.
550 LazyCXXBaseSpecifiersPtr VBases;
552 /// The conversion functions of this C++ class (but not its
553 /// inherited conversion functions).
555 /// Each of the entries in this overload set is a CXXConversionDecl.
556 LazyASTUnresolvedSet Conversions;
558 /// The conversion functions of this C++ class and all those
559 /// inherited conversion functions that are visible in this class.
561 /// Each of the entries in this overload set is a CXXConversionDecl or a
562 /// FunctionTemplateDecl.
563 LazyASTUnresolvedSet VisibleConversions;
565 /// The declaration which defines this record.
566 CXXRecordDecl *Definition;
568 /// The first friend declaration in this class, or null if there
571 /// This is actually currently stored in reverse order.
572 LazyDeclPtr FirstFriend;
574 DefinitionData(CXXRecordDecl *D);
576 /// Retrieve the set of direct base classes.
577 CXXBaseSpecifier *getBases() const {
578 if (!Bases.isOffset())
579 return Bases.get(nullptr);
580 return getBasesSlowCase();
583 /// Retrieve the set of virtual base classes.
584 CXXBaseSpecifier *getVBases() const {
585 if (!VBases.isOffset())
586 return VBases.get(nullptr);
587 return getVBasesSlowCase();
590 ArrayRef<CXXBaseSpecifier> bases() const {
591 return llvm::makeArrayRef(getBases(), NumBases);
594 ArrayRef<CXXBaseSpecifier> vbases() const {
595 return llvm::makeArrayRef(getVBases(), NumVBases);
599 CXXBaseSpecifier *getBasesSlowCase() const;
600 CXXBaseSpecifier *getVBasesSlowCase() const;
603 struct DefinitionData *DefinitionData;
605 /// Describes a C++ closure type (generated by a lambda expression).
606 struct LambdaDefinitionData : public DefinitionData {
607 using Capture = LambdaCapture;
609 /// Whether this lambda is known to be dependent, even if its
610 /// context isn't dependent.
612 /// A lambda with a non-dependent context can be dependent if it occurs
613 /// within the default argument of a function template, because the
614 /// lambda will have been created with the enclosing context as its
615 /// declaration context, rather than function. This is an unfortunate
616 /// artifact of having to parse the default arguments before.
617 unsigned Dependent : 1;
619 /// Whether this lambda is a generic lambda.
620 unsigned IsGenericLambda : 1;
622 /// The Default Capture.
623 unsigned CaptureDefault : 2;
625 /// The number of captures in this lambda is limited 2^NumCaptures.
626 unsigned NumCaptures : 15;
628 /// The number of explicit captures in this lambda.
629 unsigned NumExplicitCaptures : 13;
631 /// The number used to indicate this lambda expression for name
632 /// mangling in the Itanium C++ ABI.
633 unsigned ManglingNumber = 0;
635 /// The declaration that provides context for this lambda, if the
636 /// actual DeclContext does not suffice. This is used for lambdas that
637 /// occur within default arguments of function parameters within the class
638 /// or within a data member initializer.
639 LazyDeclPtr ContextDecl;
641 /// The list of captures, both explicit and implicit, for this
643 Capture *Captures = nullptr;
645 /// The type of the call method.
646 TypeSourceInfo *MethodTyInfo;
648 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info,
649 bool Dependent, bool IsGeneric,
650 LambdaCaptureDefault CaptureDefault)
651 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
652 CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0),
656 // C++1z [expr.prim.lambda]p4:
657 // This class type is not an aggregate type.
659 PlainOldData = false;
663 struct DefinitionData *dataPtr() const {
664 // Complete the redecl chain (if necessary).
666 return DefinitionData;
669 struct DefinitionData &data() const {
670 auto *DD = dataPtr();
671 assert(DD && "queried property of class with no definition");
675 struct LambdaDefinitionData &getLambdaData() const {
676 // No update required: a merged definition cannot change any lambda
678 auto *DD = DefinitionData;
679 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
680 return static_cast<LambdaDefinitionData&>(*DD);
683 /// The template or declaration that this declaration
684 /// describes or was instantiated from, respectively.
686 /// For non-templates, this value will be null. For record
687 /// declarations that describe a class template, this will be a
688 /// pointer to a ClassTemplateDecl. For member
689 /// classes of class template specializations, this will be the
690 /// MemberSpecializationInfo referring to the member class that was
691 /// instantiated or specialized.
692 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
693 TemplateOrInstantiation;
695 /// Called from setBases and addedMember to notify the class that a
696 /// direct or virtual base class or a member of class type has been added.
697 void addedClassSubobject(CXXRecordDecl *Base);
699 /// Notify the class that member has been added.
701 /// This routine helps maintain information about the class based on which
702 /// members have been added. It will be invoked by DeclContext::addDecl()
703 /// whenever a member is added to this record.
704 void addedMember(Decl *D);
706 void markedVirtualFunctionPure();
708 /// Get the head of our list of friend declarations, possibly
709 /// deserializing the friends from an external AST source.
710 FriendDecl *getFirstFriend() const;
712 /// Determine whether this class has an empty base class subobject of type X
713 /// or of one of the types that might be at offset 0 within X (per the C++
714 /// "standard layout" rules).
715 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
716 const CXXRecordDecl *X);
719 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
720 SourceLocation StartLoc, SourceLocation IdLoc,
721 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
724 /// Iterator that traverses the base classes of a class.
725 using base_class_iterator = CXXBaseSpecifier *;
727 /// Iterator that traverses the base classes of a class.
728 using base_class_const_iterator = const CXXBaseSpecifier *;
730 CXXRecordDecl *getCanonicalDecl() override {
731 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
734 const CXXRecordDecl *getCanonicalDecl() const {
735 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
738 CXXRecordDecl *getPreviousDecl() {
739 return cast_or_null<CXXRecordDecl>(
740 static_cast<RecordDecl *>(this)->getPreviousDecl());
743 const CXXRecordDecl *getPreviousDecl() const {
744 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
747 CXXRecordDecl *getMostRecentDecl() {
748 return cast<CXXRecordDecl>(
749 static_cast<RecordDecl *>(this)->getMostRecentDecl());
752 const CXXRecordDecl *getMostRecentDecl() const {
753 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
756 CXXRecordDecl *getMostRecentNonInjectedDecl() {
757 CXXRecordDecl *Recent =
758 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
759 while (Recent->isInjectedClassName()) {
760 // FIXME: Does injected class name need to be in the redeclarations chain?
761 assert(Recent->getPreviousDecl());
762 Recent = Recent->getPreviousDecl();
767 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
768 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
771 CXXRecordDecl *getDefinition() const {
772 // We only need an update if we don't already know which
773 // declaration is the definition.
774 auto *DD = DefinitionData ? DefinitionData : dataPtr();
775 return DD ? DD->Definition : nullptr;
778 bool hasDefinition() const { return DefinitionData || dataPtr(); }
780 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
781 SourceLocation StartLoc, SourceLocation IdLoc,
783 CXXRecordDecl *PrevDecl = nullptr,
784 bool DelayTypeCreation = false);
785 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
786 TypeSourceInfo *Info, SourceLocation Loc,
787 bool DependentLambda, bool IsGeneric,
788 LambdaCaptureDefault CaptureDefault);
789 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
791 bool isDynamicClass() const {
792 return data().Polymorphic || data().NumVBases != 0;
795 /// @returns true if class is dynamic or might be dynamic because the
796 /// definition is incomplete of dependent.
797 bool mayBeDynamicClass() const {
798 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
801 /// @returns true if class is non dynamic or might be non dynamic because the
802 /// definition is incomplete of dependent.
803 bool mayBeNonDynamicClass() const {
804 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
807 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
809 bool isParsingBaseSpecifiers() const {
810 return data().IsParsingBaseSpecifiers;
813 unsigned getODRHash() const;
815 /// Sets the base classes of this struct or class.
816 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
818 /// Retrieves the number of base classes of this class.
819 unsigned getNumBases() const { return data().NumBases; }
821 using base_class_range = llvm::iterator_range<base_class_iterator>;
822 using base_class_const_range =
823 llvm::iterator_range<base_class_const_iterator>;
825 base_class_range bases() {
826 return base_class_range(bases_begin(), bases_end());
828 base_class_const_range bases() const {
829 return base_class_const_range(bases_begin(), bases_end());
832 base_class_iterator bases_begin() { return data().getBases(); }
833 base_class_const_iterator bases_begin() const { return data().getBases(); }
834 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
835 base_class_const_iterator bases_end() const {
836 return bases_begin() + data().NumBases;
839 /// Retrieves the number of virtual base classes of this class.
840 unsigned getNumVBases() const { return data().NumVBases; }
842 base_class_range vbases() {
843 return base_class_range(vbases_begin(), vbases_end());
845 base_class_const_range vbases() const {
846 return base_class_const_range(vbases_begin(), vbases_end());
849 base_class_iterator vbases_begin() { return data().getVBases(); }
850 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
851 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
852 base_class_const_iterator vbases_end() const {
853 return vbases_begin() + data().NumVBases;
856 /// Determine whether this class has any dependent base classes which
857 /// are not the current instantiation.
858 bool hasAnyDependentBases() const;
860 /// Iterator access to method members. The method iterator visits
861 /// all method members of the class, including non-instance methods,
862 /// special methods, etc.
863 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
865 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
867 method_range methods() const {
868 return method_range(method_begin(), method_end());
871 /// Method begin iterator. Iterates in the order the methods
873 method_iterator method_begin() const {
874 return method_iterator(decls_begin());
877 /// Method past-the-end iterator.
878 method_iterator method_end() const {
879 return method_iterator(decls_end());
882 /// Iterator access to constructor members.
883 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
885 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
887 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
889 ctor_iterator ctor_begin() const {
890 return ctor_iterator(decls_begin());
893 ctor_iterator ctor_end() const {
894 return ctor_iterator(decls_end());
897 /// An iterator over friend declarations. All of these are defined
899 class friend_iterator;
900 using friend_range = llvm::iterator_range<friend_iterator>;
902 friend_range friends() const;
903 friend_iterator friend_begin() const;
904 friend_iterator friend_end() const;
905 void pushFriendDecl(FriendDecl *FD);
907 /// Determines whether this record has any friends.
908 bool hasFriends() const {
909 return data().FirstFriend.isValid();
912 /// \c true if a defaulted copy constructor for this class would be
914 bool defaultedCopyConstructorIsDeleted() const {
915 assert((!needsOverloadResolutionForCopyConstructor() ||
916 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
917 "this property has not yet been computed by Sema");
918 return data().DefaultedCopyConstructorIsDeleted;
921 /// \c true if a defaulted move constructor for this class would be
923 bool defaultedMoveConstructorIsDeleted() const {
924 assert((!needsOverloadResolutionForMoveConstructor() ||
925 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
926 "this property has not yet been computed by Sema");
927 return data().DefaultedMoveConstructorIsDeleted;
930 /// \c true if a defaulted destructor for this class would be deleted.
931 bool defaultedDestructorIsDeleted() const {
932 assert((!needsOverloadResolutionForDestructor() ||
933 (data().DeclaredSpecialMembers & SMF_Destructor)) &&
934 "this property has not yet been computed by Sema");
935 return data().DefaultedDestructorIsDeleted;
938 /// \c true if we know for sure that this class has a single,
939 /// accessible, unambiguous copy constructor that is not deleted.
940 bool hasSimpleCopyConstructor() const {
941 return !hasUserDeclaredCopyConstructor() &&
942 !data().DefaultedCopyConstructorIsDeleted;
945 /// \c true if we know for sure that this class has a single,
946 /// accessible, unambiguous move constructor that is not deleted.
947 bool hasSimpleMoveConstructor() const {
948 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
949 !data().DefaultedMoveConstructorIsDeleted;
952 /// \c true if we know for sure that this class has a single,
953 /// accessible, unambiguous move assignment operator that is not deleted.
954 bool hasSimpleMoveAssignment() const {
955 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
956 !data().DefaultedMoveAssignmentIsDeleted;
959 /// \c true if we know for sure that this class has an accessible
960 /// destructor that is not deleted.
961 bool hasSimpleDestructor() const {
962 return !hasUserDeclaredDestructor() &&
963 !data().DefaultedDestructorIsDeleted;
966 /// Determine whether this class has any default constructors.
967 bool hasDefaultConstructor() const {
968 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
969 needsImplicitDefaultConstructor();
972 /// Determine if we need to declare a default constructor for
975 /// This value is used for lazy creation of default constructors.
976 bool needsImplicitDefaultConstructor() const {
977 return !data().UserDeclaredConstructor &&
978 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
979 // C++14 [expr.prim.lambda]p20:
980 // The closure type associated with a lambda-expression has no
981 // default constructor.
985 /// Determine whether this class has any user-declared constructors.
987 /// When true, a default constructor will not be implicitly declared.
988 bool hasUserDeclaredConstructor() const {
989 return data().UserDeclaredConstructor;
992 /// Whether this class has a user-provided default constructor
994 bool hasUserProvidedDefaultConstructor() const {
995 return data().UserProvidedDefaultConstructor;
998 /// Determine whether this class has a user-declared copy constructor.
1000 /// When false, a copy constructor will be implicitly declared.
1001 bool hasUserDeclaredCopyConstructor() const {
1002 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
1005 /// Determine whether this class needs an implicit copy
1006 /// constructor to be lazily declared.
1007 bool needsImplicitCopyConstructor() const {
1008 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
1011 /// Determine whether we need to eagerly declare a defaulted copy
1012 /// constructor for this class.
1013 bool needsOverloadResolutionForCopyConstructor() const {
1014 // C++17 [class.copy.ctor]p6:
1015 // If the class definition declares a move constructor or move assignment
1016 // operator, the implicitly declared copy constructor is defined as
1018 // In MSVC mode, sometimes a declared move assignment does not delete an
1019 // implicit copy constructor, so defer this choice to Sema.
1020 if (data().UserDeclaredSpecialMembers &
1021 (SMF_MoveConstructor | SMF_MoveAssignment))
1023 return data().NeedOverloadResolutionForCopyConstructor;
1026 /// Determine whether an implicit copy constructor for this type
1027 /// would have a parameter with a const-qualified reference type.
1028 bool implicitCopyConstructorHasConstParam() const {
1029 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
1031 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
1034 /// Determine whether this class has a copy constructor with
1035 /// a parameter type which is a reference to a const-qualified type.
1036 bool hasCopyConstructorWithConstParam() const {
1037 return data().HasDeclaredCopyConstructorWithConstParam ||
1038 (needsImplicitCopyConstructor() &&
1039 implicitCopyConstructorHasConstParam());
1042 /// Whether this class has a user-declared move constructor or
1043 /// assignment operator.
1045 /// When false, a move constructor and assignment operator may be
1046 /// implicitly declared.
1047 bool hasUserDeclaredMoveOperation() const {
1048 return data().UserDeclaredSpecialMembers &
1049 (SMF_MoveConstructor | SMF_MoveAssignment);
1052 /// Determine whether this class has had a move constructor
1053 /// declared by the user.
1054 bool hasUserDeclaredMoveConstructor() const {
1055 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
1058 /// Determine whether this class has a move constructor.
1059 bool hasMoveConstructor() const {
1060 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
1061 needsImplicitMoveConstructor();
1064 /// Set that we attempted to declare an implicit copy
1065 /// constructor, but overload resolution failed so we deleted it.
1066 void setImplicitCopyConstructorIsDeleted() {
1067 assert((data().DefaultedCopyConstructorIsDeleted ||
1068 needsOverloadResolutionForCopyConstructor()) &&
1069 "Copy constructor should not be deleted");
1070 data().DefaultedCopyConstructorIsDeleted = true;
1073 /// Set that we attempted to declare an implicit move
1074 /// constructor, but overload resolution failed so we deleted it.
1075 void setImplicitMoveConstructorIsDeleted() {
1076 assert((data().DefaultedMoveConstructorIsDeleted ||
1077 needsOverloadResolutionForMoveConstructor()) &&
1078 "move constructor should not be deleted");
1079 data().DefaultedMoveConstructorIsDeleted = true;
1082 /// Set that we attempted to declare an implicit destructor,
1083 /// but overload resolution failed so we deleted it.
1084 void setImplicitDestructorIsDeleted() {
1085 assert((data().DefaultedDestructorIsDeleted ||
1086 needsOverloadResolutionForDestructor()) &&
1087 "destructor should not be deleted");
1088 data().DefaultedDestructorIsDeleted = true;
1091 /// Determine whether this class should get an implicit move
1092 /// constructor or if any existing special member function inhibits this.
1093 bool needsImplicitMoveConstructor() const {
1094 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
1095 !hasUserDeclaredCopyConstructor() &&
1096 !hasUserDeclaredCopyAssignment() &&
1097 !hasUserDeclaredMoveAssignment() &&
1098 !hasUserDeclaredDestructor();
1101 /// Determine whether we need to eagerly declare a defaulted move
1102 /// constructor for this class.
1103 bool needsOverloadResolutionForMoveConstructor() const {
1104 return data().NeedOverloadResolutionForMoveConstructor;
1107 /// Determine whether this class has a user-declared copy assignment
1110 /// When false, a copy assignment operator will be implicitly declared.
1111 bool hasUserDeclaredCopyAssignment() const {
1112 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
1115 /// Determine whether this class needs an implicit copy
1116 /// assignment operator to be lazily declared.
1117 bool needsImplicitCopyAssignment() const {
1118 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
1121 /// Determine whether we need to eagerly declare a defaulted copy
1122 /// assignment operator for this class.
1123 bool needsOverloadResolutionForCopyAssignment() const {
1124 return data().HasMutableFields;
1127 /// Determine whether an implicit copy assignment operator for this
1128 /// type would have a parameter with a const-qualified reference type.
1129 bool implicitCopyAssignmentHasConstParam() const {
1130 return data().ImplicitCopyAssignmentHasConstParam;
1133 /// Determine whether this class has a copy assignment operator with
1134 /// a parameter type which is a reference to a const-qualified type or is not
1136 bool hasCopyAssignmentWithConstParam() const {
1137 return data().HasDeclaredCopyAssignmentWithConstParam ||
1138 (needsImplicitCopyAssignment() &&
1139 implicitCopyAssignmentHasConstParam());
1142 /// Determine whether this class has had a move assignment
1143 /// declared by the user.
1144 bool hasUserDeclaredMoveAssignment() const {
1145 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
1148 /// Determine whether this class has a move assignment operator.
1149 bool hasMoveAssignment() const {
1150 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
1151 needsImplicitMoveAssignment();
1154 /// Set that we attempted to declare an implicit move assignment
1155 /// operator, but overload resolution failed so we deleted it.
1156 void setImplicitMoveAssignmentIsDeleted() {
1157 assert((data().DefaultedMoveAssignmentIsDeleted ||
1158 needsOverloadResolutionForMoveAssignment()) &&
1159 "move assignment should not be deleted");
1160 data().DefaultedMoveAssignmentIsDeleted = true;
1163 /// Determine whether this class should get an implicit move
1164 /// assignment operator or if any existing special member function inhibits
1166 bool needsImplicitMoveAssignment() const {
1167 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
1168 !hasUserDeclaredCopyConstructor() &&
1169 !hasUserDeclaredCopyAssignment() &&
1170 !hasUserDeclaredMoveConstructor() &&
1171 !hasUserDeclaredDestructor() &&
1172 // C++1z [expr.prim.lambda]p21: "the closure type has a deleted copy
1173 // assignment operator". The intent is that this counts as a user
1174 // declared copy assignment, but we do not model it that way.
1178 /// Determine whether we need to eagerly declare a move assignment
1179 /// operator for this class.
1180 bool needsOverloadResolutionForMoveAssignment() const {
1181 return data().NeedOverloadResolutionForMoveAssignment;
1184 /// Determine whether this class has a user-declared destructor.
1186 /// When false, a destructor will be implicitly declared.
1187 bool hasUserDeclaredDestructor() const {
1188 return data().UserDeclaredSpecialMembers & SMF_Destructor;
1191 /// Determine whether this class needs an implicit destructor to
1192 /// be lazily declared.
1193 bool needsImplicitDestructor() const {
1194 return !(data().DeclaredSpecialMembers & SMF_Destructor);
1197 /// Determine whether we need to eagerly declare a destructor for this
1199 bool needsOverloadResolutionForDestructor() const {
1200 return data().NeedOverloadResolutionForDestructor;
1203 /// Determine whether this class describes a lambda function object.
1204 bool isLambda() const {
1205 // An update record can't turn a non-lambda into a lambda.
1206 auto *DD = DefinitionData;
1207 return DD && DD->IsLambda;
1210 /// Determine whether this class describes a generic
1211 /// lambda function object (i.e. function call operator is
1213 bool isGenericLambda() const;
1215 /// Retrieve the lambda call operator of the closure type
1216 /// if this is a closure type.
1217 CXXMethodDecl *getLambdaCallOperator() const;
1219 /// Retrieve the lambda static invoker, the address of which
1220 /// is returned by the conversion operator, and the body of which
1221 /// is forwarded to the lambda call operator.
1222 CXXMethodDecl *getLambdaStaticInvoker() const;
1224 /// Retrieve the generic lambda's template parameter list.
1225 /// Returns null if the class does not represent a lambda or a generic
1227 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1229 LambdaCaptureDefault getLambdaCaptureDefault() const {
1231 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1234 /// For a closure type, retrieve the mapping from captured
1235 /// variables and \c this to the non-static data members that store the
1236 /// values or references of the captures.
1238 /// \param Captures Will be populated with the mapping from captured
1239 /// variables to the corresponding fields.
1241 /// \param ThisCapture Will be set to the field declaration for the
1242 /// \c this capture.
1244 /// \note No entries will be added for init-captures, as they do not capture
1246 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1247 FieldDecl *&ThisCapture) const;
1249 using capture_const_iterator = const LambdaCapture *;
1250 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1252 capture_const_range captures() const {
1253 return capture_const_range(captures_begin(), captures_end());
1256 capture_const_iterator captures_begin() const {
1257 return isLambda() ? getLambdaData().Captures : nullptr;
1260 capture_const_iterator captures_end() const {
1261 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1265 using conversion_iterator = UnresolvedSetIterator;
1267 conversion_iterator conversion_begin() const {
1268 return data().Conversions.get(getASTContext()).begin();
1271 conversion_iterator conversion_end() const {
1272 return data().Conversions.get(getASTContext()).end();
1275 /// Removes a conversion function from this class. The conversion
1276 /// function must currently be a member of this class. Furthermore,
1277 /// this class must currently be in the process of being defined.
1278 void removeConversion(const NamedDecl *Old);
1280 /// Get all conversion functions visible in current class,
1281 /// including conversion function templates.
1282 llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1284 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1285 /// which is a class with no user-declared constructors, no private
1286 /// or protected non-static data members, no base classes, and no virtual
1287 /// functions (C++ [dcl.init.aggr]p1).
1288 bool isAggregate() const { return data().Aggregate; }
1290 /// Whether this class has any in-class initializers
1291 /// for non-static data members (including those in anonymous unions or
1293 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1295 /// Whether this class or any of its subobjects has any members of
1296 /// reference type which would make value-initialization ill-formed.
1298 /// Per C++03 [dcl.init]p5:
1299 /// - if T is a non-union class type without a user-declared constructor,
1300 /// then every non-static data member and base-class component of T is
1301 /// value-initialized [...] A program that calls for [...]
1302 /// value-initialization of an entity of reference type is ill-formed.
1303 bool hasUninitializedReferenceMember() const {
1304 return !isUnion() && !hasUserDeclaredConstructor() &&
1305 data().HasUninitializedReferenceMember;
1308 /// Whether this class is a POD-type (C++ [class]p4)
1310 /// For purposes of this function a class is POD if it is an aggregate
1311 /// that has no non-static non-POD data members, no reference data
1312 /// members, no user-defined copy assignment operator and no
1313 /// user-defined destructor.
1315 /// Note that this is the C++ TR1 definition of POD.
1316 bool isPOD() const { return data().PlainOldData; }
1318 /// True if this class is C-like, without C++-specific features, e.g.
1319 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1320 bool isCLike() const;
1322 /// Determine whether this is an empty class in the sense of
1323 /// (C++11 [meta.unary.prop]).
1325 /// The CXXRecordDecl is a class type, but not a union type,
1326 /// with no non-static data members other than bit-fields of length 0,
1327 /// no virtual member functions, no virtual base classes,
1328 /// and no base class B for which is_empty<B>::value is false.
1330 /// \note This does NOT include a check for union-ness.
1331 bool isEmpty() const { return data().Empty; }
1333 /// Determine whether this class has direct non-static data members.
1334 bool hasDirectFields() const {
1336 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1339 /// Whether this class is polymorphic (C++ [class.virtual]),
1340 /// which means that the class contains or inherits a virtual function.
1341 bool isPolymorphic() const { return data().Polymorphic; }
1343 /// Determine whether this class has a pure virtual function.
1345 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1346 /// a pure virtual function or inherits a pure virtual function that is
1348 bool isAbstract() const { return data().Abstract; }
1350 /// Determine whether this class is standard-layout per
1352 bool isStandardLayout() const { return data().IsStandardLayout; }
1354 /// Determine whether this class was standard-layout per
1355 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1356 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1358 /// Determine whether this class, or any of its class subobjects,
1359 /// contains a mutable field.
1360 bool hasMutableFields() const { return data().HasMutableFields; }
1362 /// Determine whether this class has any variant members.
1363 bool hasVariantMembers() const { return data().HasVariantMembers; }
1365 /// Determine whether this class has a trivial default constructor
1366 /// (C++11 [class.ctor]p5).
1367 bool hasTrivialDefaultConstructor() const {
1368 return hasDefaultConstructor() &&
1369 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1372 /// Determine whether this class has a non-trivial default constructor
1373 /// (C++11 [class.ctor]p5).
1374 bool hasNonTrivialDefaultConstructor() const {
1375 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1376 (needsImplicitDefaultConstructor() &&
1377 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1380 /// Determine whether this class has at least one constexpr constructor
1381 /// other than the copy or move constructors.
1382 bool hasConstexprNonCopyMoveConstructor() const {
1383 return data().HasConstexprNonCopyMoveConstructor ||
1384 (needsImplicitDefaultConstructor() &&
1385 defaultedDefaultConstructorIsConstexpr());
1388 /// Determine whether a defaulted default constructor for this class
1389 /// would be constexpr.
1390 bool defaultedDefaultConstructorIsConstexpr() const {
1391 return data().DefaultedDefaultConstructorIsConstexpr &&
1392 (!isUnion() || hasInClassInitializer() || !hasVariantMembers());
1395 /// Determine whether this class has a constexpr default constructor.
1396 bool hasConstexprDefaultConstructor() const {
1397 return data().HasConstexprDefaultConstructor ||
1398 (needsImplicitDefaultConstructor() &&
1399 defaultedDefaultConstructorIsConstexpr());
1402 /// Determine whether this class has a trivial copy constructor
1403 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1404 bool hasTrivialCopyConstructor() const {
1405 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1408 bool hasTrivialCopyConstructorForCall() const {
1409 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1412 /// Determine whether this class has a non-trivial copy constructor
1413 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1414 bool hasNonTrivialCopyConstructor() const {
1415 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1416 !hasTrivialCopyConstructor();
1419 bool hasNonTrivialCopyConstructorForCall() const {
1420 return (data().DeclaredNonTrivialSpecialMembersForCall &
1421 SMF_CopyConstructor) ||
1422 !hasTrivialCopyConstructorForCall();
1425 /// Determine whether this class has a trivial move constructor
1426 /// (C++11 [class.copy]p12)
1427 bool hasTrivialMoveConstructor() const {
1428 return hasMoveConstructor() &&
1429 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1432 bool hasTrivialMoveConstructorForCall() const {
1433 return hasMoveConstructor() &&
1434 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1437 /// Determine whether this class has a non-trivial move constructor
1438 /// (C++11 [class.copy]p12)
1439 bool hasNonTrivialMoveConstructor() const {
1440 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1441 (needsImplicitMoveConstructor() &&
1442 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1445 bool hasNonTrivialMoveConstructorForCall() const {
1446 return (data().DeclaredNonTrivialSpecialMembersForCall &
1447 SMF_MoveConstructor) ||
1448 (needsImplicitMoveConstructor() &&
1449 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1452 /// Determine whether this class has a trivial copy assignment operator
1453 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1454 bool hasTrivialCopyAssignment() const {
1455 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1458 /// Determine whether this class has a non-trivial copy assignment
1459 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1460 bool hasNonTrivialCopyAssignment() const {
1461 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1462 !hasTrivialCopyAssignment();
1465 /// Determine whether this class has a trivial move assignment operator
1466 /// (C++11 [class.copy]p25)
1467 bool hasTrivialMoveAssignment() const {
1468 return hasMoveAssignment() &&
1469 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1472 /// Determine whether this class has a non-trivial move assignment
1473 /// operator (C++11 [class.copy]p25)
1474 bool hasNonTrivialMoveAssignment() const {
1475 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1476 (needsImplicitMoveAssignment() &&
1477 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1480 /// Determine whether this class has a trivial destructor
1481 /// (C++ [class.dtor]p3)
1482 bool hasTrivialDestructor() const {
1483 return data().HasTrivialSpecialMembers & SMF_Destructor;
1486 bool hasTrivialDestructorForCall() const {
1487 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1490 /// Determine whether this class has a non-trivial destructor
1491 /// (C++ [class.dtor]p3)
1492 bool hasNonTrivialDestructor() const {
1493 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1496 bool hasNonTrivialDestructorForCall() const {
1497 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1500 void setHasTrivialSpecialMemberForCall() {
1501 data().HasTrivialSpecialMembersForCall =
1502 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1505 /// Determine whether declaring a const variable with this type is ok
1506 /// per core issue 253.
1507 bool allowConstDefaultInit() const {
1508 return !data().HasUninitializedFields ||
1509 !(data().HasDefaultedDefaultConstructor ||
1510 needsImplicitDefaultConstructor());
1513 /// Determine whether this class has a destructor which has no
1514 /// semantic effect.
1516 /// Any such destructor will be trivial, public, defaulted and not deleted,
1517 /// and will call only irrelevant destructors.
1518 bool hasIrrelevantDestructor() const {
1519 return data().HasIrrelevantDestructor;
1522 /// Determine whether this class has a non-literal or/ volatile type
1523 /// non-static data member or base class.
1524 bool hasNonLiteralTypeFieldsOrBases() const {
1525 return data().HasNonLiteralTypeFieldsOrBases;
1528 /// Determine whether this class has a using-declaration that names
1529 /// a user-declared base class constructor.
1530 bool hasInheritedConstructor() const {
1531 return data().HasInheritedConstructor;
1534 /// Determine whether this class has a using-declaration that names
1535 /// a base class assignment operator.
1536 bool hasInheritedAssignment() const {
1537 return data().HasInheritedAssignment;
1540 /// Determine whether this class is considered trivially copyable per
1541 /// (C++11 [class]p6).
1542 bool isTriviallyCopyable() const;
1544 /// Determine whether this class is considered trivial.
1546 /// C++11 [class]p6:
1547 /// "A trivial class is a class that has a trivial default constructor and
1548 /// is trivially copiable."
1549 bool isTrivial() const {
1550 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1553 /// Determine whether this class is a literal type.
1555 /// C++11 [basic.types]p10:
1556 /// A class type that has all the following properties:
1557 /// - it has a trivial destructor
1558 /// - every constructor call and full-expression in the
1559 /// brace-or-equal-intializers for non-static data members (if any) is
1560 /// a constant expression.
1561 /// - it is an aggregate type or has at least one constexpr constructor
1562 /// or constructor template that is not a copy or move constructor, and
1563 /// - all of its non-static data members and base classes are of literal
1566 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1567 /// treating types with trivial default constructors as literal types.
1569 /// Only in C++17 and beyond, are lambdas literal types.
1570 bool isLiteral() const {
1571 return hasTrivialDestructor() &&
1572 (!isLambda() || getASTContext().getLangOpts().CPlusPlus17) &&
1573 !hasNonLiteralTypeFieldsOrBases() &&
1574 (isAggregate() || isLambda() ||
1575 hasConstexprNonCopyMoveConstructor() ||
1576 hasTrivialDefaultConstructor());
1579 /// If this record is an instantiation of a member class,
1580 /// retrieves the member class from which it was instantiated.
1582 /// This routine will return non-null for (non-templated) member
1583 /// classes of class templates. For example, given:
1586 /// template<typename T>
1592 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1593 /// whose parent is the class template specialization X<int>. For
1594 /// this declaration, getInstantiatedFromMemberClass() will return
1595 /// the CXXRecordDecl X<T>::A. When a complete definition of
1596 /// X<int>::A is required, it will be instantiated from the
1597 /// declaration returned by getInstantiatedFromMemberClass().
1598 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1600 /// If this class is an instantiation of a member class of a
1601 /// class template specialization, retrieves the member specialization
1603 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1605 /// Specify that this record is an instantiation of the
1606 /// member class \p RD.
1607 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1608 TemplateSpecializationKind TSK);
1610 /// Retrieves the class template that is described by this
1611 /// class declaration.
1613 /// Every class template is represented as a ClassTemplateDecl and a
1614 /// CXXRecordDecl. The former contains template properties (such as
1615 /// the template parameter lists) while the latter contains the
1616 /// actual description of the template's
1617 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1618 /// CXXRecordDecl that from a ClassTemplateDecl, while
1619 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1620 /// a CXXRecordDecl.
1621 ClassTemplateDecl *getDescribedClassTemplate() const;
1623 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1625 /// Determine whether this particular class is a specialization or
1626 /// instantiation of a class template or member class of a class template,
1627 /// and how it was instantiated or specialized.
1628 TemplateSpecializationKind getTemplateSpecializationKind() const;
1630 /// Set the kind of specialization or template instantiation this is.
1631 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1633 /// Retrieve the record declaration from which this record could be
1634 /// instantiated. Returns null if this class is not a template instantiation.
1635 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1637 CXXRecordDecl *getTemplateInstantiationPattern() {
1638 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1639 ->getTemplateInstantiationPattern());
1642 /// Returns the destructor decl for this class.
1643 CXXDestructorDecl *getDestructor() const;
1645 /// Returns true if the class destructor, or any implicitly invoked
1646 /// destructors are marked noreturn.
1647 bool isAnyDestructorNoReturn() const;
1649 /// If the class is a local class [class.local], returns
1650 /// the enclosing function declaration.
1651 const FunctionDecl *isLocalClass() const {
1652 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1653 return RD->isLocalClass();
1655 return dyn_cast<FunctionDecl>(getDeclContext());
1658 FunctionDecl *isLocalClass() {
1659 return const_cast<FunctionDecl*>(
1660 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1663 /// Determine whether this dependent class is a current instantiation,
1664 /// when viewed from within the given context.
1665 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1667 /// Determine whether this class is derived from the class \p Base.
1669 /// This routine only determines whether this class is derived from \p Base,
1670 /// but does not account for factors that may make a Derived -> Base class
1671 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1672 /// base class subobjects.
1674 /// \param Base the base class we are searching for.
1676 /// \returns true if this class is derived from Base, false otherwise.
1677 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1679 /// Determine whether this class is derived from the type \p Base.
1681 /// This routine only determines whether this class is derived from \p Base,
1682 /// but does not account for factors that may make a Derived -> Base class
1683 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1684 /// base class subobjects.
1686 /// \param Base the base class we are searching for.
1688 /// \param Paths will contain the paths taken from the current class to the
1689 /// given \p Base class.
1691 /// \returns true if this class is derived from \p Base, false otherwise.
1693 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1694 /// tangling input and output in \p Paths
1695 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1697 /// Determine whether this class is virtually derived from
1698 /// the class \p Base.
1700 /// This routine only determines whether this class is virtually
1701 /// derived from \p Base, but does not account for factors that may
1702 /// make a Derived -> Base class ill-formed, such as
1703 /// private/protected inheritance or multiple, ambiguous base class
1706 /// \param Base the base class we are searching for.
1708 /// \returns true if this class is virtually derived from Base,
1709 /// false otherwise.
1710 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1712 /// Determine whether this class is provably not derived from
1713 /// the type \p Base.
1714 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1716 /// Function type used by forallBases() as a callback.
1718 /// \param BaseDefinition the definition of the base class
1720 /// \returns true if this base matched the search criteria
1721 using ForallBasesCallback =
1722 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1724 /// Determines if the given callback holds for all the direct
1725 /// or indirect base classes of this type.
1727 /// The class itself does not count as a base class. This routine
1728 /// returns false if the class has non-computable base classes.
1730 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1731 /// class of this type, or if \p AllowShortCircuit is true then until a call
1734 /// \param AllowShortCircuit if false, forces the callback to be called
1735 /// for every base class, even if a dependent or non-matching base was
1737 bool forallBases(ForallBasesCallback BaseMatches,
1738 bool AllowShortCircuit = true) const;
1740 /// Function type used by lookupInBases() to determine whether a
1741 /// specific base class subobject matches the lookup criteria.
1743 /// \param Specifier the base-class specifier that describes the inheritance
1744 /// from the base class we are trying to match.
1746 /// \param Path the current path, from the most-derived class down to the
1747 /// base named by the \p Specifier.
1749 /// \returns true if this base matched the search criteria, false otherwise.
1750 using BaseMatchesCallback =
1751 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1752 CXXBasePath &Path)>;
1754 /// Look for entities within the base classes of this C++ class,
1755 /// transitively searching all base class subobjects.
1757 /// This routine uses the callback function \p BaseMatches to find base
1758 /// classes meeting some search criteria, walking all base class subobjects
1759 /// and populating the given \p Paths structure with the paths through the
1760 /// inheritance hierarchy that resulted in a match. On a successful search,
1761 /// the \p Paths structure can be queried to retrieve the matching paths and
1762 /// to determine if there were any ambiguities.
1764 /// \param BaseMatches callback function used to determine whether a given
1765 /// base matches the user-defined search criteria.
1767 /// \param Paths used to record the paths from this class to its base class
1768 /// subobjects that match the search criteria.
1770 /// \param LookupInDependent can be set to true to extend the search to
1771 /// dependent base classes.
1773 /// \returns true if there exists any path from this class to a base class
1774 /// subobject that matches the search criteria.
1775 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1776 bool LookupInDependent = false) const;
1778 /// Base-class lookup callback that determines whether the given
1779 /// base class specifier refers to a specific class declaration.
1781 /// This callback can be used with \c lookupInBases() to determine whether
1782 /// a given derived class has is a base class subobject of a particular type.
1783 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1784 /// base class that we are searching for.
1785 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1786 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1788 /// Base-class lookup callback that determines whether the
1789 /// given base class specifier refers to a specific class
1790 /// declaration and describes virtual derivation.
1792 /// This callback can be used with \c lookupInBases() to determine
1793 /// whether a given derived class has is a virtual base class
1794 /// subobject of a particular type. The base record pointer should
1795 /// refer to the canonical CXXRecordDecl of the base class that we
1796 /// are searching for.
1797 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1799 const CXXRecordDecl *BaseRecord);
1801 /// Base-class lookup callback that determines whether there exists
1802 /// a tag with the given name.
1804 /// This callback can be used with \c lookupInBases() to find tag members
1805 /// of the given name within a C++ class hierarchy.
1806 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1807 CXXBasePath &Path, DeclarationName Name);
1809 /// Base-class lookup callback that determines whether there exists
1810 /// a member with the given name.
1812 /// This callback can be used with \c lookupInBases() to find members
1813 /// of the given name within a C++ class hierarchy.
1814 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1815 CXXBasePath &Path, DeclarationName Name);
1817 /// Base-class lookup callback that determines whether there exists
1818 /// a member with the given name.
1820 /// This callback can be used with \c lookupInBases() to find members
1821 /// of the given name within a C++ class hierarchy, including dependent
1824 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1825 CXXBasePath &Path, DeclarationName Name);
1827 /// Base-class lookup callback that determines whether there exists
1828 /// an OpenMP declare reduction member with the given name.
1830 /// This callback can be used with \c lookupInBases() to find members
1831 /// of the given name within a C++ class hierarchy.
1832 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1833 CXXBasePath &Path, DeclarationName Name);
1835 /// Base-class lookup callback that determines whether there exists
1836 /// a member with the given name that can be used in a nested-name-specifier.
1838 /// This callback can be used with \c lookupInBases() to find members of
1839 /// the given name within a C++ class hierarchy that can occur within
1840 /// nested-name-specifiers.
1841 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1843 DeclarationName Name);
1845 /// Retrieve the final overriders for each virtual member
1846 /// function in the class hierarchy where this class is the
1847 /// most-derived class in the class hierarchy.
1848 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1850 /// Get the indirect primary bases for this class.
1851 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1853 /// Performs an imprecise lookup of a dependent name in this class.
1855 /// This function does not follow strict semantic rules and should be used
1856 /// only when lookup rules can be relaxed, e.g. indexing.
1857 std::vector<const NamedDecl *>
1858 lookupDependentName(const DeclarationName &Name,
1859 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1861 /// Renders and displays an inheritance diagram
1862 /// for this C++ class and all of its base classes (transitively) using
1864 void viewInheritance(ASTContext& Context) const;
1866 /// Calculates the access of a decl that is reached
1868 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1869 AccessSpecifier DeclAccess) {
1870 assert(DeclAccess != AS_none);
1871 if (DeclAccess == AS_private) return AS_none;
1872 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1875 /// Indicates that the declaration of a defaulted or deleted special
1876 /// member function is now complete.
1877 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1879 void setTrivialForCallFlags(CXXMethodDecl *MD);
1881 /// Indicates that the definition of this class is now complete.
1882 void completeDefinition() override;
1884 /// Indicates that the definition of this class is now complete,
1885 /// and provides a final overrider map to help determine
1887 /// \param FinalOverriders The final overrider map for this class, which can
1888 /// be provided as an optimization for abstract-class checking. If NULL,
1889 /// final overriders will be computed if they are needed to complete the
1891 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1893 /// Determine whether this class may end up being abstract, even though
1894 /// it is not yet known to be abstract.
1896 /// \returns true if this class is not known to be abstract but has any
1897 /// base classes that are abstract. In this case, \c completeDefinition()
1898 /// will need to compute final overriders to determine whether the class is
1899 /// actually abstract.
1900 bool mayBeAbstract() const;
1902 /// If this is the closure type of a lambda expression, retrieve the
1903 /// number to be used for name mangling in the Itanium C++ ABI.
1905 /// Zero indicates that this closure type has internal linkage, so the
1906 /// mangling number does not matter, while a non-zero value indicates which
1907 /// lambda expression this is in this particular context.
1908 unsigned getLambdaManglingNumber() const {
1909 assert(isLambda() && "Not a lambda closure type!");
1910 return getLambdaData().ManglingNumber;
1913 /// Retrieve the declaration that provides additional context for a
1914 /// lambda, when the normal declaration context is not specific enough.
1916 /// Certain contexts (default arguments of in-class function parameters and
1917 /// the initializers of data members) have separate name mangling rules for
1918 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1919 /// the declaration in which the lambda occurs, e.g., the function parameter
1920 /// or the non-static data member. Otherwise, it returns NULL to imply that
1921 /// the declaration context suffices.
1922 Decl *getLambdaContextDecl() const;
1924 /// Set the mangling number and context declaration for a lambda
1926 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
1927 getLambdaData().ManglingNumber = ManglingNumber;
1928 getLambdaData().ContextDecl = ContextDecl;
1931 /// Returns the inheritance model used for this record.
1932 MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1934 /// Calculate what the inheritance model would be for this class.
1935 MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1937 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1938 /// member pointer if we can guarantee that zero is not a valid field offset,
1939 /// or if the member pointer has multiple fields. Polymorphic classes have a
1940 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1941 /// fields, we can use zero even if it is a valid field offset because
1942 /// null-ness testing will check the other fields.
1943 bool nullFieldOffsetIsZero() const {
1944 return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1945 getMSInheritanceModel()) ||
1946 (hasDefinition() && isPolymorphic());
1949 /// Controls when vtordisps will be emitted if this record is used as a
1951 MSVtorDispAttr::Mode getMSVtorDispMode() const;
1953 /// Determine whether this lambda expression was known to be dependent
1954 /// at the time it was created, even if its context does not appear to be
1957 /// This flag is a workaround for an issue with parsing, where default
1958 /// arguments are parsed before their enclosing function declarations have
1959 /// been created. This means that any lambda expressions within those
1960 /// default arguments will have as their DeclContext the context enclosing
1961 /// the function declaration, which may be non-dependent even when the
1962 /// function declaration itself is dependent. This flag indicates when we
1963 /// know that the lambda is dependent despite that.
1964 bool isDependentLambda() const {
1965 return isLambda() && getLambdaData().Dependent;
1968 TypeSourceInfo *getLambdaTypeInfo() const {
1969 return getLambdaData().MethodTyInfo;
1972 // Determine whether this type is an Interface Like type for
1973 // __interface inheritance purposes.
1974 bool isInterfaceLike() const;
1976 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1977 static bool classofKind(Kind K) {
1978 return K >= firstCXXRecord && K <= lastCXXRecord;
1982 /// Represents a C++ deduction guide declaration.
1985 /// template<typename T> struct A { A(); A(T); };
1989 /// In this example, there will be an explicit deduction guide from the
1990 /// second line, and implicit deduction guide templates synthesized from
1991 /// the constructors of \c A.
1992 class CXXDeductionGuideDecl : public FunctionDecl {
1993 void anchor() override;
1996 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1997 bool IsExplicit, const DeclarationNameInfo &NameInfo,
1998 QualType T, TypeSourceInfo *TInfo,
1999 SourceLocation EndLocation)
2000 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
2001 SC_None, false, false) {
2002 if (EndLocation.isValid())
2003 setRangeEnd(EndLocation);
2004 IsExplicitSpecified = IsExplicit;
2008 friend class ASTDeclReader;
2009 friend class ASTDeclWriter;
2011 static CXXDeductionGuideDecl *Create(ASTContext &C, DeclContext *DC,
2012 SourceLocation StartLoc, bool IsExplicit,
2013 const DeclarationNameInfo &NameInfo,
2014 QualType T, TypeSourceInfo *TInfo,
2015 SourceLocation EndLocation);
2017 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2019 /// Whether this deduction guide is explicit.
2020 bool isExplicit() const { return IsExplicitSpecified; }
2022 /// Whether this deduction guide was declared with the 'explicit' specifier.
2023 bool isExplicitSpecified() const { return IsExplicitSpecified; }
2025 /// Get the template for which this guide performs deduction.
2026 TemplateDecl *getDeducedTemplate() const {
2027 return getDeclName().getCXXDeductionGuideTemplate();
2030 void setIsCopyDeductionCandidate() {
2031 IsCopyDeductionCandidate = true;
2034 bool isCopyDeductionCandidate() const { return IsCopyDeductionCandidate; }
2036 // Implement isa/cast/dyncast/etc.
2037 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2038 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
2041 /// Represents a static or instance method of a struct/union/class.
2043 /// In the terminology of the C++ Standard, these are the (static and
2044 /// non-static) member functions, whether virtual or not.
2045 class CXXMethodDecl : public FunctionDecl {
2046 void anchor() override;
2049 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2050 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2051 QualType T, TypeSourceInfo *TInfo,
2052 StorageClass SC, bool isInline,
2053 bool isConstexpr, SourceLocation EndLocation)
2054 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo,
2055 SC, isInline, isConstexpr) {
2056 if (EndLocation.isValid())
2057 setRangeEnd(EndLocation);
2061 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2062 SourceLocation StartLoc,
2063 const DeclarationNameInfo &NameInfo,
2064 QualType T, TypeSourceInfo *TInfo,
2068 SourceLocation EndLocation);
2070 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2072 bool isStatic() const;
2073 bool isInstance() const { return !isStatic(); }
2075 /// Returns true if the given operator is implicitly static in a record
2077 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2079 // Any allocation function for a class T is a static member
2080 // (even if not explicitly declared static).
2081 // [class.free]p6 Any deallocation function for a class X is a static member
2082 // (even if not explicitly declared static).
2083 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2084 OOK == OO_Array_Delete;
2087 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2088 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2090 bool isVirtual() const {
2091 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2093 // Member function is virtual if it is marked explicitly so, or if it is
2094 // declared in __interface -- then it is automatically pure virtual.
2095 if (CD->isVirtualAsWritten() || CD->isPure())
2098 return CD->size_overridden_methods() != 0;
2101 /// If it's possible to devirtualize a call to this method, return the called
2102 /// function. Otherwise, return null.
2104 /// \param Base The object on which this virtual function is called.
2105 /// \param IsAppleKext True if we are compiling for Apple kext.
2106 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2108 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2109 bool IsAppleKext) const {
2110 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2114 /// Determine whether this is a usual deallocation function
2115 /// (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded
2116 /// delete or delete[] operator with a particular signature.
2117 bool isUsualDeallocationFunction() const;
2119 /// Determine whether this is a copy-assignment operator, regardless
2120 /// of whether it was declared implicitly or explicitly.
2121 bool isCopyAssignmentOperator() const;
2123 /// Determine whether this is a move assignment operator.
2124 bool isMoveAssignmentOperator() const;
2126 CXXMethodDecl *getCanonicalDecl() override {
2127 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2129 const CXXMethodDecl *getCanonicalDecl() const {
2130 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2133 CXXMethodDecl *getMostRecentDecl() {
2134 return cast<CXXMethodDecl>(
2135 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2137 const CXXMethodDecl *getMostRecentDecl() const {
2138 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2141 /// True if this method is user-declared and was not
2142 /// deleted or defaulted on its first declaration.
2143 bool isUserProvided() const {
2144 auto *DeclAsWritten = this;
2145 if (auto *Pattern = getTemplateInstantiationPattern())
2146 DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2147 return !(DeclAsWritten->isDeleted() ||
2148 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2151 void addOverriddenMethod(const CXXMethodDecl *MD);
2153 using method_iterator = const CXXMethodDecl *const *;
2155 method_iterator begin_overridden_methods() const;
2156 method_iterator end_overridden_methods() const;
2157 unsigned size_overridden_methods() const;
2159 using overridden_method_range= ASTContext::overridden_method_range;
2161 overridden_method_range overridden_methods() const;
2163 /// Returns the parent of this method declaration, which
2164 /// is the class in which this method is defined.
2165 const CXXRecordDecl *getParent() const {
2166 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2169 /// Returns the parent of this method declaration, which
2170 /// is the class in which this method is defined.
2171 CXXRecordDecl *getParent() {
2172 return const_cast<CXXRecordDecl *>(
2173 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2176 /// Returns the type of the \c this pointer.
2178 /// Should only be called for instance (i.e., non-static) methods. Note
2179 /// that for the call operator of a lambda closure type, this returns the
2180 /// desugared 'this' type (a pointer to the closure type), not the captured
2182 QualType getThisType(ASTContext &C) const;
2184 unsigned getTypeQualifiers() const {
2185 return getType()->getAs<FunctionProtoType>()->getTypeQuals();
2188 /// Retrieve the ref-qualifier associated with this method.
2190 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2191 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2199 RefQualifierKind getRefQualifier() const {
2200 return getType()->getAs<FunctionProtoType>()->getRefQualifier();
2203 bool hasInlineBody() const;
2205 /// Determine whether this is a lambda closure type's static member
2206 /// function that is used for the result of the lambda's conversion to
2207 /// function pointer (for a lambda with no captures).
2209 /// The function itself, if used, will have a placeholder body that will be
2210 /// supplied by IR generation to either forward to the function call operator
2211 /// or clone the function call operator.
2212 bool isLambdaStaticInvoker() const;
2214 /// Find the method in \p RD that corresponds to this one.
2216 /// Find if \p RD or one of the classes it inherits from override this method.
2217 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2218 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2220 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2221 bool MayBeBase = false);
2223 const CXXMethodDecl *
2224 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2225 bool MayBeBase = false) const {
2226 return const_cast<CXXMethodDecl *>(this)
2227 ->getCorrespondingMethodInClass(RD, MayBeBase);
2230 // Implement isa/cast/dyncast/etc.
2231 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2232 static bool classofKind(Kind K) {
2233 return K >= firstCXXMethod && K <= lastCXXMethod;
2237 /// Represents a C++ base or member initializer.
2239 /// This is part of a constructor initializer that
2240 /// initializes one non-static member variable or one base class. For
2241 /// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2246 /// class B : public A {
2249 /// B(A& a) : A(a), f(3.14159) { }
2252 class CXXCtorInitializer final {
2253 /// Either the base class name/delegating constructor type (stored as
2254 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2255 /// (IndirectFieldDecl*) being initialized.
2256 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2259 /// The source location for the field name or, for a base initializer
2260 /// pack expansion, the location of the ellipsis.
2262 /// In the case of a delegating
2263 /// constructor, it will still include the type's source location as the
2264 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2265 SourceLocation MemberOrEllipsisLocation;
2267 /// The argument used to initialize the base or member, which may
2268 /// end up constructing an object (when multiple arguments are involved).
2271 /// Location of the left paren of the ctor-initializer.
2272 SourceLocation LParenLoc;
2274 /// Location of the right paren of the ctor-initializer.
2275 SourceLocation RParenLoc;
2277 /// If the initializee is a type, whether that type makes this
2278 /// a delegating initialization.
2279 unsigned IsDelegating : 1;
2281 /// If the initializer is a base initializer, this keeps track
2282 /// of whether the base is virtual or not.
2283 unsigned IsVirtual : 1;
2285 /// Whether or not the initializer is explicitly written
2287 unsigned IsWritten : 1;
2289 /// If IsWritten is true, then this number keeps track of the textual order
2290 /// of this initializer in the original sources, counting from 0.
2291 unsigned SourceOrder : 13;
2294 /// Creates a new base-class initializer.
2296 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2297 SourceLocation L, Expr *Init, SourceLocation R,
2298 SourceLocation EllipsisLoc);
2300 /// Creates a new member initializer.
2302 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2303 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2306 /// Creates a new anonymous field initializer.
2308 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2309 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2312 /// Creates a new delegating initializer.
2314 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2315 SourceLocation L, Expr *Init, SourceLocation R);
2317 /// Determine whether this initializer is initializing a base class.
2318 bool isBaseInitializer() const {
2319 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2322 /// Determine whether this initializer is initializing a non-static
2324 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2326 bool isAnyMemberInitializer() const {
2327 return isMemberInitializer() || isIndirectMemberInitializer();
2330 bool isIndirectMemberInitializer() const {
2331 return Initializee.is<IndirectFieldDecl*>();
2334 /// Determine whether this initializer is an implicit initializer
2335 /// generated for a field with an initializer defined on the member
2338 /// In-class member initializers (also known as "non-static data member
2339 /// initializations", NSDMIs) were introduced in C++11.
2340 bool isInClassMemberInitializer() const {
2341 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2344 /// Determine whether this initializer is creating a delegating
2346 bool isDelegatingInitializer() const {
2347 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2350 /// Determine whether this initializer is a pack expansion.
2351 bool isPackExpansion() const {
2352 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2355 // For a pack expansion, returns the location of the ellipsis.
2356 SourceLocation getEllipsisLoc() const {
2357 assert(isPackExpansion() && "Initializer is not a pack expansion");
2358 return MemberOrEllipsisLocation;
2361 /// If this is a base class initializer, returns the type of the
2362 /// base class with location information. Otherwise, returns an NULL
2364 TypeLoc getBaseClassLoc() const;
2366 /// If this is a base class initializer, returns the type of the base class.
2367 /// Otherwise, returns null.
2368 const Type *getBaseClass() const;
2370 /// Returns whether the base is virtual or not.
2371 bool isBaseVirtual() const {
2372 assert(isBaseInitializer() && "Must call this on base initializer!");
2377 /// Returns the declarator information for a base class or delegating
2379 TypeSourceInfo *getTypeSourceInfo() const {
2380 return Initializee.dyn_cast<TypeSourceInfo *>();
2383 /// If this is a member initializer, returns the declaration of the
2384 /// non-static data member being initialized. Otherwise, returns null.
2385 FieldDecl *getMember() const {
2386 if (isMemberInitializer())
2387 return Initializee.get<FieldDecl*>();
2391 FieldDecl *getAnyMember() const {
2392 if (isMemberInitializer())
2393 return Initializee.get<FieldDecl*>();
2394 if (isIndirectMemberInitializer())
2395 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2399 IndirectFieldDecl *getIndirectMember() const {
2400 if (isIndirectMemberInitializer())
2401 return Initializee.get<IndirectFieldDecl*>();
2405 SourceLocation getMemberLocation() const {
2406 return MemberOrEllipsisLocation;
2409 /// Determine the source location of the initializer.
2410 SourceLocation getSourceLocation() const;
2412 /// Determine the source range covering the entire initializer.
2413 SourceRange getSourceRange() const LLVM_READONLY;
2415 /// Determine whether this initializer is explicitly written
2416 /// in the source code.
2417 bool isWritten() const { return IsWritten; }
2419 /// Return the source position of the initializer, counting from 0.
2420 /// If the initializer was implicit, -1 is returned.
2421 int getSourceOrder() const {
2422 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2425 /// Set the source order of this initializer.
2427 /// This can only be called once for each initializer; it cannot be called
2428 /// on an initializer having a positive number of (implicit) array indices.
2430 /// This assumes that the initializer was written in the source code, and
2431 /// ensures that isWritten() returns true.
2432 void setSourceOrder(int Pos) {
2433 assert(!IsWritten &&
2434 "setSourceOrder() used on implicit initializer");
2435 assert(SourceOrder == 0 &&
2436 "calling twice setSourceOrder() on the same initializer");
2438 "setSourceOrder() used to make an initializer implicit");
2440 SourceOrder = static_cast<unsigned>(Pos);
2443 SourceLocation getLParenLoc() const { return LParenLoc; }
2444 SourceLocation getRParenLoc() const { return RParenLoc; }
2446 /// Get the initializer.
2447 Expr *getInit() const { return static_cast<Expr *>(Init); }
2450 /// Description of a constructor that was inherited from a base class.
2451 class InheritedConstructor {
2452 ConstructorUsingShadowDecl *Shadow = nullptr;
2453 CXXConstructorDecl *BaseCtor = nullptr;
2456 InheritedConstructor() = default;
2457 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2458 CXXConstructorDecl *BaseCtor)
2459 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2461 explicit operator bool() const { return Shadow; }
2463 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2464 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2467 /// Represents a C++ constructor within a class.
2474 /// explicit X(int); // represented by a CXXConstructorDecl.
2477 class CXXConstructorDecl final
2478 : public CXXMethodDecl,
2479 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor> {
2480 /// \name Support for base and member initializers.
2482 /// The arguments used to initialize the base or member.
2483 LazyCXXCtorInitializersPtr CtorInitializers;
2484 unsigned NumCtorInitializers : 31;
2487 /// Whether this constructor declaration is an implicitly-declared
2488 /// inheriting constructor.
2489 unsigned IsInheritingConstructor : 1;
2491 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2492 const DeclarationNameInfo &NameInfo,
2493 QualType T, TypeSourceInfo *TInfo,
2494 bool isExplicitSpecified, bool isInline,
2495 bool isImplicitlyDeclared, bool isConstexpr,
2496 InheritedConstructor Inherited)
2497 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2498 SC_None, isInline, isConstexpr, SourceLocation()),
2499 NumCtorInitializers(0), IsInheritingConstructor((bool)Inherited) {
2500 setImplicit(isImplicitlyDeclared);
2502 *getTrailingObjects<InheritedConstructor>() = Inherited;
2503 IsExplicitSpecified = isExplicitSpecified;
2506 void anchor() override;
2509 friend class ASTDeclReader;
2510 friend class ASTDeclWriter;
2511 friend TrailingObjects;
2513 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2514 bool InheritsConstructor);
2515 static CXXConstructorDecl *
2516 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2517 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2518 bool isExplicit, bool isInline, bool isImplicitlyDeclared,
2520 InheritedConstructor Inherited = InheritedConstructor());
2522 /// Iterates through the member/base initializer list.
2523 using init_iterator = CXXCtorInitializer **;
2525 /// Iterates through the member/base initializer list.
2526 using init_const_iterator = CXXCtorInitializer *const *;
2528 using init_range = llvm::iterator_range<init_iterator>;
2529 using init_const_range = llvm::iterator_range<init_const_iterator>;
2531 init_range inits() { return init_range(init_begin(), init_end()); }
2532 init_const_range inits() const {
2533 return init_const_range(init_begin(), init_end());
2536 /// Retrieve an iterator to the first initializer.
2537 init_iterator init_begin() {
2538 const auto *ConstThis = this;
2539 return const_cast<init_iterator>(ConstThis->init_begin());
2542 /// Retrieve an iterator to the first initializer.
2543 init_const_iterator init_begin() const;
2545 /// Retrieve an iterator past the last initializer.
2546 init_iterator init_end() {
2547 return init_begin() + NumCtorInitializers;
2550 /// Retrieve an iterator past the last initializer.
2551 init_const_iterator init_end() const {
2552 return init_begin() + NumCtorInitializers;
2555 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2556 using init_const_reverse_iterator =
2557 std::reverse_iterator<init_const_iterator>;
2559 init_reverse_iterator init_rbegin() {
2560 return init_reverse_iterator(init_end());
2562 init_const_reverse_iterator init_rbegin() const {
2563 return init_const_reverse_iterator(init_end());
2566 init_reverse_iterator init_rend() {
2567 return init_reverse_iterator(init_begin());
2569 init_const_reverse_iterator init_rend() const {
2570 return init_const_reverse_iterator(init_begin());
2573 /// Determine the number of arguments used to initialize the member
2575 unsigned getNumCtorInitializers() const {
2576 return NumCtorInitializers;
2579 void setNumCtorInitializers(unsigned numCtorInitializers) {
2580 NumCtorInitializers = numCtorInitializers;
2583 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2584 CtorInitializers = Initializers;
2587 /// Whether this function is marked as explicit explicitly.
2588 bool isExplicitSpecified() const { return IsExplicitSpecified; }
2590 /// Whether this function is explicit.
2591 bool isExplicit() const {
2592 return getCanonicalDecl()->isExplicitSpecified();
2595 /// Determine whether this constructor is a delegating constructor.
2596 bool isDelegatingConstructor() const {
2597 return (getNumCtorInitializers() == 1) &&
2598 init_begin()[0]->isDelegatingInitializer();
2601 /// When this constructor delegates to another, retrieve the target.
2602 CXXConstructorDecl *getTargetConstructor() const;
2604 /// Whether this constructor is a default
2605 /// constructor (C++ [class.ctor]p5), which can be used to
2606 /// default-initialize a class of this type.
2607 bool isDefaultConstructor() const;
2609 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2610 /// which can be used to copy the class.
2612 /// \p TypeQuals will be set to the qualifiers on the
2613 /// argument type. For example, \p TypeQuals would be set to \c
2614 /// Qualifiers::Const for the following copy constructor:
2622 bool isCopyConstructor(unsigned &TypeQuals) const;
2624 /// Whether this constructor is a copy
2625 /// constructor (C++ [class.copy]p2, which can be used to copy the
2627 bool isCopyConstructor() const {
2628 unsigned TypeQuals = 0;
2629 return isCopyConstructor(TypeQuals);
2632 /// Determine whether this constructor is a move constructor
2633 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2635 /// \param TypeQuals If this constructor is a move constructor, will be set
2636 /// to the type qualifiers on the referent of the first parameter's type.
2637 bool isMoveConstructor(unsigned &TypeQuals) const;
2639 /// Determine whether this constructor is a move constructor
2640 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2641 bool isMoveConstructor() const {
2642 unsigned TypeQuals = 0;
2643 return isMoveConstructor(TypeQuals);
2646 /// Determine whether this is a copy or move constructor.
2648 /// \param TypeQuals Will be set to the type qualifiers on the reference
2649 /// parameter, if in fact this is a copy or move constructor.
2650 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2652 /// Determine whether this a copy or move constructor.
2653 bool isCopyOrMoveConstructor() const {
2655 return isCopyOrMoveConstructor(Quals);
2658 /// Whether this constructor is a
2659 /// converting constructor (C++ [class.conv.ctor]), which can be
2660 /// used for user-defined conversions.
2661 bool isConvertingConstructor(bool AllowExplicit) const;
2663 /// Determine whether this is a member template specialization that
2664 /// would copy the object to itself. Such constructors are never used to copy
2666 bool isSpecializationCopyingObject() const;
2668 /// Determine whether this is an implicit constructor synthesized to
2669 /// model a call to a constructor inherited from a base class.
2670 bool isInheritingConstructor() const { return IsInheritingConstructor; }
2672 /// Get the constructor that this inheriting constructor is based on.
2673 InheritedConstructor getInheritedConstructor() const {
2674 return IsInheritingConstructor ? *getTrailingObjects<InheritedConstructor>()
2675 : InheritedConstructor();
2678 CXXConstructorDecl *getCanonicalDecl() override {
2679 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2681 const CXXConstructorDecl *getCanonicalDecl() const {
2682 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2685 // Implement isa/cast/dyncast/etc.
2686 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2687 static bool classofKind(Kind K) { return K == CXXConstructor; }
2690 /// Represents a C++ destructor within a class.
2697 /// ~X(); // represented by a CXXDestructorDecl.
2700 class CXXDestructorDecl : public CXXMethodDecl {
2701 friend class ASTDeclReader;
2702 friend class ASTDeclWriter;
2704 // FIXME: Don't allocate storage for these except in the first declaration
2705 // of a virtual destructor.
2706 FunctionDecl *OperatorDelete = nullptr;
2707 Expr *OperatorDeleteThisArg = nullptr;
2709 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2710 const DeclarationNameInfo &NameInfo,
2711 QualType T, TypeSourceInfo *TInfo,
2712 bool isInline, bool isImplicitlyDeclared)
2713 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2714 SC_None, isInline, /*isConstexpr=*/false, SourceLocation())
2716 setImplicit(isImplicitlyDeclared);
2719 void anchor() override;
2722 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2723 SourceLocation StartLoc,
2724 const DeclarationNameInfo &NameInfo,
2725 QualType T, TypeSourceInfo* TInfo,
2727 bool isImplicitlyDeclared);
2728 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2730 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2732 const FunctionDecl *getOperatorDelete() const {
2733 return getCanonicalDecl()->OperatorDelete;
2736 Expr *getOperatorDeleteThisArg() const {
2737 return getCanonicalDecl()->OperatorDeleteThisArg;
2740 CXXDestructorDecl *getCanonicalDecl() override {
2741 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2743 const CXXDestructorDecl *getCanonicalDecl() const {
2744 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2747 // Implement isa/cast/dyncast/etc.
2748 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2749 static bool classofKind(Kind K) { return K == CXXDestructor; }
2752 /// Represents a C++ conversion function within a class.
2759 /// operator bool();
2762 class CXXConversionDecl : public CXXMethodDecl {
2763 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2764 const DeclarationNameInfo &NameInfo, QualType T,
2765 TypeSourceInfo *TInfo, bool isInline,
2766 bool isExplicitSpecified, bool isConstexpr,
2767 SourceLocation EndLocation)
2768 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2769 SC_None, isInline, isConstexpr, EndLocation) {
2770 IsExplicitSpecified = isExplicitSpecified;
2773 void anchor() override;
2776 friend class ASTDeclReader;
2777 friend class ASTDeclWriter;
2779 static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2780 SourceLocation StartLoc,
2781 const DeclarationNameInfo &NameInfo,
2782 QualType T, TypeSourceInfo *TInfo,
2783 bool isInline, bool isExplicit,
2785 SourceLocation EndLocation);
2786 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2788 /// Whether this function is marked as explicit explicitly.
2789 bool isExplicitSpecified() const { return IsExplicitSpecified; }
2791 /// Whether this function is explicit.
2792 bool isExplicit() const {
2793 return getCanonicalDecl()->isExplicitSpecified();
2796 /// Returns the type that this conversion function is converting to.
2797 QualType getConversionType() const {
2798 return getType()->getAs<FunctionType>()->getReturnType();
2801 /// Determine whether this conversion function is a conversion from
2802 /// a lambda closure type to a block pointer.
2803 bool isLambdaToBlockPointerConversion() const;
2805 CXXConversionDecl *getCanonicalDecl() override {
2806 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2808 const CXXConversionDecl *getCanonicalDecl() const {
2809 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2812 // Implement isa/cast/dyncast/etc.
2813 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2814 static bool classofKind(Kind K) { return K == CXXConversion; }
2817 /// Represents a linkage specification.
2821 /// extern "C" void foo();
2823 class LinkageSpecDecl : public Decl, public DeclContext {
2824 virtual void anchor();
2827 /// Represents the language in a linkage specification.
2829 /// The values are part of the serialization ABI for
2830 /// ASTs and cannot be changed without altering that ABI. To help
2831 /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
2832 /// from the dwarf standard.
2834 lang_c = /* DW_LANG_C */ 0x0002,
2835 lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004
2839 /// The language for this linkage specification.
2840 unsigned Language : 3;
2842 /// True if this linkage spec has braces.
2844 /// This is needed so that hasBraces() returns the correct result while the
2845 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
2846 /// not used, so it doesn't need to be serialized.
2847 unsigned HasBraces : 1;
2849 /// The source location for the extern keyword.
2850 SourceLocation ExternLoc;
2852 /// The source location for the right brace (if valid).
2853 SourceLocation RBraceLoc;
2855 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2856 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces)
2857 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
2858 Language(lang), HasBraces(HasBraces), ExternLoc(ExternLoc),
2859 RBraceLoc(SourceLocation()) {}
2862 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2863 SourceLocation ExternLoc,
2864 SourceLocation LangLoc, LanguageIDs Lang,
2866 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2868 /// Return the language specified by this linkage specification.
2869 LanguageIDs getLanguage() const { return LanguageIDs(Language); }
2871 /// Set the language specified by this linkage specification.
2872 void setLanguage(LanguageIDs L) { Language = L; }
2874 /// Determines whether this linkage specification had braces in
2875 /// its syntactic form.
2876 bool hasBraces() const {
2877 assert(!RBraceLoc.isValid() || HasBraces);
2881 SourceLocation getExternLoc() const { return ExternLoc; }
2882 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2883 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2884 void setRBraceLoc(SourceLocation L) {
2886 HasBraces = RBraceLoc.isValid();
2889 SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
2890 SourceLocation getEndLoc() const LLVM_READONLY {
2892 return getRBraceLoc();
2893 // No braces: get the end location of the (only) declaration in context
2895 return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
2898 SourceRange getSourceRange() const override LLVM_READONLY {
2899 return SourceRange(ExternLoc, getLocEnd());
2902 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2903 static bool classofKind(Kind K) { return K == LinkageSpec; }
2905 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2906 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2909 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2910 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2914 /// Represents C++ using-directive.
2918 /// using namespace std;
2921 /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2922 /// artificial names for all using-directives in order to store
2923 /// them in DeclContext effectively.
2924 class UsingDirectiveDecl : public NamedDecl {
2925 /// The location of the \c using keyword.
2926 SourceLocation UsingLoc;
2928 /// The location of the \c namespace keyword.
2929 SourceLocation NamespaceLoc;
2931 /// The nested-name-specifier that precedes the namespace.
2932 NestedNameSpecifierLoc QualifierLoc;
2934 /// The namespace nominated by this using-directive.
2935 NamedDecl *NominatedNamespace;
2937 /// Enclosing context containing both using-directive and nominated
2939 DeclContext *CommonAncestor;
2941 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2942 SourceLocation NamespcLoc,
2943 NestedNameSpecifierLoc QualifierLoc,
2944 SourceLocation IdentLoc,
2945 NamedDecl *Nominated,
2946 DeclContext *CommonAncestor)
2947 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2948 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2949 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2951 /// Returns special DeclarationName used by using-directives.
2953 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2954 /// its lookup structure.
2955 static DeclarationName getName() {
2956 return DeclarationName::getUsingDirectiveName();
2959 void anchor() override;
2962 friend class ASTDeclReader;
2964 // Friend for getUsingDirectiveName.
2965 friend class DeclContext;
2967 /// Retrieve the nested-name-specifier that qualifies the
2968 /// name of the namespace, with source-location information.
2969 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2971 /// Retrieve the nested-name-specifier that qualifies the
2972 /// name of the namespace.
2973 NestedNameSpecifier *getQualifier() const {
2974 return QualifierLoc.getNestedNameSpecifier();
2977 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2978 const NamedDecl *getNominatedNamespaceAsWritten() const {
2979 return NominatedNamespace;
2982 /// Returns the namespace nominated by this using-directive.
2983 NamespaceDecl *getNominatedNamespace();
2985 const NamespaceDecl *getNominatedNamespace() const {
2986 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2989 /// Returns the common ancestor context of this using-directive and
2990 /// its nominated namespace.
2991 DeclContext *getCommonAncestor() { return CommonAncestor; }
2992 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2994 /// Return the location of the \c using keyword.
2995 SourceLocation getUsingLoc() const { return UsingLoc; }
2997 // FIXME: Could omit 'Key' in name.
2998 /// Returns the location of the \c namespace keyword.
2999 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
3001 /// Returns the location of this using declaration's identifier.
3002 SourceLocation getIdentLocation() const { return getLocation(); }
3004 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
3005 SourceLocation UsingLoc,
3006 SourceLocation NamespaceLoc,
3007 NestedNameSpecifierLoc QualifierLoc,
3008 SourceLocation IdentLoc,
3009 NamedDecl *Nominated,
3010 DeclContext *CommonAncestor);
3011 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3013 SourceRange getSourceRange() const override LLVM_READONLY {
3014 return SourceRange(UsingLoc, getLocation());
3017 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3018 static bool classofKind(Kind K) { return K == UsingDirective; }
3021 /// Represents a C++ namespace alias.
3026 /// namespace Foo = Bar;
3028 class NamespaceAliasDecl : public NamedDecl,
3029 public Redeclarable<NamespaceAliasDecl> {
3030 friend class ASTDeclReader;
3032 /// The location of the \c namespace keyword.
3033 SourceLocation NamespaceLoc;
3035 /// The location of the namespace's identifier.
3037 /// This is accessed by TargetNameLoc.
3038 SourceLocation IdentLoc;
3040 /// The nested-name-specifier that precedes the namespace.
3041 NestedNameSpecifierLoc QualifierLoc;
3043 /// The Decl that this alias points to, either a NamespaceDecl or
3044 /// a NamespaceAliasDecl.
3045 NamedDecl *Namespace;
3047 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3048 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3049 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3050 SourceLocation IdentLoc, NamedDecl *Namespace)
3051 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3052 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3053 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3055 void anchor() override;
3057 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3059 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3060 NamespaceAliasDecl *getPreviousDeclImpl() override;
3061 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3064 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3065 SourceLocation NamespaceLoc,
3066 SourceLocation AliasLoc,
3067 IdentifierInfo *Alias,
3068 NestedNameSpecifierLoc QualifierLoc,
3069 SourceLocation IdentLoc,
3070 NamedDecl *Namespace);
3072 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3074 using redecl_range = redeclarable_base::redecl_range;
3075 using redecl_iterator = redeclarable_base::redecl_iterator;
3077 using redeclarable_base::redecls_begin;
3078 using redeclarable_base::redecls_end;
3079 using redeclarable_base::redecls;
3080 using redeclarable_base::getPreviousDecl;
3081 using redeclarable_base::getMostRecentDecl;
3083 NamespaceAliasDecl *getCanonicalDecl() override {
3084 return getFirstDecl();
3086 const NamespaceAliasDecl *getCanonicalDecl() const {
3087 return getFirstDecl();
3090 /// Retrieve the nested-name-specifier that qualifies the
3091 /// name of the namespace, with source-location information.
3092 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3094 /// Retrieve the nested-name-specifier that qualifies the
3095 /// name of the namespace.
3096 NestedNameSpecifier *getQualifier() const {
3097 return QualifierLoc.getNestedNameSpecifier();
3100 /// Retrieve the namespace declaration aliased by this directive.
3101 NamespaceDecl *getNamespace() {
3102 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3103 return AD->getNamespace();
3105 return cast<NamespaceDecl>(Namespace);
3108 const NamespaceDecl *getNamespace() const {
3109 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3112 /// Returns the location of the alias name, i.e. 'foo' in
3113 /// "namespace foo = ns::bar;".
3114 SourceLocation getAliasLoc() const { return getLocation(); }
3116 /// Returns the location of the \c namespace keyword.
3117 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3119 /// Returns the location of the identifier in the named namespace.
3120 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3122 /// Retrieve the namespace that this alias refers to, which
3123 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3124 NamedDecl *getAliasedNamespace() const { return Namespace; }
3126 SourceRange getSourceRange() const override LLVM_READONLY {
3127 return SourceRange(NamespaceLoc, IdentLoc);
3130 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3131 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3134 /// Represents a shadow declaration introduced into a scope by a
3135 /// (resolved) using declaration.
3143 /// using A::foo; // <- a UsingDecl
3144 /// // Also creates a UsingShadowDecl for A::foo() in B
3147 class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3148 friend class UsingDecl;
3150 /// The referenced declaration.
3151 NamedDecl *Underlying = nullptr;
3153 /// The using declaration which introduced this decl or the next using
3154 /// shadow declaration contained in the aforementioned using declaration.
3155 NamedDecl *UsingOrNextShadow = nullptr;
3157 void anchor() override;
3159 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3161 UsingShadowDecl *getNextRedeclarationImpl() override {
3162 return getNextRedeclaration();
3165 UsingShadowDecl *getPreviousDeclImpl() override {
3166 return getPreviousDecl();
3169 UsingShadowDecl *getMostRecentDeclImpl() override {
3170 return getMostRecentDecl();
3174 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3175 UsingDecl *Using, NamedDecl *Target);
3176 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3179 friend class ASTDeclReader;
3180 friend class ASTDeclWriter;
3182 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3183 SourceLocation Loc, UsingDecl *Using,
3184 NamedDecl *Target) {
3185 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3188 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3190 using redecl_range = redeclarable_base::redecl_range;
3191 using redecl_iterator = redeclarable_base::redecl_iterator;
3193 using redeclarable_base::redecls_begin;
3194 using redeclarable_base::redecls_end;
3195 using redeclarable_base::redecls;
3196 using redeclarable_base::getPreviousDecl;
3197 using redeclarable_base::getMostRecentDecl;
3198 using redeclarable_base::isFirstDecl;
3200 UsingShadowDecl *getCanonicalDecl() override {
3201 return getFirstDecl();
3203 const UsingShadowDecl *getCanonicalDecl() const {
3204 return getFirstDecl();
3207 /// Gets the underlying declaration which has been brought into the
3209 NamedDecl *getTargetDecl() const { return Underlying; }
3211 /// Sets the underlying declaration which has been brought into the
3213 void setTargetDecl(NamedDecl *ND) {
3214 assert(ND && "Target decl is null!");
3216 // A UsingShadowDecl is never a friend or local extern declaration, even
3217 // if it is a shadow declaration for one.
3218 IdentifierNamespace =
3219 ND->getIdentifierNamespace() &
3220 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3223 /// Gets the using declaration to which this declaration is tied.
3224 UsingDecl *getUsingDecl() const;
3226 /// The next using shadow declaration contained in the shadow decl
3227 /// chain of the using declaration which introduced this decl.
3228 UsingShadowDecl *getNextUsingShadowDecl() const {
3229 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3232 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3233 static bool classofKind(Kind K) {
3234 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3238 /// Represents a shadow constructor declaration introduced into a
3239 /// class by a C++11 using-declaration that names a constructor.
3243 /// struct Base { Base(int); };
3244 /// struct Derived {
3245 /// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3248 class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3249 /// If this constructor using declaration inherted the constructor
3250 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3251 /// in the named direct base class from which the declaration was inherited.
3252 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3254 /// If this constructor using declaration inherted the constructor
3255 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3256 /// that will be used to construct the unique direct or virtual base class
3257 /// that receives the constructor arguments.
3258 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3260 /// \c true if the constructor ultimately named by this using shadow
3261 /// declaration is within a virtual base class subobject of the class that
3262 /// contains this declaration.
3263 unsigned IsVirtual : 1;
3265 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3266 UsingDecl *Using, NamedDecl *Target,
3267 bool TargetInVirtualBase)
3268 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3269 Target->getUnderlyingDecl()),
3270 NominatedBaseClassShadowDecl(
3271 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3272 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3273 IsVirtual(TargetInVirtualBase) {
3274 // If we found a constructor that chains to a constructor for a virtual
3275 // base, we should directly call that virtual base constructor instead.
3276 // FIXME: This logic belongs in Sema.
3277 if (NominatedBaseClassShadowDecl &&
3278 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3279 ConstructedBaseClassShadowDecl =
3280 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3285 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3286 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3288 void anchor() override;
3291 friend class ASTDeclReader;
3292 friend class ASTDeclWriter;
3294 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3296 UsingDecl *Using, NamedDecl *Target,
3298 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3301 /// Returns the parent of this using shadow declaration, which
3302 /// is the class in which this is declared.
3304 const CXXRecordDecl *getParent() const {
3305 return cast<CXXRecordDecl>(getDeclContext());
3307 CXXRecordDecl *getParent() {
3308 return cast<CXXRecordDecl>(getDeclContext());
3312 /// Get the inheriting constructor declaration for the direct base
3313 /// class from which this using shadow declaration was inherited, if there is
3314 /// one. This can be different for each redeclaration of the same shadow decl.
3315 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3316 return NominatedBaseClassShadowDecl;
3319 /// Get the inheriting constructor declaration for the base class
3320 /// for which we don't have an explicit initializer, if there is one.
3321 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3322 return ConstructedBaseClassShadowDecl;
3325 /// Get the base class that was named in the using declaration. This
3326 /// can be different for each redeclaration of this same shadow decl.
3327 CXXRecordDecl *getNominatedBaseClass() const;
3329 /// Get the base class whose constructor or constructor shadow
3330 /// declaration is passed the constructor arguments.
3331 CXXRecordDecl *getConstructedBaseClass() const {
3332 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3333 ? ConstructedBaseClassShadowDecl
3335 ->getDeclContext());
3338 /// Returns \c true if the constructed base class is a virtual base
3339 /// class subobject of this declaration's class.
3340 bool constructsVirtualBase() const {
3344 /// Get the constructor or constructor template in the derived class
3345 /// correspnding to this using shadow declaration, if it has been implicitly
3346 /// declared already.
3347 CXXConstructorDecl *getConstructor() const;
3348 void setConstructor(NamedDecl *Ctor);
3350 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3351 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3354 /// Represents a C++ using-declaration.
3358 /// using someNameSpace::someIdentifier;
3360 class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3361 /// The source location of the 'using' keyword itself.
3362 SourceLocation UsingLocation;
3364 /// The nested-name-specifier that precedes the name.
3365 NestedNameSpecifierLoc QualifierLoc;
3367 /// Provides source/type location info for the declaration name
3368 /// embedded in the ValueDecl base class.
3369 DeclarationNameLoc DNLoc;
3371 /// The first shadow declaration of the shadow decl chain associated
3372 /// with this using declaration.
3374 /// The bool member of the pair store whether this decl has the \c typename
3376 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3378 UsingDecl(DeclContext *DC, SourceLocation UL,
3379 NestedNameSpecifierLoc QualifierLoc,
3380 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3381 : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3382 UsingLocation(UL), QualifierLoc(QualifierLoc),
3383 DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3386 void anchor() override;
3389 friend class ASTDeclReader;
3390 friend class ASTDeclWriter;
3392 /// Return the source location of the 'using' keyword.
3393 SourceLocation getUsingLoc() const { return UsingLocation; }
3395 /// Set the source location of the 'using' keyword.
3396 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3398 /// Retrieve the nested-name-specifier that qualifies the name,
3399 /// with source-location information.
3400 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3402 /// Retrieve the nested-name-specifier that qualifies the name.
3403 NestedNameSpecifier *getQualifier() const {
3404 return QualifierLoc.getNestedNameSpecifier();
3407 DeclarationNameInfo getNameInfo() const {
3408 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3411 /// Return true if it is a C++03 access declaration (no 'using').
3412 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3414 /// Return true if the using declaration has 'typename'.
3415 bool hasTypename() const { return FirstUsingShadow.getInt(); }
3417 /// Sets whether the using declaration has 'typename'.
3418 void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3420 /// Iterates through the using shadow declarations associated with
3421 /// this using declaration.
3422 class shadow_iterator {
3423 /// The current using shadow declaration.
3424 UsingShadowDecl *Current = nullptr;
3427 using value_type = UsingShadowDecl *;
3428 using reference = UsingShadowDecl *;
3429 using pointer = UsingShadowDecl *;
3430 using iterator_category = std::forward_iterator_tag;
3431 using difference_type = std::ptrdiff_t;
3433 shadow_iterator() = default;
3434 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3436 reference operator*() const { return Current; }
3437 pointer operator->() const { return Current; }
3439 shadow_iterator& operator++() {
3440 Current = Current->getNextUsingShadowDecl();
3444 shadow_iterator operator++(int) {
3445 shadow_iterator tmp(*this);
3450 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3451 return x.Current == y.Current;
3453 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3454 return x.Current != y.Current;
3458 using shadow_range = llvm::iterator_range<shadow_iterator>;
3460 shadow_range shadows() const {
3461 return shadow_range(shadow_begin(), shadow_end());
3464 shadow_iterator shadow_begin() const {
3465 return shadow_iterator(FirstUsingShadow.getPointer());
3468 shadow_iterator shadow_end() const { return shadow_iterator(); }
3470 /// Return the number of shadowed declarations associated with this
3471 /// using declaration.
3472 unsigned shadow_size() const {
3473 return std::distance(shadow_begin(), shadow_end());
3476 void addShadowDecl(UsingShadowDecl *S);
3477 void removeShadowDecl(UsingShadowDecl *S);
3479 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3480 SourceLocation UsingL,
3481 NestedNameSpecifierLoc QualifierLoc,
3482 const DeclarationNameInfo &NameInfo,
3483 bool HasTypenameKeyword);
3485 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3487 SourceRange getSourceRange() const override LLVM_READONLY;
3489 /// Retrieves the canonical declaration of this declaration.
3490 UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3491 const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3493 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3494 static bool classofKind(Kind K) { return K == Using; }
3497 /// Represents a pack of using declarations that a single
3498 /// using-declarator pack-expanded into.
3501 /// template<typename ...T> struct X : T... {
3502 /// using T::operator()...;
3503 /// using T::operator T...;
3507 /// In the second case above, the UsingPackDecl will have the name
3508 /// 'operator T' (which contains an unexpanded pack), but the individual
3509 /// UsingDecls and UsingShadowDecls will have more reasonable names.
3510 class UsingPackDecl final
3511 : public NamedDecl, public Mergeable<UsingPackDecl>,
3512 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3513 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3514 /// which this waas instantiated.
3515 NamedDecl *InstantiatedFrom;
3517 /// The number of using-declarations created by this pack expansion.
3518 unsigned NumExpansions;
3520 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3521 ArrayRef<NamedDecl *> UsingDecls)
3522 : NamedDecl(UsingPack, DC,
3523 InstantiatedFrom ? InstantiatedFrom->getLocation()
3525 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3526 : DeclarationName()),
3527 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3528 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3529 getTrailingObjects<NamedDecl *>());
3532 void anchor() override;
3535 friend class ASTDeclReader;
3536 friend class ASTDeclWriter;
3537 friend TrailingObjects;
3539 /// Get the using declaration from which this was instantiated. This will
3540 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3541 /// that is a pack expansion.
3542 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3544 /// Get the set of using declarations that this pack expanded into. Note that
3545 /// some of these may still be unresolved.
3546 ArrayRef<NamedDecl *> expansions() const {
3547 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3550 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3551 NamedDecl *InstantiatedFrom,
3552 ArrayRef<NamedDecl *> UsingDecls);
3554 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3555 unsigned NumExpansions);
3557 SourceRange getSourceRange() const override LLVM_READONLY {
3558 return InstantiatedFrom->getSourceRange();
3561 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3562 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3564 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3565 static bool classofKind(Kind K) { return K == UsingPack; }
3568 /// Represents a dependent using declaration which was not marked with
3571 /// Unlike non-dependent using declarations, these *only* bring through
3572 /// non-types; otherwise they would break two-phase lookup.
3575 /// template \<class T> class A : public Base<T> {
3576 /// using Base<T>::foo;
3579 class UnresolvedUsingValueDecl : public ValueDecl,
3580 public Mergeable<UnresolvedUsingValueDecl> {
3581 /// The source location of the 'using' keyword
3582 SourceLocation UsingLocation;
3584 /// If this is a pack expansion, the location of the '...'.
3585 SourceLocation EllipsisLoc;
3587 /// The nested-name-specifier that precedes the name.
3588 NestedNameSpecifierLoc QualifierLoc;
3590 /// Provides source/type location info for the declaration name
3591 /// embedded in the ValueDecl base class.
3592 DeclarationNameLoc DNLoc;
3594 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3595 SourceLocation UsingLoc,
3596 NestedNameSpecifierLoc QualifierLoc,
3597 const DeclarationNameInfo &NameInfo,
3598 SourceLocation EllipsisLoc)
3599 : ValueDecl(UnresolvedUsingValue, DC,
3600 NameInfo.getLoc(), NameInfo.getName(), Ty),
3601 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3602 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3604 void anchor() override;
3607 friend class ASTDeclReader;
3608 friend class ASTDeclWriter;
3610 /// Returns the source location of the 'using' keyword.
3611 SourceLocation getUsingLoc() const { return UsingLocation; }
3613 /// Set the source location of the 'using' keyword.
3614 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3616 /// Return true if it is a C++03 access declaration (no 'using').
3617 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3619 /// Retrieve the nested-name-specifier that qualifies the name,
3620 /// with source-location information.
3621 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3623 /// Retrieve the nested-name-specifier that qualifies the name.
3624 NestedNameSpecifier *getQualifier() const {
3625 return QualifierLoc.getNestedNameSpecifier();
3628 DeclarationNameInfo getNameInfo() const {
3629 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3632 /// Determine whether this is a pack expansion.
3633 bool isPackExpansion() const {
3634 return EllipsisLoc.isValid();
3637 /// Get the location of the ellipsis if this is a pack expansion.
3638 SourceLocation getEllipsisLoc() const {
3642 static UnresolvedUsingValueDecl *
3643 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3644 NestedNameSpecifierLoc QualifierLoc,
3645 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3647 static UnresolvedUsingValueDecl *
3648 CreateDeserialized(ASTContext &C, unsigned ID);
3650 SourceRange getSourceRange() const override LLVM_READONLY;
3652 /// Retrieves the canonical declaration of this declaration.
3653 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3654 return getFirstDecl();
3656 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3657 return getFirstDecl();
3660 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3661 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3664 /// Represents a dependent using declaration which was marked with
3668 /// template \<class T> class A : public Base<T> {
3669 /// using typename Base<T>::foo;
3673 /// The type associated with an unresolved using typename decl is
3674 /// currently always a typename type.
3675 class UnresolvedUsingTypenameDecl
3677 public Mergeable<UnresolvedUsingTypenameDecl> {
3678 friend class ASTDeclReader;
3680 /// The source location of the 'typename' keyword
3681 SourceLocation TypenameLocation;
3683 /// If this is a pack expansion, the location of the '...'.
3684 SourceLocation EllipsisLoc;
3686 /// The nested-name-specifier that precedes the name.
3687 NestedNameSpecifierLoc QualifierLoc;
3689 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3690 SourceLocation TypenameLoc,
3691 NestedNameSpecifierLoc QualifierLoc,
3692 SourceLocation TargetNameLoc,
3693 IdentifierInfo *TargetName,
3694 SourceLocation EllipsisLoc)
3695 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3697 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3698 QualifierLoc(QualifierLoc) {}
3700 void anchor() override;
3703 /// Returns the source location of the 'using' keyword.
3704 SourceLocation getUsingLoc() const { return getLocStart(); }
3706 /// Returns the source location of the 'typename' keyword.
3707 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3709 /// Retrieve the nested-name-specifier that qualifies the name,
3710 /// with source-location information.
3711 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3713 /// Retrieve the nested-name-specifier that qualifies the name.
3714 NestedNameSpecifier *getQualifier() const {
3715 return QualifierLoc.getNestedNameSpecifier();
3718 DeclarationNameInfo getNameInfo() const {
3719 return DeclarationNameInfo(getDeclName(), getLocation());
3722 /// Determine whether this is a pack expansion.
3723 bool isPackExpansion() const {
3724 return EllipsisLoc.isValid();
3727 /// Get the location of the ellipsis if this is a pack expansion.
3728 SourceLocation getEllipsisLoc() const {
3732 static UnresolvedUsingTypenameDecl *
3733 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3734 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3735 SourceLocation TargetNameLoc, DeclarationName TargetName,
3736 SourceLocation EllipsisLoc);
3738 static UnresolvedUsingTypenameDecl *
3739 CreateDeserialized(ASTContext &C, unsigned ID);
3741 /// Retrieves the canonical declaration of this declaration.
3742 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3743 return getFirstDecl();
3745 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3746 return getFirstDecl();
3749 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3750 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3753 /// Represents a C++11 static_assert declaration.
3754 class StaticAssertDecl : public Decl {
3755 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3756 StringLiteral *Message;
3757 SourceLocation RParenLoc;
3759 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3760 Expr *AssertExpr, StringLiteral *Message,
3761 SourceLocation RParenLoc, bool Failed)
3762 : Decl(StaticAssert, DC, StaticAssertLoc),
3763 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3764 RParenLoc(RParenLoc) {}
3766 virtual void anchor();
3769 friend class ASTDeclReader;
3771 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3772 SourceLocation StaticAssertLoc,
3773 Expr *AssertExpr, StringLiteral *Message,
3774 SourceLocation RParenLoc, bool Failed);
3775 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3777 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3778 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3780 StringLiteral *getMessage() { return Message; }
3781 const StringLiteral *getMessage() const { return Message; }
3783 bool isFailed() const { return AssertExprAndFailed.getInt(); }
3785 SourceLocation getRParenLoc() const { return RParenLoc; }
3787 SourceRange getSourceRange() const override LLVM_READONLY {
3788 return SourceRange(getLocation(), getRParenLoc());
3791 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3792 static bool classofKind(Kind K) { return K == StaticAssert; }
3795 /// A binding in a decomposition declaration. For instance, given:
3798 /// auto &[a, b, c] = n;
3800 /// a, b, and c are BindingDecls, whose bindings are the expressions
3801 /// x[0], x[1], and x[2] respectively, where x is the implicit
3802 /// DecompositionDecl of type 'int (&)[3]'.
3803 class BindingDecl : public ValueDecl {
3804 /// The binding represented by this declaration. References to this
3805 /// declaration are effectively equivalent to this expression (except
3806 /// that it is only evaluated once at the point of declaration of the
3808 Expr *Binding = nullptr;
3810 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3811 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3813 void anchor() override;
3816 friend class ASTDeclReader;
3818 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3819 SourceLocation IdLoc, IdentifierInfo *Id);
3820 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3822 /// Get the expression to which this declaration is bound. This may be null
3823 /// in two different cases: while parsing the initializer for the
3824 /// decomposition declaration, and when the initializer is type-dependent.
3825 Expr *getBinding() const { return Binding; }
3827 /// Get the variable (if any) that holds the value of evaluating the binding.
3828 /// Only present for user-defined bindings for tuple-like types.
3829 VarDecl *getHoldingVar() const;
3831 /// Set the binding for this BindingDecl, along with its declared type (which
3832 /// should be a possibly-cv-qualified form of the type of the binding, or a
3833 /// reference to such a type).
3834 void setBinding(QualType DeclaredType, Expr *Binding) {
3835 setType(DeclaredType);
3836 this->Binding = Binding;
3839 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3840 static bool classofKind(Kind K) { return K == Decl::Binding; }
3843 /// A decomposition declaration. For instance, given:
3846 /// auto &[a, b, c] = n;
3848 /// the second line declares a DecompositionDecl of type 'int (&)[3]', and
3849 /// three BindingDecls (named a, b, and c). An instance of this class is always
3850 /// unnamed, but behaves in almost all other respects like a VarDecl.
3851 class DecompositionDecl final
3853 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
3854 /// The number of BindingDecl*s following this object.
3855 unsigned NumBindings;
3857 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3858 SourceLocation LSquareLoc, QualType T,
3859 TypeSourceInfo *TInfo, StorageClass SC,
3860 ArrayRef<BindingDecl *> Bindings)
3861 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
3863 NumBindings(Bindings.size()) {
3864 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
3865 getTrailingObjects<BindingDecl *>());
3868 void anchor() override;
3871 friend class ASTDeclReader;
3872 friend TrailingObjects;
3874 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
3875 SourceLocation StartLoc,
3876 SourceLocation LSquareLoc,
3877 QualType T, TypeSourceInfo *TInfo,
3879 ArrayRef<BindingDecl *> Bindings);
3880 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3881 unsigned NumBindings);
3883 ArrayRef<BindingDecl *> bindings() const {
3884 return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
3887 void printName(raw_ostream &os) const override;
3889 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3890 static bool classofKind(Kind K) { return K == Decomposition; }
3893 /// An instance of this class represents the declaration of a property
3894 /// member. This is a Microsoft extension to C++, first introduced in
3895 /// Visual Studio .NET 2003 as a parallel to similar features in C#
3896 /// and Managed C++.
3898 /// A property must always be a non-static class member.
3900 /// A property member superficially resembles a non-static data
3901 /// member, except preceded by a property attribute:
3902 /// __declspec(property(get=GetX, put=PutX)) int x;
3903 /// Either (but not both) of the 'get' and 'put' names may be omitted.
3905 /// A reference to a property is always an lvalue. If the lvalue
3906 /// undergoes lvalue-to-rvalue conversion, then a getter name is
3907 /// required, and that member is called with no arguments.
3908 /// If the lvalue is assigned into, then a setter name is required,
3909 /// and that member is called with one argument, the value assigned.
3910 /// Both operations are potentially overloaded. Compound assignments
3911 /// are permitted, as are the increment and decrement operators.
3913 /// The getter and putter methods are permitted to be overloaded,
3914 /// although their return and parameter types are subject to certain
3915 /// restrictions according to the type of the property.
3917 /// A property declared using an incomplete array type may
3918 /// additionally be subscripted, adding extra parameters to the getter
3919 /// and putter methods.
3920 class MSPropertyDecl : public DeclaratorDecl {
3921 IdentifierInfo *GetterId, *SetterId;
3923 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
3924 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
3925 IdentifierInfo *Getter, IdentifierInfo *Setter)
3926 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
3927 GetterId(Getter), SetterId(Setter) {}
3930 friend class ASTDeclReader;
3932 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
3933 SourceLocation L, DeclarationName N, QualType T,
3934 TypeSourceInfo *TInfo, SourceLocation StartL,
3935 IdentifierInfo *Getter, IdentifierInfo *Setter);
3936 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3938 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
3940 bool hasGetter() const { return GetterId != nullptr; }
3941 IdentifierInfo* getGetterId() const { return GetterId; }
3942 bool hasSetter() const { return SetterId != nullptr; }
3943 IdentifierInfo* getSetterId() const { return SetterId; }
3946 /// Insertion operator for diagnostics. This allows sending an AccessSpecifier
3947 /// into a diagnostic with <<.
3948 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3949 AccessSpecifier AS);
3951 const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
3952 AccessSpecifier AS);
3954 } // namespace clang
3956 #endif // LLVM_CLANG_AST_DECLCXX_H