1 //===- DeclBase.h - Base Classes for representing 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 // This file defines the Decl and DeclContext interfaces. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_AST_DECLBASE_H 14 #define LLVM_CLANG_AST_DECLBASE_H 15 16 #include "clang/AST/ASTDumperUtils.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/DeclID.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/SelectorLocationsKind.h" 21 #include "clang/Basic/IdentifierTable.h" 22 #include "clang/Basic/LLVM.h" 23 #include "clang/Basic/LangOptions.h" 24 #include "clang/Basic/SourceLocation.h" 25 #include "clang/Basic/Specifiers.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/PointerIntPair.h" 28 #include "llvm/ADT/PointerUnion.h" 29 #include "llvm/ADT/iterator.h" 30 #include "llvm/ADT/iterator_range.h" 31 #include "llvm/Support/Casting.h" 32 #include "llvm/Support/Compiler.h" 33 #include "llvm/Support/PrettyStackTrace.h" 34 #include "llvm/Support/VersionTuple.h" 35 #include <algorithm> 36 #include <cassert> 37 #include <cstddef> 38 #include <iterator> 39 #include <string> 40 #include <type_traits> 41 #include <utility> 42 43 namespace clang { 44 45 class ASTContext; 46 class ASTMutationListener; 47 class Attr; 48 class BlockDecl; 49 class DeclContext; 50 class ExternalSourceSymbolAttr; 51 class FunctionDecl; 52 class FunctionType; 53 class IdentifierInfo; 54 enum class Linkage : unsigned char; 55 class LinkageSpecDecl; 56 class Module; 57 class NamedDecl; 58 class ObjCContainerDecl; 59 class ObjCMethodDecl; 60 struct PrintingPolicy; 61 class RecordDecl; 62 class SourceManager; 63 class Stmt; 64 class StoredDeclsMap; 65 class TemplateDecl; 66 class TemplateParameterList; 67 class TranslationUnitDecl; 68 class UsingDirectiveDecl; 69 70 /// Captures the result of checking the availability of a 71 /// declaration. 72 enum AvailabilityResult { 73 AR_Available = 0, 74 AR_NotYetIntroduced, 75 AR_Deprecated, 76 AR_Unavailable 77 }; 78 79 /// Decl - This represents one declaration (or definition), e.g. a variable, 80 /// typedef, function, struct, etc. 81 /// 82 /// Note: There are objects tacked on before the *beginning* of Decl 83 /// (and its subclasses) in its Decl::operator new(). Proper alignment 84 /// of all subclasses (not requiring more than the alignment of Decl) is 85 /// asserted in DeclBase.cpp. 86 class alignas(8) Decl { 87 public: 88 /// Lists the kind of concrete classes of Decl. 89 enum Kind { 90 #define DECL(DERIVED, BASE) DERIVED, 91 #define ABSTRACT_DECL(DECL) 92 #define DECL_RANGE(BASE, START, END) \ 93 first##BASE = START, last##BASE = END, 94 #define LAST_DECL_RANGE(BASE, START, END) \ 95 first##BASE = START, last##BASE = END 96 #include "clang/AST/DeclNodes.inc" 97 }; 98 99 /// A placeholder type used to construct an empty shell of a 100 /// decl-derived type that will be filled in later (e.g., by some 101 /// deserialization method). 102 struct EmptyShell {}; 103 104 /// IdentifierNamespace - The different namespaces in which 105 /// declarations may appear. According to C99 6.2.3, there are 106 /// four namespaces, labels, tags, members and ordinary 107 /// identifiers. C++ describes lookup completely differently: 108 /// certain lookups merely "ignore" certain kinds of declarations, 109 /// usually based on whether the declaration is of a type, etc. 110 /// 111 /// These are meant as bitmasks, so that searches in 112 /// C++ can look into the "tag" namespace during ordinary lookup. 113 /// 114 /// Decl currently provides 15 bits of IDNS bits. 115 enum IdentifierNamespace { 116 /// Labels, declared with 'x:' and referenced with 'goto x'. 117 IDNS_Label = 0x0001, 118 119 /// Tags, declared with 'struct foo;' and referenced with 120 /// 'struct foo'. All tags are also types. This is what 121 /// elaborated-type-specifiers look for in C. 122 /// This also contains names that conflict with tags in the 123 /// same scope but that are otherwise ordinary names (non-type 124 /// template parameters and indirect field declarations). 125 IDNS_Tag = 0x0002, 126 127 /// Types, declared with 'struct foo', typedefs, etc. 128 /// This is what elaborated-type-specifiers look for in C++, 129 /// but note that it's ill-formed to find a non-tag. 130 IDNS_Type = 0x0004, 131 132 /// Members, declared with object declarations within tag 133 /// definitions. In C, these can only be found by "qualified" 134 /// lookup in member expressions. In C++, they're found by 135 /// normal lookup. 136 IDNS_Member = 0x0008, 137 138 /// Namespaces, declared with 'namespace foo {}'. 139 /// Lookup for nested-name-specifiers find these. 140 IDNS_Namespace = 0x0010, 141 142 /// Ordinary names. In C, everything that's not a label, tag, 143 /// member, or function-local extern ends up here. 144 IDNS_Ordinary = 0x0020, 145 146 /// Objective C \@protocol. 147 IDNS_ObjCProtocol = 0x0040, 148 149 /// This declaration is a friend function. A friend function 150 /// declaration is always in this namespace but may also be in 151 /// IDNS_Ordinary if it was previously declared. 152 IDNS_OrdinaryFriend = 0x0080, 153 154 /// This declaration is a friend class. A friend class 155 /// declaration is always in this namespace but may also be in 156 /// IDNS_Tag|IDNS_Type if it was previously declared. 157 IDNS_TagFriend = 0x0100, 158 159 /// This declaration is a using declaration. A using declaration 160 /// *introduces* a number of other declarations into the current 161 /// scope, and those declarations use the IDNS of their targets, 162 /// but the actual using declarations go in this namespace. 163 IDNS_Using = 0x0200, 164 165 /// This declaration is a C++ operator declared in a non-class 166 /// context. All such operators are also in IDNS_Ordinary. 167 /// C++ lexical operator lookup looks for these. 168 IDNS_NonMemberOperator = 0x0400, 169 170 /// This declaration is a function-local extern declaration of a 171 /// variable or function. This may also be IDNS_Ordinary if it 172 /// has been declared outside any function. These act mostly like 173 /// invisible friend declarations, but are also visible to unqualified 174 /// lookup within the scope of the declaring function. 175 IDNS_LocalExtern = 0x0800, 176 177 /// This declaration is an OpenMP user defined reduction construction. 178 IDNS_OMPReduction = 0x1000, 179 180 /// This declaration is an OpenMP user defined mapper. 181 IDNS_OMPMapper = 0x2000, 182 }; 183 184 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and 185 /// parameter types in method declarations. Other than remembering 186 /// them and mangling them into the method's signature string, these 187 /// are ignored by the compiler; they are consumed by certain 188 /// remote-messaging frameworks. 189 /// 190 /// in, inout, and out are mutually exclusive and apply only to 191 /// method parameters. bycopy and byref are mutually exclusive and 192 /// apply only to method parameters (?). oneway applies only to 193 /// results. All of these expect their corresponding parameter to 194 /// have a particular type. None of this is currently enforced by 195 /// clang. 196 /// 197 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier. 198 enum ObjCDeclQualifier { 199 OBJC_TQ_None = 0x0, 200 OBJC_TQ_In = 0x1, 201 OBJC_TQ_Inout = 0x2, 202 OBJC_TQ_Out = 0x4, 203 OBJC_TQ_Bycopy = 0x8, 204 OBJC_TQ_Byref = 0x10, 205 OBJC_TQ_Oneway = 0x20, 206 207 /// The nullability qualifier is set when the nullability of the 208 /// result or parameter was expressed via a context-sensitive 209 /// keyword. 210 OBJC_TQ_CSNullability = 0x40 211 }; 212 213 /// The kind of ownership a declaration has, for visibility purposes. 214 /// This enumeration is designed such that higher values represent higher 215 /// levels of name hiding. 216 enum class ModuleOwnershipKind : unsigned char { 217 /// This declaration is not owned by a module. 218 Unowned, 219 220 /// This declaration has an owning module, but is globally visible 221 /// (typically because its owning module is visible and we know that 222 /// modules cannot later become hidden in this compilation). 223 /// After serialization and deserialization, this will be converted 224 /// to VisibleWhenImported. 225 Visible, 226 227 /// This declaration has an owning module, and is visible when that 228 /// module is imported. 229 VisibleWhenImported, 230 231 /// This declaration has an owning module, and is visible to lookups 232 /// that occurs within that module. And it is reachable in other module 233 /// when the owning module is transitively imported. 234 ReachableWhenImported, 235 236 /// This declaration has an owning module, but is only visible to 237 /// lookups that occur within that module. 238 /// The discarded declarations in global module fragment belongs 239 /// to this group too. 240 ModulePrivate 241 }; 242 243 protected: 244 /// The next declaration within the same lexical 245 /// DeclContext. These pointers form the linked list that is 246 /// traversed via DeclContext's decls_begin()/decls_end(). 247 /// 248 /// The extra three bits are used for the ModuleOwnershipKind. 249 llvm::PointerIntPair<Decl *, 3, ModuleOwnershipKind> NextInContextAndBits; 250 251 private: 252 friend class DeclContext; 253 254 struct MultipleDC { 255 DeclContext *SemanticDC; 256 DeclContext *LexicalDC; 257 }; 258 259 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. 260 /// For declarations that don't contain C++ scope specifiers, it contains 261 /// the DeclContext where the Decl was declared. 262 /// For declarations with C++ scope specifiers, it contains a MultipleDC* 263 /// with the context where it semantically belongs (SemanticDC) and the 264 /// context where it was lexically declared (LexicalDC). 265 /// e.g.: 266 /// 267 /// namespace A { 268 /// void f(); // SemanticDC == LexicalDC == 'namespace A' 269 /// } 270 /// void A::f(); // SemanticDC == namespace 'A' 271 /// // LexicalDC == global namespace 272 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx; 273 274 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); } 275 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); } 276 277 MultipleDC *getMultipleDC() const { 278 return DeclCtx.get<MultipleDC*>(); 279 } 280 281 DeclContext *getSemanticDC() const { 282 return DeclCtx.get<DeclContext*>(); 283 } 284 285 /// Loc - The location of this decl. 286 SourceLocation Loc; 287 288 /// DeclKind - This indicates which class this is. 289 LLVM_PREFERRED_TYPE(Kind) 290 unsigned DeclKind : 7; 291 292 /// InvalidDecl - This indicates a semantic error occurred. 293 LLVM_PREFERRED_TYPE(bool) 294 unsigned InvalidDecl : 1; 295 296 /// HasAttrs - This indicates whether the decl has attributes or not. 297 LLVM_PREFERRED_TYPE(bool) 298 unsigned HasAttrs : 1; 299 300 /// Implicit - Whether this declaration was implicitly generated by 301 /// the implementation rather than explicitly written by the user. 302 LLVM_PREFERRED_TYPE(bool) 303 unsigned Implicit : 1; 304 305 /// Whether this declaration was "used", meaning that a definition is 306 /// required. 307 LLVM_PREFERRED_TYPE(bool) 308 unsigned Used : 1; 309 310 /// Whether this declaration was "referenced". 311 /// The difference with 'Used' is whether the reference appears in a 312 /// evaluated context or not, e.g. functions used in uninstantiated templates 313 /// are regarded as "referenced" but not "used". 314 LLVM_PREFERRED_TYPE(bool) 315 unsigned Referenced : 1; 316 317 /// Whether this declaration is a top-level declaration (function, 318 /// global variable, etc.) that is lexically inside an objc container 319 /// definition. 320 LLVM_PREFERRED_TYPE(bool) 321 unsigned TopLevelDeclInObjCContainer : 1; 322 323 /// Whether statistic collection is enabled. 324 static bool StatisticsEnabled; 325 326 protected: 327 friend class ASTDeclReader; 328 friend class ASTDeclWriter; 329 friend class ASTNodeImporter; 330 friend class ASTReader; 331 friend class CXXClassMemberWrapper; 332 friend class LinkageComputer; 333 friend class RecordDecl; 334 template<typename decl_type> friend class Redeclarable; 335 336 /// Access - Used by C++ decls for the access specifier. 337 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum 338 LLVM_PREFERRED_TYPE(AccessSpecifier) 339 unsigned Access : 2; 340 341 /// Whether this declaration was loaded from an AST file. 342 LLVM_PREFERRED_TYPE(bool) 343 unsigned FromASTFile : 1; 344 345 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. 346 LLVM_PREFERRED_TYPE(IdentifierNamespace) 347 unsigned IdentifierNamespace : 14; 348 349 /// If 0, we have not computed the linkage of this declaration. 350 LLVM_PREFERRED_TYPE(Linkage) 351 mutable unsigned CacheValidAndLinkage : 3; 352 353 /// Allocate memory for a deserialized declaration. 354 /// 355 /// This routine must be used to allocate memory for any declaration that is 356 /// deserialized from a module file. 357 /// 358 /// \param Size The size of the allocated object. 359 /// \param Ctx The context in which we will allocate memory. 360 /// \param ID The global ID of the deserialized declaration. 361 /// \param Extra The amount of extra space to allocate after the object. 362 void *operator new(std::size_t Size, const ASTContext &Ctx, GlobalDeclID ID, 363 std::size_t Extra = 0); 364 365 /// Allocate memory for a non-deserialized declaration. 366 void *operator new(std::size_t Size, const ASTContext &Ctx, 367 DeclContext *Parent, std::size_t Extra = 0); 368 369 private: 370 bool AccessDeclContextCheck() const; 371 372 /// Get the module ownership kind to use for a local lexical child of \p DC, 373 /// which may be either a local or (rarely) an imported declaration. 374 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) { 375 if (DC) { 376 auto *D = cast<Decl>(DC); 377 auto MOK = D->getModuleOwnershipKind(); 378 if (MOK != ModuleOwnershipKind::Unowned && 379 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage())) 380 return MOK; 381 // If D is not local and we have no local module storage, then we don't 382 // need to track module ownership at all. 383 } 384 return ModuleOwnershipKind::Unowned; 385 } 386 387 public: 388 Decl() = delete; 389 Decl(const Decl&) = delete; 390 Decl(Decl &&) = delete; 391 Decl &operator=(const Decl&) = delete; 392 Decl &operator=(Decl&&) = delete; 393 394 protected: 395 Decl(Kind DK, DeclContext *DC, SourceLocation L) 396 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)), 397 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false), 398 Implicit(false), Used(false), Referenced(false), 399 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0), 400 IdentifierNamespace(getIdentifierNamespaceForKind(DK)), 401 CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) { 402 if (StatisticsEnabled) add(DK); 403 } 404 405 Decl(Kind DK, EmptyShell Empty) 406 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false), 407 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false), 408 Access(AS_none), FromASTFile(0), 409 IdentifierNamespace(getIdentifierNamespaceForKind(DK)), 410 CacheValidAndLinkage(llvm::to_underlying(Linkage::Invalid)) { 411 if (StatisticsEnabled) add(DK); 412 } 413 414 virtual ~Decl(); 415 416 /// Update a potentially out-of-date declaration. 417 void updateOutOfDate(IdentifierInfo &II) const; 418 419 Linkage getCachedLinkage() const { 420 return static_cast<Linkage>(CacheValidAndLinkage); 421 } 422 423 void setCachedLinkage(Linkage L) const { 424 CacheValidAndLinkage = llvm::to_underlying(L); 425 } 426 427 bool hasCachedLinkage() const { 428 return CacheValidAndLinkage; 429 } 430 431 public: 432 /// Source range that this declaration covers. 433 virtual SourceRange getSourceRange() const LLVM_READONLY { 434 return SourceRange(getLocation(), getLocation()); 435 } 436 437 SourceLocation getBeginLoc() const LLVM_READONLY { 438 return getSourceRange().getBegin(); 439 } 440 441 SourceLocation getEndLoc() const LLVM_READONLY { 442 return getSourceRange().getEnd(); 443 } 444 445 SourceLocation getLocation() const { return Loc; } 446 void setLocation(SourceLocation L) { Loc = L; } 447 448 Kind getKind() const { return static_cast<Kind>(DeclKind); } 449 const char *getDeclKindName() const; 450 451 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); } 452 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();} 453 454 DeclContext *getDeclContext() { 455 if (isInSemaDC()) 456 return getSemanticDC(); 457 return getMultipleDC()->SemanticDC; 458 } 459 const DeclContext *getDeclContext() const { 460 return const_cast<Decl*>(this)->getDeclContext(); 461 } 462 463 /// Return the non transparent context. 464 /// See the comment of `DeclContext::isTransparentContext()` for the 465 /// definition of transparent context. 466 DeclContext *getNonTransparentDeclContext(); 467 const DeclContext *getNonTransparentDeclContext() const { 468 return const_cast<Decl *>(this)->getNonTransparentDeclContext(); 469 } 470 471 /// Find the innermost non-closure ancestor of this declaration, 472 /// walking up through blocks, lambdas, etc. If that ancestor is 473 /// not a code context (!isFunctionOrMethod()), returns null. 474 /// 475 /// A declaration may be its own non-closure context. 476 Decl *getNonClosureContext(); 477 const Decl *getNonClosureContext() const { 478 return const_cast<Decl*>(this)->getNonClosureContext(); 479 } 480 481 TranslationUnitDecl *getTranslationUnitDecl(); 482 const TranslationUnitDecl *getTranslationUnitDecl() const { 483 return const_cast<Decl*>(this)->getTranslationUnitDecl(); 484 } 485 486 bool isInAnonymousNamespace() const; 487 488 bool isInStdNamespace() const; 489 490 // Return true if this is a FileContext Decl. 491 bool isFileContextDecl() const; 492 493 /// Whether it resembles a flexible array member. This is a static member 494 /// because we want to be able to call it with a nullptr. That allows us to 495 /// perform non-Decl specific checks based on the object's type and strict 496 /// flex array level. 497 static bool isFlexibleArrayMemberLike( 498 ASTContext &Context, const Decl *D, QualType Ty, 499 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, 500 bool IgnoreTemplateOrMacroSubstitution); 501 502 ASTContext &getASTContext() const LLVM_READONLY; 503 504 /// Helper to get the language options from the ASTContext. 505 /// Defined out of line to avoid depending on ASTContext.h. 506 const LangOptions &getLangOpts() const LLVM_READONLY; 507 508 void setAccess(AccessSpecifier AS) { 509 Access = AS; 510 assert(AccessDeclContextCheck()); 511 } 512 513 AccessSpecifier getAccess() const { 514 assert(AccessDeclContextCheck()); 515 return AccessSpecifier(Access); 516 } 517 518 /// Retrieve the access specifier for this declaration, even though 519 /// it may not yet have been properly set. 520 AccessSpecifier getAccessUnsafe() const { 521 return AccessSpecifier(Access); 522 } 523 524 bool hasAttrs() const { return HasAttrs; } 525 526 void setAttrs(const AttrVec& Attrs) { 527 return setAttrsImpl(Attrs, getASTContext()); 528 } 529 530 AttrVec &getAttrs() { 531 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs()); 532 } 533 534 const AttrVec &getAttrs() const; 535 void dropAttrs(); 536 void addAttr(Attr *A); 537 538 using attr_iterator = AttrVec::const_iterator; 539 using attr_range = llvm::iterator_range<attr_iterator>; 540 541 attr_range attrs() const { 542 return attr_range(attr_begin(), attr_end()); 543 } 544 545 attr_iterator attr_begin() const { 546 return hasAttrs() ? getAttrs().begin() : nullptr; 547 } 548 attr_iterator attr_end() const { 549 return hasAttrs() ? getAttrs().end() : nullptr; 550 } 551 552 template <typename... Ts> void dropAttrs() { 553 if (!HasAttrs) return; 554 555 AttrVec &Vec = getAttrs(); 556 llvm::erase_if(Vec, [](Attr *A) { return isa<Ts...>(A); }); 557 558 if (Vec.empty()) 559 HasAttrs = false; 560 } 561 562 template <typename T> void dropAttr() { dropAttrs<T>(); } 563 564 template <typename T> 565 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const { 566 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>()); 567 } 568 569 template <typename T> 570 specific_attr_iterator<T> specific_attr_begin() const { 571 return specific_attr_iterator<T>(attr_begin()); 572 } 573 574 template <typename T> 575 specific_attr_iterator<T> specific_attr_end() const { 576 return specific_attr_iterator<T>(attr_end()); 577 } 578 579 template<typename T> T *getAttr() const { 580 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr; 581 } 582 583 template<typename T> bool hasAttr() const { 584 return hasAttrs() && hasSpecificAttr<T>(getAttrs()); 585 } 586 587 /// getMaxAlignment - return the maximum alignment specified by attributes 588 /// on this decl, 0 if there are none. 589 unsigned getMaxAlignment() const; 590 591 /// setInvalidDecl - Indicates the Decl had a semantic error. This 592 /// allows for graceful error recovery. 593 void setInvalidDecl(bool Invalid = true); 594 bool isInvalidDecl() const { return (bool) InvalidDecl; } 595 596 /// isImplicit - Indicates whether the declaration was implicitly 597 /// generated by the implementation. If false, this declaration 598 /// was written explicitly in the source code. 599 bool isImplicit() const { return Implicit; } 600 void setImplicit(bool I = true) { Implicit = I; } 601 602 /// Whether *any* (re-)declaration of the entity was used, meaning that 603 /// a definition is required. 604 /// 605 /// \param CheckUsedAttr When true, also consider the "used" attribute 606 /// (in addition to the "used" bit set by \c setUsed()) when determining 607 /// whether the function is used. 608 bool isUsed(bool CheckUsedAttr = true) const; 609 610 /// Set whether the declaration is used, in the sense of odr-use. 611 /// 612 /// This should only be used immediately after creating a declaration. 613 /// It intentionally doesn't notify any listeners. 614 void setIsUsed() { getCanonicalDecl()->Used = true; } 615 616 /// Mark the declaration used, in the sense of odr-use. 617 /// 618 /// This notifies any mutation listeners in addition to setting a bit 619 /// indicating the declaration is used. 620 void markUsed(ASTContext &C); 621 622 /// Whether any declaration of this entity was referenced. 623 bool isReferenced() const; 624 625 /// Whether this declaration was referenced. This should not be relied 626 /// upon for anything other than debugging. 627 bool isThisDeclarationReferenced() const { return Referenced; } 628 629 void setReferenced(bool R = true) { Referenced = R; } 630 631 /// Whether this declaration is a top-level declaration (function, 632 /// global variable, etc.) that is lexically inside an objc container 633 /// definition. 634 bool isTopLevelDeclInObjCContainer() const { 635 return TopLevelDeclInObjCContainer; 636 } 637 638 void setTopLevelDeclInObjCContainer(bool V = true) { 639 TopLevelDeclInObjCContainer = V; 640 } 641 642 /// Looks on this and related declarations for an applicable 643 /// external source symbol attribute. 644 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const; 645 646 /// Whether this declaration was marked as being private to the 647 /// module in which it was defined. 648 bool isModulePrivate() const { 649 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate; 650 } 651 652 /// Whether this declaration was exported in a lexical context. 653 /// e.g.: 654 /// 655 /// export namespace A { 656 /// void f1(); // isInExportDeclContext() == true 657 /// } 658 /// void A::f1(); // isInExportDeclContext() == false 659 /// 660 /// namespace B { 661 /// void f2(); // isInExportDeclContext() == false 662 /// } 663 /// export void B::f2(); // isInExportDeclContext() == true 664 bool isInExportDeclContext() const; 665 666 bool isInvisibleOutsideTheOwningModule() const { 667 return getModuleOwnershipKind() > ModuleOwnershipKind::VisibleWhenImported; 668 } 669 670 /// Whether this declaration comes from another module unit. 671 bool isInAnotherModuleUnit() const; 672 673 /// Whether this declaration comes from the same module unit being compiled. 674 bool isInCurrentModuleUnit() const; 675 676 /// Whether the definition of the declaration should be emitted in external 677 /// sources. 678 bool shouldEmitInExternalSource() const; 679 680 /// Whether this declaration comes from explicit global module. 681 bool isFromExplicitGlobalModule() const; 682 683 /// Whether this declaration comes from global module. 684 bool isFromGlobalModule() const; 685 686 /// Whether this declaration comes from a named module. 687 bool isInNamedModule() const; 688 689 /// Return true if this declaration has an attribute which acts as 690 /// definition of the entity, such as 'alias' or 'ifunc'. 691 bool hasDefiningAttr() const; 692 693 /// Return this declaration's defining attribute if it has one. 694 const Attr *getDefiningAttr() const; 695 696 protected: 697 /// Specify that this declaration was marked as being private 698 /// to the module in which it was defined. 699 void setModulePrivate() { 700 // The module-private specifier has no effect on unowned declarations. 701 // FIXME: We should track this in some way for source fidelity. 702 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned) 703 return; 704 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate); 705 } 706 707 public: 708 /// Set the FromASTFile flag. This indicates that this declaration 709 /// was deserialized and not parsed from source code and enables 710 /// features such as module ownership information. 711 void setFromASTFile() { 712 FromASTFile = true; 713 } 714 715 /// Set the owning module ID. This may only be called for 716 /// deserialized Decls. 717 void setOwningModuleID(unsigned ID); 718 719 public: 720 /// Determine the availability of the given declaration. 721 /// 722 /// This routine will determine the most restrictive availability of 723 /// the given declaration (e.g., preferring 'unavailable' to 724 /// 'deprecated'). 725 /// 726 /// \param Message If non-NULL and the result is not \c 727 /// AR_Available, will be set to a (possibly empty) message 728 /// describing why the declaration has not been introduced, is 729 /// deprecated, or is unavailable. 730 /// 731 /// \param EnclosingVersion The version to compare with. If empty, assume the 732 /// deployment target version. 733 /// 734 /// \param RealizedPlatform If non-NULL and the availability result is found 735 /// in an available attribute it will set to the platform which is written in 736 /// the available attribute. 737 AvailabilityResult 738 getAvailability(std::string *Message = nullptr, 739 VersionTuple EnclosingVersion = VersionTuple(), 740 StringRef *RealizedPlatform = nullptr) const; 741 742 /// Retrieve the version of the target platform in which this 743 /// declaration was introduced. 744 /// 745 /// \returns An empty version tuple if this declaration has no 'introduced' 746 /// availability attributes, or the version tuple that's specified in the 747 /// attribute otherwise. 748 VersionTuple getVersionIntroduced() const; 749 750 /// Determine whether this declaration is marked 'deprecated'. 751 /// 752 /// \param Message If non-NULL and the declaration is deprecated, 753 /// this will be set to the message describing why the declaration 754 /// was deprecated (which may be empty). 755 bool isDeprecated(std::string *Message = nullptr) const { 756 return getAvailability(Message) == AR_Deprecated; 757 } 758 759 /// Determine whether this declaration is marked 'unavailable'. 760 /// 761 /// \param Message If non-NULL and the declaration is unavailable, 762 /// this will be set to the message describing why the declaration 763 /// was made unavailable (which may be empty). 764 bool isUnavailable(std::string *Message = nullptr) const { 765 return getAvailability(Message) == AR_Unavailable; 766 } 767 768 /// Determine whether this is a weak-imported symbol. 769 /// 770 /// Weak-imported symbols are typically marked with the 771 /// 'weak_import' attribute, but may also be marked with an 772 /// 'availability' attribute where we're targing a platform prior to 773 /// the introduction of this feature. 774 bool isWeakImported() const; 775 776 /// Determines whether this symbol can be weak-imported, 777 /// e.g., whether it would be well-formed to add the weak_import 778 /// attribute. 779 /// 780 /// \param IsDefinition Set to \c true to indicate that this 781 /// declaration cannot be weak-imported because it has a definition. 782 bool canBeWeakImported(bool &IsDefinition) const; 783 784 /// Determine whether this declaration came from an AST file (such as 785 /// a precompiled header or module) rather than having been parsed. 786 bool isFromASTFile() const { return FromASTFile; } 787 788 /// Retrieve the global declaration ID associated with this 789 /// declaration, which specifies where this Decl was loaded from. 790 GlobalDeclID getGlobalID() const; 791 792 /// Retrieve the global ID of the module that owns this particular 793 /// declaration. 794 unsigned getOwningModuleID() const; 795 796 private: 797 Module *getOwningModuleSlow() const; 798 799 protected: 800 bool hasLocalOwningModuleStorage() const; 801 802 public: 803 /// Get the imported owning module, if this decl is from an imported 804 /// (non-local) module. 805 Module *getImportedOwningModule() const { 806 if (!isFromASTFile() || !hasOwningModule()) 807 return nullptr; 808 809 return getOwningModuleSlow(); 810 } 811 812 /// Get the local owning module, if known. Returns nullptr if owner is 813 /// not yet known or declaration is not from a module. 814 Module *getLocalOwningModule() const { 815 if (isFromASTFile() || !hasOwningModule()) 816 return nullptr; 817 818 assert(hasLocalOwningModuleStorage() && 819 "owned local decl but no local module storage"); 820 return reinterpret_cast<Module *const *>(this)[-1]; 821 } 822 void setLocalOwningModule(Module *M) { 823 assert(!isFromASTFile() && hasOwningModule() && 824 hasLocalOwningModuleStorage() && 825 "should not have a cached owning module"); 826 reinterpret_cast<Module **>(this)[-1] = M; 827 } 828 829 /// Is this declaration owned by some module? 830 bool hasOwningModule() const { 831 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned; 832 } 833 834 /// Get the module that owns this declaration (for visibility purposes). 835 Module *getOwningModule() const { 836 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule(); 837 } 838 839 /// Get the module that owns this declaration for linkage purposes. 840 /// There only ever is such a standard C++ module. 841 Module *getOwningModuleForLinkage() const; 842 843 /// Determine whether this declaration is definitely visible to name lookup, 844 /// independent of whether the owning module is visible. 845 /// Note: The declaration may be visible even if this returns \c false if the 846 /// owning module is visible within the query context. This is a low-level 847 /// helper function; most code should be calling Sema::isVisible() instead. 848 bool isUnconditionallyVisible() const { 849 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible; 850 } 851 852 bool isReachable() const { 853 return (int)getModuleOwnershipKind() <= 854 (int)ModuleOwnershipKind::ReachableWhenImported; 855 } 856 857 /// Set that this declaration is globally visible, even if it came from a 858 /// module that is not visible. 859 void setVisibleDespiteOwningModule() { 860 if (!isUnconditionallyVisible()) 861 setModuleOwnershipKind(ModuleOwnershipKind::Visible); 862 } 863 864 /// Get the kind of module ownership for this declaration. 865 ModuleOwnershipKind getModuleOwnershipKind() const { 866 return NextInContextAndBits.getInt(); 867 } 868 869 /// Set whether this declaration is hidden from name lookup. 870 void setModuleOwnershipKind(ModuleOwnershipKind MOK) { 871 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && 872 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && 873 !hasLocalOwningModuleStorage()) && 874 "no storage available for owning module for this declaration"); 875 NextInContextAndBits.setInt(MOK); 876 } 877 878 unsigned getIdentifierNamespace() const { 879 return IdentifierNamespace; 880 } 881 882 bool isInIdentifierNamespace(unsigned NS) const { 883 return getIdentifierNamespace() & NS; 884 } 885 886 static unsigned getIdentifierNamespaceForKind(Kind DK); 887 888 bool hasTagIdentifierNamespace() const { 889 return isTagIdentifierNamespace(getIdentifierNamespace()); 890 } 891 892 static bool isTagIdentifierNamespace(unsigned NS) { 893 // TagDecls have Tag and Type set and may also have TagFriend. 894 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type); 895 } 896 897 /// getLexicalDeclContext - The declaration context where this Decl was 898 /// lexically declared (LexicalDC). May be different from 899 /// getDeclContext() (SemanticDC). 900 /// e.g.: 901 /// 902 /// namespace A { 903 /// void f(); // SemanticDC == LexicalDC == 'namespace A' 904 /// } 905 /// void A::f(); // SemanticDC == namespace 'A' 906 /// // LexicalDC == global namespace 907 DeclContext *getLexicalDeclContext() { 908 if (isInSemaDC()) 909 return getSemanticDC(); 910 return getMultipleDC()->LexicalDC; 911 } 912 const DeclContext *getLexicalDeclContext() const { 913 return const_cast<Decl*>(this)->getLexicalDeclContext(); 914 } 915 916 /// Determine whether this declaration is declared out of line (outside its 917 /// semantic context). 918 virtual bool isOutOfLine() const; 919 920 /// setDeclContext - Set both the semantic and lexical DeclContext 921 /// to DC. 922 void setDeclContext(DeclContext *DC); 923 924 void setLexicalDeclContext(DeclContext *DC); 925 926 /// Determine whether this declaration is a templated entity (whether it is 927 // within the scope of a template parameter). 928 bool isTemplated() const; 929 930 /// Determine the number of levels of template parameter surrounding this 931 /// declaration. 932 unsigned getTemplateDepth() const; 933 934 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this 935 /// scoped decl is defined outside the current function or method. This is 936 /// roughly global variables and functions, but also handles enums (which 937 /// could be defined inside or outside a function etc). 938 bool isDefinedOutsideFunctionOrMethod() const { 939 return getParentFunctionOrMethod() == nullptr; 940 } 941 942 /// Determine whether a substitution into this declaration would occur as 943 /// part of a substitution into a dependent local scope. Such a substitution 944 /// transitively substitutes into all constructs nested within this 945 /// declaration. 946 /// 947 /// This recognizes non-defining declarations as well as members of local 948 /// classes and lambdas: 949 /// \code 950 /// template<typename T> void foo() { void bar(); } 951 /// template<typename T> void foo2() { class ABC { void bar(); }; } 952 /// template<typename T> inline int x = [](){ return 0; }(); 953 /// \endcode 954 bool isInLocalScopeForInstantiation() const; 955 956 /// If this decl is defined inside a function/method/block it returns 957 /// the corresponding DeclContext, otherwise it returns null. 958 const DeclContext * 959 getParentFunctionOrMethod(bool LexicalParent = false) const; 960 DeclContext *getParentFunctionOrMethod(bool LexicalParent = false) { 961 return const_cast<DeclContext *>( 962 const_cast<const Decl *>(this)->getParentFunctionOrMethod( 963 LexicalParent)); 964 } 965 966 /// Retrieves the "canonical" declaration of the given declaration. 967 virtual Decl *getCanonicalDecl() { return this; } 968 const Decl *getCanonicalDecl() const { 969 return const_cast<Decl*>(this)->getCanonicalDecl(); 970 } 971 972 /// Whether this particular Decl is a canonical one. 973 bool isCanonicalDecl() const { return getCanonicalDecl() == this; } 974 975 protected: 976 /// Returns the next redeclaration or itself if this is the only decl. 977 /// 978 /// Decl subclasses that can be redeclared should override this method so that 979 /// Decl::redecl_iterator can iterate over them. 980 virtual Decl *getNextRedeclarationImpl() { return this; } 981 982 /// Implementation of getPreviousDecl(), to be overridden by any 983 /// subclass that has a redeclaration chain. 984 virtual Decl *getPreviousDeclImpl() { return nullptr; } 985 986 /// Implementation of getMostRecentDecl(), to be overridden by any 987 /// subclass that has a redeclaration chain. 988 virtual Decl *getMostRecentDeclImpl() { return this; } 989 990 public: 991 /// Iterates through all the redeclarations of the same decl. 992 class redecl_iterator { 993 /// Current - The current declaration. 994 Decl *Current = nullptr; 995 Decl *Starter; 996 997 public: 998 using value_type = Decl *; 999 using reference = const value_type &; 1000 using pointer = const value_type *; 1001 using iterator_category = std::forward_iterator_tag; 1002 using difference_type = std::ptrdiff_t; 1003 1004 redecl_iterator() = default; 1005 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {} 1006 1007 reference operator*() const { return Current; } 1008 value_type operator->() const { return Current; } 1009 1010 redecl_iterator& operator++() { 1011 assert(Current && "Advancing while iterator has reached end"); 1012 // Get either previous decl or latest decl. 1013 Decl *Next = Current->getNextRedeclarationImpl(); 1014 assert(Next && "Should return next redeclaration or itself, never null!"); 1015 Current = (Next != Starter) ? Next : nullptr; 1016 return *this; 1017 } 1018 1019 redecl_iterator operator++(int) { 1020 redecl_iterator tmp(*this); 1021 ++(*this); 1022 return tmp; 1023 } 1024 1025 friend bool operator==(redecl_iterator x, redecl_iterator y) { 1026 return x.Current == y.Current; 1027 } 1028 1029 friend bool operator!=(redecl_iterator x, redecl_iterator y) { 1030 return x.Current != y.Current; 1031 } 1032 }; 1033 1034 using redecl_range = llvm::iterator_range<redecl_iterator>; 1035 1036 /// Returns an iterator range for all the redeclarations of the same 1037 /// decl. It will iterate at least once (when this decl is the only one). 1038 redecl_range redecls() const { 1039 return redecl_range(redecls_begin(), redecls_end()); 1040 } 1041 1042 redecl_iterator redecls_begin() const { 1043 return redecl_iterator(const_cast<Decl *>(this)); 1044 } 1045 1046 redecl_iterator redecls_end() const { return redecl_iterator(); } 1047 1048 /// Retrieve the previous declaration that declares the same entity 1049 /// as this declaration, or NULL if there is no previous declaration. 1050 Decl *getPreviousDecl() { return getPreviousDeclImpl(); } 1051 1052 /// Retrieve the previous declaration that declares the same entity 1053 /// as this declaration, or NULL if there is no previous declaration. 1054 const Decl *getPreviousDecl() const { 1055 return const_cast<Decl *>(this)->getPreviousDeclImpl(); 1056 } 1057 1058 /// True if this is the first declaration in its redeclaration chain. 1059 bool isFirstDecl() const { 1060 return getPreviousDecl() == nullptr; 1061 } 1062 1063 /// Retrieve the most recent declaration that declares the same entity 1064 /// as this declaration (which may be this declaration). 1065 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); } 1066 1067 /// Retrieve the most recent declaration that declares the same entity 1068 /// as this declaration (which may be this declaration). 1069 const Decl *getMostRecentDecl() const { 1070 return const_cast<Decl *>(this)->getMostRecentDeclImpl(); 1071 } 1072 1073 /// getBody - If this Decl represents a declaration for a body of code, 1074 /// such as a function or method definition, this method returns the 1075 /// top-level Stmt* of that body. Otherwise this method returns null. 1076 virtual Stmt* getBody() const { return nullptr; } 1077 1078 /// Returns true if this \c Decl represents a declaration for a body of 1079 /// code, such as a function or method definition. 1080 /// Note that \c hasBody can also return true if any redeclaration of this 1081 /// \c Decl represents a declaration for a body of code. 1082 virtual bool hasBody() const { return getBody() != nullptr; } 1083 1084 /// getBodyRBrace - Gets the right brace of the body, if a body exists. 1085 /// This works whether the body is a CompoundStmt or a CXXTryStmt. 1086 SourceLocation getBodyRBrace() const; 1087 1088 // global temp stats (until we have a per-module visitor) 1089 static void add(Kind k); 1090 static void EnableStatistics(); 1091 static void PrintStats(); 1092 1093 /// isTemplateParameter - Determines whether this declaration is a 1094 /// template parameter. 1095 bool isTemplateParameter() const; 1096 1097 /// isTemplateParameter - Determines whether this declaration is a 1098 /// template parameter pack. 1099 bool isTemplateParameterPack() const; 1100 1101 /// Whether this declaration is a parameter pack. 1102 bool isParameterPack() const; 1103 1104 /// returns true if this declaration is a template 1105 bool isTemplateDecl() const; 1106 1107 /// Whether this declaration is a function or function template. 1108 bool isFunctionOrFunctionTemplate() const { 1109 return (DeclKind >= Decl::firstFunction && 1110 DeclKind <= Decl::lastFunction) || 1111 DeclKind == FunctionTemplate; 1112 } 1113 1114 /// If this is a declaration that describes some template, this 1115 /// method returns that template declaration. 1116 /// 1117 /// Note that this returns nullptr for partial specializations, because they 1118 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle 1119 /// those cases. 1120 TemplateDecl *getDescribedTemplate() const; 1121 1122 /// If this is a declaration that describes some template or partial 1123 /// specialization, this returns the corresponding template parameter list. 1124 const TemplateParameterList *getDescribedTemplateParams() const; 1125 1126 /// Returns the function itself, or the templated function if this is a 1127 /// function template. 1128 FunctionDecl *getAsFunction() LLVM_READONLY; 1129 1130 const FunctionDecl *getAsFunction() const { 1131 return const_cast<Decl *>(this)->getAsFunction(); 1132 } 1133 1134 /// Changes the namespace of this declaration to reflect that it's 1135 /// a function-local extern declaration. 1136 /// 1137 /// These declarations appear in the lexical context of the extern 1138 /// declaration, but in the semantic context of the enclosing namespace 1139 /// scope. 1140 void setLocalExternDecl() { 1141 Decl *Prev = getPreviousDecl(); 1142 IdentifierNamespace &= ~IDNS_Ordinary; 1143 1144 // It's OK for the declaration to still have the "invisible friend" flag or 1145 // the "conflicts with tag declarations in this scope" flag for the outer 1146 // scope. 1147 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && 1148 "namespace is not ordinary"); 1149 1150 IdentifierNamespace |= IDNS_LocalExtern; 1151 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary) 1152 IdentifierNamespace |= IDNS_Ordinary; 1153 } 1154 1155 /// Determine whether this is a block-scope declaration with linkage. 1156 /// This will either be a local variable declaration declared 'extern', or a 1157 /// local function declaration. 1158 bool isLocalExternDecl() const { 1159 return IdentifierNamespace & IDNS_LocalExtern; 1160 } 1161 1162 /// Changes the namespace of this declaration to reflect that it's 1163 /// the object of a friend declaration. 1164 /// 1165 /// These declarations appear in the lexical context of the friending 1166 /// class, but in the semantic context of the actual entity. This property 1167 /// applies only to a specific decl object; other redeclarations of the 1168 /// same entity may not (and probably don't) share this property. 1169 void setObjectOfFriendDecl(bool PerformFriendInjection = false) { 1170 unsigned OldNS = IdentifierNamespace; 1171 assert((OldNS & (IDNS_Tag | IDNS_Ordinary | 1172 IDNS_TagFriend | IDNS_OrdinaryFriend | 1173 IDNS_LocalExtern | IDNS_NonMemberOperator)) && 1174 "namespace includes neither ordinary nor tag"); 1175 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | 1176 IDNS_TagFriend | IDNS_OrdinaryFriend | 1177 IDNS_LocalExtern | IDNS_NonMemberOperator)) && 1178 "namespace includes other than ordinary or tag"); 1179 1180 Decl *Prev = getPreviousDecl(); 1181 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type); 1182 1183 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) { 1184 IdentifierNamespace |= IDNS_TagFriend; 1185 if (PerformFriendInjection || 1186 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag)) 1187 IdentifierNamespace |= IDNS_Tag | IDNS_Type; 1188 } 1189 1190 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | 1191 IDNS_LocalExtern | IDNS_NonMemberOperator)) { 1192 IdentifierNamespace |= IDNS_OrdinaryFriend; 1193 if (PerformFriendInjection || 1194 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)) 1195 IdentifierNamespace |= IDNS_Ordinary; 1196 } 1197 } 1198 1199 /// Clears the namespace of this declaration. 1200 /// 1201 /// This is useful if we want this declaration to be available for 1202 /// redeclaration lookup but otherwise hidden for ordinary name lookups. 1203 void clearIdentifierNamespace() { IdentifierNamespace = 0; } 1204 1205 enum FriendObjectKind { 1206 FOK_None, ///< Not a friend object. 1207 FOK_Declared, ///< A friend of a previously-declared entity. 1208 FOK_Undeclared ///< A friend of a previously-undeclared entity. 1209 }; 1210 1211 /// Determines whether this declaration is the object of a 1212 /// friend declaration and, if so, what kind. 1213 /// 1214 /// There is currently no direct way to find the associated FriendDecl. 1215 FriendObjectKind getFriendObjectKind() const { 1216 unsigned mask = 1217 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend)); 1218 if (!mask) return FOK_None; 1219 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared 1220 : FOK_Undeclared); 1221 } 1222 1223 /// Specifies that this declaration is a C++ overloaded non-member. 1224 void setNonMemberOperator() { 1225 assert(getKind() == Function || getKind() == FunctionTemplate); 1226 assert((IdentifierNamespace & IDNS_Ordinary) && 1227 "visible non-member operators should be in ordinary namespace"); 1228 IdentifierNamespace |= IDNS_NonMemberOperator; 1229 } 1230 1231 static bool classofKind(Kind K) { return true; } 1232 static DeclContext *castToDeclContext(const Decl *); 1233 static Decl *castFromDeclContext(const DeclContext *); 1234 1235 void print(raw_ostream &Out, unsigned Indentation = 0, 1236 bool PrintInstantiation = false) const; 1237 void print(raw_ostream &Out, const PrintingPolicy &Policy, 1238 unsigned Indentation = 0, bool PrintInstantiation = false) const; 1239 static void printGroup(Decl** Begin, unsigned NumDecls, 1240 raw_ostream &Out, const PrintingPolicy &Policy, 1241 unsigned Indentation = 0); 1242 1243 // Debuggers don't usually respect default arguments. 1244 void dump() const; 1245 1246 // Same as dump(), but forces color printing. 1247 void dumpColor() const; 1248 1249 void dump(raw_ostream &Out, bool Deserialize = false, 1250 ASTDumpOutputFormat OutputFormat = ADOF_Default) const; 1251 1252 /// \return Unique reproducible object identifier 1253 int64_t getID() const; 1254 1255 /// Looks through the Decl's underlying type to extract a FunctionType 1256 /// when possible. Will return null if the type underlying the Decl does not 1257 /// have a FunctionType. 1258 const FunctionType *getFunctionType(bool BlocksToo = true) const; 1259 1260 // Looks through the Decl's underlying type to determine if it's a 1261 // function pointer type. 1262 bool isFunctionPointerType() const; 1263 1264 private: 1265 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx); 1266 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, 1267 ASTContext &Ctx); 1268 1269 protected: 1270 ASTMutationListener *getASTMutationListener() const; 1271 }; 1272 1273 /// Determine whether two declarations declare the same entity. 1274 inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { 1275 if (!D1 || !D2) 1276 return false; 1277 1278 if (D1 == D2) 1279 return true; 1280 1281 return D1->getCanonicalDecl() == D2->getCanonicalDecl(); 1282 } 1283 1284 /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when 1285 /// doing something to a specific decl. 1286 class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { 1287 const Decl *TheDecl; 1288 SourceLocation Loc; 1289 SourceManager &SM; 1290 const char *Message; 1291 1292 public: 1293 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L, 1294 SourceManager &sm, const char *Msg) 1295 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} 1296 1297 void print(raw_ostream &OS) const override; 1298 }; 1299 } // namespace clang 1300 1301 // Required to determine the layout of the PointerUnion<NamedDecl*> before 1302 // seeing the NamedDecl definition being first used in DeclListNode::operator*. 1303 namespace llvm { 1304 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> { 1305 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; } 1306 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) { 1307 return static_cast<::clang::NamedDecl *>(P); 1308 } 1309 static constexpr int NumLowBitsAvailable = 3; 1310 }; 1311 } 1312 1313 namespace clang { 1314 /// A list storing NamedDecls in the lookup tables. 1315 class DeclListNode { 1316 friend class ASTContext; // allocate, deallocate nodes. 1317 friend class StoredDeclsList; 1318 public: 1319 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>; 1320 class iterator { 1321 friend class DeclContextLookupResult; 1322 friend class StoredDeclsList; 1323 1324 Decls Ptr; 1325 iterator(Decls Node) : Ptr(Node) { } 1326 public: 1327 using difference_type = ptrdiff_t; 1328 using value_type = NamedDecl*; 1329 using pointer = void; 1330 using reference = value_type; 1331 using iterator_category = std::forward_iterator_tag; 1332 1333 iterator() = default; 1334 1335 reference operator*() const { 1336 assert(Ptr && "dereferencing end() iterator"); 1337 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>()) 1338 return CurNode->D; 1339 return Ptr.get<NamedDecl*>(); 1340 } 1341 void operator->() const { } // Unsupported. 1342 bool operator==(const iterator &X) const { return Ptr == X.Ptr; } 1343 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; } 1344 inline iterator &operator++() { // ++It 1345 assert(!Ptr.isNull() && "Advancing empty iterator"); 1346 1347 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>()) 1348 Ptr = CurNode->Rest; 1349 else 1350 Ptr = nullptr; 1351 return *this; 1352 } 1353 iterator operator++(int) { // It++ 1354 iterator temp = *this; 1355 ++(*this); 1356 return temp; 1357 } 1358 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I) 1359 iterator end() { return iterator(); } 1360 }; 1361 private: 1362 NamedDecl *D = nullptr; 1363 Decls Rest = nullptr; 1364 DeclListNode(NamedDecl *ND) : D(ND) {} 1365 }; 1366 1367 /// The results of name lookup within a DeclContext. 1368 class DeclContextLookupResult { 1369 using Decls = DeclListNode::Decls; 1370 1371 /// When in collection form, this is what the Data pointer points to. 1372 Decls Result; 1373 1374 public: 1375 DeclContextLookupResult() = default; 1376 DeclContextLookupResult(Decls Result) : Result(Result) {} 1377 1378 using iterator = DeclListNode::iterator; 1379 using const_iterator = iterator; 1380 using reference = iterator::reference; 1381 1382 iterator begin() { return iterator(Result); } 1383 iterator end() { return iterator(); } 1384 const_iterator begin() const { 1385 return const_cast<DeclContextLookupResult*>(this)->begin(); 1386 } 1387 const_iterator end() const { return iterator(); } 1388 1389 bool empty() const { return Result.isNull(); } 1390 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); } 1391 reference front() const { return *begin(); } 1392 1393 // Find the first declaration of the given type in the list. Note that this 1394 // is not in general the earliest-declared declaration, and should only be 1395 // used when it's not possible for there to be more than one match or where 1396 // it doesn't matter which one is found. 1397 template<class T> T *find_first() const { 1398 for (auto *D : *this) 1399 if (T *Decl = dyn_cast<T>(D)) 1400 return Decl; 1401 1402 return nullptr; 1403 } 1404 }; 1405 1406 /// Only used by CXXDeductionGuideDecl. 1407 enum class DeductionCandidate : unsigned char { 1408 Normal, 1409 Copy, 1410 Aggregate, 1411 }; 1412 1413 enum class RecordArgPassingKind; 1414 enum class OMPDeclareReductionInitKind; 1415 enum class ObjCImplementationControl; 1416 enum class LinkageSpecLanguageIDs; 1417 1418 /// DeclContext - This is used only as base class of specific decl types that 1419 /// can act as declaration contexts. These decls are (only the top classes 1420 /// that directly derive from DeclContext are mentioned, not their subclasses): 1421 /// 1422 /// TranslationUnitDecl 1423 /// ExternCContext 1424 /// NamespaceDecl 1425 /// TagDecl 1426 /// OMPDeclareReductionDecl 1427 /// OMPDeclareMapperDecl 1428 /// FunctionDecl 1429 /// ObjCMethodDecl 1430 /// ObjCContainerDecl 1431 /// LinkageSpecDecl 1432 /// ExportDecl 1433 /// BlockDecl 1434 /// CapturedDecl 1435 class DeclContext { 1436 /// For makeDeclVisibleInContextImpl 1437 friend class ASTDeclReader; 1438 /// For checking the new bits in the Serialization part. 1439 friend class ASTDeclWriter; 1440 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap, 1441 /// hasNeedToReconcileExternalVisibleStorage 1442 friend class ExternalASTSource; 1443 /// For CreateStoredDeclsMap 1444 friend class DependentDiagnostic; 1445 /// For hasNeedToReconcileExternalVisibleStorage, 1446 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups 1447 friend class ASTWriter; 1448 1449 // We use uint64_t in the bit-fields below since some bit-fields 1450 // cross the unsigned boundary and this breaks the packing. 1451 1452 /// Stores the bits used by DeclContext. 1453 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor 1454 /// methods in DeclContext should be updated appropriately. 1455 class DeclContextBitfields { 1456 friend class DeclContext; 1457 /// DeclKind - This indicates which class this is. 1458 LLVM_PREFERRED_TYPE(Decl::Kind) 1459 uint64_t DeclKind : 7; 1460 1461 /// Whether this declaration context also has some external 1462 /// storage that contains additional declarations that are lexically 1463 /// part of this context. 1464 LLVM_PREFERRED_TYPE(bool) 1465 mutable uint64_t ExternalLexicalStorage : 1; 1466 1467 /// Whether this declaration context also has some external 1468 /// storage that contains additional declarations that are visible 1469 /// in this context. 1470 LLVM_PREFERRED_TYPE(bool) 1471 mutable uint64_t ExternalVisibleStorage : 1; 1472 1473 /// Whether this declaration context has had externally visible 1474 /// storage added since the last lookup. In this case, \c LookupPtr's 1475 /// invariant may not hold and needs to be fixed before we perform 1476 /// another lookup. 1477 LLVM_PREFERRED_TYPE(bool) 1478 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1; 1479 1480 /// If \c true, this context may have local lexical declarations 1481 /// that are missing from the lookup table. 1482 LLVM_PREFERRED_TYPE(bool) 1483 mutable uint64_t HasLazyLocalLexicalLookups : 1; 1484 1485 /// If \c true, the external source may have lexical declarations 1486 /// that are missing from the lookup table. 1487 LLVM_PREFERRED_TYPE(bool) 1488 mutable uint64_t HasLazyExternalLexicalLookups : 1; 1489 1490 /// If \c true, lookups should only return identifier from 1491 /// DeclContext scope (for example TranslationUnit). Used in 1492 /// LookupQualifiedName() 1493 LLVM_PREFERRED_TYPE(bool) 1494 mutable uint64_t UseQualifiedLookup : 1; 1495 }; 1496 1497 /// Number of bits in DeclContextBitfields. 1498 enum { NumDeclContextBits = 13 }; 1499 1500 /// Stores the bits used by NamespaceDecl. 1501 /// If modified NumNamespaceDeclBits and the accessor 1502 /// methods in NamespaceDecl should be updated appropriately. 1503 class NamespaceDeclBitfields { 1504 friend class NamespaceDecl; 1505 /// For the bits in DeclContextBitfields 1506 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1507 uint64_t : NumDeclContextBits; 1508 1509 /// True if this is an inline namespace. 1510 LLVM_PREFERRED_TYPE(bool) 1511 uint64_t IsInline : 1; 1512 1513 /// True if this is a nested-namespace-definition. 1514 LLVM_PREFERRED_TYPE(bool) 1515 uint64_t IsNested : 1; 1516 }; 1517 1518 /// Number of inherited and non-inherited bits in NamespaceDeclBitfields. 1519 enum { NumNamespaceDeclBits = NumDeclContextBits + 2 }; 1520 1521 /// Stores the bits used by TagDecl. 1522 /// If modified NumTagDeclBits and the accessor 1523 /// methods in TagDecl should be updated appropriately. 1524 class TagDeclBitfields { 1525 friend class TagDecl; 1526 /// For the bits in DeclContextBitfields 1527 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1528 uint64_t : NumDeclContextBits; 1529 1530 /// The TagKind enum. 1531 LLVM_PREFERRED_TYPE(TagTypeKind) 1532 uint64_t TagDeclKind : 3; 1533 1534 /// True if this is a definition ("struct foo {};"), false if it is a 1535 /// declaration ("struct foo;"). It is not considered a definition 1536 /// until the definition has been fully processed. 1537 LLVM_PREFERRED_TYPE(bool) 1538 uint64_t IsCompleteDefinition : 1; 1539 1540 /// True if this is currently being defined. 1541 LLVM_PREFERRED_TYPE(bool) 1542 uint64_t IsBeingDefined : 1; 1543 1544 /// True if this tag declaration is "embedded" (i.e., defined or declared 1545 /// for the very first time) in the syntax of a declarator. 1546 LLVM_PREFERRED_TYPE(bool) 1547 uint64_t IsEmbeddedInDeclarator : 1; 1548 1549 /// True if this tag is free standing, e.g. "struct foo;". 1550 LLVM_PREFERRED_TYPE(bool) 1551 uint64_t IsFreeStanding : 1; 1552 1553 /// Indicates whether it is possible for declarations of this kind 1554 /// to have an out-of-date definition. 1555 /// 1556 /// This option is only enabled when modules are enabled. 1557 LLVM_PREFERRED_TYPE(bool) 1558 uint64_t MayHaveOutOfDateDef : 1; 1559 1560 /// Has the full definition of this type been required by a use somewhere in 1561 /// the TU. 1562 LLVM_PREFERRED_TYPE(bool) 1563 uint64_t IsCompleteDefinitionRequired : 1; 1564 1565 /// Whether this tag is a definition which was demoted due to 1566 /// a module merge. 1567 LLVM_PREFERRED_TYPE(bool) 1568 uint64_t IsThisDeclarationADemotedDefinition : 1; 1569 }; 1570 1571 /// Number of inherited and non-inherited bits in TagDeclBitfields. 1572 enum { NumTagDeclBits = NumDeclContextBits + 10 }; 1573 1574 /// Stores the bits used by EnumDecl. 1575 /// If modified NumEnumDeclBit and the accessor 1576 /// methods in EnumDecl should be updated appropriately. 1577 class EnumDeclBitfields { 1578 friend class EnumDecl; 1579 /// For the bits in TagDeclBitfields. 1580 LLVM_PREFERRED_TYPE(TagDeclBitfields) 1581 uint64_t : NumTagDeclBits; 1582 1583 /// Width in bits required to store all the non-negative 1584 /// enumerators of this enum. 1585 uint64_t NumPositiveBits : 8; 1586 1587 /// Width in bits required to store all the negative 1588 /// enumerators of this enum. 1589 uint64_t NumNegativeBits : 8; 1590 1591 /// True if this tag declaration is a scoped enumeration. Only 1592 /// possible in C++11 mode. 1593 LLVM_PREFERRED_TYPE(bool) 1594 uint64_t IsScoped : 1; 1595 1596 /// If this tag declaration is a scoped enum, 1597 /// then this is true if the scoped enum was declared using the class 1598 /// tag, false if it was declared with the struct tag. No meaning is 1599 /// associated if this tag declaration is not a scoped enum. 1600 LLVM_PREFERRED_TYPE(bool) 1601 uint64_t IsScopedUsingClassTag : 1; 1602 1603 /// True if this is an enumeration with fixed underlying type. Only 1604 /// possible in C++11, Microsoft extensions, or Objective C mode. 1605 LLVM_PREFERRED_TYPE(bool) 1606 uint64_t IsFixed : 1; 1607 1608 /// True if a valid hash is stored in ODRHash. 1609 LLVM_PREFERRED_TYPE(bool) 1610 uint64_t HasODRHash : 1; 1611 }; 1612 1613 /// Number of inherited and non-inherited bits in EnumDeclBitfields. 1614 enum { NumEnumDeclBits = NumTagDeclBits + 20 }; 1615 1616 /// Stores the bits used by RecordDecl. 1617 /// If modified NumRecordDeclBits and the accessor 1618 /// methods in RecordDecl should be updated appropriately. 1619 class RecordDeclBitfields { 1620 friend class RecordDecl; 1621 /// For the bits in TagDeclBitfields. 1622 LLVM_PREFERRED_TYPE(TagDeclBitfields) 1623 uint64_t : NumTagDeclBits; 1624 1625 /// This is true if this struct ends with a flexible 1626 /// array member (e.g. int X[]) or if this union contains a struct that does. 1627 /// If so, this cannot be contained in arrays or other structs as a member. 1628 LLVM_PREFERRED_TYPE(bool) 1629 uint64_t HasFlexibleArrayMember : 1; 1630 1631 /// Whether this is the type of an anonymous struct or union. 1632 LLVM_PREFERRED_TYPE(bool) 1633 uint64_t AnonymousStructOrUnion : 1; 1634 1635 /// This is true if this struct has at least one member 1636 /// containing an Objective-C object pointer type. 1637 LLVM_PREFERRED_TYPE(bool) 1638 uint64_t HasObjectMember : 1; 1639 1640 /// This is true if struct has at least one member of 1641 /// 'volatile' type. 1642 LLVM_PREFERRED_TYPE(bool) 1643 uint64_t HasVolatileMember : 1; 1644 1645 /// Whether the field declarations of this record have been loaded 1646 /// from external storage. To avoid unnecessary deserialization of 1647 /// methods/nested types we allow deserialization of just the fields 1648 /// when needed. 1649 LLVM_PREFERRED_TYPE(bool) 1650 mutable uint64_t LoadedFieldsFromExternalStorage : 1; 1651 1652 /// Basic properties of non-trivial C structs. 1653 LLVM_PREFERRED_TYPE(bool) 1654 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1; 1655 LLVM_PREFERRED_TYPE(bool) 1656 uint64_t NonTrivialToPrimitiveCopy : 1; 1657 LLVM_PREFERRED_TYPE(bool) 1658 uint64_t NonTrivialToPrimitiveDestroy : 1; 1659 1660 /// The following bits indicate whether this is or contains a C union that 1661 /// is non-trivial to default-initialize, destruct, or copy. These bits 1662 /// imply the associated basic non-triviality predicates declared above. 1663 LLVM_PREFERRED_TYPE(bool) 1664 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1; 1665 LLVM_PREFERRED_TYPE(bool) 1666 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1; 1667 LLVM_PREFERRED_TYPE(bool) 1668 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1; 1669 1670 /// Indicates whether this struct is destroyed in the callee. 1671 LLVM_PREFERRED_TYPE(bool) 1672 uint64_t ParamDestroyedInCallee : 1; 1673 1674 /// Represents the way this type is passed to a function. 1675 LLVM_PREFERRED_TYPE(RecordArgPassingKind) 1676 uint64_t ArgPassingRestrictions : 2; 1677 1678 /// Indicates whether this struct has had its field layout randomized. 1679 LLVM_PREFERRED_TYPE(bool) 1680 uint64_t IsRandomized : 1; 1681 1682 /// True if a valid hash is stored in ODRHash. This should shave off some 1683 /// extra storage and prevent CXXRecordDecl to store unused bits. 1684 uint64_t ODRHash : 26; 1685 }; 1686 1687 /// Number of inherited and non-inherited bits in RecordDeclBitfields. 1688 enum { NumRecordDeclBits = NumTagDeclBits + 41 }; 1689 1690 /// Stores the bits used by OMPDeclareReductionDecl. 1691 /// If modified NumOMPDeclareReductionDeclBits and the accessor 1692 /// methods in OMPDeclareReductionDecl should be updated appropriately. 1693 class OMPDeclareReductionDeclBitfields { 1694 friend class OMPDeclareReductionDecl; 1695 /// For the bits in DeclContextBitfields 1696 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1697 uint64_t : NumDeclContextBits; 1698 1699 /// Kind of initializer, 1700 /// function call or omp_priv<init_expr> initialization. 1701 LLVM_PREFERRED_TYPE(OMPDeclareReductionInitKind) 1702 uint64_t InitializerKind : 2; 1703 }; 1704 1705 /// Number of inherited and non-inherited bits in 1706 /// OMPDeclareReductionDeclBitfields. 1707 enum { NumOMPDeclareReductionDeclBits = NumDeclContextBits + 2 }; 1708 1709 /// Stores the bits used by FunctionDecl. 1710 /// If modified NumFunctionDeclBits and the accessor 1711 /// methods in FunctionDecl and CXXDeductionGuideDecl 1712 /// (for DeductionCandidateKind) should be updated appropriately. 1713 class FunctionDeclBitfields { 1714 friend class FunctionDecl; 1715 /// For DeductionCandidateKind 1716 friend class CXXDeductionGuideDecl; 1717 /// For the bits in DeclContextBitfields. 1718 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1719 uint64_t : NumDeclContextBits; 1720 1721 LLVM_PREFERRED_TYPE(StorageClass) 1722 uint64_t SClass : 3; 1723 LLVM_PREFERRED_TYPE(bool) 1724 uint64_t IsInline : 1; 1725 LLVM_PREFERRED_TYPE(bool) 1726 uint64_t IsInlineSpecified : 1; 1727 1728 LLVM_PREFERRED_TYPE(bool) 1729 uint64_t IsVirtualAsWritten : 1; 1730 LLVM_PREFERRED_TYPE(bool) 1731 uint64_t IsPureVirtual : 1; 1732 LLVM_PREFERRED_TYPE(bool) 1733 uint64_t HasInheritedPrototype : 1; 1734 LLVM_PREFERRED_TYPE(bool) 1735 uint64_t HasWrittenPrototype : 1; 1736 LLVM_PREFERRED_TYPE(bool) 1737 uint64_t IsDeleted : 1; 1738 /// Used by CXXMethodDecl 1739 LLVM_PREFERRED_TYPE(bool) 1740 uint64_t IsTrivial : 1; 1741 1742 /// This flag indicates whether this function is trivial for the purpose of 1743 /// calls. This is meaningful only when this function is a copy/move 1744 /// constructor or a destructor. 1745 LLVM_PREFERRED_TYPE(bool) 1746 uint64_t IsTrivialForCall : 1; 1747 1748 LLVM_PREFERRED_TYPE(bool) 1749 uint64_t IsDefaulted : 1; 1750 LLVM_PREFERRED_TYPE(bool) 1751 uint64_t IsExplicitlyDefaulted : 1; 1752 LLVM_PREFERRED_TYPE(bool) 1753 uint64_t HasDefaultedOrDeletedInfo : 1; 1754 1755 /// For member functions of complete types, whether this is an ineligible 1756 /// special member function or an unselected destructor. See 1757 /// [class.mem.special]. 1758 LLVM_PREFERRED_TYPE(bool) 1759 uint64_t IsIneligibleOrNotSelected : 1; 1760 1761 LLVM_PREFERRED_TYPE(bool) 1762 uint64_t HasImplicitReturnZero : 1; 1763 LLVM_PREFERRED_TYPE(bool) 1764 uint64_t IsLateTemplateParsed : 1; 1765 1766 /// Kind of contexpr specifier as defined by ConstexprSpecKind. 1767 LLVM_PREFERRED_TYPE(ConstexprSpecKind) 1768 uint64_t ConstexprKind : 2; 1769 LLVM_PREFERRED_TYPE(bool) 1770 uint64_t BodyContainsImmediateEscalatingExpression : 1; 1771 1772 LLVM_PREFERRED_TYPE(bool) 1773 uint64_t InstantiationIsPending : 1; 1774 1775 /// Indicates if the function uses __try. 1776 LLVM_PREFERRED_TYPE(bool) 1777 uint64_t UsesSEHTry : 1; 1778 1779 /// Indicates if the function was a definition 1780 /// but its body was skipped. 1781 LLVM_PREFERRED_TYPE(bool) 1782 uint64_t HasSkippedBody : 1; 1783 1784 /// Indicates if the function declaration will 1785 /// have a body, once we're done parsing it. 1786 LLVM_PREFERRED_TYPE(bool) 1787 uint64_t WillHaveBody : 1; 1788 1789 /// Indicates that this function is a multiversioned 1790 /// function using attribute 'target'. 1791 LLVM_PREFERRED_TYPE(bool) 1792 uint64_t IsMultiVersion : 1; 1793 1794 /// Only used by CXXDeductionGuideDecl. Indicates the kind 1795 /// of the Deduction Guide that is implicitly generated 1796 /// (used during overload resolution). 1797 LLVM_PREFERRED_TYPE(DeductionCandidate) 1798 uint64_t DeductionCandidateKind : 2; 1799 1800 /// Store the ODRHash after first calculation. 1801 LLVM_PREFERRED_TYPE(bool) 1802 uint64_t HasODRHash : 1; 1803 1804 /// Indicates if the function uses Floating Point Constrained Intrinsics 1805 LLVM_PREFERRED_TYPE(bool) 1806 uint64_t UsesFPIntrin : 1; 1807 1808 // Indicates this function is a constrained friend, where the constraint 1809 // refers to an enclosing template for hte purposes of [temp.friend]p9. 1810 LLVM_PREFERRED_TYPE(bool) 1811 uint64_t FriendConstraintRefersToEnclosingTemplate : 1; 1812 }; 1813 1814 /// Number of inherited and non-inherited bits in FunctionDeclBitfields. 1815 enum { NumFunctionDeclBits = NumDeclContextBits + 31 }; 1816 1817 /// Stores the bits used by CXXConstructorDecl. If modified 1818 /// NumCXXConstructorDeclBits and the accessor 1819 /// methods in CXXConstructorDecl should be updated appropriately. 1820 class CXXConstructorDeclBitfields { 1821 friend class CXXConstructorDecl; 1822 /// For the bits in FunctionDeclBitfields. 1823 LLVM_PREFERRED_TYPE(FunctionDeclBitfields) 1824 uint64_t : NumFunctionDeclBits; 1825 1826 /// 20 bits to fit in the remaining available space. 1827 /// Note that this makes CXXConstructorDeclBitfields take 1828 /// exactly 64 bits and thus the width of NumCtorInitializers 1829 /// will need to be shrunk if some bit is added to NumDeclContextBitfields, 1830 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields. 1831 uint64_t NumCtorInitializers : 17; 1832 LLVM_PREFERRED_TYPE(bool) 1833 uint64_t IsInheritingConstructor : 1; 1834 1835 /// Whether this constructor has a trail-allocated explicit specifier. 1836 LLVM_PREFERRED_TYPE(bool) 1837 uint64_t HasTrailingExplicitSpecifier : 1; 1838 /// If this constructor does't have a trail-allocated explicit specifier. 1839 /// Whether this constructor is explicit specified. 1840 LLVM_PREFERRED_TYPE(bool) 1841 uint64_t IsSimpleExplicit : 1; 1842 }; 1843 1844 /// Number of inherited and non-inherited bits in CXXConstructorDeclBitfields. 1845 enum { NumCXXConstructorDeclBits = NumFunctionDeclBits + 20 }; 1846 1847 /// Stores the bits used by ObjCMethodDecl. 1848 /// If modified NumObjCMethodDeclBits and the accessor 1849 /// methods in ObjCMethodDecl should be updated appropriately. 1850 class ObjCMethodDeclBitfields { 1851 friend class ObjCMethodDecl; 1852 1853 /// For the bits in DeclContextBitfields. 1854 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1855 uint64_t : NumDeclContextBits; 1856 1857 /// The conventional meaning of this method; an ObjCMethodFamily. 1858 /// This is not serialized; instead, it is computed on demand and 1859 /// cached. 1860 LLVM_PREFERRED_TYPE(ObjCMethodFamily) 1861 mutable uint64_t Family : ObjCMethodFamilyBitWidth; 1862 1863 /// instance (true) or class (false) method. 1864 LLVM_PREFERRED_TYPE(bool) 1865 uint64_t IsInstance : 1; 1866 LLVM_PREFERRED_TYPE(bool) 1867 uint64_t IsVariadic : 1; 1868 1869 /// True if this method is the getter or setter for an explicit property. 1870 LLVM_PREFERRED_TYPE(bool) 1871 uint64_t IsPropertyAccessor : 1; 1872 1873 /// True if this method is a synthesized property accessor stub. 1874 LLVM_PREFERRED_TYPE(bool) 1875 uint64_t IsSynthesizedAccessorStub : 1; 1876 1877 /// Method has a definition. 1878 LLVM_PREFERRED_TYPE(bool) 1879 uint64_t IsDefined : 1; 1880 1881 /// Method redeclaration in the same interface. 1882 LLVM_PREFERRED_TYPE(bool) 1883 uint64_t IsRedeclaration : 1; 1884 1885 /// Is redeclared in the same interface. 1886 LLVM_PREFERRED_TYPE(bool) 1887 mutable uint64_t HasRedeclaration : 1; 1888 1889 /// \@required/\@optional 1890 LLVM_PREFERRED_TYPE(ObjCImplementationControl) 1891 uint64_t DeclImplementation : 2; 1892 1893 /// in, inout, etc. 1894 LLVM_PREFERRED_TYPE(Decl::ObjCDeclQualifier) 1895 uint64_t objcDeclQualifier : 7; 1896 1897 /// Indicates whether this method has a related result type. 1898 LLVM_PREFERRED_TYPE(bool) 1899 uint64_t RelatedResultType : 1; 1900 1901 /// Whether the locations of the selector identifiers are in a 1902 /// "standard" position, a enum SelectorLocationsKind. 1903 LLVM_PREFERRED_TYPE(SelectorLocationsKind) 1904 uint64_t SelLocsKind : 2; 1905 1906 /// Whether this method overrides any other in the class hierarchy. 1907 /// 1908 /// A method is said to override any method in the class's 1909 /// base classes, its protocols, or its categories' protocols, that has 1910 /// the same selector and is of the same kind (class or instance). 1911 /// A method in an implementation is not considered as overriding the same 1912 /// method in the interface or its categories. 1913 LLVM_PREFERRED_TYPE(bool) 1914 uint64_t IsOverriding : 1; 1915 1916 /// Indicates if the method was a definition but its body was skipped. 1917 LLVM_PREFERRED_TYPE(bool) 1918 uint64_t HasSkippedBody : 1; 1919 }; 1920 1921 /// Number of inherited and non-inherited bits in ObjCMethodDeclBitfields. 1922 enum { NumObjCMethodDeclBits = NumDeclContextBits + 24 }; 1923 1924 /// Stores the bits used by ObjCContainerDecl. 1925 /// If modified NumObjCContainerDeclBits and the accessor 1926 /// methods in ObjCContainerDecl should be updated appropriately. 1927 class ObjCContainerDeclBitfields { 1928 friend class ObjCContainerDecl; 1929 /// For the bits in DeclContextBitfields 1930 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1931 uint32_t : NumDeclContextBits; 1932 1933 // Not a bitfield but this saves space. 1934 // Note that ObjCContainerDeclBitfields is full. 1935 SourceLocation AtStart; 1936 }; 1937 1938 /// Number of inherited and non-inherited bits in ObjCContainerDeclBitfields. 1939 /// Note that here we rely on the fact that SourceLocation is 32 bits 1940 /// wide. We check this with the static_assert in the ctor of DeclContext. 1941 enum { NumObjCContainerDeclBits = 64 }; 1942 1943 /// Stores the bits used by LinkageSpecDecl. 1944 /// If modified NumLinkageSpecDeclBits and the accessor 1945 /// methods in LinkageSpecDecl should be updated appropriately. 1946 class LinkageSpecDeclBitfields { 1947 friend class LinkageSpecDecl; 1948 /// For the bits in DeclContextBitfields. 1949 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1950 uint64_t : NumDeclContextBits; 1951 1952 /// The language for this linkage specification. 1953 LLVM_PREFERRED_TYPE(LinkageSpecLanguageIDs) 1954 uint64_t Language : 3; 1955 1956 /// True if this linkage spec has braces. 1957 /// This is needed so that hasBraces() returns the correct result while the 1958 /// linkage spec body is being parsed. Once RBraceLoc has been set this is 1959 /// not used, so it doesn't need to be serialized. 1960 LLVM_PREFERRED_TYPE(bool) 1961 uint64_t HasBraces : 1; 1962 }; 1963 1964 /// Number of inherited and non-inherited bits in LinkageSpecDeclBitfields. 1965 enum { NumLinkageSpecDeclBits = NumDeclContextBits + 4 }; 1966 1967 /// Stores the bits used by BlockDecl. 1968 /// If modified NumBlockDeclBits and the accessor 1969 /// methods in BlockDecl should be updated appropriately. 1970 class BlockDeclBitfields { 1971 friend class BlockDecl; 1972 /// For the bits in DeclContextBitfields. 1973 LLVM_PREFERRED_TYPE(DeclContextBitfields) 1974 uint64_t : NumDeclContextBits; 1975 1976 LLVM_PREFERRED_TYPE(bool) 1977 uint64_t IsVariadic : 1; 1978 LLVM_PREFERRED_TYPE(bool) 1979 uint64_t CapturesCXXThis : 1; 1980 LLVM_PREFERRED_TYPE(bool) 1981 uint64_t BlockMissingReturnType : 1; 1982 LLVM_PREFERRED_TYPE(bool) 1983 uint64_t IsConversionFromLambda : 1; 1984 1985 /// A bit that indicates this block is passed directly to a function as a 1986 /// non-escaping parameter. 1987 LLVM_PREFERRED_TYPE(bool) 1988 uint64_t DoesNotEscape : 1; 1989 1990 /// A bit that indicates whether it's possible to avoid coying this block to 1991 /// the heap when it initializes or is assigned to a local variable with 1992 /// automatic storage. 1993 LLVM_PREFERRED_TYPE(bool) 1994 uint64_t CanAvoidCopyToHeap : 1; 1995 }; 1996 1997 /// Number of inherited and non-inherited bits in BlockDeclBitfields. 1998 enum { NumBlockDeclBits = NumDeclContextBits + 5 }; 1999 2000 /// Pointer to the data structure used to lookup declarations 2001 /// within this context (or a DependentStoredDeclsMap if this is a 2002 /// dependent context). We maintain the invariant that, if the map 2003 /// contains an entry for a DeclarationName (and we haven't lazily 2004 /// omitted anything), then it contains all relevant entries for that 2005 /// name (modulo the hasExternalDecls() flag). 2006 mutable StoredDeclsMap *LookupPtr = nullptr; 2007 2008 protected: 2009 /// This anonymous union stores the bits belonging to DeclContext and classes 2010 /// deriving from it. The goal is to use otherwise wasted 2011 /// space in DeclContext to store data belonging to derived classes. 2012 /// The space saved is especially significient when pointers are aligned 2013 /// to 8 bytes. In this case due to alignment requirements we have a 2014 /// little less than 8 bytes free in DeclContext which we can use. 2015 /// We check that none of the classes in this union is larger than 2016 /// 8 bytes with static_asserts in the ctor of DeclContext. 2017 union { 2018 DeclContextBitfields DeclContextBits; 2019 NamespaceDeclBitfields NamespaceDeclBits; 2020 TagDeclBitfields TagDeclBits; 2021 EnumDeclBitfields EnumDeclBits; 2022 RecordDeclBitfields RecordDeclBits; 2023 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits; 2024 FunctionDeclBitfields FunctionDeclBits; 2025 CXXConstructorDeclBitfields CXXConstructorDeclBits; 2026 ObjCMethodDeclBitfields ObjCMethodDeclBits; 2027 ObjCContainerDeclBitfields ObjCContainerDeclBits; 2028 LinkageSpecDeclBitfields LinkageSpecDeclBits; 2029 BlockDeclBitfields BlockDeclBits; 2030 2031 static_assert(sizeof(DeclContextBitfields) <= 8, 2032 "DeclContextBitfields is larger than 8 bytes!"); 2033 static_assert(sizeof(NamespaceDeclBitfields) <= 8, 2034 "NamespaceDeclBitfields is larger than 8 bytes!"); 2035 static_assert(sizeof(TagDeclBitfields) <= 8, 2036 "TagDeclBitfields is larger than 8 bytes!"); 2037 static_assert(sizeof(EnumDeclBitfields) <= 8, 2038 "EnumDeclBitfields is larger than 8 bytes!"); 2039 static_assert(sizeof(RecordDeclBitfields) <= 8, 2040 "RecordDeclBitfields is larger than 8 bytes!"); 2041 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8, 2042 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!"); 2043 static_assert(sizeof(FunctionDeclBitfields) <= 8, 2044 "FunctionDeclBitfields is larger than 8 bytes!"); 2045 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8, 2046 "CXXConstructorDeclBitfields is larger than 8 bytes!"); 2047 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8, 2048 "ObjCMethodDeclBitfields is larger than 8 bytes!"); 2049 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8, 2050 "ObjCContainerDeclBitfields is larger than 8 bytes!"); 2051 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8, 2052 "LinkageSpecDeclBitfields is larger than 8 bytes!"); 2053 static_assert(sizeof(BlockDeclBitfields) <= 8, 2054 "BlockDeclBitfields is larger than 8 bytes!"); 2055 }; 2056 2057 /// FirstDecl - The first declaration stored within this declaration 2058 /// context. 2059 mutable Decl *FirstDecl = nullptr; 2060 2061 /// LastDecl - The last declaration stored within this declaration 2062 /// context. FIXME: We could probably cache this value somewhere 2063 /// outside of the DeclContext, to reduce the size of DeclContext by 2064 /// another pointer. 2065 mutable Decl *LastDecl = nullptr; 2066 2067 /// Build up a chain of declarations. 2068 /// 2069 /// \returns the first/last pair of declarations. 2070 static std::pair<Decl *, Decl *> 2071 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded); 2072 2073 DeclContext(Decl::Kind K); 2074 2075 public: 2076 ~DeclContext(); 2077 2078 // For use when debugging; hasValidDeclKind() will always return true for 2079 // a correctly constructed object within its lifetime. 2080 bool hasValidDeclKind() const; 2081 2082 Decl::Kind getDeclKind() const { 2083 return static_cast<Decl::Kind>(DeclContextBits.DeclKind); 2084 } 2085 2086 const char *getDeclKindName() const; 2087 2088 /// getParent - Returns the containing DeclContext. 2089 DeclContext *getParent() { 2090 return cast<Decl>(this)->getDeclContext(); 2091 } 2092 const DeclContext *getParent() const { 2093 return const_cast<DeclContext*>(this)->getParent(); 2094 } 2095 2096 /// getLexicalParent - Returns the containing lexical DeclContext. May be 2097 /// different from getParent, e.g.: 2098 /// 2099 /// namespace A { 2100 /// struct S; 2101 /// } 2102 /// struct A::S {}; // getParent() == namespace 'A' 2103 /// // getLexicalParent() == translation unit 2104 /// 2105 DeclContext *getLexicalParent() { 2106 return cast<Decl>(this)->getLexicalDeclContext(); 2107 } 2108 const DeclContext *getLexicalParent() const { 2109 return const_cast<DeclContext*>(this)->getLexicalParent(); 2110 } 2111 2112 DeclContext *getLookupParent(); 2113 2114 const DeclContext *getLookupParent() const { 2115 return const_cast<DeclContext*>(this)->getLookupParent(); 2116 } 2117 2118 ASTContext &getParentASTContext() const { 2119 return cast<Decl>(this)->getASTContext(); 2120 } 2121 2122 bool isClosure() const { return getDeclKind() == Decl::Block; } 2123 2124 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the 2125 /// innermost enclosing BlockDecl or null if there are no enclosing blocks. 2126 const BlockDecl *getInnermostBlockDecl() const; 2127 2128 bool isObjCContainer() const { 2129 switch (getDeclKind()) { 2130 case Decl::ObjCCategory: 2131 case Decl::ObjCCategoryImpl: 2132 case Decl::ObjCImplementation: 2133 case Decl::ObjCInterface: 2134 case Decl::ObjCProtocol: 2135 return true; 2136 default: 2137 return false; 2138 } 2139 } 2140 2141 bool isFunctionOrMethod() const { 2142 switch (getDeclKind()) { 2143 case Decl::Block: 2144 case Decl::Captured: 2145 case Decl::ObjCMethod: 2146 case Decl::TopLevelStmt: 2147 return true; 2148 default: 2149 return getDeclKind() >= Decl::firstFunction && 2150 getDeclKind() <= Decl::lastFunction; 2151 } 2152 } 2153 2154 /// Test whether the context supports looking up names. 2155 bool isLookupContext() const { 2156 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec && 2157 getDeclKind() != Decl::Export; 2158 } 2159 2160 bool isFileContext() const { 2161 return getDeclKind() == Decl::TranslationUnit || 2162 getDeclKind() == Decl::Namespace; 2163 } 2164 2165 bool isTranslationUnit() const { 2166 return getDeclKind() == Decl::TranslationUnit; 2167 } 2168 2169 bool isRecord() const { 2170 return getDeclKind() >= Decl::firstRecord && 2171 getDeclKind() <= Decl::lastRecord; 2172 } 2173 2174 bool isRequiresExprBody() const { 2175 return getDeclKind() == Decl::RequiresExprBody; 2176 } 2177 2178 bool isNamespace() const { return getDeclKind() == Decl::Namespace; } 2179 2180 bool isStdNamespace() const; 2181 2182 bool isInlineNamespace() const; 2183 2184 /// Determines whether this context is dependent on a 2185 /// template parameter. 2186 bool isDependentContext() const; 2187 2188 /// isTransparentContext - Determines whether this context is a 2189 /// "transparent" context, meaning that the members declared in this 2190 /// context are semantically declared in the nearest enclosing 2191 /// non-transparent (opaque) context but are lexically declared in 2192 /// this context. For example, consider the enumerators of an 2193 /// enumeration type: 2194 /// @code 2195 /// enum E { 2196 /// Val1 2197 /// }; 2198 /// @endcode 2199 /// Here, E is a transparent context, so its enumerator (Val1) will 2200 /// appear (semantically) that it is in the same context of E. 2201 /// Examples of transparent contexts include: enumerations (except for 2202 /// C++0x scoped enums), C++ linkage specifications and export declaration. 2203 bool isTransparentContext() const; 2204 2205 /// Determines whether this context or some of its ancestors is a 2206 /// linkage specification context that specifies C linkage. 2207 bool isExternCContext() const; 2208 2209 /// Retrieve the nearest enclosing C linkage specification context. 2210 const LinkageSpecDecl *getExternCContext() const; 2211 2212 /// Determines whether this context or some of its ancestors is a 2213 /// linkage specification context that specifies C++ linkage. 2214 bool isExternCXXContext() const; 2215 2216 /// Determine whether this declaration context is equivalent 2217 /// to the declaration context DC. 2218 bool Equals(const DeclContext *DC) const { 2219 return DC && this->getPrimaryContext() == DC->getPrimaryContext(); 2220 } 2221 2222 /// Determine whether this declaration context encloses the 2223 /// declaration context DC. 2224 bool Encloses(const DeclContext *DC) const; 2225 2226 /// Find the nearest non-closure ancestor of this context, 2227 /// i.e. the innermost semantic parent of this context which is not 2228 /// a closure. A context may be its own non-closure ancestor. 2229 Decl *getNonClosureAncestor(); 2230 const Decl *getNonClosureAncestor() const { 2231 return const_cast<DeclContext*>(this)->getNonClosureAncestor(); 2232 } 2233 2234 // Retrieve the nearest context that is not a transparent context. 2235 DeclContext *getNonTransparentContext(); 2236 const DeclContext *getNonTransparentContext() const { 2237 return const_cast<DeclContext *>(this)->getNonTransparentContext(); 2238 } 2239 2240 /// getPrimaryContext - There may be many different 2241 /// declarations of the same entity (including forward declarations 2242 /// of classes, multiple definitions of namespaces, etc.), each with 2243 /// a different set of declarations. This routine returns the 2244 /// "primary" DeclContext structure, which will contain the 2245 /// information needed to perform name lookup into this context. 2246 DeclContext *getPrimaryContext(); 2247 const DeclContext *getPrimaryContext() const { 2248 return const_cast<DeclContext*>(this)->getPrimaryContext(); 2249 } 2250 2251 /// getRedeclContext - Retrieve the context in which an entity conflicts with 2252 /// other entities of the same name, or where it is a redeclaration if the 2253 /// two entities are compatible. This skips through transparent contexts. 2254 DeclContext *getRedeclContext(); 2255 const DeclContext *getRedeclContext() const { 2256 return const_cast<DeclContext *>(this)->getRedeclContext(); 2257 } 2258 2259 /// Retrieve the nearest enclosing namespace context. 2260 DeclContext *getEnclosingNamespaceContext(); 2261 const DeclContext *getEnclosingNamespaceContext() const { 2262 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext(); 2263 } 2264 2265 /// Retrieve the outermost lexically enclosing record context. 2266 RecordDecl *getOuterLexicalRecordContext(); 2267 const RecordDecl *getOuterLexicalRecordContext() const { 2268 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext(); 2269 } 2270 2271 /// Test if this context is part of the enclosing namespace set of 2272 /// the context NS, as defined in C++0x [namespace.def]p9. If either context 2273 /// isn't a namespace, this is equivalent to Equals(). 2274 /// 2275 /// The enclosing namespace set of a namespace is the namespace and, if it is 2276 /// inline, its enclosing namespace, recursively. 2277 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; 2278 2279 /// Collects all of the declaration contexts that are semantically 2280 /// connected to this declaration context. 2281 /// 2282 /// For declaration contexts that have multiple semantically connected but 2283 /// syntactically distinct contexts, such as C++ namespaces, this routine 2284 /// retrieves the complete set of such declaration contexts in source order. 2285 /// For example, given: 2286 /// 2287 /// \code 2288 /// namespace N { 2289 /// int x; 2290 /// } 2291 /// namespace N { 2292 /// int y; 2293 /// } 2294 /// \endcode 2295 /// 2296 /// The \c Contexts parameter will contain both definitions of N. 2297 /// 2298 /// \param Contexts Will be cleared and set to the set of declaration 2299 /// contexts that are semanticaly connected to this declaration context, 2300 /// in source order, including this context (which may be the only result, 2301 /// for non-namespace contexts). 2302 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts); 2303 2304 /// decl_iterator - Iterates through the declarations stored 2305 /// within this context. 2306 class decl_iterator { 2307 /// Current - The current declaration. 2308 Decl *Current = nullptr; 2309 2310 public: 2311 using value_type = Decl *; 2312 using reference = const value_type &; 2313 using pointer = const value_type *; 2314 using iterator_category = std::forward_iterator_tag; 2315 using difference_type = std::ptrdiff_t; 2316 2317 decl_iterator() = default; 2318 explicit decl_iterator(Decl *C) : Current(C) {} 2319 2320 reference operator*() const { return Current; } 2321 2322 // This doesn't meet the iterator requirements, but it's convenient 2323 value_type operator->() const { return Current; } 2324 2325 decl_iterator& operator++() { 2326 Current = Current->getNextDeclInContext(); 2327 return *this; 2328 } 2329 2330 decl_iterator operator++(int) { 2331 decl_iterator tmp(*this); 2332 ++(*this); 2333 return tmp; 2334 } 2335 2336 friend bool operator==(decl_iterator x, decl_iterator y) { 2337 return x.Current == y.Current; 2338 } 2339 2340 friend bool operator!=(decl_iterator x, decl_iterator y) { 2341 return x.Current != y.Current; 2342 } 2343 }; 2344 2345 using decl_range = llvm::iterator_range<decl_iterator>; 2346 2347 /// decls_begin/decls_end - Iterate over the declarations stored in 2348 /// this context. 2349 decl_range decls() const { return decl_range(decls_begin(), decls_end()); } 2350 decl_iterator decls_begin() const; 2351 decl_iterator decls_end() const { return decl_iterator(); } 2352 bool decls_empty() const; 2353 2354 /// noload_decls_begin/end - Iterate over the declarations stored in this 2355 /// context that are currently loaded; don't attempt to retrieve anything 2356 /// from an external source. 2357 decl_range noload_decls() const { 2358 return decl_range(noload_decls_begin(), noload_decls_end()); 2359 } 2360 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); } 2361 decl_iterator noload_decls_end() const { return decl_iterator(); } 2362 2363 /// specific_decl_iterator - Iterates over a subrange of 2364 /// declarations stored in a DeclContext, providing only those that 2365 /// are of type SpecificDecl (or a class derived from it). This 2366 /// iterator is used, for example, to provide iteration over just 2367 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl). 2368 template<typename SpecificDecl> 2369 class specific_decl_iterator { 2370 /// Current - The current, underlying declaration iterator, which 2371 /// will either be NULL or will point to a declaration of 2372 /// type SpecificDecl. 2373 DeclContext::decl_iterator Current; 2374 2375 /// SkipToNextDecl - Advances the current position up to the next 2376 /// declaration of type SpecificDecl that also meets the criteria 2377 /// required by Acceptable. 2378 void SkipToNextDecl() { 2379 while (*Current && !isa<SpecificDecl>(*Current)) 2380 ++Current; 2381 } 2382 2383 public: 2384 using value_type = SpecificDecl *; 2385 // TODO: Add reference and pointer types (with some appropriate proxy type) 2386 // if we ever have a need for them. 2387 using reference = void; 2388 using pointer = void; 2389 using difference_type = 2390 std::iterator_traits<DeclContext::decl_iterator>::difference_type; 2391 using iterator_category = std::forward_iterator_tag; 2392 2393 specific_decl_iterator() = default; 2394 2395 /// specific_decl_iterator - Construct a new iterator over a 2396 /// subset of the declarations the range [C, 2397 /// end-of-declarations). If A is non-NULL, it is a pointer to a 2398 /// member function of SpecificDecl that should return true for 2399 /// all of the SpecificDecl instances that will be in the subset 2400 /// of iterators. For example, if you want Objective-C instance 2401 /// methods, SpecificDecl will be ObjCMethodDecl and A will be 2402 /// &ObjCMethodDecl::isInstanceMethod. 2403 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) { 2404 SkipToNextDecl(); 2405 } 2406 2407 value_type operator*() const { return cast<SpecificDecl>(*Current); } 2408 2409 // This doesn't meet the iterator requirements, but it's convenient 2410 value_type operator->() const { return **this; } 2411 2412 specific_decl_iterator& operator++() { 2413 ++Current; 2414 SkipToNextDecl(); 2415 return *this; 2416 } 2417 2418 specific_decl_iterator operator++(int) { 2419 specific_decl_iterator tmp(*this); 2420 ++(*this); 2421 return tmp; 2422 } 2423 2424 friend bool operator==(const specific_decl_iterator& x, 2425 const specific_decl_iterator& y) { 2426 return x.Current == y.Current; 2427 } 2428 2429 friend bool operator!=(const specific_decl_iterator& x, 2430 const specific_decl_iterator& y) { 2431 return x.Current != y.Current; 2432 } 2433 }; 2434 2435 /// Iterates over a filtered subrange of declarations stored 2436 /// in a DeclContext. 2437 /// 2438 /// This iterator visits only those declarations that are of type 2439 /// SpecificDecl (or a class derived from it) and that meet some 2440 /// additional run-time criteria. This iterator is used, for 2441 /// example, to provide access to the instance methods within an 2442 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and 2443 /// Acceptable = ObjCMethodDecl::isInstanceMethod). 2444 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const> 2445 class filtered_decl_iterator { 2446 /// Current - The current, underlying declaration iterator, which 2447 /// will either be NULL or will point to a declaration of 2448 /// type SpecificDecl. 2449 DeclContext::decl_iterator Current; 2450 2451 /// SkipToNextDecl - Advances the current position up to the next 2452 /// declaration of type SpecificDecl that also meets the criteria 2453 /// required by Acceptable. 2454 void SkipToNextDecl() { 2455 while (*Current && 2456 (!isa<SpecificDecl>(*Current) || 2457 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)()))) 2458 ++Current; 2459 } 2460 2461 public: 2462 using value_type = SpecificDecl *; 2463 // TODO: Add reference and pointer types (with some appropriate proxy type) 2464 // if we ever have a need for them. 2465 using reference = void; 2466 using pointer = void; 2467 using difference_type = 2468 std::iterator_traits<DeclContext::decl_iterator>::difference_type; 2469 using iterator_category = std::forward_iterator_tag; 2470 2471 filtered_decl_iterator() = default; 2472 2473 /// filtered_decl_iterator - Construct a new iterator over a 2474 /// subset of the declarations the range [C, 2475 /// end-of-declarations). If A is non-NULL, it is a pointer to a 2476 /// member function of SpecificDecl that should return true for 2477 /// all of the SpecificDecl instances that will be in the subset 2478 /// of iterators. For example, if you want Objective-C instance 2479 /// methods, SpecificDecl will be ObjCMethodDecl and A will be 2480 /// &ObjCMethodDecl::isInstanceMethod. 2481 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) { 2482 SkipToNextDecl(); 2483 } 2484 2485 value_type operator*() const { return cast<SpecificDecl>(*Current); } 2486 value_type operator->() const { return cast<SpecificDecl>(*Current); } 2487 2488 filtered_decl_iterator& operator++() { 2489 ++Current; 2490 SkipToNextDecl(); 2491 return *this; 2492 } 2493 2494 filtered_decl_iterator operator++(int) { 2495 filtered_decl_iterator tmp(*this); 2496 ++(*this); 2497 return tmp; 2498 } 2499 2500 friend bool operator==(const filtered_decl_iterator& x, 2501 const filtered_decl_iterator& y) { 2502 return x.Current == y.Current; 2503 } 2504 2505 friend bool operator!=(const filtered_decl_iterator& x, 2506 const filtered_decl_iterator& y) { 2507 return x.Current != y.Current; 2508 } 2509 }; 2510 2511 /// Add the declaration D into this context. 2512 /// 2513 /// This routine should be invoked when the declaration D has first 2514 /// been declared, to place D into the context where it was 2515 /// (lexically) defined. Every declaration must be added to one 2516 /// (and only one!) context, where it can be visited via 2517 /// [decls_begin(), decls_end()). Once a declaration has been added 2518 /// to its lexical context, the corresponding DeclContext owns the 2519 /// declaration. 2520 /// 2521 /// If D is also a NamedDecl, it will be made visible within its 2522 /// semantic context via makeDeclVisibleInContext. 2523 void addDecl(Decl *D); 2524 2525 /// Add the declaration D into this context, but suppress 2526 /// searches for external declarations with the same name. 2527 /// 2528 /// Although analogous in function to addDecl, this removes an 2529 /// important check. This is only useful if the Decl is being 2530 /// added in response to an external search; in all other cases, 2531 /// addDecl() is the right function to use. 2532 /// See the ASTImporter for use cases. 2533 void addDeclInternal(Decl *D); 2534 2535 /// Add the declaration D to this context without modifying 2536 /// any lookup tables. 2537 /// 2538 /// This is useful for some operations in dependent contexts where 2539 /// the semantic context might not be dependent; this basically 2540 /// only happens with friends. 2541 void addHiddenDecl(Decl *D); 2542 2543 /// Removes a declaration from this context. 2544 void removeDecl(Decl *D); 2545 2546 /// Checks whether a declaration is in this context. 2547 bool containsDecl(Decl *D) const; 2548 2549 /// Checks whether a declaration is in this context. 2550 /// This also loads the Decls from the external source before the check. 2551 bool containsDeclAndLoad(Decl *D) const; 2552 2553 using lookup_result = DeclContextLookupResult; 2554 using lookup_iterator = lookup_result::iterator; 2555 2556 /// lookup - Find the declarations (if any) with the given Name in 2557 /// this context. Returns a range of iterators that contains all of 2558 /// the declarations with this name, with object, function, member, 2559 /// and enumerator names preceding any tag name. Note that this 2560 /// routine will not look into parent contexts. 2561 lookup_result lookup(DeclarationName Name) const; 2562 2563 /// Find the declarations with the given name that are visible 2564 /// within this context; don't attempt to retrieve anything from an 2565 /// external source. 2566 lookup_result noload_lookup(DeclarationName Name); 2567 2568 /// A simplistic name lookup mechanism that performs name lookup 2569 /// into this declaration context without consulting the external source. 2570 /// 2571 /// This function should almost never be used, because it subverts the 2572 /// usual relationship between a DeclContext and the external source. 2573 /// See the ASTImporter for the (few, but important) use cases. 2574 /// 2575 /// FIXME: This is very inefficient; replace uses of it with uses of 2576 /// noload_lookup. 2577 void localUncachedLookup(DeclarationName Name, 2578 SmallVectorImpl<NamedDecl *> &Results); 2579 2580 /// Makes a declaration visible within this context. 2581 /// 2582 /// This routine makes the declaration D visible to name lookup 2583 /// within this context and, if this is a transparent context, 2584 /// within its parent contexts up to the first enclosing 2585 /// non-transparent context. Making a declaration visible within a 2586 /// context does not transfer ownership of a declaration, and a 2587 /// declaration can be visible in many contexts that aren't its 2588 /// lexical context. 2589 /// 2590 /// If D is a redeclaration of an existing declaration that is 2591 /// visible from this context, as determined by 2592 /// NamedDecl::declarationReplaces, the previous declaration will be 2593 /// replaced with D. 2594 void makeDeclVisibleInContext(NamedDecl *D); 2595 2596 /// all_lookups_iterator - An iterator that provides a view over the results 2597 /// of looking up every possible name. 2598 class all_lookups_iterator; 2599 2600 using lookups_range = llvm::iterator_range<all_lookups_iterator>; 2601 2602 lookups_range lookups() const; 2603 // Like lookups(), but avoids loading external declarations. 2604 // If PreserveInternalState, avoids building lookup data structures too. 2605 lookups_range noload_lookups(bool PreserveInternalState) const; 2606 2607 /// Iterators over all possible lookups within this context. 2608 all_lookups_iterator lookups_begin() const; 2609 all_lookups_iterator lookups_end() const; 2610 2611 /// Iterators over all possible lookups within this context that are 2612 /// currently loaded; don't attempt to retrieve anything from an external 2613 /// source. 2614 all_lookups_iterator noload_lookups_begin() const; 2615 all_lookups_iterator noload_lookups_end() const; 2616 2617 struct udir_iterator; 2618 2619 using udir_iterator_base = 2620 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator, 2621 typename lookup_iterator::iterator_category, 2622 UsingDirectiveDecl *>; 2623 2624 struct udir_iterator : udir_iterator_base { 2625 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {} 2626 2627 UsingDirectiveDecl *operator*() const; 2628 }; 2629 2630 using udir_range = llvm::iterator_range<udir_iterator>; 2631 2632 udir_range using_directives() const; 2633 2634 // These are all defined in DependentDiagnostic.h. 2635 class ddiag_iterator; 2636 2637 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>; 2638 2639 inline ddiag_range ddiags() const; 2640 2641 // Low-level accessors 2642 2643 /// Mark that there are external lexical declarations that we need 2644 /// to include in our lookup table (and that are not available as external 2645 /// visible lookups). These extra lookup results will be found by walking 2646 /// the lexical declarations of this context. This should be used only if 2647 /// setHasExternalLexicalStorage() has been called on any decl context for 2648 /// which this is the primary context. 2649 void setMustBuildLookupTable() { 2650 assert(this == getPrimaryContext() && 2651 "should only be called on primary context"); 2652 DeclContextBits.HasLazyExternalLexicalLookups = true; 2653 } 2654 2655 /// Retrieve the internal representation of the lookup structure. 2656 /// This may omit some names if we are lazily building the structure. 2657 StoredDeclsMap *getLookupPtr() const { return LookupPtr; } 2658 2659 /// Ensure the lookup structure is fully-built and return it. 2660 StoredDeclsMap *buildLookup(); 2661 2662 /// Whether this DeclContext has external storage containing 2663 /// additional declarations that are lexically in this context. 2664 bool hasExternalLexicalStorage() const { 2665 return DeclContextBits.ExternalLexicalStorage; 2666 } 2667 2668 /// State whether this DeclContext has external storage for 2669 /// declarations lexically in this context. 2670 void setHasExternalLexicalStorage(bool ES = true) const { 2671 DeclContextBits.ExternalLexicalStorage = ES; 2672 } 2673 2674 /// Whether this DeclContext has external storage containing 2675 /// additional declarations that are visible in this context. 2676 bool hasExternalVisibleStorage() const { 2677 return DeclContextBits.ExternalVisibleStorage; 2678 } 2679 2680 /// State whether this DeclContext has external storage for 2681 /// declarations visible in this context. 2682 void setHasExternalVisibleStorage(bool ES = true) const { 2683 DeclContextBits.ExternalVisibleStorage = ES; 2684 if (ES && LookupPtr) 2685 DeclContextBits.NeedToReconcileExternalVisibleStorage = true; 2686 } 2687 2688 /// Determine whether the given declaration is stored in the list of 2689 /// declarations lexically within this context. 2690 bool isDeclInLexicalTraversal(const Decl *D) const { 2691 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || 2692 D == LastDecl); 2693 } 2694 2695 void setUseQualifiedLookup(bool use = true) const { 2696 DeclContextBits.UseQualifiedLookup = use; 2697 } 2698 2699 bool shouldUseQualifiedLookup() const { 2700 return DeclContextBits.UseQualifiedLookup; 2701 } 2702 2703 static bool classof(const Decl *D); 2704 static bool classof(const DeclContext *D) { return true; } 2705 2706 void dumpAsDecl() const; 2707 void dumpAsDecl(const ASTContext *Ctx) const; 2708 void dumpDeclContext() const; 2709 void dumpLookups() const; 2710 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false, 2711 bool Deserialize = false) const; 2712 2713 private: 2714 /// Whether this declaration context has had externally visible 2715 /// storage added since the last lookup. In this case, \c LookupPtr's 2716 /// invariant may not hold and needs to be fixed before we perform 2717 /// another lookup. 2718 bool hasNeedToReconcileExternalVisibleStorage() const { 2719 return DeclContextBits.NeedToReconcileExternalVisibleStorage; 2720 } 2721 2722 /// State that this declaration context has had externally visible 2723 /// storage added since the last lookup. In this case, \c LookupPtr's 2724 /// invariant may not hold and needs to be fixed before we perform 2725 /// another lookup. 2726 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const { 2727 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need; 2728 } 2729 2730 /// If \c true, this context may have local lexical declarations 2731 /// that are missing from the lookup table. 2732 bool hasLazyLocalLexicalLookups() const { 2733 return DeclContextBits.HasLazyLocalLexicalLookups; 2734 } 2735 2736 /// If \c true, this context may have local lexical declarations 2737 /// that are missing from the lookup table. 2738 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const { 2739 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL; 2740 } 2741 2742 /// If \c true, the external source may have lexical declarations 2743 /// that are missing from the lookup table. 2744 bool hasLazyExternalLexicalLookups() const { 2745 return DeclContextBits.HasLazyExternalLexicalLookups; 2746 } 2747 2748 /// If \c true, the external source may have lexical declarations 2749 /// that are missing from the lookup table. 2750 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const { 2751 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL; 2752 } 2753 2754 void reconcileExternalVisibleStorage() const; 2755 bool LoadLexicalDeclsFromExternalStorage() const; 2756 2757 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; 2758 2759 void loadLazyLocalLexicalLookups(); 2760 void buildLookupImpl(DeclContext *DCtx, bool Internal); 2761 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, 2762 bool Rediscoverable); 2763 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal); 2764 }; 2765 2766 inline bool Decl::isTemplateParameter() const { 2767 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm || 2768 getKind() == TemplateTemplateParm; 2769 } 2770 2771 // Specialization selected when ToTy is not a known subclass of DeclContext. 2772 template <class ToTy, 2773 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value> 2774 struct cast_convert_decl_context { 2775 static const ToTy *doit(const DeclContext *Val) { 2776 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val)); 2777 } 2778 2779 static ToTy *doit(DeclContext *Val) { 2780 return static_cast<ToTy*>(Decl::castFromDeclContext(Val)); 2781 } 2782 }; 2783 2784 // Specialization selected when ToTy is a known subclass of DeclContext. 2785 template <class ToTy> 2786 struct cast_convert_decl_context<ToTy, true> { 2787 static const ToTy *doit(const DeclContext *Val) { 2788 return static_cast<const ToTy*>(Val); 2789 } 2790 2791 static ToTy *doit(DeclContext *Val) { 2792 return static_cast<ToTy*>(Val); 2793 } 2794 }; 2795 2796 } // namespace clang 2797 2798 namespace llvm { 2799 2800 /// isa<T>(DeclContext*) 2801 template <typename To> 2802 struct isa_impl<To, ::clang::DeclContext> { 2803 static bool doit(const ::clang::DeclContext &Val) { 2804 return To::classofKind(Val.getDeclKind()); 2805 } 2806 }; 2807 2808 /// cast<T>(DeclContext*) 2809 template<class ToTy> 2810 struct cast_convert_val<ToTy, 2811 const ::clang::DeclContext,const ::clang::DeclContext> { 2812 static const ToTy &doit(const ::clang::DeclContext &Val) { 2813 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); 2814 } 2815 }; 2816 2817 template<class ToTy> 2818 struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> { 2819 static ToTy &doit(::clang::DeclContext &Val) { 2820 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); 2821 } 2822 }; 2823 2824 template<class ToTy> 2825 struct cast_convert_val<ToTy, 2826 const ::clang::DeclContext*, const ::clang::DeclContext*> { 2827 static const ToTy *doit(const ::clang::DeclContext *Val) { 2828 return ::clang::cast_convert_decl_context<ToTy>::doit(Val); 2829 } 2830 }; 2831 2832 template<class ToTy> 2833 struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> { 2834 static ToTy *doit(::clang::DeclContext *Val) { 2835 return ::clang::cast_convert_decl_context<ToTy>::doit(Val); 2836 } 2837 }; 2838 2839 /// Implement cast_convert_val for Decl -> DeclContext conversions. 2840 template<class FromTy> 2841 struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> { 2842 static ::clang::DeclContext &doit(const FromTy &Val) { 2843 return *FromTy::castToDeclContext(&Val); 2844 } 2845 }; 2846 2847 template<class FromTy> 2848 struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> { 2849 static ::clang::DeclContext *doit(const FromTy *Val) { 2850 return FromTy::castToDeclContext(Val); 2851 } 2852 }; 2853 2854 template<class FromTy> 2855 struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> { 2856 static const ::clang::DeclContext &doit(const FromTy &Val) { 2857 return *FromTy::castToDeclContext(&Val); 2858 } 2859 }; 2860 2861 template<class FromTy> 2862 struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> { 2863 static const ::clang::DeclContext *doit(const FromTy *Val) { 2864 return FromTy::castToDeclContext(Val); 2865 } 2866 }; 2867 2868 } // namespace llvm 2869 2870 #endif // LLVM_CLANG_AST_DECLBASE_H 2871