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