1 //===--- IdentifierTable.h - Hash table for identifier lookup ---*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file 11 /// \brief Defines the clang::IdentifierInfo, clang::IdentifierTable, and 12 /// clang::Selector interfaces. 13 /// 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H 17 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H 18 19 #include "clang/Basic/LLVM.h" 20 #include "clang/Basic/TokenKinds.h" 21 #include "llvm/ADT/StringMap.h" 22 #include "llvm/ADT/StringRef.h" 23 #include <cassert> 24 #include <string> 25 26 namespace llvm { 27 template <typename T> struct DenseMapInfo; 28 } 29 30 namespace clang { 31 class LangOptions; 32 class IdentifierInfo; 33 class IdentifierTable; 34 class SourceLocation; 35 class MultiKeywordSelector; // private class used by Selector 36 class DeclarationName; // AST class that stores declaration names 37 38 /// \brief A simple pair of identifier info and location. 39 typedef std::pair<IdentifierInfo*, SourceLocation> IdentifierLocPair; 40 41 42 /// One of these records is kept for each identifier that 43 /// is lexed. This contains information about whether the token was \#define'd, 44 /// is a language keyword, or if it is a front-end token of some sort (e.g. a 45 /// variable or function name). The preprocessor keeps this information in a 46 /// set, and all tok::identifier tokens have a pointer to one of these. 47 class IdentifierInfo { 48 unsigned TokenID : 9; // Front-end token ID or tok::identifier. 49 // Objective-C keyword ('protocol' in '@protocol') or builtin (__builtin_inf). 50 // First NUM_OBJC_KEYWORDS values are for Objective-C, the remaining values 51 // are for builtins. 52 unsigned ObjCOrBuiltinID :11; 53 bool HasMacro : 1; // True if there is a #define for this. 54 bool HadMacro : 1; // True if there was a #define for this. 55 bool IsExtension : 1; // True if identifier is a lang extension. 56 bool IsCXX11CompatKeyword : 1; // True if identifier is a keyword in C++11. 57 bool IsPoisoned : 1; // True if identifier is poisoned. 58 bool IsCPPOperatorKeyword : 1; // True if ident is a C++ operator keyword. 59 bool NeedsHandleIdentifier : 1; // See "RecomputeNeedsHandleIdentifier". 60 bool IsFromAST : 1; // True if identifier was loaded (at least 61 // partially) from an AST file. 62 bool ChangedAfterLoad : 1; // True if identifier has changed from the 63 // definition loaded from an AST file. 64 bool RevertedTokenID : 1; // True if RevertTokenIDToIdentifier was 65 // called. 66 bool OutOfDate : 1; // True if there may be additional 67 // information about this identifier 68 // stored externally. 69 bool IsModulesImport : 1; // True if this is the 'import' contextual 70 // keyword. 71 // 32-bit word is filled. 72 73 void *FETokenInfo; // Managed by the language front-end. 74 llvm::StringMapEntry<IdentifierInfo*> *Entry; 75 76 IdentifierInfo(const IdentifierInfo&) LLVM_DELETED_FUNCTION; 77 void operator=(const IdentifierInfo&) LLVM_DELETED_FUNCTION; 78 79 friend class IdentifierTable; 80 81 public: 82 IdentifierInfo(); 83 84 85 /// \brief Return true if this is the identifier for the specified string. 86 /// 87 /// This is intended to be used for string literals only: II->isStr("foo"). 88 template <std::size_t StrLen> isStr(const char (& Str)[StrLen])89 bool isStr(const char (&Str)[StrLen]) const { 90 return getLength() == StrLen-1 && !memcmp(getNameStart(), Str, StrLen-1); 91 } 92 93 /// \brief Return the beginning of the actual null-terminated string for this 94 /// identifier. 95 /// getNameStart()96 const char *getNameStart() const { 97 if (Entry) return Entry->getKeyData(); 98 // FIXME: This is gross. It would be best not to embed specific details 99 // of the PTH file format here. 100 // The 'this' pointer really points to a 101 // std::pair<IdentifierInfo, const char*>, where internal pointer 102 // points to the external string data. 103 typedef std::pair<IdentifierInfo, const char*> actualtype; 104 return ((const actualtype*) this)->second; 105 } 106 107 /// \brief Efficiently return the length of this identifier info. 108 /// getLength()109 unsigned getLength() const { 110 if (Entry) return Entry->getKeyLength(); 111 // FIXME: This is gross. It would be best not to embed specific details 112 // of the PTH file format here. 113 // The 'this' pointer really points to a 114 // std::pair<IdentifierInfo, const char*>, where internal pointer 115 // points to the external string data. 116 typedef std::pair<IdentifierInfo, const char*> actualtype; 117 const char* p = ((const actualtype*) this)->second - 2; 118 return (((unsigned) p[0]) | (((unsigned) p[1]) << 8)) - 1; 119 } 120 121 /// \brief Return the actual identifier string. getName()122 StringRef getName() const { 123 return StringRef(getNameStart(), getLength()); 124 } 125 126 /// \brief Return true if this identifier is \#defined to some other value. hasMacroDefinition()127 bool hasMacroDefinition() const { 128 return HasMacro; 129 } setHasMacroDefinition(bool Val)130 void setHasMacroDefinition(bool Val) { 131 if (HasMacro == Val) return; 132 133 HasMacro = Val; 134 if (Val) { 135 NeedsHandleIdentifier = 1; 136 HadMacro = true; 137 } else { 138 RecomputeNeedsHandleIdentifier(); 139 } 140 } 141 /// \brief Returns true if this identifier was \#defined to some value at any 142 /// moment. In this case there should be an entry for the identifier in the 143 /// macro history table in Preprocessor. hadMacroDefinition()144 bool hadMacroDefinition() const { 145 return HadMacro; 146 } 147 148 /// If this is a source-language token (e.g. 'for'), this API 149 /// can be used to cause the lexer to map identifiers to source-language 150 /// tokens. getTokenID()151 tok::TokenKind getTokenID() const { return (tok::TokenKind)TokenID; } 152 153 /// \brief True if RevertTokenIDToIdentifier() was called. hasRevertedTokenIDToIdentifier()154 bool hasRevertedTokenIDToIdentifier() const { return RevertedTokenID; } 155 156 /// \brief Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2 157 /// compatibility. 158 /// 159 /// TokenID is normally read-only but there are 2 instances where we revert it 160 /// to tok::identifier for libstdc++ 4.2. Keep track of when this happens 161 /// using this method so we can inform serialization about it. RevertTokenIDToIdentifier()162 void RevertTokenIDToIdentifier() { 163 assert(TokenID != tok::identifier && "Already at tok::identifier"); 164 TokenID = tok::identifier; 165 RevertedTokenID = true; 166 } 167 168 /// \brief Return the preprocessor keyword ID for this identifier. 169 /// 170 /// For example, "define" will return tok::pp_define. 171 tok::PPKeywordKind getPPKeywordID() const; 172 173 /// \brief Return the Objective-C keyword ID for the this identifier. 174 /// 175 /// For example, 'class' will return tok::objc_class if ObjC is enabled. getObjCKeywordID()176 tok::ObjCKeywordKind getObjCKeywordID() const { 177 if (ObjCOrBuiltinID < tok::NUM_OBJC_KEYWORDS) 178 return tok::ObjCKeywordKind(ObjCOrBuiltinID); 179 else 180 return tok::objc_not_keyword; 181 } setObjCKeywordID(tok::ObjCKeywordKind ID)182 void setObjCKeywordID(tok::ObjCKeywordKind ID) { ObjCOrBuiltinID = ID; } 183 184 /// \brief Return a value indicating whether this is a builtin function. 185 /// 186 /// 0 is not-built-in. 1 is builtin-for-some-nonprimary-target. 187 /// 2+ are specific builtin functions. getBuiltinID()188 unsigned getBuiltinID() const { 189 if (ObjCOrBuiltinID >= tok::NUM_OBJC_KEYWORDS) 190 return ObjCOrBuiltinID - tok::NUM_OBJC_KEYWORDS; 191 else 192 return 0; 193 } setBuiltinID(unsigned ID)194 void setBuiltinID(unsigned ID) { 195 ObjCOrBuiltinID = ID + tok::NUM_OBJC_KEYWORDS; 196 assert(ObjCOrBuiltinID - unsigned(tok::NUM_OBJC_KEYWORDS) == ID 197 && "ID too large for field!"); 198 } 199 getObjCOrBuiltinID()200 unsigned getObjCOrBuiltinID() const { return ObjCOrBuiltinID; } setObjCOrBuiltinID(unsigned ID)201 void setObjCOrBuiltinID(unsigned ID) { ObjCOrBuiltinID = ID; } 202 203 /// get/setExtension - Initialize information about whether or not this 204 /// language token is an extension. This controls extension warnings, and is 205 /// only valid if a custom token ID is set. isExtensionToken()206 bool isExtensionToken() const { return IsExtension; } setIsExtensionToken(bool Val)207 void setIsExtensionToken(bool Val) { 208 IsExtension = Val; 209 if (Val) 210 NeedsHandleIdentifier = 1; 211 else 212 RecomputeNeedsHandleIdentifier(); 213 } 214 215 /// is/setIsCXX11CompatKeyword - Initialize information about whether or not 216 /// this language token is a keyword in C++11. This controls compatibility 217 /// warnings, and is only true when not parsing C++11. Once a compatibility 218 /// problem has been diagnosed with this keyword, the flag will be cleared. isCXX11CompatKeyword()219 bool isCXX11CompatKeyword() const { return IsCXX11CompatKeyword; } setIsCXX11CompatKeyword(bool Val)220 void setIsCXX11CompatKeyword(bool Val) { 221 IsCXX11CompatKeyword = Val; 222 if (Val) 223 NeedsHandleIdentifier = 1; 224 else 225 RecomputeNeedsHandleIdentifier(); 226 } 227 228 /// setIsPoisoned - Mark this identifier as poisoned. After poisoning, the 229 /// Preprocessor will emit an error every time this token is used. 230 void setIsPoisoned(bool Value = true) { 231 IsPoisoned = Value; 232 if (Value) 233 NeedsHandleIdentifier = 1; 234 else 235 RecomputeNeedsHandleIdentifier(); 236 } 237 238 /// \brief Return true if this token has been poisoned. isPoisoned()239 bool isPoisoned() const { return IsPoisoned; } 240 241 /// isCPlusPlusOperatorKeyword/setIsCPlusPlusOperatorKeyword controls whether 242 /// this identifier is a C++ alternate representation of an operator. 243 void setIsCPlusPlusOperatorKeyword(bool Val = true) { 244 IsCPPOperatorKeyword = Val; 245 if (Val) 246 NeedsHandleIdentifier = 1; 247 else 248 RecomputeNeedsHandleIdentifier(); 249 } isCPlusPlusOperatorKeyword()250 bool isCPlusPlusOperatorKeyword() const { return IsCPPOperatorKeyword; } 251 252 /// \brief Return true if this token is a keyword in the specified language. 253 bool isKeyword(const LangOptions &LangOpts); 254 255 /// getFETokenInfo/setFETokenInfo - The language front-end is allowed to 256 /// associate arbitrary metadata with this token. 257 template<typename T> getFETokenInfo()258 T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); } setFETokenInfo(void * T)259 void setFETokenInfo(void *T) { FETokenInfo = T; } 260 261 /// \brief Return true if the Preprocessor::HandleIdentifier must be called 262 /// on a token of this identifier. 263 /// 264 /// If this returns false, we know that HandleIdentifier will not affect 265 /// the token. isHandleIdentifierCase()266 bool isHandleIdentifierCase() const { return NeedsHandleIdentifier; } 267 268 /// \brief Return true if the identifier in its current state was loaded 269 /// from an AST file. isFromAST()270 bool isFromAST() const { return IsFromAST; } 271 setIsFromAST()272 void setIsFromAST() { IsFromAST = true; } 273 274 /// \brief Determine whether this identifier has changed since it was loaded 275 /// from an AST file. hasChangedSinceDeserialization()276 bool hasChangedSinceDeserialization() const { 277 return ChangedAfterLoad; 278 } 279 280 /// \brief Note that this identifier has changed since it was loaded from 281 /// an AST file. setChangedSinceDeserialization()282 void setChangedSinceDeserialization() { 283 ChangedAfterLoad = true; 284 } 285 286 /// \brief Determine whether the information for this identifier is out of 287 /// date with respect to the external source. isOutOfDate()288 bool isOutOfDate() const { return OutOfDate; } 289 290 /// \brief Set whether the information for this identifier is out of 291 /// date with respect to the external source. setOutOfDate(bool OOD)292 void setOutOfDate(bool OOD) { 293 OutOfDate = OOD; 294 if (OOD) 295 NeedsHandleIdentifier = true; 296 else 297 RecomputeNeedsHandleIdentifier(); 298 } 299 300 /// \brief Determine whether this is the contextual keyword \c import. isModulesImport()301 bool isModulesImport() const { return IsModulesImport; } 302 303 /// \brief Set whether this identifier is the contextual keyword \c import. setModulesImport(bool I)304 void setModulesImport(bool I) { 305 IsModulesImport = I; 306 if (I) 307 NeedsHandleIdentifier = true; 308 else 309 RecomputeNeedsHandleIdentifier(); 310 } 311 312 private: 313 /// The Preprocessor::HandleIdentifier does several special (but rare) 314 /// things to identifiers of various sorts. For example, it changes the 315 /// \c for keyword token from tok::identifier to tok::for. 316 /// 317 /// This method is very tied to the definition of HandleIdentifier. Any 318 /// change to it should be reflected here. RecomputeNeedsHandleIdentifier()319 void RecomputeNeedsHandleIdentifier() { 320 NeedsHandleIdentifier = 321 (isPoisoned() | hasMacroDefinition() | isCPlusPlusOperatorKeyword() | 322 isExtensionToken() | isCXX11CompatKeyword() || isOutOfDate() || 323 isModulesImport()); 324 } 325 }; 326 327 /// \brief An RAII object for [un]poisoning an identifier within a scope. 328 /// 329 /// \p II is allowed to be null, in which case objects of this type have 330 /// no effect. 331 class PoisonIdentifierRAIIObject { 332 IdentifierInfo *const II; 333 const bool OldValue; 334 public: PoisonIdentifierRAIIObject(IdentifierInfo * II,bool NewValue)335 PoisonIdentifierRAIIObject(IdentifierInfo *II, bool NewValue) 336 : II(II), OldValue(II ? II->isPoisoned() : false) { 337 if(II) 338 II->setIsPoisoned(NewValue); 339 } 340 ~PoisonIdentifierRAIIObject()341 ~PoisonIdentifierRAIIObject() { 342 if(II) 343 II->setIsPoisoned(OldValue); 344 } 345 }; 346 347 /// \brief An iterator that walks over all of the known identifiers 348 /// in the lookup table. 349 /// 350 /// Since this iterator uses an abstract interface via virtual 351 /// functions, it uses an object-oriented interface rather than the 352 /// more standard C++ STL iterator interface. In this OO-style 353 /// iteration, the single function \c Next() provides dereference, 354 /// advance, and end-of-sequence checking in a single 355 /// operation. Subclasses of this iterator type will provide the 356 /// actual functionality. 357 class IdentifierIterator { 358 private: 359 IdentifierIterator(const IdentifierIterator &) LLVM_DELETED_FUNCTION; 360 void operator=(const IdentifierIterator &) LLVM_DELETED_FUNCTION; 361 362 protected: IdentifierIterator()363 IdentifierIterator() { } 364 365 public: 366 virtual ~IdentifierIterator(); 367 368 /// \brief Retrieve the next string in the identifier table and 369 /// advances the iterator for the following string. 370 /// 371 /// \returns The next string in the identifier table. If there is 372 /// no such string, returns an empty \c StringRef. 373 virtual StringRef Next() = 0; 374 }; 375 376 /// \brief Provides lookups to, and iteration over, IdentiferInfo objects. 377 class IdentifierInfoLookup { 378 public: 379 virtual ~IdentifierInfoLookup(); 380 381 /// \brief Return the IdentifierInfo for the specified named identifier. 382 /// 383 /// Unlike the version in IdentifierTable, this returns a pointer instead 384 /// of a reference. If the pointer is null then the IdentifierInfo cannot 385 /// be found. 386 virtual IdentifierInfo* get(StringRef Name) = 0; 387 388 /// \brief Retrieve an iterator into the set of all identifiers 389 /// known to this identifier lookup source. 390 /// 391 /// This routine provides access to all of the identifiers known to 392 /// the identifier lookup, allowing access to the contents of the 393 /// identifiers without introducing the overhead of constructing 394 /// IdentifierInfo objects for each. 395 /// 396 /// \returns A new iterator into the set of known identifiers. The 397 /// caller is responsible for deleting this iterator. 398 virtual IdentifierIterator *getIdentifiers(); 399 }; 400 401 /// \brief An abstract class used to resolve numerical identifier 402 /// references (meaningful only to some external source) into 403 /// IdentifierInfo pointers. 404 class ExternalIdentifierLookup { 405 public: 406 virtual ~ExternalIdentifierLookup(); 407 408 /// \brief Return the identifier associated with the given ID number. 409 /// 410 /// The ID 0 is associated with the NULL identifier. 411 virtual IdentifierInfo *GetIdentifier(unsigned ID) = 0; 412 }; 413 414 /// \brief Implements an efficient mapping from strings to IdentifierInfo nodes. 415 /// 416 /// This has no other purpose, but this is an extremely performance-critical 417 /// piece of the code, as each occurrence of every identifier goes through 418 /// here when lexed. 419 class IdentifierTable { 420 // Shark shows that using MallocAllocator is *much* slower than using this 421 // BumpPtrAllocator! 422 typedef llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator> HashTableTy; 423 HashTableTy HashTable; 424 425 IdentifierInfoLookup* ExternalLookup; 426 427 public: 428 /// \brief Create the identifier table, populating it with info about the 429 /// language keywords for the language specified by \p LangOpts. 430 IdentifierTable(const LangOptions &LangOpts, 431 IdentifierInfoLookup* externalLookup = nullptr); 432 433 /// \brief Set the external identifier lookup mechanism. setExternalIdentifierLookup(IdentifierInfoLookup * IILookup)434 void setExternalIdentifierLookup(IdentifierInfoLookup *IILookup) { 435 ExternalLookup = IILookup; 436 } 437 438 /// \brief Retrieve the external identifier lookup object, if any. getExternalIdentifierLookup()439 IdentifierInfoLookup *getExternalIdentifierLookup() const { 440 return ExternalLookup; 441 } 442 getAllocator()443 llvm::BumpPtrAllocator& getAllocator() { 444 return HashTable.getAllocator(); 445 } 446 447 /// \brief Return the identifier token info for the specified named 448 /// identifier. get(StringRef Name)449 IdentifierInfo &get(StringRef Name) { 450 auto &Entry = *HashTable.insert(std::make_pair(Name, nullptr)).first; 451 452 IdentifierInfo *&II = Entry.second; 453 if (II) return *II; 454 455 // No entry; if we have an external lookup, look there first. 456 if (ExternalLookup) { 457 II = ExternalLookup->get(Name); 458 if (II) 459 return *II; 460 } 461 462 // Lookups failed, make a new IdentifierInfo. 463 void *Mem = getAllocator().Allocate<IdentifierInfo>(); 464 II = new (Mem) IdentifierInfo(); 465 466 // Make sure getName() knows how to find the IdentifierInfo 467 // contents. 468 II->Entry = &Entry; 469 470 return *II; 471 } 472 get(StringRef Name,tok::TokenKind TokenCode)473 IdentifierInfo &get(StringRef Name, tok::TokenKind TokenCode) { 474 IdentifierInfo &II = get(Name); 475 II.TokenID = TokenCode; 476 assert(II.TokenID == (unsigned) TokenCode && "TokenCode too large"); 477 return II; 478 } 479 480 /// \brief Gets an IdentifierInfo for the given name without consulting 481 /// external sources. 482 /// 483 /// This is a version of get() meant for external sources that want to 484 /// introduce or modify an identifier. If they called get(), they would 485 /// likely end up in a recursion. getOwn(StringRef Name)486 IdentifierInfo &getOwn(StringRef Name) { 487 auto &Entry = *HashTable.insert(std::make_pair(Name, nullptr)).first; 488 489 IdentifierInfo *&II = Entry.second; 490 if (II) 491 return *II; 492 493 // Lookups failed, make a new IdentifierInfo. 494 void *Mem = getAllocator().Allocate<IdentifierInfo>(); 495 II = new (Mem) IdentifierInfo(); 496 497 // Make sure getName() knows how to find the IdentifierInfo 498 // contents. 499 II->Entry = &Entry; 500 501 // If this is the 'import' contextual keyword, mark it as such. 502 if (Name.equals("import")) 503 II->setModulesImport(true); 504 505 return *II; 506 } 507 508 typedef HashTableTy::const_iterator iterator; 509 typedef HashTableTy::const_iterator const_iterator; 510 begin()511 iterator begin() const { return HashTable.begin(); } end()512 iterator end() const { return HashTable.end(); } size()513 unsigned size() const { return HashTable.size(); } 514 515 /// \brief Print some statistics to stderr that indicate how well the 516 /// hashing is doing. 517 void PrintStats() const; 518 519 void AddKeywords(const LangOptions &LangOpts); 520 }; 521 522 /// \brief A family of Objective-C methods. 523 /// 524 /// These families have no inherent meaning in the language, but are 525 /// nonetheless central enough in the existing implementations to 526 /// merit direct AST support. While, in theory, arbitrary methods can 527 /// be considered to form families, we focus here on the methods 528 /// involving allocation and retain-count management, as these are the 529 /// most "core" and the most likely to be useful to diverse clients 530 /// without extra information. 531 /// 532 /// Both selectors and actual method declarations may be classified 533 /// into families. Method families may impose additional restrictions 534 /// beyond their selector name; for example, a method called '_init' 535 /// that returns void is not considered to be in the 'init' family 536 /// (but would be if it returned 'id'). It is also possible to 537 /// explicitly change or remove a method's family. Therefore the 538 /// method's family should be considered the single source of truth. 539 enum ObjCMethodFamily { 540 /// \brief No particular method family. 541 OMF_None, 542 543 // Selectors in these families may have arbitrary arity, may be 544 // written with arbitrary leading underscores, and may have 545 // additional CamelCase "words" in their first selector chunk 546 // following the family name. 547 OMF_alloc, 548 OMF_copy, 549 OMF_init, 550 OMF_mutableCopy, 551 OMF_new, 552 553 // These families are singletons consisting only of the nullary 554 // selector with the given name. 555 OMF_autorelease, 556 OMF_dealloc, 557 OMF_finalize, 558 OMF_release, 559 OMF_retain, 560 OMF_retainCount, 561 OMF_self, 562 OMF_initialize, 563 564 // performSelector families 565 OMF_performSelector 566 }; 567 568 /// Enough bits to store any enumerator in ObjCMethodFamily or 569 /// InvalidObjCMethodFamily. 570 enum { ObjCMethodFamilyBitWidth = 4 }; 571 572 /// \brief An invalid value of ObjCMethodFamily. 573 enum { InvalidObjCMethodFamily = (1 << ObjCMethodFamilyBitWidth) - 1 }; 574 575 /// \brief A family of Objective-C methods. 576 /// 577 /// These are family of methods whose result type is initially 'id', but 578 /// but are candidate for the result type to be changed to 'instancetype'. 579 enum ObjCInstanceTypeFamily { 580 OIT_None, 581 OIT_Array, 582 OIT_Dictionary, 583 OIT_Singleton, 584 OIT_Init, 585 OIT_ReturnsSelf 586 }; 587 588 enum ObjCStringFormatFamily { 589 SFF_None, 590 SFF_NSString, 591 SFF_CFString 592 }; 593 594 /// \brief Smart pointer class that efficiently represents Objective-C method 595 /// names. 596 /// 597 /// This class will either point to an IdentifierInfo or a 598 /// MultiKeywordSelector (which is private). This enables us to optimize 599 /// selectors that take no arguments and selectors that take 1 argument, which 600 /// accounts for 78% of all selectors in Cocoa.h. 601 class Selector { 602 friend class Diagnostic; 603 604 enum IdentifierInfoFlag { 605 // Empty selector = 0. 606 ZeroArg = 0x1, 607 OneArg = 0x2, 608 MultiArg = 0x3, 609 ArgFlags = ZeroArg|OneArg 610 }; 611 uintptr_t InfoPtr; // a pointer to the MultiKeywordSelector or IdentifierInfo. 612 Selector(IdentifierInfo * II,unsigned nArgs)613 Selector(IdentifierInfo *II, unsigned nArgs) { 614 InfoPtr = reinterpret_cast<uintptr_t>(II); 615 assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo"); 616 assert(nArgs < 2 && "nArgs not equal to 0/1"); 617 InfoPtr |= nArgs+1; 618 } Selector(MultiKeywordSelector * SI)619 Selector(MultiKeywordSelector *SI) { 620 InfoPtr = reinterpret_cast<uintptr_t>(SI); 621 assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo"); 622 InfoPtr |= MultiArg; 623 } 624 getAsIdentifierInfo()625 IdentifierInfo *getAsIdentifierInfo() const { 626 if (getIdentifierInfoFlag() < MultiArg) 627 return reinterpret_cast<IdentifierInfo *>(InfoPtr & ~ArgFlags); 628 return nullptr; 629 } getMultiKeywordSelector()630 MultiKeywordSelector *getMultiKeywordSelector() const { 631 return reinterpret_cast<MultiKeywordSelector *>(InfoPtr & ~ArgFlags); 632 } 633 getIdentifierInfoFlag()634 unsigned getIdentifierInfoFlag() const { 635 return InfoPtr & ArgFlags; 636 } 637 638 static ObjCMethodFamily getMethodFamilyImpl(Selector sel); 639 640 static ObjCStringFormatFamily getStringFormatFamilyImpl(Selector sel); 641 642 public: 643 friend class SelectorTable; // only the SelectorTable can create these 644 friend class DeclarationName; // and the AST's DeclarationName. 645 646 /// The default ctor should only be used when creating data structures that 647 /// will contain selectors. Selector()648 Selector() : InfoPtr(0) {} Selector(uintptr_t V)649 Selector(uintptr_t V) : InfoPtr(V) {} 650 651 /// operator==/!= - Indicate whether the specified selectors are identical. 652 bool operator==(Selector RHS) const { 653 return InfoPtr == RHS.InfoPtr; 654 } 655 bool operator!=(Selector RHS) const { 656 return InfoPtr != RHS.InfoPtr; 657 } getAsOpaquePtr()658 void *getAsOpaquePtr() const { 659 return reinterpret_cast<void*>(InfoPtr); 660 } 661 662 /// \brief Determine whether this is the empty selector. isNull()663 bool isNull() const { return InfoPtr == 0; } 664 665 // Predicates to identify the selector type. isKeywordSelector()666 bool isKeywordSelector() const { 667 return getIdentifierInfoFlag() != ZeroArg; 668 } isUnarySelector()669 bool isUnarySelector() const { 670 return getIdentifierInfoFlag() == ZeroArg; 671 } 672 unsigned getNumArgs() const; 673 674 675 /// \brief Retrieve the identifier at a given position in the selector. 676 /// 677 /// Note that the identifier pointer returned may be NULL. Clients that only 678 /// care about the text of the identifier string, and not the specific, 679 /// uniqued identifier pointer, should use \c getNameForSlot(), which returns 680 /// an empty string when the identifier pointer would be NULL. 681 /// 682 /// \param argIndex The index for which we want to retrieve the identifier. 683 /// This index shall be less than \c getNumArgs() unless this is a keyword 684 /// selector, in which case 0 is the only permissible value. 685 /// 686 /// \returns the uniqued identifier for this slot, or NULL if this slot has 687 /// no corresponding identifier. 688 IdentifierInfo *getIdentifierInfoForSlot(unsigned argIndex) const; 689 690 /// \brief Retrieve the name at a given position in the selector. 691 /// 692 /// \param argIndex The index for which we want to retrieve the name. 693 /// This index shall be less than \c getNumArgs() unless this is a keyword 694 /// selector, in which case 0 is the only permissible value. 695 /// 696 /// \returns the name for this slot, which may be the empty string if no 697 /// name was supplied. 698 StringRef getNameForSlot(unsigned argIndex) const; 699 700 /// \brief Derive the full selector name (e.g. "foo:bar:") and return 701 /// it as an std::string. 702 std::string getAsString() const; 703 704 /// \brief Prints the full selector name (e.g. "foo:bar:"). 705 void print(llvm::raw_ostream &OS) const; 706 707 /// \brief Derive the conventional family of this method. getMethodFamily()708 ObjCMethodFamily getMethodFamily() const { 709 return getMethodFamilyImpl(*this); 710 } 711 getStringFormatFamily()712 ObjCStringFormatFamily getStringFormatFamily() const { 713 return getStringFormatFamilyImpl(*this); 714 } 715 getEmptyMarker()716 static Selector getEmptyMarker() { 717 return Selector(uintptr_t(-1)); 718 } getTombstoneMarker()719 static Selector getTombstoneMarker() { 720 return Selector(uintptr_t(-2)); 721 } 722 723 static ObjCInstanceTypeFamily getInstTypeMethodFamily(Selector sel); 724 }; 725 726 /// \brief This table allows us to fully hide how we implement 727 /// multi-keyword caching. 728 class SelectorTable { 729 void *Impl; // Actually a SelectorTableImpl 730 SelectorTable(const SelectorTable &) LLVM_DELETED_FUNCTION; 731 void operator=(const SelectorTable &) LLVM_DELETED_FUNCTION; 732 public: 733 SelectorTable(); 734 ~SelectorTable(); 735 736 /// \brief Can create any sort of selector. 737 /// 738 /// \p NumArgs indicates whether this is a no argument selector "foo", a 739 /// single argument selector "foo:" or multi-argument "foo:bar:". 740 Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV); 741 getUnarySelector(IdentifierInfo * ID)742 Selector getUnarySelector(IdentifierInfo *ID) { 743 return Selector(ID, 1); 744 } getNullarySelector(IdentifierInfo * ID)745 Selector getNullarySelector(IdentifierInfo *ID) { 746 return Selector(ID, 0); 747 } 748 749 /// \brief Return the total amount of memory allocated for managing selectors. 750 size_t getTotalMemory() const; 751 752 /// \brief Return the default setter name for the given identifier. 753 /// 754 /// This is "set" + \p Name where the initial character of \p Name 755 /// has been capitalized. 756 static SmallString<64> constructSetterName(StringRef Name); 757 758 /// \brief Return the default setter selector for the given identifier. 759 /// 760 /// This is "set" + \p Name where the initial character of \p Name 761 /// has been capitalized. 762 static Selector constructSetterSelector(IdentifierTable &Idents, 763 SelectorTable &SelTable, 764 const IdentifierInfo *Name); 765 }; 766 767 /// DeclarationNameExtra - Common base of the MultiKeywordSelector, 768 /// CXXSpecialName, and CXXOperatorIdName classes, all of which are 769 /// private classes that describe different kinds of names. 770 class DeclarationNameExtra { 771 public: 772 /// ExtraKind - The kind of "extra" information stored in the 773 /// DeclarationName. See @c ExtraKindOrNumArgs for an explanation of 774 /// how these enumerator values are used. 775 enum ExtraKind { 776 CXXConstructor = 0, 777 CXXDestructor, 778 CXXConversionFunction, 779 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 780 CXXOperator##Name, 781 #include "clang/Basic/OperatorKinds.def" 782 CXXLiteralOperator, 783 CXXUsingDirective, 784 NUM_EXTRA_KINDS 785 }; 786 787 /// ExtraKindOrNumArgs - Either the kind of C++ special name or 788 /// operator-id (if the value is one of the CXX* enumerators of 789 /// ExtraKind), in which case the DeclarationNameExtra is also a 790 /// CXXSpecialName, (for CXXConstructor, CXXDestructor, or 791 /// CXXConversionFunction) CXXOperatorIdName, or CXXLiteralOperatorName, 792 /// it may be also name common to C++ using-directives (CXXUsingDirective), 793 /// otherwise it is NUM_EXTRA_KINDS+NumArgs, where NumArgs is the number of 794 /// arguments in the Objective-C selector, in which case the 795 /// DeclarationNameExtra is also a MultiKeywordSelector. 796 unsigned ExtraKindOrNumArgs; 797 }; 798 799 } // end namespace clang 800 801 namespace llvm { 802 /// Define DenseMapInfo so that Selectors can be used as keys in DenseMap and 803 /// DenseSets. 804 template <> 805 struct DenseMapInfo<clang::Selector> { 806 static inline clang::Selector getEmptyKey() { 807 return clang::Selector::getEmptyMarker(); 808 } 809 static inline clang::Selector getTombstoneKey() { 810 return clang::Selector::getTombstoneMarker(); 811 } 812 813 static unsigned getHashValue(clang::Selector S); 814 815 static bool isEqual(clang::Selector LHS, clang::Selector RHS) { 816 return LHS == RHS; 817 } 818 }; 819 820 template <> 821 struct isPodLike<clang::Selector> { static const bool value = true; }; 822 823 template <typename T> class PointerLikeTypeTraits; 824 825 template<> 826 class PointerLikeTypeTraits<clang::Selector> { 827 public: 828 static inline const void *getAsVoidPointer(clang::Selector P) { 829 return P.getAsOpaquePtr(); 830 } 831 static inline clang::Selector getFromVoidPointer(const void *P) { 832 return clang::Selector(reinterpret_cast<uintptr_t>(P)); 833 } 834 enum { NumLowBitsAvailable = 0 }; 835 }; 836 837 // Provide PointerLikeTypeTraits for IdentifierInfo pointers, which 838 // are not guaranteed to be 8-byte aligned. 839 template<> 840 class PointerLikeTypeTraits<clang::IdentifierInfo*> { 841 public: 842 static inline void *getAsVoidPointer(clang::IdentifierInfo* P) { 843 return P; 844 } 845 static inline clang::IdentifierInfo *getFromVoidPointer(void *P) { 846 return static_cast<clang::IdentifierInfo*>(P); 847 } 848 enum { NumLowBitsAvailable = 1 }; 849 }; 850 851 template<> 852 class PointerLikeTypeTraits<const clang::IdentifierInfo*> { 853 public: 854 static inline const void *getAsVoidPointer(const clang::IdentifierInfo* P) { 855 return P; 856 } 857 static inline const clang::IdentifierInfo *getFromVoidPointer(const void *P) { 858 return static_cast<const clang::IdentifierInfo*>(P); 859 } 860 enum { NumLowBitsAvailable = 1 }; 861 }; 862 863 } // end namespace llvm 864 #endif 865