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