1 //===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Defines the C++ Decl subclasses, other than those for templates
11 /// (found in DeclTemplate.h) and friends (in DeclFriend.h).
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_AST_DECLCXX_H
16 #define LLVM_CLANG_AST_DECLCXX_H
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTUnresolvedSet.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/LambdaCapture.h"
27 #include "clang/AST/NestedNameSpecifier.h"
28 #include "clang/AST/Redeclarable.h"
29 #include "clang/AST/Stmt.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/UnresolvedSet.h"
33 #include "clang/Basic/LLVM.h"
34 #include "clang/Basic/Lambda.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/OperatorKinds.h"
37 #include "clang/Basic/SourceLocation.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/PointerIntPair.h"
42 #include "llvm/ADT/PointerUnion.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/iterator_range.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/PointerLikeTypeTraits.h"
48 #include "llvm/Support/TrailingObjects.h"
57 class ClassTemplateDecl;
58 class ConstructorUsingShadowDecl;
61 class CXXConstructorDecl;
62 class CXXDestructorDecl;
63 class CXXFinalOverriderMap;
64 class CXXIndirectPrimaryBaseSet;
66 class DecompositionDecl;
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 getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
237 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
239 /// Get the location at which the base class type was written.
240 SourceLocation getBaseTypeLoc() const LLVM_READONLY {
241 return BaseTypeInfo->getTypeLoc().getBeginLoc();
244 /// Determines whether the base class is a virtual base class (or not).
245 bool isVirtual() const { return Virtual; }
247 /// Determine whether this base class is a base of a class declared
248 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
249 bool isBaseOfClass() const { return BaseOfClass; }
251 /// Determine whether this base specifier is a pack expansion.
252 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
254 /// Determine whether this base class's constructors get inherited.
255 bool getInheritConstructors() const { return InheritConstructors; }
257 /// Set that this base class's constructors should be inherited.
258 void setInheritConstructors(bool Inherit = true) {
259 InheritConstructors = Inherit;
262 /// For a pack expansion, determine the location of the ellipsis.
263 SourceLocation getEllipsisLoc() const {
267 /// Returns the access specifier for this base specifier.
269 /// This is the actual base specifier as used for semantic analysis, so
270 /// the result can never be AS_none. To retrieve the access specifier as
271 /// written in the source code, use getAccessSpecifierAsWritten().
272 AccessSpecifier getAccessSpecifier() const {
273 if ((AccessSpecifier)Access == AS_none)
274 return BaseOfClass? AS_private : AS_public;
276 return (AccessSpecifier)Access;
279 /// Retrieves the access specifier as written in the source code
280 /// (which may mean that no access specifier was explicitly written).
282 /// Use getAccessSpecifier() to retrieve the access specifier for use in
283 /// semantic analysis.
284 AccessSpecifier getAccessSpecifierAsWritten() const {
285 return (AccessSpecifier)Access;
288 /// Retrieves the type of the base class.
290 /// This type will always be an unqualified class type.
291 QualType getType() const {
292 return BaseTypeInfo->getType().getUnqualifiedType();
295 /// Retrieves the type and source location of the base class.
296 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
299 /// Represents a C++ struct/union/class.
300 class CXXRecordDecl : public RecordDecl {
301 friend class ASTDeclReader;
302 friend class ASTDeclWriter;
303 friend class ASTNodeImporter;
304 friend class ASTReader;
305 friend class ASTRecordWriter;
306 friend class ASTWriter;
307 friend class DeclContext;
308 friend class LambdaExpr;
310 friend void FunctionDecl::setPure(bool);
311 friend void TagDecl::startDefinition();
313 /// Values used in DefinitionData fields to represent special members.
314 enum SpecialMemberFlags {
315 SMF_DefaultConstructor = 0x1,
316 SMF_CopyConstructor = 0x2,
317 SMF_MoveConstructor = 0x4,
318 SMF_CopyAssignment = 0x8,
319 SMF_MoveAssignment = 0x10,
320 SMF_Destructor = 0x20,
324 struct DefinitionData {
325 /// True if this class has any user-declared constructors.
326 unsigned UserDeclaredConstructor : 1;
328 /// The user-declared special members which this class has.
329 unsigned UserDeclaredSpecialMembers : 6;
331 /// True when this class is an aggregate.
332 unsigned Aggregate : 1;
334 /// True when this class is a POD-type.
335 unsigned PlainOldData : 1;
337 /// True when this class is empty for traits purposes, that is:
338 /// * has no data members other than 0-width bit-fields and empty fields
339 /// marked [[no_unique_address]]
340 /// * has no virtual function/base, and
341 /// * doesn't inherit from a non-empty class.
342 /// 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 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
982 /// Determine whether this class has any user-declared constructors.
984 /// When true, a default constructor will not be implicitly declared.
985 bool hasUserDeclaredConstructor() const {
986 return data().UserDeclaredConstructor;
989 /// Whether this class has a user-provided default constructor
991 bool hasUserProvidedDefaultConstructor() const {
992 return data().UserProvidedDefaultConstructor;
995 /// Determine whether this class has a user-declared copy constructor.
997 /// When false, a copy constructor will be implicitly declared.
998 bool hasUserDeclaredCopyConstructor() const {
999 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
1002 /// Determine whether this class needs an implicit copy
1003 /// constructor to be lazily declared.
1004 bool needsImplicitCopyConstructor() const {
1005 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
1008 /// Determine whether we need to eagerly declare a defaulted copy
1009 /// constructor for this class.
1010 bool needsOverloadResolutionForCopyConstructor() const {
1011 // C++17 [class.copy.ctor]p6:
1012 // If the class definition declares a move constructor or move assignment
1013 // operator, the implicitly declared copy constructor is defined as
1015 // In MSVC mode, sometimes a declared move assignment does not delete an
1016 // implicit copy constructor, so defer this choice to Sema.
1017 if (data().UserDeclaredSpecialMembers &
1018 (SMF_MoveConstructor | SMF_MoveAssignment))
1020 return data().NeedOverloadResolutionForCopyConstructor;
1023 /// Determine whether an implicit copy constructor for this type
1024 /// would have a parameter with a const-qualified reference type.
1025 bool implicitCopyConstructorHasConstParam() const {
1026 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
1028 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
1031 /// Determine whether this class has a copy constructor with
1032 /// a parameter type which is a reference to a const-qualified type.
1033 bool hasCopyConstructorWithConstParam() const {
1034 return data().HasDeclaredCopyConstructorWithConstParam ||
1035 (needsImplicitCopyConstructor() &&
1036 implicitCopyConstructorHasConstParam());
1039 /// Whether this class has a user-declared move constructor or
1040 /// assignment operator.
1042 /// When false, a move constructor and assignment operator may be
1043 /// implicitly declared.
1044 bool hasUserDeclaredMoveOperation() const {
1045 return data().UserDeclaredSpecialMembers &
1046 (SMF_MoveConstructor | SMF_MoveAssignment);
1049 /// Determine whether this class has had a move constructor
1050 /// declared by the user.
1051 bool hasUserDeclaredMoveConstructor() const {
1052 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
1055 /// Determine whether this class has a move constructor.
1056 bool hasMoveConstructor() const {
1057 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
1058 needsImplicitMoveConstructor();
1061 /// Set that we attempted to declare an implicit copy
1062 /// constructor, but overload resolution failed so we deleted it.
1063 void setImplicitCopyConstructorIsDeleted() {
1064 assert((data().DefaultedCopyConstructorIsDeleted ||
1065 needsOverloadResolutionForCopyConstructor()) &&
1066 "Copy constructor should not be deleted");
1067 data().DefaultedCopyConstructorIsDeleted = true;
1070 /// Set that we attempted to declare an implicit move
1071 /// constructor, but overload resolution failed so we deleted it.
1072 void setImplicitMoveConstructorIsDeleted() {
1073 assert((data().DefaultedMoveConstructorIsDeleted ||
1074 needsOverloadResolutionForMoveConstructor()) &&
1075 "move constructor should not be deleted");
1076 data().DefaultedMoveConstructorIsDeleted = true;
1079 /// Set that we attempted to declare an implicit destructor,
1080 /// but overload resolution failed so we deleted it.
1081 void setImplicitDestructorIsDeleted() {
1082 assert((data().DefaultedDestructorIsDeleted ||
1083 needsOverloadResolutionForDestructor()) &&
1084 "destructor should not be deleted");
1085 data().DefaultedDestructorIsDeleted = true;
1088 /// Determine whether this class should get an implicit move
1089 /// constructor or if any existing special member function inhibits this.
1090 bool needsImplicitMoveConstructor() const {
1091 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
1092 !hasUserDeclaredCopyConstructor() &&
1093 !hasUserDeclaredCopyAssignment() &&
1094 !hasUserDeclaredMoveAssignment() &&
1095 !hasUserDeclaredDestructor();
1098 /// Determine whether we need to eagerly declare a defaulted move
1099 /// constructor for this class.
1100 bool needsOverloadResolutionForMoveConstructor() const {
1101 return data().NeedOverloadResolutionForMoveConstructor;
1104 /// Determine whether this class has a user-declared copy assignment
1107 /// When false, a copy assignment operator will be implicitly declared.
1108 bool hasUserDeclaredCopyAssignment() const {
1109 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
1112 /// Determine whether this class needs an implicit copy
1113 /// assignment operator to be lazily declared.
1114 bool needsImplicitCopyAssignment() const {
1115 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
1118 /// Determine whether we need to eagerly declare a defaulted copy
1119 /// assignment operator for this class.
1120 bool needsOverloadResolutionForCopyAssignment() const {
1121 return data().HasMutableFields;
1124 /// Determine whether an implicit copy assignment operator for this
1125 /// type would have a parameter with a const-qualified reference type.
1126 bool implicitCopyAssignmentHasConstParam() const {
1127 return data().ImplicitCopyAssignmentHasConstParam;
1130 /// Determine whether this class has a copy assignment operator with
1131 /// a parameter type which is a reference to a const-qualified type or is not
1133 bool hasCopyAssignmentWithConstParam() const {
1134 return data().HasDeclaredCopyAssignmentWithConstParam ||
1135 (needsImplicitCopyAssignment() &&
1136 implicitCopyAssignmentHasConstParam());
1139 /// Determine whether this class has had a move assignment
1140 /// declared by the user.
1141 bool hasUserDeclaredMoveAssignment() const {
1142 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
1145 /// Determine whether this class has a move assignment operator.
1146 bool hasMoveAssignment() const {
1147 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
1148 needsImplicitMoveAssignment();
1151 /// Set that we attempted to declare an implicit move assignment
1152 /// operator, but overload resolution failed so we deleted it.
1153 void setImplicitMoveAssignmentIsDeleted() {
1154 assert((data().DefaultedMoveAssignmentIsDeleted ||
1155 needsOverloadResolutionForMoveAssignment()) &&
1156 "move assignment should not be deleted");
1157 data().DefaultedMoveAssignmentIsDeleted = true;
1160 /// Determine whether this class should get an implicit move
1161 /// assignment operator or if any existing special member function inhibits
1163 bool needsImplicitMoveAssignment() const {
1164 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
1165 !hasUserDeclaredCopyConstructor() &&
1166 !hasUserDeclaredCopyAssignment() &&
1167 !hasUserDeclaredMoveConstructor() &&
1168 !hasUserDeclaredDestructor() &&
1169 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
1172 /// Determine whether we need to eagerly declare a move assignment
1173 /// operator for this class.
1174 bool needsOverloadResolutionForMoveAssignment() const {
1175 return data().NeedOverloadResolutionForMoveAssignment;
1178 /// Determine whether this class has a user-declared destructor.
1180 /// When false, a destructor will be implicitly declared.
1181 bool hasUserDeclaredDestructor() const {
1182 return data().UserDeclaredSpecialMembers & SMF_Destructor;
1185 /// Determine whether this class needs an implicit destructor to
1186 /// be lazily declared.
1187 bool needsImplicitDestructor() const {
1188 return !(data().DeclaredSpecialMembers & SMF_Destructor);
1191 /// Determine whether we need to eagerly declare a destructor for this
1193 bool needsOverloadResolutionForDestructor() const {
1194 return data().NeedOverloadResolutionForDestructor;
1197 /// Determine whether this class describes a lambda function object.
1198 bool isLambda() const {
1199 // An update record can't turn a non-lambda into a lambda.
1200 auto *DD = DefinitionData;
1201 return DD && DD->IsLambda;
1204 /// Determine whether this class describes a generic
1205 /// lambda function object (i.e. function call operator is
1207 bool isGenericLambda() const;
1209 /// Determine whether this lambda should have an implicit default constructor
1210 /// and copy and move assignment operators.
1211 bool lambdaIsDefaultConstructibleAndAssignable() const;
1213 /// Retrieve the lambda call operator of the closure type
1214 /// if this is a closure type.
1215 CXXMethodDecl *getLambdaCallOperator() const;
1217 /// Retrieve the lambda static invoker, the address of which
1218 /// is returned by the conversion operator, and the body of which
1219 /// is forwarded to the lambda call operator.
1220 CXXMethodDecl *getLambdaStaticInvoker() const;
1222 /// Retrieve the generic lambda's template parameter list.
1223 /// Returns null if the class does not represent a lambda or a generic
1225 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1227 /// Retrieve the lambda template parameters that were specified explicitly.
1228 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1230 LambdaCaptureDefault getLambdaCaptureDefault() const {
1232 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1235 /// For a closure type, retrieve the mapping from captured
1236 /// variables and \c this to the non-static data members that store the
1237 /// values or references of the captures.
1239 /// \param Captures Will be populated with the mapping from captured
1240 /// variables to the corresponding fields.
1242 /// \param ThisCapture Will be set to the field declaration for the
1243 /// \c this capture.
1245 /// \note No entries will be added for init-captures, as they do not capture
1247 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1248 FieldDecl *&ThisCapture) const;
1250 using capture_const_iterator = const LambdaCapture *;
1251 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1253 capture_const_range captures() const {
1254 return capture_const_range(captures_begin(), captures_end());
1257 capture_const_iterator captures_begin() const {
1258 return isLambda() ? getLambdaData().Captures : nullptr;
1261 capture_const_iterator captures_end() const {
1262 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1266 using conversion_iterator = UnresolvedSetIterator;
1268 conversion_iterator conversion_begin() const {
1269 return data().Conversions.get(getASTContext()).begin();
1272 conversion_iterator conversion_end() const {
1273 return data().Conversions.get(getASTContext()).end();
1276 /// Removes a conversion function from this class. The conversion
1277 /// function must currently be a member of this class. Furthermore,
1278 /// this class must currently be in the process of being defined.
1279 void removeConversion(const NamedDecl *Old);
1281 /// Get all conversion functions visible in current class,
1282 /// including conversion function templates.
1283 llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1285 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1286 /// which is a class with no user-declared constructors, no private
1287 /// or protected non-static data members, no base classes, and no virtual
1288 /// functions (C++ [dcl.init.aggr]p1).
1289 bool isAggregate() const { return data().Aggregate; }
1291 /// Whether this class has any in-class initializers
1292 /// for non-static data members (including those in anonymous unions or
1294 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1296 /// Whether this class or any of its subobjects has any members of
1297 /// reference type which would make value-initialization ill-formed.
1299 /// Per C++03 [dcl.init]p5:
1300 /// - if T is a non-union class type without a user-declared constructor,
1301 /// then every non-static data member and base-class component of T is
1302 /// value-initialized [...] A program that calls for [...]
1303 /// value-initialization of an entity of reference type is ill-formed.
1304 bool hasUninitializedReferenceMember() const {
1305 return !isUnion() && !hasUserDeclaredConstructor() &&
1306 data().HasUninitializedReferenceMember;
1309 /// Whether this class is a POD-type (C++ [class]p4)
1311 /// For purposes of this function a class is POD if it is an aggregate
1312 /// that has no non-static non-POD data members, no reference data
1313 /// members, no user-defined copy assignment operator and no
1314 /// user-defined destructor.
1316 /// Note that this is the C++ TR1 definition of POD.
1317 bool isPOD() const { return data().PlainOldData; }
1319 /// True if this class is C-like, without C++-specific features, e.g.
1320 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1321 bool isCLike() const;
1323 /// Determine whether this is an empty class in the sense of
1324 /// (C++11 [meta.unary.prop]).
1326 /// The CXXRecordDecl is a class type, but not a union type,
1327 /// with no non-static data members other than bit-fields of length 0,
1328 /// no virtual member functions, no virtual base classes,
1329 /// and no base class B for which is_empty<B>::value is false.
1331 /// \note This does NOT include a check for union-ness.
1332 bool isEmpty() const { return data().Empty; }
1334 bool hasPrivateFields() const {
1335 return data().HasPrivateFields;
1338 bool hasProtectedFields() const {
1339 return data().HasProtectedFields;
1342 /// Determine whether this class has direct non-static data members.
1343 bool hasDirectFields() const {
1345 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1348 /// Whether this class is polymorphic (C++ [class.virtual]),
1349 /// which means that the class contains or inherits a virtual function.
1350 bool isPolymorphic() const { return data().Polymorphic; }
1352 /// Determine whether this class has a pure virtual function.
1354 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1355 /// a pure virtual function or inherits a pure virtual function that is
1357 bool isAbstract() const { return data().Abstract; }
1359 /// Determine whether this class is standard-layout per
1361 bool isStandardLayout() const { return data().IsStandardLayout; }
1363 /// Determine whether this class was standard-layout per
1364 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1365 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1367 /// Determine whether this class, or any of its class subobjects,
1368 /// contains a mutable field.
1369 bool hasMutableFields() const { return data().HasMutableFields; }
1371 /// Determine whether this class has any variant members.
1372 bool hasVariantMembers() const { return data().HasVariantMembers; }
1374 /// Determine whether this class has a trivial default constructor
1375 /// (C++11 [class.ctor]p5).
1376 bool hasTrivialDefaultConstructor() const {
1377 return hasDefaultConstructor() &&
1378 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1381 /// Determine whether this class has a non-trivial default constructor
1382 /// (C++11 [class.ctor]p5).
1383 bool hasNonTrivialDefaultConstructor() const {
1384 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1385 (needsImplicitDefaultConstructor() &&
1386 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1389 /// Determine whether this class has at least one constexpr constructor
1390 /// other than the copy or move constructors.
1391 bool hasConstexprNonCopyMoveConstructor() const {
1392 return data().HasConstexprNonCopyMoveConstructor ||
1393 (needsImplicitDefaultConstructor() &&
1394 defaultedDefaultConstructorIsConstexpr());
1397 /// Determine whether a defaulted default constructor for this class
1398 /// would be constexpr.
1399 bool defaultedDefaultConstructorIsConstexpr() const {
1400 return data().DefaultedDefaultConstructorIsConstexpr &&
1401 (!isUnion() || hasInClassInitializer() || !hasVariantMembers());
1404 /// Determine whether this class has a constexpr default constructor.
1405 bool hasConstexprDefaultConstructor() const {
1406 return data().HasConstexprDefaultConstructor ||
1407 (needsImplicitDefaultConstructor() &&
1408 defaultedDefaultConstructorIsConstexpr());
1411 /// Determine whether this class has a trivial copy constructor
1412 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1413 bool hasTrivialCopyConstructor() const {
1414 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1417 bool hasTrivialCopyConstructorForCall() const {
1418 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1421 /// Determine whether this class has a non-trivial copy constructor
1422 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1423 bool hasNonTrivialCopyConstructor() const {
1424 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1425 !hasTrivialCopyConstructor();
1428 bool hasNonTrivialCopyConstructorForCall() const {
1429 return (data().DeclaredNonTrivialSpecialMembersForCall &
1430 SMF_CopyConstructor) ||
1431 !hasTrivialCopyConstructorForCall();
1434 /// Determine whether this class has a trivial move constructor
1435 /// (C++11 [class.copy]p12)
1436 bool hasTrivialMoveConstructor() const {
1437 return hasMoveConstructor() &&
1438 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1441 bool hasTrivialMoveConstructorForCall() const {
1442 return hasMoveConstructor() &&
1443 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1446 /// Determine whether this class has a non-trivial move constructor
1447 /// (C++11 [class.copy]p12)
1448 bool hasNonTrivialMoveConstructor() const {
1449 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1450 (needsImplicitMoveConstructor() &&
1451 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1454 bool hasNonTrivialMoveConstructorForCall() const {
1455 return (data().DeclaredNonTrivialSpecialMembersForCall &
1456 SMF_MoveConstructor) ||
1457 (needsImplicitMoveConstructor() &&
1458 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1461 /// Determine whether this class has a trivial copy assignment operator
1462 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1463 bool hasTrivialCopyAssignment() const {
1464 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1467 /// Determine whether this class has a non-trivial copy assignment
1468 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1469 bool hasNonTrivialCopyAssignment() const {
1470 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1471 !hasTrivialCopyAssignment();
1474 /// Determine whether this class has a trivial move assignment operator
1475 /// (C++11 [class.copy]p25)
1476 bool hasTrivialMoveAssignment() const {
1477 return hasMoveAssignment() &&
1478 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1481 /// Determine whether this class has a non-trivial move assignment
1482 /// operator (C++11 [class.copy]p25)
1483 bool hasNonTrivialMoveAssignment() const {
1484 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1485 (needsImplicitMoveAssignment() &&
1486 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1489 /// Determine whether this class has a trivial destructor
1490 /// (C++ [class.dtor]p3)
1491 bool hasTrivialDestructor() const {
1492 return data().HasTrivialSpecialMembers & SMF_Destructor;
1495 bool hasTrivialDestructorForCall() const {
1496 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1499 /// Determine whether this class has a non-trivial destructor
1500 /// (C++ [class.dtor]p3)
1501 bool hasNonTrivialDestructor() const {
1502 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1505 bool hasNonTrivialDestructorForCall() const {
1506 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1509 void setHasTrivialSpecialMemberForCall() {
1510 data().HasTrivialSpecialMembersForCall =
1511 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1514 /// Determine whether declaring a const variable with this type is ok
1515 /// per core issue 253.
1516 bool allowConstDefaultInit() const {
1517 return !data().HasUninitializedFields ||
1518 !(data().HasDefaultedDefaultConstructor ||
1519 needsImplicitDefaultConstructor());
1522 /// Determine whether this class has a destructor which has no
1523 /// semantic effect.
1525 /// Any such destructor will be trivial, public, defaulted and not deleted,
1526 /// and will call only irrelevant destructors.
1527 bool hasIrrelevantDestructor() const {
1528 return data().HasIrrelevantDestructor;
1531 /// Determine whether this class has a non-literal or/ volatile type
1532 /// non-static data member or base class.
1533 bool hasNonLiteralTypeFieldsOrBases() const {
1534 return data().HasNonLiteralTypeFieldsOrBases;
1537 /// Determine whether this class has a using-declaration that names
1538 /// a user-declared base class constructor.
1539 bool hasInheritedConstructor() const {
1540 return data().HasInheritedConstructor;
1543 /// Determine whether this class has a using-declaration that names
1544 /// a base class assignment operator.
1545 bool hasInheritedAssignment() const {
1546 return data().HasInheritedAssignment;
1549 /// Determine whether this class is considered trivially copyable per
1550 /// (C++11 [class]p6).
1551 bool isTriviallyCopyable() const;
1553 /// Determine whether this class is considered trivial.
1555 /// C++11 [class]p6:
1556 /// "A trivial class is a class that has a trivial default constructor and
1557 /// is trivially copyable."
1558 bool isTrivial() const {
1559 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1562 /// Determine whether this class is a literal type.
1564 /// C++11 [basic.types]p10:
1565 /// A class type that has all the following properties:
1566 /// - it has a trivial destructor
1567 /// - every constructor call and full-expression in the
1568 /// brace-or-equal-intializers for non-static data members (if any) is
1569 /// a constant expression.
1570 /// - it is an aggregate type or has at least one constexpr constructor
1571 /// or constructor template that is not a copy or move constructor, and
1572 /// - all of its non-static data members and base classes are of literal
1575 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1576 /// treating types with trivial default constructors as literal types.
1578 /// Only in C++17 and beyond, are lambdas literal types.
1579 bool isLiteral() const {
1580 return hasTrivialDestructor() &&
1581 (!isLambda() || getASTContext().getLangOpts().CPlusPlus17) &&
1582 !hasNonLiteralTypeFieldsOrBases() &&
1583 (isAggregate() || isLambda() ||
1584 hasConstexprNonCopyMoveConstructor() ||
1585 hasTrivialDefaultConstructor());
1588 /// If this record is an instantiation of a member class,
1589 /// retrieves the member class from which it was instantiated.
1591 /// This routine will return non-null for (non-templated) member
1592 /// classes of class templates. For example, given:
1595 /// template<typename T>
1601 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1602 /// whose parent is the class template specialization X<int>. For
1603 /// this declaration, getInstantiatedFromMemberClass() will return
1604 /// the CXXRecordDecl X<T>::A. When a complete definition of
1605 /// X<int>::A is required, it will be instantiated from the
1606 /// declaration returned by getInstantiatedFromMemberClass().
1607 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1609 /// If this class is an instantiation of a member class of a
1610 /// class template specialization, retrieves the member specialization
1612 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1614 /// Specify that this record is an instantiation of the
1615 /// member class \p RD.
1616 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1617 TemplateSpecializationKind TSK);
1619 /// Retrieves the class template that is described by this
1620 /// class declaration.
1622 /// Every class template is represented as a ClassTemplateDecl and a
1623 /// CXXRecordDecl. The former contains template properties (such as
1624 /// the template parameter lists) while the latter contains the
1625 /// actual description of the template's
1626 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1627 /// CXXRecordDecl that from a ClassTemplateDecl, while
1628 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1629 /// a CXXRecordDecl.
1630 ClassTemplateDecl *getDescribedClassTemplate() const;
1632 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1634 /// Determine whether this particular class is a specialization or
1635 /// instantiation of a class template or member class of a class template,
1636 /// and how it was instantiated or specialized.
1637 TemplateSpecializationKind getTemplateSpecializationKind() const;
1639 /// Set the kind of specialization or template instantiation this is.
1640 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1642 /// Retrieve the record declaration from which this record could be
1643 /// instantiated. Returns null if this class is not a template instantiation.
1644 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1646 CXXRecordDecl *getTemplateInstantiationPattern() {
1647 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1648 ->getTemplateInstantiationPattern());
1651 /// Returns the destructor decl for this class.
1652 CXXDestructorDecl *getDestructor() const;
1654 /// Returns true if the class destructor, or any implicitly invoked
1655 /// destructors are marked noreturn.
1656 bool isAnyDestructorNoReturn() const;
1658 /// If the class is a local class [class.local], returns
1659 /// the enclosing function declaration.
1660 const FunctionDecl *isLocalClass() const {
1661 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1662 return RD->isLocalClass();
1664 return dyn_cast<FunctionDecl>(getDeclContext());
1667 FunctionDecl *isLocalClass() {
1668 return const_cast<FunctionDecl*>(
1669 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1672 /// Determine whether this dependent class is a current instantiation,
1673 /// when viewed from within the given context.
1674 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1676 /// Determine whether this class is derived from the class \p Base.
1678 /// This routine only determines whether this class is derived from \p Base,
1679 /// but does not account for factors that may make a Derived -> Base class
1680 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1681 /// base class subobjects.
1683 /// \param Base the base class we are searching for.
1685 /// \returns true if this class is derived from Base, false otherwise.
1686 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1688 /// Determine whether this class is derived from the type \p Base.
1690 /// This routine only determines whether this class is derived from \p Base,
1691 /// but does not account for factors that may make a Derived -> Base class
1692 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1693 /// base class subobjects.
1695 /// \param Base the base class we are searching for.
1697 /// \param Paths will contain the paths taken from the current class to the
1698 /// given \p Base class.
1700 /// \returns true if this class is derived from \p Base, false otherwise.
1702 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1703 /// tangling input and output in \p Paths
1704 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1706 /// Determine whether this class is virtually derived from
1707 /// the class \p Base.
1709 /// This routine only determines whether this class is virtually
1710 /// derived from \p Base, but does not account for factors that may
1711 /// make a Derived -> Base class ill-formed, such as
1712 /// private/protected inheritance or multiple, ambiguous base class
1715 /// \param Base the base class we are searching for.
1717 /// \returns true if this class is virtually derived from Base,
1718 /// false otherwise.
1719 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1721 /// Determine whether this class is provably not derived from
1722 /// the type \p Base.
1723 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1725 /// Function type used by forallBases() as a callback.
1727 /// \param BaseDefinition the definition of the base class
1729 /// \returns true if this base matched the search criteria
1730 using ForallBasesCallback =
1731 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1733 /// Determines if the given callback holds for all the direct
1734 /// or indirect base classes of this type.
1736 /// The class itself does not count as a base class. This routine
1737 /// returns false if the class has non-computable base classes.
1739 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1740 /// class of this type, or if \p AllowShortCircuit is true then until a call
1743 /// \param AllowShortCircuit if false, forces the callback to be called
1744 /// for every base class, even if a dependent or non-matching base was
1746 bool forallBases(ForallBasesCallback BaseMatches,
1747 bool AllowShortCircuit = true) const;
1749 /// Function type used by lookupInBases() to determine whether a
1750 /// specific base class subobject matches the lookup criteria.
1752 /// \param Specifier the base-class specifier that describes the inheritance
1753 /// from the base class we are trying to match.
1755 /// \param Path the current path, from the most-derived class down to the
1756 /// base named by the \p Specifier.
1758 /// \returns true if this base matched the search criteria, false otherwise.
1759 using BaseMatchesCallback =
1760 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1761 CXXBasePath &Path)>;
1763 /// Look for entities within the base classes of this C++ class,
1764 /// transitively searching all base class subobjects.
1766 /// This routine uses the callback function \p BaseMatches to find base
1767 /// classes meeting some search criteria, walking all base class subobjects
1768 /// and populating the given \p Paths structure with the paths through the
1769 /// inheritance hierarchy that resulted in a match. On a successful search,
1770 /// the \p Paths structure can be queried to retrieve the matching paths and
1771 /// to determine if there were any ambiguities.
1773 /// \param BaseMatches callback function used to determine whether a given
1774 /// base matches the user-defined search criteria.
1776 /// \param Paths used to record the paths from this class to its base class
1777 /// subobjects that match the search criteria.
1779 /// \param LookupInDependent can be set to true to extend the search to
1780 /// dependent base classes.
1782 /// \returns true if there exists any path from this class to a base class
1783 /// subobject that matches the search criteria.
1784 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1785 bool LookupInDependent = false) const;
1787 /// Base-class lookup callback that determines whether the given
1788 /// base class specifier refers to a specific class declaration.
1790 /// This callback can be used with \c lookupInBases() to determine whether
1791 /// a given derived class has is a base class subobject of a particular type.
1792 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1793 /// base class that we are searching for.
1794 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1795 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1797 /// Base-class lookup callback that determines whether the
1798 /// given base class specifier refers to a specific class
1799 /// declaration and describes virtual derivation.
1801 /// This callback can be used with \c lookupInBases() to determine
1802 /// whether a given derived class has is a virtual base class
1803 /// subobject of a particular type. The base record pointer should
1804 /// refer to the canonical CXXRecordDecl of the base class that we
1805 /// are searching for.
1806 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1808 const CXXRecordDecl *BaseRecord);
1810 /// Base-class lookup callback that determines whether there exists
1811 /// a tag with the given name.
1813 /// This callback can be used with \c lookupInBases() to find tag members
1814 /// of the given name within a C++ class hierarchy.
1815 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1816 CXXBasePath &Path, DeclarationName Name);
1818 /// Base-class lookup callback that determines whether there exists
1819 /// a member with the given name.
1821 /// This callback can be used with \c lookupInBases() to find members
1822 /// of the given name within a C++ class hierarchy.
1823 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1824 CXXBasePath &Path, DeclarationName Name);
1826 /// Base-class lookup callback that determines whether there exists
1827 /// a member with the given name.
1829 /// This callback can be used with \c lookupInBases() to find members
1830 /// of the given name within a C++ class hierarchy, including dependent
1833 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1834 CXXBasePath &Path, DeclarationName Name);
1836 /// Base-class lookup callback that determines whether there exists
1837 /// an OpenMP declare reduction member with the given name.
1839 /// This callback can be used with \c lookupInBases() to find members
1840 /// of the given name within a C++ class hierarchy.
1841 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1842 CXXBasePath &Path, DeclarationName Name);
1844 /// Base-class lookup callback that determines whether there exists
1845 /// an OpenMP declare mapper member with the given name.
1847 /// This callback can be used with \c lookupInBases() to find members
1848 /// of the given name within a C++ class hierarchy.
1849 static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
1850 CXXBasePath &Path, DeclarationName Name);
1852 /// Base-class lookup callback that determines whether there exists
1853 /// a member with the given name that can be used in a nested-name-specifier.
1855 /// This callback can be used with \c lookupInBases() to find members of
1856 /// the given name within a C++ class hierarchy that can occur within
1857 /// nested-name-specifiers.
1858 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1860 DeclarationName Name);
1862 /// Retrieve the final overriders for each virtual member
1863 /// function in the class hierarchy where this class is the
1864 /// most-derived class in the class hierarchy.
1865 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1867 /// Get the indirect primary bases for this class.
1868 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1870 /// Performs an imprecise lookup of a dependent name in this class.
1872 /// This function does not follow strict semantic rules and should be used
1873 /// only when lookup rules can be relaxed, e.g. indexing.
1874 std::vector<const NamedDecl *>
1875 lookupDependentName(const DeclarationName &Name,
1876 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1878 /// Renders and displays an inheritance diagram
1879 /// for this C++ class and all of its base classes (transitively) using
1881 void viewInheritance(ASTContext& Context) const;
1883 /// Calculates the access of a decl that is reached
1885 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1886 AccessSpecifier DeclAccess) {
1887 assert(DeclAccess != AS_none);
1888 if (DeclAccess == AS_private) return AS_none;
1889 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1892 /// Indicates that the declaration of a defaulted or deleted special
1893 /// member function is now complete.
1894 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1896 void setTrivialForCallFlags(CXXMethodDecl *MD);
1898 /// Indicates that the definition of this class is now complete.
1899 void completeDefinition() override;
1901 /// Indicates that the definition of this class is now complete,
1902 /// and provides a final overrider map to help determine
1904 /// \param FinalOverriders The final overrider map for this class, which can
1905 /// be provided as an optimization for abstract-class checking. If NULL,
1906 /// final overriders will be computed if they are needed to complete the
1908 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1910 /// Determine whether this class may end up being abstract, even though
1911 /// it is not yet known to be abstract.
1913 /// \returns true if this class is not known to be abstract but has any
1914 /// base classes that are abstract. In this case, \c completeDefinition()
1915 /// will need to compute final overriders to determine whether the class is
1916 /// actually abstract.
1917 bool mayBeAbstract() const;
1919 /// If this is the closure type of a lambda expression, retrieve the
1920 /// number to be used for name mangling in the Itanium C++ ABI.
1922 /// Zero indicates that this closure type has internal linkage, so the
1923 /// mangling number does not matter, while a non-zero value indicates which
1924 /// lambda expression this is in this particular context.
1925 unsigned getLambdaManglingNumber() const {
1926 assert(isLambda() && "Not a lambda closure type!");
1927 return getLambdaData().ManglingNumber;
1930 /// Retrieve the declaration that provides additional context for a
1931 /// lambda, when the normal declaration context is not specific enough.
1933 /// Certain contexts (default arguments of in-class function parameters and
1934 /// the initializers of data members) have separate name mangling rules for
1935 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1936 /// the declaration in which the lambda occurs, e.g., the function parameter
1937 /// or the non-static data member. Otherwise, it returns NULL to imply that
1938 /// the declaration context suffices.
1939 Decl *getLambdaContextDecl() const;
1941 /// Set the mangling number and context declaration for a lambda
1943 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
1944 getLambdaData().ManglingNumber = ManglingNumber;
1945 getLambdaData().ContextDecl = ContextDecl;
1948 /// Returns the inheritance model used for this record.
1949 MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1951 /// Calculate what the inheritance model would be for this class.
1952 MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1954 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1955 /// member pointer if we can guarantee that zero is not a valid field offset,
1956 /// or if the member pointer has multiple fields. Polymorphic classes have a
1957 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1958 /// fields, we can use zero even if it is a valid field offset because
1959 /// null-ness testing will check the other fields.
1960 bool nullFieldOffsetIsZero() const {
1961 return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1962 getMSInheritanceModel()) ||
1963 (hasDefinition() && isPolymorphic());
1966 /// Controls when vtordisps will be emitted if this record is used as a
1968 MSVtorDispAttr::Mode getMSVtorDispMode() const;
1970 /// Determine whether this lambda expression was known to be dependent
1971 /// at the time it was created, even if its context does not appear to be
1974 /// This flag is a workaround for an issue with parsing, where default
1975 /// arguments are parsed before their enclosing function declarations have
1976 /// been created. This means that any lambda expressions within those
1977 /// default arguments will have as their DeclContext the context enclosing
1978 /// the function declaration, which may be non-dependent even when the
1979 /// function declaration itself is dependent. This flag indicates when we
1980 /// know that the lambda is dependent despite that.
1981 bool isDependentLambda() const {
1982 return isLambda() && getLambdaData().Dependent;
1985 TypeSourceInfo *getLambdaTypeInfo() const {
1986 return getLambdaData().MethodTyInfo;
1989 // Determine whether this type is an Interface Like type for
1990 // __interface inheritance purposes.
1991 bool isInterfaceLike() const;
1993 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1994 static bool classofKind(Kind K) {
1995 return K >= firstCXXRecord && K <= lastCXXRecord;
1999 /// Store information needed for an explicit specifier.
2000 /// used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
2001 class ExplicitSpecifier {
2002 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
2003 nullptr, ExplicitSpecKind::ResolvedFalse};
2006 ExplicitSpecifier() = default;
2007 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
2008 : ExplicitSpec(Expression, Kind) {}
2009 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
2010 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
2011 Expr *getExpr() { return ExplicitSpec.getPointer(); }
2013 /// Return true if the ExplicitSpecifier isn't defaulted.
2014 bool isSpecified() const {
2015 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
2016 ExplicitSpec.getPointer();
2019 /// Check for Equivalence of explicit specifiers.
2020 /// Return True if the explicit specifier are equivalent false otherwise.
2021 bool isEquivalent(const ExplicitSpecifier Other) const;
2022 /// Return true if the explicit specifier is already resolved to be explicit.
2023 bool isExplicit() const {
2024 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
2026 /// Return true if the ExplicitSpecifier isn't valid.
2027 /// This state occurs after a substitution failures.
2028 bool isInvalid() const {
2029 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
2030 !ExplicitSpec.getPointer();
2032 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
2033 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
2034 // getFromDecl - retrieve the explicit specifier in the given declaration.
2035 // if the given declaration has no explicit. the returned explicit specifier
2036 // is defaulted. .isSpecified() will be false.
2037 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
2038 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
2039 return getFromDecl(const_cast<FunctionDecl *>(Function));
2041 static ExplicitSpecifier Invalid() {
2042 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
2046 /// Represents a C++ deduction guide declaration.
2049 /// template<typename T> struct A { A(); A(T); };
2053 /// In this example, there will be an explicit deduction guide from the
2054 /// second line, and implicit deduction guide templates synthesized from
2055 /// the constructors of \c A.
2056 class CXXDeductionGuideDecl : public FunctionDecl {
2057 void anchor() override;
2060 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2061 ExplicitSpecifier ES,
2062 const DeclarationNameInfo &NameInfo, QualType T,
2063 TypeSourceInfo *TInfo, SourceLocation EndLocation)
2064 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
2065 SC_None, false, CSK_unspecified),
2067 if (EndLocation.isValid())
2068 setRangeEnd(EndLocation);
2069 setIsCopyDeductionCandidate(false);
2072 ExplicitSpecifier ExplicitSpec;
2073 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2076 friend class ASTDeclReader;
2077 friend class ASTDeclWriter;
2079 static CXXDeductionGuideDecl *
2080 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2081 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2082 TypeSourceInfo *TInfo, SourceLocation EndLocation);
2084 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2086 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
2087 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
2089 /// Return true if the declartion is already resolved to be explicit.
2090 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
2092 /// Get the template for which this guide performs deduction.
2093 TemplateDecl *getDeducedTemplate() const {
2094 return getDeclName().getCXXDeductionGuideTemplate();
2097 void setIsCopyDeductionCandidate(bool isCDC = true) {
2098 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
2101 bool isCopyDeductionCandidate() const {
2102 return FunctionDeclBits.IsCopyDeductionCandidate;
2105 // Implement isa/cast/dyncast/etc.
2106 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2107 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
2110 /// Represents a static or instance method of a struct/union/class.
2112 /// In the terminology of the C++ Standard, these are the (static and
2113 /// non-static) member functions, whether virtual or not.
2114 class CXXMethodDecl : public FunctionDecl {
2115 void anchor() override;
2118 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2119 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2120 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
2121 bool isInline, ConstexprSpecKind ConstexprKind,
2122 SourceLocation EndLocation)
2123 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
2125 if (EndLocation.isValid())
2126 setRangeEnd(EndLocation);
2130 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2131 SourceLocation StartLoc,
2132 const DeclarationNameInfo &NameInfo, QualType T,
2133 TypeSourceInfo *TInfo, StorageClass SC,
2134 bool isInline, ConstexprSpecKind ConstexprKind,
2135 SourceLocation EndLocation);
2137 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2139 bool isStatic() const;
2140 bool isInstance() const { return !isStatic(); }
2142 /// Returns true if the given operator is implicitly static in a record
2144 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2146 // Any allocation function for a class T is a static member
2147 // (even if not explicitly declared static).
2148 // [class.free]p6 Any deallocation function for a class X is a static member
2149 // (even if not explicitly declared static).
2150 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2151 OOK == OO_Array_Delete;
2154 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2155 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2157 bool isVirtual() const {
2158 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2160 // Member function is virtual if it is marked explicitly so, or if it is
2161 // declared in __interface -- then it is automatically pure virtual.
2162 if (CD->isVirtualAsWritten() || CD->isPure())
2165 return CD->size_overridden_methods() != 0;
2168 /// If it's possible to devirtualize a call to this method, return the called
2169 /// function. Otherwise, return null.
2171 /// \param Base The object on which this virtual function is called.
2172 /// \param IsAppleKext True if we are compiling for Apple kext.
2173 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2175 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2176 bool IsAppleKext) const {
2177 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2181 /// Determine whether this is a usual deallocation function (C++
2182 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2183 /// delete[] operator with a particular signature. Populates \p PreventedBy
2184 /// with the declarations of the functions of the same kind if they were the
2185 /// reason for this function returning false. This is used by
2186 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2188 bool isUsualDeallocationFunction(
2189 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2191 /// Determine whether this is a copy-assignment operator, regardless
2192 /// of whether it was declared implicitly or explicitly.
2193 bool isCopyAssignmentOperator() const;
2195 /// Determine whether this is a move assignment operator.
2196 bool isMoveAssignmentOperator() const;
2198 CXXMethodDecl *getCanonicalDecl() override {
2199 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2201 const CXXMethodDecl *getCanonicalDecl() const {
2202 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2205 CXXMethodDecl *getMostRecentDecl() {
2206 return cast<CXXMethodDecl>(
2207 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2209 const CXXMethodDecl *getMostRecentDecl() const {
2210 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2213 /// True if this method is user-declared and was not
2214 /// deleted or defaulted on its first declaration.
2215 bool isUserProvided() const {
2216 auto *DeclAsWritten = this;
2217 if (auto *Pattern = getTemplateInstantiationPattern())
2218 DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2219 return !(DeclAsWritten->isDeleted() ||
2220 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2223 void addOverriddenMethod(const CXXMethodDecl *MD);
2225 using method_iterator = const CXXMethodDecl *const *;
2227 method_iterator begin_overridden_methods() const;
2228 method_iterator end_overridden_methods() const;
2229 unsigned size_overridden_methods() const;
2231 using overridden_method_range= ASTContext::overridden_method_range;
2233 overridden_method_range overridden_methods() const;
2235 /// Return the parent of this method declaration, which
2236 /// is the class in which this method is defined.
2237 const CXXRecordDecl *getParent() const {
2238 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2241 /// Return the parent of this method declaration, which
2242 /// is the class in which this method is defined.
2243 CXXRecordDecl *getParent() {
2244 return const_cast<CXXRecordDecl *>(
2245 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2248 /// Return the type of the \c this pointer.
2250 /// Should only be called for instance (i.e., non-static) methods. Note
2251 /// that for the call operator of a lambda closure type, this returns the
2252 /// desugared 'this' type (a pointer to the closure type), not the captured
2254 QualType getThisType() const;
2256 /// Return the type of the object pointed by \c this.
2258 /// See getThisType() for usage restriction.
2259 QualType getThisObjectType() const;
2261 static QualType getThisType(const FunctionProtoType *FPT,
2262 const CXXRecordDecl *Decl);
2264 static QualType getThisObjectType(const FunctionProtoType *FPT,
2265 const CXXRecordDecl *Decl);
2267 Qualifiers getMethodQualifiers() const {
2268 return getType()->getAs<FunctionProtoType>()->getMethodQuals();
2271 /// Retrieve the ref-qualifier associated with this method.
2273 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2274 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2282 RefQualifierKind getRefQualifier() const {
2283 return getType()->getAs<FunctionProtoType>()->getRefQualifier();
2286 bool hasInlineBody() const;
2288 /// Determine whether this is a lambda closure type's static member
2289 /// function that is used for the result of the lambda's conversion to
2290 /// function pointer (for a lambda with no captures).
2292 /// The function itself, if used, will have a placeholder body that will be
2293 /// supplied by IR generation to either forward to the function call operator
2294 /// or clone the function call operator.
2295 bool isLambdaStaticInvoker() const;
2297 /// Find the method in \p RD that corresponds to this one.
2299 /// Find if \p RD or one of the classes it inherits from override this method.
2300 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2301 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2303 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2304 bool MayBeBase = false);
2306 const CXXMethodDecl *
2307 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2308 bool MayBeBase = false) const {
2309 return const_cast<CXXMethodDecl *>(this)
2310 ->getCorrespondingMethodInClass(RD, MayBeBase);
2313 /// Find if \p RD declares a function that overrides this function, and if so,
2314 /// return it. Does not search base classes.
2315 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2316 bool MayBeBase = false);
2317 const CXXMethodDecl *
2318 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2319 bool MayBeBase = false) const {
2320 return const_cast<CXXMethodDecl *>(this)
2321 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2324 // Implement isa/cast/dyncast/etc.
2325 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2326 static bool classofKind(Kind K) {
2327 return K >= firstCXXMethod && K <= lastCXXMethod;
2331 /// Represents a C++ base or member initializer.
2333 /// This is part of a constructor initializer that
2334 /// initializes one non-static member variable or one base class. For
2335 /// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2340 /// class B : public A {
2343 /// B(A& a) : A(a), f(3.14159) { }
2346 class CXXCtorInitializer final {
2347 /// Either the base class name/delegating constructor type (stored as
2348 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2349 /// (IndirectFieldDecl*) being initialized.
2350 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2353 /// The source location for the field name or, for a base initializer
2354 /// pack expansion, the location of the ellipsis.
2356 /// In the case of a delegating
2357 /// constructor, it will still include the type's source location as the
2358 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2359 SourceLocation MemberOrEllipsisLocation;
2361 /// The argument used to initialize the base or member, which may
2362 /// end up constructing an object (when multiple arguments are involved).
2365 /// Location of the left paren of the ctor-initializer.
2366 SourceLocation LParenLoc;
2368 /// Location of the right paren of the ctor-initializer.
2369 SourceLocation RParenLoc;
2371 /// If the initializee is a type, whether that type makes this
2372 /// a delegating initialization.
2373 unsigned IsDelegating : 1;
2375 /// If the initializer is a base initializer, this keeps track
2376 /// of whether the base is virtual or not.
2377 unsigned IsVirtual : 1;
2379 /// Whether or not the initializer is explicitly written
2381 unsigned IsWritten : 1;
2383 /// If IsWritten is true, then this number keeps track of the textual order
2384 /// of this initializer in the original sources, counting from 0.
2385 unsigned SourceOrder : 13;
2388 /// Creates a new base-class initializer.
2390 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2391 SourceLocation L, Expr *Init, SourceLocation R,
2392 SourceLocation EllipsisLoc);
2394 /// Creates a new member initializer.
2396 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2397 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2400 /// Creates a new anonymous field initializer.
2402 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2403 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2406 /// Creates a new delegating initializer.
2408 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2409 SourceLocation L, Expr *Init, SourceLocation R);
2411 /// \return Unique reproducible object identifier.
2412 int64_t getID(const ASTContext &Context) const;
2414 /// Determine whether this initializer is initializing a base class.
2415 bool isBaseInitializer() const {
2416 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2419 /// Determine whether this initializer is initializing a non-static
2421 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2423 bool isAnyMemberInitializer() const {
2424 return isMemberInitializer() || isIndirectMemberInitializer();
2427 bool isIndirectMemberInitializer() const {
2428 return Initializee.is<IndirectFieldDecl*>();
2431 /// Determine whether this initializer is an implicit initializer
2432 /// generated for a field with an initializer defined on the member
2435 /// In-class member initializers (also known as "non-static data member
2436 /// initializations", NSDMIs) were introduced in C++11.
2437 bool isInClassMemberInitializer() const {
2438 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2441 /// Determine whether this initializer is creating a delegating
2443 bool isDelegatingInitializer() const {
2444 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2447 /// Determine whether this initializer is a pack expansion.
2448 bool isPackExpansion() const {
2449 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2452 // For a pack expansion, returns the location of the ellipsis.
2453 SourceLocation getEllipsisLoc() const {
2454 assert(isPackExpansion() && "Initializer is not a pack expansion");
2455 return MemberOrEllipsisLocation;
2458 /// If this is a base class initializer, returns the type of the
2459 /// base class with location information. Otherwise, returns an NULL
2461 TypeLoc getBaseClassLoc() const;
2463 /// If this is a base class initializer, returns the type of the base class.
2464 /// Otherwise, returns null.
2465 const Type *getBaseClass() const;
2467 /// Returns whether the base is virtual or not.
2468 bool isBaseVirtual() const {
2469 assert(isBaseInitializer() && "Must call this on base initializer!");
2474 /// Returns the declarator information for a base class or delegating
2476 TypeSourceInfo *getTypeSourceInfo() const {
2477 return Initializee.dyn_cast<TypeSourceInfo *>();
2480 /// If this is a member initializer, returns the declaration of the
2481 /// non-static data member being initialized. Otherwise, returns null.
2482 FieldDecl *getMember() const {
2483 if (isMemberInitializer())
2484 return Initializee.get<FieldDecl*>();
2488 FieldDecl *getAnyMember() const {
2489 if (isMemberInitializer())
2490 return Initializee.get<FieldDecl*>();
2491 if (isIndirectMemberInitializer())
2492 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2496 IndirectFieldDecl *getIndirectMember() const {
2497 if (isIndirectMemberInitializer())
2498 return Initializee.get<IndirectFieldDecl*>();
2502 SourceLocation getMemberLocation() const {
2503 return MemberOrEllipsisLocation;
2506 /// Determine the source location of the initializer.
2507 SourceLocation getSourceLocation() const;
2509 /// Determine the source range covering the entire initializer.
2510 SourceRange getSourceRange() const LLVM_READONLY;
2512 /// Determine whether this initializer is explicitly written
2513 /// in the source code.
2514 bool isWritten() const { return IsWritten; }
2516 /// Return the source position of the initializer, counting from 0.
2517 /// If the initializer was implicit, -1 is returned.
2518 int getSourceOrder() const {
2519 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2522 /// Set the source order of this initializer.
2524 /// This can only be called once for each initializer; it cannot be called
2525 /// on an initializer having a positive number of (implicit) array indices.
2527 /// This assumes that the initializer was written in the source code, and
2528 /// ensures that isWritten() returns true.
2529 void setSourceOrder(int Pos) {
2530 assert(!IsWritten &&
2531 "setSourceOrder() used on implicit initializer");
2532 assert(SourceOrder == 0 &&
2533 "calling twice setSourceOrder() on the same initializer");
2535 "setSourceOrder() used to make an initializer implicit");
2537 SourceOrder = static_cast<unsigned>(Pos);
2540 SourceLocation getLParenLoc() const { return LParenLoc; }
2541 SourceLocation getRParenLoc() const { return RParenLoc; }
2543 /// Get the initializer.
2544 Expr *getInit() const { return static_cast<Expr *>(Init); }
2547 /// Description of a constructor that was inherited from a base class.
2548 class InheritedConstructor {
2549 ConstructorUsingShadowDecl *Shadow = nullptr;
2550 CXXConstructorDecl *BaseCtor = nullptr;
2553 InheritedConstructor() = default;
2554 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2555 CXXConstructorDecl *BaseCtor)
2556 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2558 explicit operator bool() const { return Shadow; }
2560 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2561 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2564 /// Represents a C++ constructor within a class.
2571 /// explicit X(int); // represented by a CXXConstructorDecl.
2574 class CXXConstructorDecl final
2575 : public CXXMethodDecl,
2576 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2577 ExplicitSpecifier> {
2578 // This class stores some data in DeclContext::CXXConstructorDeclBits
2579 // to save some space. Use the provided accessors to access it.
2581 /// \name Support for base and member initializers.
2583 /// The arguments used to initialize the base or member.
2584 LazyCXXCtorInitializersPtr CtorInitializers;
2586 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2587 const DeclarationNameInfo &NameInfo, QualType T,
2588 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2589 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2590 InheritedConstructor Inherited);
2592 void anchor() override;
2594 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2595 return CXXConstructorDeclBits.IsInheritingConstructor;
2597 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2598 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2601 ExplicitSpecifier getExplicitSpecifierInternal() const {
2602 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2603 return *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>();
2604 return ExplicitSpecifier(
2605 nullptr, getCanonicalDecl()->CXXConstructorDeclBits.IsSimpleExplicit
2606 ? ExplicitSpecKind::ResolvedTrue
2607 : ExplicitSpecKind::ResolvedFalse);
2610 void setExplicitSpecifier(ExplicitSpecifier ES) {
2611 assert((!ES.getExpr() ||
2612 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&
2613 "cannot set this explicit specifier. no trail-allocated space for "
2616 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2618 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2621 enum TraillingAllocKind {
2622 TAKInheritsConstructor = 1,
2623 TAKHasTailExplicit = 1 << 1,
2626 uint64_t getTraillingAllocKind() const {
2627 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2628 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2632 friend class ASTDeclReader;
2633 friend class ASTDeclWriter;
2634 friend TrailingObjects;
2636 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2637 uint64_t AllocKind);
2638 static CXXConstructorDecl *
2639 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2640 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2641 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2642 ConstexprSpecKind ConstexprKind,
2643 InheritedConstructor Inherited = InheritedConstructor());
2645 ExplicitSpecifier getExplicitSpecifier() {
2646 return getExplicitSpecifierInternal();
2648 const ExplicitSpecifier getExplicitSpecifier() const {
2649 return getExplicitSpecifierInternal();
2652 /// Return true if the declartion is already resolved to be explicit.
2653 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2655 /// Iterates through the member/base initializer list.
2656 using init_iterator = CXXCtorInitializer **;
2658 /// Iterates through the member/base initializer list.
2659 using init_const_iterator = CXXCtorInitializer *const *;
2661 using init_range = llvm::iterator_range<init_iterator>;
2662 using init_const_range = llvm::iterator_range<init_const_iterator>;
2664 init_range inits() { return init_range(init_begin(), init_end()); }
2665 init_const_range inits() const {
2666 return init_const_range(init_begin(), init_end());
2669 /// Retrieve an iterator to the first initializer.
2670 init_iterator init_begin() {
2671 const auto *ConstThis = this;
2672 return const_cast<init_iterator>(ConstThis->init_begin());
2675 /// Retrieve an iterator to the first initializer.
2676 init_const_iterator init_begin() const;
2678 /// Retrieve an iterator past the last initializer.
2679 init_iterator init_end() {
2680 return init_begin() + getNumCtorInitializers();
2683 /// Retrieve an iterator past the last initializer.
2684 init_const_iterator init_end() const {
2685 return init_begin() + getNumCtorInitializers();
2688 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2689 using init_const_reverse_iterator =
2690 std::reverse_iterator<init_const_iterator>;
2692 init_reverse_iterator init_rbegin() {
2693 return init_reverse_iterator(init_end());
2695 init_const_reverse_iterator init_rbegin() const {
2696 return init_const_reverse_iterator(init_end());
2699 init_reverse_iterator init_rend() {
2700 return init_reverse_iterator(init_begin());
2702 init_const_reverse_iterator init_rend() const {
2703 return init_const_reverse_iterator(init_begin());
2706 /// Determine the number of arguments used to initialize the member
2708 unsigned getNumCtorInitializers() const {
2709 return CXXConstructorDeclBits.NumCtorInitializers;
2712 void setNumCtorInitializers(unsigned numCtorInitializers) {
2713 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2714 // This assert added because NumCtorInitializers is stored
2715 // in CXXConstructorDeclBits as a bitfield and its width has
2716 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2717 assert(CXXConstructorDeclBits.NumCtorInitializers ==
2718 numCtorInitializers && "NumCtorInitializers overflow!");
2721 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2722 CtorInitializers = Initializers;
2725 /// Determine whether this constructor is a delegating constructor.
2726 bool isDelegatingConstructor() const {
2727 return (getNumCtorInitializers() == 1) &&
2728 init_begin()[0]->isDelegatingInitializer();
2731 /// When this constructor delegates to another, retrieve the target.
2732 CXXConstructorDecl *getTargetConstructor() const;
2734 /// Whether this constructor is a default
2735 /// constructor (C++ [class.ctor]p5), which can be used to
2736 /// default-initialize a class of this type.
2737 bool isDefaultConstructor() const;
2739 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2740 /// which can be used to copy the class.
2742 /// \p TypeQuals will be set to the qualifiers on the
2743 /// argument type. For example, \p TypeQuals would be set to \c
2744 /// Qualifiers::Const for the following copy constructor:
2752 bool isCopyConstructor(unsigned &TypeQuals) const;
2754 /// Whether this constructor is a copy
2755 /// constructor (C++ [class.copy]p2, which can be used to copy the
2757 bool isCopyConstructor() const {
2758 unsigned TypeQuals = 0;
2759 return isCopyConstructor(TypeQuals);
2762 /// Determine whether this constructor is a move constructor
2763 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2765 /// \param TypeQuals If this constructor is a move constructor, will be set
2766 /// to the type qualifiers on the referent of the first parameter's type.
2767 bool isMoveConstructor(unsigned &TypeQuals) const;
2769 /// Determine whether this constructor is a move constructor
2770 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2771 bool isMoveConstructor() const {
2772 unsigned TypeQuals = 0;
2773 return isMoveConstructor(TypeQuals);
2776 /// Determine whether this is a copy or move constructor.
2778 /// \param TypeQuals Will be set to the type qualifiers on the reference
2779 /// parameter, if in fact this is a copy or move constructor.
2780 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2782 /// Determine whether this a copy or move constructor.
2783 bool isCopyOrMoveConstructor() const {
2785 return isCopyOrMoveConstructor(Quals);
2788 /// Whether this constructor is a
2789 /// converting constructor (C++ [class.conv.ctor]), which can be
2790 /// used for user-defined conversions.
2791 bool isConvertingConstructor(bool AllowExplicit) const;
2793 /// Determine whether this is a member template specialization that
2794 /// would copy the object to itself. Such constructors are never used to copy
2796 bool isSpecializationCopyingObject() const;
2798 /// Determine whether this is an implicit constructor synthesized to
2799 /// model a call to a constructor inherited from a base class.
2800 bool isInheritingConstructor() const {
2801 return CXXConstructorDeclBits.IsInheritingConstructor;
2804 /// State that this is an implicit constructor synthesized to
2805 /// model a call to a constructor inherited from a base class.
2806 void setInheritingConstructor(bool isIC = true) {
2807 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2810 /// Get the constructor that this inheriting constructor is based on.
2811 InheritedConstructor getInheritedConstructor() const {
2812 return isInheritingConstructor() ?
2813 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2816 CXXConstructorDecl *getCanonicalDecl() override {
2817 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2819 const CXXConstructorDecl *getCanonicalDecl() const {
2820 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2823 // Implement isa/cast/dyncast/etc.
2824 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2825 static bool classofKind(Kind K) { return K == CXXConstructor; }
2828 /// Represents a C++ destructor within a class.
2835 /// ~X(); // represented by a CXXDestructorDecl.
2838 class CXXDestructorDecl : public CXXMethodDecl {
2839 friend class ASTDeclReader;
2840 friend class ASTDeclWriter;
2842 // FIXME: Don't allocate storage for these except in the first declaration
2843 // of a virtual destructor.
2844 FunctionDecl *OperatorDelete = nullptr;
2845 Expr *OperatorDeleteThisArg = nullptr;
2847 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2848 const DeclarationNameInfo &NameInfo, QualType T,
2849 TypeSourceInfo *TInfo, bool isInline,
2850 bool isImplicitlyDeclared)
2851 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2852 SC_None, isInline, CSK_unspecified, SourceLocation()) {
2853 setImplicit(isImplicitlyDeclared);
2856 void anchor() override;
2859 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2860 SourceLocation StartLoc,
2861 const DeclarationNameInfo &NameInfo,
2862 QualType T, TypeSourceInfo* TInfo,
2864 bool isImplicitlyDeclared);
2865 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2867 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2869 const FunctionDecl *getOperatorDelete() const {
2870 return getCanonicalDecl()->OperatorDelete;
2873 Expr *getOperatorDeleteThisArg() const {
2874 return getCanonicalDecl()->OperatorDeleteThisArg;
2877 CXXDestructorDecl *getCanonicalDecl() override {
2878 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2880 const CXXDestructorDecl *getCanonicalDecl() const {
2881 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2884 // Implement isa/cast/dyncast/etc.
2885 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2886 static bool classofKind(Kind K) { return K == CXXDestructor; }
2889 /// Represents a C++ conversion function within a class.
2896 /// operator bool();
2899 class CXXConversionDecl : public CXXMethodDecl {
2900 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2901 const DeclarationNameInfo &NameInfo, QualType T,
2902 TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES,
2903 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation)
2904 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2905 SC_None, isInline, ConstexprKind, EndLocation),
2907 void anchor() override;
2909 ExplicitSpecifier ExplicitSpec;
2911 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2914 friend class ASTDeclReader;
2915 friend class ASTDeclWriter;
2917 static CXXConversionDecl *
2918 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2919 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2920 bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2921 SourceLocation EndLocation);
2922 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2924 ExplicitSpecifier getExplicitSpecifier() {
2925 return getCanonicalDecl()->ExplicitSpec;
2928 const ExplicitSpecifier getExplicitSpecifier() const {
2929 return getCanonicalDecl()->ExplicitSpec;
2932 /// Return true if the declartion is already resolved to be explicit.
2933 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2935 /// Returns the type that this conversion function is converting to.
2936 QualType getConversionType() const {
2937 return getType()->getAs<FunctionType>()->getReturnType();
2940 /// Determine whether this conversion function is a conversion from
2941 /// a lambda closure type to a block pointer.
2942 bool isLambdaToBlockPointerConversion() const;
2944 CXXConversionDecl *getCanonicalDecl() override {
2945 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2947 const CXXConversionDecl *getCanonicalDecl() const {
2948 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2951 // Implement isa/cast/dyncast/etc.
2952 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2953 static bool classofKind(Kind K) { return K == CXXConversion; }
2956 /// Represents a linkage specification.
2960 /// extern "C" void foo();
2962 class LinkageSpecDecl : public Decl, public DeclContext {
2963 virtual void anchor();
2964 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2965 // some space. Use the provided accessors to access it.
2967 /// Represents the language in a linkage specification.
2969 /// The values are part of the serialization ABI for
2970 /// ASTs and cannot be changed without altering that ABI. To help
2971 /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
2972 /// from the dwarf standard.
2974 lang_c = /* DW_LANG_C */ 0x0002,
2975 lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004
2979 /// The source location for the extern keyword.
2980 SourceLocation ExternLoc;
2982 /// The source location for the right brace (if valid).
2983 SourceLocation RBraceLoc;
2985 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2986 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2989 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2990 SourceLocation ExternLoc,
2991 SourceLocation LangLoc, LanguageIDs Lang,
2993 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2995 /// Return the language specified by this linkage specification.
2996 LanguageIDs getLanguage() const {
2997 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
3000 /// Set the language specified by this linkage specification.
3001 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
3003 /// Determines whether this linkage specification had braces in
3004 /// its syntactic form.
3005 bool hasBraces() const {
3006 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces);
3007 return LinkageSpecDeclBits.HasBraces;
3010 SourceLocation getExternLoc() const { return ExternLoc; }
3011 SourceLocation getRBraceLoc() const { return RBraceLoc; }
3012 void setExternLoc(SourceLocation L) { ExternLoc = L; }
3013 void setRBraceLoc(SourceLocation L) {
3015 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
3018 SourceLocation getEndLoc() const LLVM_READONLY {
3020 return getRBraceLoc();
3021 // No braces: get the end location of the (only) declaration in context
3023 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
3026 SourceRange getSourceRange() const override LLVM_READONLY {
3027 return SourceRange(ExternLoc, getEndLoc());
3030 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3031 static bool classofKind(Kind K) { return K == LinkageSpec; }
3033 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
3034 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
3037 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
3038 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
3042 /// Represents C++ using-directive.
3046 /// using namespace std;
3049 /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
3050 /// artificial names for all using-directives in order to store
3051 /// them in DeclContext effectively.
3052 class UsingDirectiveDecl : public NamedDecl {
3053 /// The location of the \c using keyword.
3054 SourceLocation UsingLoc;
3056 /// The location of the \c namespace keyword.
3057 SourceLocation NamespaceLoc;
3059 /// The nested-name-specifier that precedes the namespace.
3060 NestedNameSpecifierLoc QualifierLoc;
3062 /// The namespace nominated by this using-directive.
3063 NamedDecl *NominatedNamespace;
3065 /// Enclosing context containing both using-directive and nominated
3067 DeclContext *CommonAncestor;
3069 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
3070 SourceLocation NamespcLoc,
3071 NestedNameSpecifierLoc QualifierLoc,
3072 SourceLocation IdentLoc,
3073 NamedDecl *Nominated,
3074 DeclContext *CommonAncestor)
3075 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
3076 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
3077 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
3079 /// Returns special DeclarationName used by using-directives.
3081 /// This is only used by DeclContext for storing UsingDirectiveDecls in
3082 /// its lookup structure.
3083 static DeclarationName getName() {
3084 return DeclarationName::getUsingDirectiveName();
3087 void anchor() override;
3090 friend class ASTDeclReader;
3092 // Friend for getUsingDirectiveName.
3093 friend class DeclContext;
3095 /// Retrieve the nested-name-specifier that qualifies the
3096 /// name of the namespace, with source-location information.
3097 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3099 /// Retrieve the nested-name-specifier that qualifies the
3100 /// name of the namespace.
3101 NestedNameSpecifier *getQualifier() const {
3102 return QualifierLoc.getNestedNameSpecifier();
3105 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
3106 const NamedDecl *getNominatedNamespaceAsWritten() const {
3107 return NominatedNamespace;
3110 /// Returns the namespace nominated by this using-directive.
3111 NamespaceDecl *getNominatedNamespace();
3113 const NamespaceDecl *getNominatedNamespace() const {
3114 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
3117 /// Returns the common ancestor context of this using-directive and
3118 /// its nominated namespace.
3119 DeclContext *getCommonAncestor() { return CommonAncestor; }
3120 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
3122 /// Return the location of the \c using keyword.
3123 SourceLocation getUsingLoc() const { return UsingLoc; }
3125 // FIXME: Could omit 'Key' in name.
3126 /// Returns the location of the \c namespace keyword.
3127 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
3129 /// Returns the location of this using declaration's identifier.
3130 SourceLocation getIdentLocation() const { return getLocation(); }
3132 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
3133 SourceLocation UsingLoc,
3134 SourceLocation NamespaceLoc,
3135 NestedNameSpecifierLoc QualifierLoc,
3136 SourceLocation IdentLoc,
3137 NamedDecl *Nominated,
3138 DeclContext *CommonAncestor);
3139 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3141 SourceRange getSourceRange() const override LLVM_READONLY {
3142 return SourceRange(UsingLoc, getLocation());
3145 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3146 static bool classofKind(Kind K) { return K == UsingDirective; }
3149 /// Represents a C++ namespace alias.
3154 /// namespace Foo = Bar;
3156 class NamespaceAliasDecl : public NamedDecl,
3157 public Redeclarable<NamespaceAliasDecl> {
3158 friend class ASTDeclReader;
3160 /// The location of the \c namespace keyword.
3161 SourceLocation NamespaceLoc;
3163 /// The location of the namespace's identifier.
3165 /// This is accessed by TargetNameLoc.
3166 SourceLocation IdentLoc;
3168 /// The nested-name-specifier that precedes the namespace.
3169 NestedNameSpecifierLoc QualifierLoc;
3171 /// The Decl that this alias points to, either a NamespaceDecl or
3172 /// a NamespaceAliasDecl.
3173 NamedDecl *Namespace;
3175 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3176 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3177 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3178 SourceLocation IdentLoc, NamedDecl *Namespace)
3179 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3180 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3181 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3183 void anchor() override;
3185 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3187 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3188 NamespaceAliasDecl *getPreviousDeclImpl() override;
3189 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3192 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3193 SourceLocation NamespaceLoc,
3194 SourceLocation AliasLoc,
3195 IdentifierInfo *Alias,
3196 NestedNameSpecifierLoc QualifierLoc,
3197 SourceLocation IdentLoc,
3198 NamedDecl *Namespace);
3200 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3202 using redecl_range = redeclarable_base::redecl_range;
3203 using redecl_iterator = redeclarable_base::redecl_iterator;
3205 using redeclarable_base::redecls_begin;
3206 using redeclarable_base::redecls_end;
3207 using redeclarable_base::redecls;
3208 using redeclarable_base::getPreviousDecl;
3209 using redeclarable_base::getMostRecentDecl;
3211 NamespaceAliasDecl *getCanonicalDecl() override {
3212 return getFirstDecl();
3214 const NamespaceAliasDecl *getCanonicalDecl() const {
3215 return getFirstDecl();
3218 /// Retrieve the nested-name-specifier that qualifies the
3219 /// name of the namespace, with source-location information.
3220 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3222 /// Retrieve the nested-name-specifier that qualifies the
3223 /// name of the namespace.
3224 NestedNameSpecifier *getQualifier() const {
3225 return QualifierLoc.getNestedNameSpecifier();
3228 /// Retrieve the namespace declaration aliased by this directive.
3229 NamespaceDecl *getNamespace() {
3230 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3231 return AD->getNamespace();
3233 return cast<NamespaceDecl>(Namespace);
3236 const NamespaceDecl *getNamespace() const {
3237 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3240 /// Returns the location of the alias name, i.e. 'foo' in
3241 /// "namespace foo = ns::bar;".
3242 SourceLocation getAliasLoc() const { return getLocation(); }
3244 /// Returns the location of the \c namespace keyword.
3245 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3247 /// Returns the location of the identifier in the named namespace.
3248 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3250 /// Retrieve the namespace that this alias refers to, which
3251 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3252 NamedDecl *getAliasedNamespace() const { return Namespace; }
3254 SourceRange getSourceRange() const override LLVM_READONLY {
3255 return SourceRange(NamespaceLoc, IdentLoc);
3258 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3259 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3262 /// Represents a shadow declaration introduced into a scope by a
3263 /// (resolved) using declaration.
3271 /// using A::foo; // <- a UsingDecl
3272 /// // Also creates a UsingShadowDecl for A::foo() in B
3275 class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3276 friend class UsingDecl;
3278 /// The referenced declaration.
3279 NamedDecl *Underlying = nullptr;
3281 /// The using declaration which introduced this decl or the next using
3282 /// shadow declaration contained in the aforementioned using declaration.
3283 NamedDecl *UsingOrNextShadow = nullptr;
3285 void anchor() override;
3287 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3289 UsingShadowDecl *getNextRedeclarationImpl() override {
3290 return getNextRedeclaration();
3293 UsingShadowDecl *getPreviousDeclImpl() override {
3294 return getPreviousDecl();
3297 UsingShadowDecl *getMostRecentDeclImpl() override {
3298 return getMostRecentDecl();
3302 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3303 UsingDecl *Using, NamedDecl *Target);
3304 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3307 friend class ASTDeclReader;
3308 friend class ASTDeclWriter;
3310 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3311 SourceLocation Loc, UsingDecl *Using,
3312 NamedDecl *Target) {
3313 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3316 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3318 using redecl_range = redeclarable_base::redecl_range;
3319 using redecl_iterator = redeclarable_base::redecl_iterator;
3321 using redeclarable_base::redecls_begin;
3322 using redeclarable_base::redecls_end;
3323 using redeclarable_base::redecls;
3324 using redeclarable_base::getPreviousDecl;
3325 using redeclarable_base::getMostRecentDecl;
3326 using redeclarable_base::isFirstDecl;
3328 UsingShadowDecl *getCanonicalDecl() override {
3329 return getFirstDecl();
3331 const UsingShadowDecl *getCanonicalDecl() const {
3332 return getFirstDecl();
3335 /// Gets the underlying declaration which has been brought into the
3337 NamedDecl *getTargetDecl() const { return Underlying; }
3339 /// Sets the underlying declaration which has been brought into the
3341 void setTargetDecl(NamedDecl *ND) {
3342 assert(ND && "Target decl is null!");
3344 // A UsingShadowDecl is never a friend or local extern declaration, even
3345 // if it is a shadow declaration for one.
3346 IdentifierNamespace =
3347 ND->getIdentifierNamespace() &
3348 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3351 /// Gets the using declaration to which this declaration is tied.
3352 UsingDecl *getUsingDecl() const;
3354 /// The next using shadow declaration contained in the shadow decl
3355 /// chain of the using declaration which introduced this decl.
3356 UsingShadowDecl *getNextUsingShadowDecl() const {
3357 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3360 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3361 static bool classofKind(Kind K) {
3362 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3366 /// Represents a shadow constructor declaration introduced into a
3367 /// class by a C++11 using-declaration that names a constructor.
3371 /// struct Base { Base(int); };
3372 /// struct Derived {
3373 /// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3376 class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3377 /// If this constructor using declaration inherted the constructor
3378 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3379 /// in the named direct base class from which the declaration was inherited.
3380 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3382 /// If this constructor using declaration inherted the constructor
3383 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3384 /// that will be used to construct the unique direct or virtual base class
3385 /// that receives the constructor arguments.
3386 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3388 /// \c true if the constructor ultimately named by this using shadow
3389 /// declaration is within a virtual base class subobject of the class that
3390 /// contains this declaration.
3391 unsigned IsVirtual : 1;
3393 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3394 UsingDecl *Using, NamedDecl *Target,
3395 bool TargetInVirtualBase)
3396 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3397 Target->getUnderlyingDecl()),
3398 NominatedBaseClassShadowDecl(
3399 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3400 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3401 IsVirtual(TargetInVirtualBase) {
3402 // If we found a constructor that chains to a constructor for a virtual
3403 // base, we should directly call that virtual base constructor instead.
3404 // FIXME: This logic belongs in Sema.
3405 if (NominatedBaseClassShadowDecl &&
3406 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3407 ConstructedBaseClassShadowDecl =
3408 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3413 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3414 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3416 void anchor() override;
3419 friend class ASTDeclReader;
3420 friend class ASTDeclWriter;
3422 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3424 UsingDecl *Using, NamedDecl *Target,
3426 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3429 /// Returns the parent of this using shadow declaration, which
3430 /// is the class in which this is declared.
3432 const CXXRecordDecl *getParent() const {
3433 return cast<CXXRecordDecl>(getDeclContext());
3435 CXXRecordDecl *getParent() {
3436 return cast<CXXRecordDecl>(getDeclContext());
3440 /// Get the inheriting constructor declaration for the direct base
3441 /// class from which this using shadow declaration was inherited, if there is
3442 /// one. This can be different for each redeclaration of the same shadow decl.
3443 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3444 return NominatedBaseClassShadowDecl;
3447 /// Get the inheriting constructor declaration for the base class
3448 /// for which we don't have an explicit initializer, if there is one.
3449 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3450 return ConstructedBaseClassShadowDecl;
3453 /// Get the base class that was named in the using declaration. This
3454 /// can be different for each redeclaration of this same shadow decl.
3455 CXXRecordDecl *getNominatedBaseClass() const;
3457 /// Get the base class whose constructor or constructor shadow
3458 /// declaration is passed the constructor arguments.
3459 CXXRecordDecl *getConstructedBaseClass() const {
3460 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3461 ? ConstructedBaseClassShadowDecl
3463 ->getDeclContext());
3466 /// Returns \c true if the constructed base class is a virtual base
3467 /// class subobject of this declaration's class.
3468 bool constructsVirtualBase() const {
3472 /// Get the constructor or constructor template in the derived class
3473 /// correspnding to this using shadow declaration, if it has been implicitly
3474 /// declared already.
3475 CXXConstructorDecl *getConstructor() const;
3476 void setConstructor(NamedDecl *Ctor);
3478 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3479 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3482 /// Represents a C++ using-declaration.
3486 /// using someNameSpace::someIdentifier;
3488 class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3489 /// The source location of the 'using' keyword itself.
3490 SourceLocation UsingLocation;
3492 /// The nested-name-specifier that precedes the name.
3493 NestedNameSpecifierLoc QualifierLoc;
3495 /// Provides source/type location info for the declaration name
3496 /// embedded in the ValueDecl base class.
3497 DeclarationNameLoc DNLoc;
3499 /// The first shadow declaration of the shadow decl chain associated
3500 /// with this using declaration.
3502 /// The bool member of the pair store whether this decl has the \c typename
3504 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3506 UsingDecl(DeclContext *DC, SourceLocation UL,
3507 NestedNameSpecifierLoc QualifierLoc,
3508 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3509 : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3510 UsingLocation(UL), QualifierLoc(QualifierLoc),
3511 DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3514 void anchor() override;
3517 friend class ASTDeclReader;
3518 friend class ASTDeclWriter;
3520 /// Return the source location of the 'using' keyword.
3521 SourceLocation getUsingLoc() const { return UsingLocation; }
3523 /// Set the source location of the 'using' keyword.
3524 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3526 /// Retrieve the nested-name-specifier that qualifies the name,
3527 /// with source-location information.
3528 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3530 /// Retrieve the nested-name-specifier that qualifies the name.
3531 NestedNameSpecifier *getQualifier() const {
3532 return QualifierLoc.getNestedNameSpecifier();
3535 DeclarationNameInfo getNameInfo() const {
3536 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3539 /// Return true if it is a C++03 access declaration (no 'using').
3540 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3542 /// Return true if the using declaration has 'typename'.
3543 bool hasTypename() const { return FirstUsingShadow.getInt(); }
3545 /// Sets whether the using declaration has 'typename'.
3546 void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3548 /// Iterates through the using shadow declarations associated with
3549 /// this using declaration.
3550 class shadow_iterator {
3551 /// The current using shadow declaration.
3552 UsingShadowDecl *Current = nullptr;
3555 using value_type = UsingShadowDecl *;
3556 using reference = UsingShadowDecl *;
3557 using pointer = UsingShadowDecl *;
3558 using iterator_category = std::forward_iterator_tag;
3559 using difference_type = std::ptrdiff_t;
3561 shadow_iterator() = default;
3562 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3564 reference operator*() const { return Current; }
3565 pointer operator->() const { return Current; }
3567 shadow_iterator& operator++() {
3568 Current = Current->getNextUsingShadowDecl();
3572 shadow_iterator operator++(int) {
3573 shadow_iterator tmp(*this);
3578 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3579 return x.Current == y.Current;
3581 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3582 return x.Current != y.Current;
3586 using shadow_range = llvm::iterator_range<shadow_iterator>;
3588 shadow_range shadows() const {
3589 return shadow_range(shadow_begin(), shadow_end());
3592 shadow_iterator shadow_begin() const {
3593 return shadow_iterator(FirstUsingShadow.getPointer());
3596 shadow_iterator shadow_end() const { return shadow_iterator(); }
3598 /// Return the number of shadowed declarations associated with this
3599 /// using declaration.
3600 unsigned shadow_size() const {
3601 return std::distance(shadow_begin(), shadow_end());
3604 void addShadowDecl(UsingShadowDecl *S);
3605 void removeShadowDecl(UsingShadowDecl *S);
3607 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3608 SourceLocation UsingL,
3609 NestedNameSpecifierLoc QualifierLoc,
3610 const DeclarationNameInfo &NameInfo,
3611 bool HasTypenameKeyword);
3613 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3615 SourceRange getSourceRange() const override LLVM_READONLY;
3617 /// Retrieves the canonical declaration of this declaration.
3618 UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3619 const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3621 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3622 static bool classofKind(Kind K) { return K == Using; }
3625 /// Represents a pack of using declarations that a single
3626 /// using-declarator pack-expanded into.
3629 /// template<typename ...T> struct X : T... {
3630 /// using T::operator()...;
3631 /// using T::operator T...;
3635 /// In the second case above, the UsingPackDecl will have the name
3636 /// 'operator T' (which contains an unexpanded pack), but the individual
3637 /// UsingDecls and UsingShadowDecls will have more reasonable names.
3638 class UsingPackDecl final
3639 : public NamedDecl, public Mergeable<UsingPackDecl>,
3640 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3641 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3642 /// which this waas instantiated.
3643 NamedDecl *InstantiatedFrom;
3645 /// The number of using-declarations created by this pack expansion.
3646 unsigned NumExpansions;
3648 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3649 ArrayRef<NamedDecl *> UsingDecls)
3650 : NamedDecl(UsingPack, DC,
3651 InstantiatedFrom ? InstantiatedFrom->getLocation()
3653 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3654 : DeclarationName()),
3655 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3656 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3657 getTrailingObjects<NamedDecl *>());
3660 void anchor() override;
3663 friend class ASTDeclReader;
3664 friend class ASTDeclWriter;
3665 friend TrailingObjects;
3667 /// Get the using declaration from which this was instantiated. This will
3668 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3669 /// that is a pack expansion.
3670 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3672 /// Get the set of using declarations that this pack expanded into. Note that
3673 /// some of these may still be unresolved.
3674 ArrayRef<NamedDecl *> expansions() const {
3675 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3678 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3679 NamedDecl *InstantiatedFrom,
3680 ArrayRef<NamedDecl *> UsingDecls);
3682 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3683 unsigned NumExpansions);
3685 SourceRange getSourceRange() const override LLVM_READONLY {
3686 return InstantiatedFrom->getSourceRange();
3689 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3690 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3692 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3693 static bool classofKind(Kind K) { return K == UsingPack; }
3696 /// Represents a dependent using declaration which was not marked with
3699 /// Unlike non-dependent using declarations, these *only* bring through
3700 /// non-types; otherwise they would break two-phase lookup.
3703 /// template \<class T> class A : public Base<T> {
3704 /// using Base<T>::foo;
3707 class UnresolvedUsingValueDecl : public ValueDecl,
3708 public Mergeable<UnresolvedUsingValueDecl> {
3709 /// The source location of the 'using' keyword
3710 SourceLocation UsingLocation;
3712 /// If this is a pack expansion, the location of the '...'.
3713 SourceLocation EllipsisLoc;
3715 /// The nested-name-specifier that precedes the name.
3716 NestedNameSpecifierLoc QualifierLoc;
3718 /// Provides source/type location info for the declaration name
3719 /// embedded in the ValueDecl base class.
3720 DeclarationNameLoc DNLoc;
3722 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3723 SourceLocation UsingLoc,
3724 NestedNameSpecifierLoc QualifierLoc,
3725 const DeclarationNameInfo &NameInfo,
3726 SourceLocation EllipsisLoc)
3727 : ValueDecl(UnresolvedUsingValue, DC,
3728 NameInfo.getLoc(), NameInfo.getName(), Ty),
3729 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3730 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3732 void anchor() override;
3735 friend class ASTDeclReader;
3736 friend class ASTDeclWriter;
3738 /// Returns the source location of the 'using' keyword.
3739 SourceLocation getUsingLoc() const { return UsingLocation; }
3741 /// Set the source location of the 'using' keyword.
3742 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3744 /// Return true if it is a C++03 access declaration (no 'using').
3745 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3747 /// Retrieve the nested-name-specifier that qualifies the name,
3748 /// with source-location information.
3749 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3751 /// Retrieve the nested-name-specifier that qualifies the name.
3752 NestedNameSpecifier *getQualifier() const {
3753 return QualifierLoc.getNestedNameSpecifier();
3756 DeclarationNameInfo getNameInfo() const {
3757 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3760 /// Determine whether this is a pack expansion.
3761 bool isPackExpansion() const {
3762 return EllipsisLoc.isValid();
3765 /// Get the location of the ellipsis if this is a pack expansion.
3766 SourceLocation getEllipsisLoc() const {
3770 static UnresolvedUsingValueDecl *
3771 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3772 NestedNameSpecifierLoc QualifierLoc,
3773 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3775 static UnresolvedUsingValueDecl *
3776 CreateDeserialized(ASTContext &C, unsigned ID);
3778 SourceRange getSourceRange() const override LLVM_READONLY;
3780 /// Retrieves the canonical declaration of this declaration.
3781 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3782 return getFirstDecl();
3784 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3785 return getFirstDecl();
3788 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3789 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3792 /// Represents a dependent using declaration which was marked with
3796 /// template \<class T> class A : public Base<T> {
3797 /// using typename Base<T>::foo;
3801 /// The type associated with an unresolved using typename decl is
3802 /// currently always a typename type.
3803 class UnresolvedUsingTypenameDecl
3805 public Mergeable<UnresolvedUsingTypenameDecl> {
3806 friend class ASTDeclReader;
3808 /// The source location of the 'typename' keyword
3809 SourceLocation TypenameLocation;
3811 /// If this is a pack expansion, the location of the '...'.
3812 SourceLocation EllipsisLoc;
3814 /// The nested-name-specifier that precedes the name.
3815 NestedNameSpecifierLoc QualifierLoc;
3817 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3818 SourceLocation TypenameLoc,
3819 NestedNameSpecifierLoc QualifierLoc,
3820 SourceLocation TargetNameLoc,
3821 IdentifierInfo *TargetName,
3822 SourceLocation EllipsisLoc)
3823 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3825 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3826 QualifierLoc(QualifierLoc) {}
3828 void anchor() override;
3831 /// Returns the source location of the 'using' keyword.
3832 SourceLocation getUsingLoc() const { return getBeginLoc(); }
3834 /// Returns the source location of the 'typename' keyword.
3835 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3837 /// Retrieve the nested-name-specifier that qualifies the name,
3838 /// with source-location information.
3839 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3841 /// Retrieve the nested-name-specifier that qualifies the name.
3842 NestedNameSpecifier *getQualifier() const {
3843 return QualifierLoc.getNestedNameSpecifier();
3846 DeclarationNameInfo getNameInfo() const {
3847 return DeclarationNameInfo(getDeclName(), getLocation());
3850 /// Determine whether this is a pack expansion.
3851 bool isPackExpansion() const {
3852 return EllipsisLoc.isValid();
3855 /// Get the location of the ellipsis if this is a pack expansion.
3856 SourceLocation getEllipsisLoc() const {
3860 static UnresolvedUsingTypenameDecl *
3861 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3862 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3863 SourceLocation TargetNameLoc, DeclarationName TargetName,
3864 SourceLocation EllipsisLoc);
3866 static UnresolvedUsingTypenameDecl *
3867 CreateDeserialized(ASTContext &C, unsigned ID);
3869 /// Retrieves the canonical declaration of this declaration.
3870 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3871 return getFirstDecl();
3873 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3874 return getFirstDecl();
3877 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3878 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3881 /// Represents a C++11 static_assert declaration.
3882 class StaticAssertDecl : public Decl {
3883 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3884 StringLiteral *Message;
3885 SourceLocation RParenLoc;
3887 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3888 Expr *AssertExpr, StringLiteral *Message,
3889 SourceLocation RParenLoc, bool Failed)
3890 : Decl(StaticAssert, DC, StaticAssertLoc),
3891 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3892 RParenLoc(RParenLoc) {}
3894 virtual void anchor();
3897 friend class ASTDeclReader;
3899 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3900 SourceLocation StaticAssertLoc,
3901 Expr *AssertExpr, StringLiteral *Message,
3902 SourceLocation RParenLoc, bool Failed);
3903 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3905 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3906 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3908 StringLiteral *getMessage() { return Message; }
3909 const StringLiteral *getMessage() const { return Message; }
3911 bool isFailed() const { return AssertExprAndFailed.getInt(); }
3913 SourceLocation getRParenLoc() const { return RParenLoc; }
3915 SourceRange getSourceRange() const override LLVM_READONLY {
3916 return SourceRange(getLocation(), getRParenLoc());
3919 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3920 static bool classofKind(Kind K) { return K == StaticAssert; }
3923 /// A binding in a decomposition declaration. For instance, given:
3926 /// auto &[a, b, c] = n;
3928 /// a, b, and c are BindingDecls, whose bindings are the expressions
3929 /// x[0], x[1], and x[2] respectively, where x is the implicit
3930 /// DecompositionDecl of type 'int (&)[3]'.
3931 class BindingDecl : public ValueDecl {
3932 /// The declaration that this binding binds to part of.
3934 /// The binding represented by this declaration. References to this
3935 /// declaration are effectively equivalent to this expression (except
3936 /// that it is only evaluated once at the point of declaration of the
3938 Expr *Binding = nullptr;
3940 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3941 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3943 void anchor() override;
3946 friend class ASTDeclReader;
3948 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3949 SourceLocation IdLoc, IdentifierInfo *Id);
3950 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3952 /// Get the expression to which this declaration is bound. This may be null
3953 /// in two different cases: while parsing the initializer for the
3954 /// decomposition declaration, and when the initializer is type-dependent.
3955 Expr *getBinding() const { return Binding; }
3957 /// Get the decomposition declaration that this binding represents a
3958 /// decomposition of.
3959 ValueDecl *getDecomposedDecl() const;
3961 /// Get the variable (if any) that holds the value of evaluating the binding.
3962 /// Only present for user-defined bindings for tuple-like types.
3963 VarDecl *getHoldingVar() const;
3965 /// Set the binding for this BindingDecl, along with its declared type (which
3966 /// should be a possibly-cv-qualified form of the type of the binding, or a
3967 /// reference to such a type).
3968 void setBinding(QualType DeclaredType, Expr *Binding) {
3969 setType(DeclaredType);
3970 this->Binding = Binding;
3973 /// Set the decomposed variable for this BindingDecl.
3974 void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
3976 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3977 static bool classofKind(Kind K) { return K == Decl::Binding; }
3980 /// A decomposition declaration. For instance, given:
3983 /// auto &[a, b, c] = n;
3985 /// the second line declares a DecompositionDecl of type 'int (&)[3]', and
3986 /// three BindingDecls (named a, b, and c). An instance of this class is always
3987 /// unnamed, but behaves in almost all other respects like a VarDecl.
3988 class DecompositionDecl final
3990 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
3991 /// The number of BindingDecl*s following this object.
3992 unsigned NumBindings;
3994 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3995 SourceLocation LSquareLoc, QualType T,
3996 TypeSourceInfo *TInfo, StorageClass SC,
3997 ArrayRef<BindingDecl *> Bindings)
3998 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
4000 NumBindings(Bindings.size()) {
4001 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
4002 getTrailingObjects<BindingDecl *>());
4003 for (auto *B : Bindings)
4004 B->setDecomposedDecl(this);
4007 void anchor() override;
4010 friend class ASTDeclReader;
4011 friend TrailingObjects;
4013 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
4014 SourceLocation StartLoc,
4015 SourceLocation LSquareLoc,
4016 QualType T, TypeSourceInfo *TInfo,
4018 ArrayRef<BindingDecl *> Bindings);
4019 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4020 unsigned NumBindings);
4022 ArrayRef<BindingDecl *> bindings() const {
4023 return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
4026 void printName(raw_ostream &os) const override;
4028 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4029 static bool classofKind(Kind K) { return K == Decomposition; }
4032 /// An instance of this class represents the declaration of a property
4033 /// member. This is a Microsoft extension to C++, first introduced in
4034 /// Visual Studio .NET 2003 as a parallel to similar features in C#
4035 /// and Managed C++.
4037 /// A property must always be a non-static class member.
4039 /// A property member superficially resembles a non-static data
4040 /// member, except preceded by a property attribute:
4041 /// __declspec(property(get=GetX, put=PutX)) int x;
4042 /// Either (but not both) of the 'get' and 'put' names may be omitted.
4044 /// A reference to a property is always an lvalue. If the lvalue
4045 /// undergoes lvalue-to-rvalue conversion, then a getter name is
4046 /// required, and that member is called with no arguments.
4047 /// If the lvalue is assigned into, then a setter name is required,
4048 /// and that member is called with one argument, the value assigned.
4049 /// Both operations are potentially overloaded. Compound assignments
4050 /// are permitted, as are the increment and decrement operators.
4052 /// The getter and putter methods are permitted to be overloaded,
4053 /// although their return and parameter types are subject to certain
4054 /// restrictions according to the type of the property.
4056 /// A property declared using an incomplete array type may
4057 /// additionally be subscripted, adding extra parameters to the getter
4058 /// and putter methods.
4059 class MSPropertyDecl : public DeclaratorDecl {
4060 IdentifierInfo *GetterId, *SetterId;
4062 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
4063 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
4064 IdentifierInfo *Getter, IdentifierInfo *Setter)
4065 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
4066 GetterId(Getter), SetterId(Setter) {}
4068 void anchor() override;
4070 friend class ASTDeclReader;
4072 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
4073 SourceLocation L, DeclarationName N, QualType T,
4074 TypeSourceInfo *TInfo, SourceLocation StartL,
4075 IdentifierInfo *Getter, IdentifierInfo *Setter);
4076 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4078 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
4080 bool hasGetter() const { return GetterId != nullptr; }
4081 IdentifierInfo* getGetterId() const { return GetterId; }
4082 bool hasSetter() const { return SetterId != nullptr; }
4083 IdentifierInfo* getSetterId() const { return SetterId; }
4086 /// Insertion operator for diagnostics. This allows sending an AccessSpecifier
4087 /// into a diagnostic with <<.
4088 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4089 AccessSpecifier AS);
4091 const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
4092 AccessSpecifier AS);
4094 } // namespace clang
4096 #endif // LLVM_CLANG_AST_DECLCXX_H