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