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