IdentifierTable.cpp revision 926df6cfabf3eaa4afc990c097fa4619b76a9b57
1//===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===// 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// This file implements the IdentifierInfo, IdentifierVisitor, and 11// IdentifierTable interfaces. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Basic/IdentifierTable.h" 16#include "clang/Basic/LangOptions.h" 17#include "llvm/ADT/FoldingSet.h" 18#include "llvm/ADT/DenseMap.h" 19#include "llvm/ADT/StringRef.h" 20#include "llvm/Support/raw_ostream.h" 21#include <cstdio> 22 23using namespace clang; 24 25//===----------------------------------------------------------------------===// 26// IdentifierInfo Implementation 27//===----------------------------------------------------------------------===// 28 29IdentifierInfo::IdentifierInfo() { 30 TokenID = tok::identifier; 31 ObjCOrBuiltinID = 0; 32 HasMacro = false; 33 IsExtension = false; 34 IsPoisoned = false; 35 IsCPPOperatorKeyword = false; 36 NeedsHandleIdentifier = false; 37 IsFromAST = false; 38 RevertedTokenID = false; 39 FETokenInfo = 0; 40 Entry = 0; 41} 42 43//===----------------------------------------------------------------------===// 44// IdentifierTable Implementation 45//===----------------------------------------------------------------------===// 46 47IdentifierIterator::~IdentifierIterator() { } 48 49IdentifierInfoLookup::~IdentifierInfoLookup() {} 50 51namespace { 52 /// \brief A simple identifier lookup iterator that represents an 53 /// empty sequence of identifiers. 54 class EmptyLookupIterator : public IdentifierIterator 55 { 56 public: 57 virtual llvm::StringRef Next() { return llvm::StringRef(); } 58 }; 59} 60 61IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const { 62 return new EmptyLookupIterator(); 63} 64 65ExternalIdentifierLookup::~ExternalIdentifierLookup() {} 66 67IdentifierTable::IdentifierTable(const LangOptions &LangOpts, 68 IdentifierInfoLookup* externalLookup) 69 : HashTable(8192), // Start with space for 8K identifiers. 70 ExternalLookup(externalLookup) { 71 72 // Populate the identifier table with info about keywords for the current 73 // language. 74 AddKeywords(LangOpts); 75} 76 77//===----------------------------------------------------------------------===// 78// Language Keyword Implementation 79//===----------------------------------------------------------------------===// 80 81// Constants for TokenKinds.def 82namespace { 83 enum { 84 KEYC99 = 0x1, 85 KEYCXX = 0x2, 86 KEYCXX0X = 0x4, 87 KEYGNU = 0x8, 88 KEYMS = 0x10, 89 BOOLSUPPORT = 0x20, 90 KEYALTIVEC = 0x40, 91 KEYNOCXX = 0x80, 92 KEYBORLAND = 0x100, 93 KEYOPENCL = 0x200, 94 KEYC1X = 0x400, 95 KEYALL = 0x7ff 96 }; 97} 98 99/// AddKeyword - This method is used to associate a token ID with specific 100/// identifiers because they are language keywords. This causes the lexer to 101/// automatically map matching identifiers to specialized token codes. 102/// 103/// The C90/C99/CPP/CPP0x flags are set to 2 if the token should be 104/// enabled in the specified langauge, set to 1 if it is an extension 105/// in the specified language, and set to 0 if disabled in the 106/// specified language. 107static void AddKeyword(llvm::StringRef Keyword, 108 tok::TokenKind TokenCode, unsigned Flags, 109 const LangOptions &LangOpts, IdentifierTable &Table) { 110 unsigned AddResult = 0; 111 if (Flags == KEYALL) AddResult = 2; 112 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2; 113 else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2; 114 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2; 115 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1; 116 else if (LangOpts.Microsoft && (Flags & KEYMS)) AddResult = 1; 117 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1; 118 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2; 119 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2; 120 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2; 121 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2; 122 else if (LangOpts.C1X && (Flags & KEYC1X)) AddResult = 2; 123 124 // Don't add this keyword if disabled in this language. 125 if (AddResult == 0) return; 126 127 IdentifierInfo &Info = Table.get(Keyword, TokenCode); 128 Info.setIsExtensionToken(AddResult == 1); 129} 130 131/// AddCXXOperatorKeyword - Register a C++ operator keyword alternative 132/// representations. 133static void AddCXXOperatorKeyword(llvm::StringRef Keyword, 134 tok::TokenKind TokenCode, 135 IdentifierTable &Table) { 136 IdentifierInfo &Info = Table.get(Keyword, TokenCode); 137 Info.setIsCPlusPlusOperatorKeyword(); 138} 139 140/// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or 141/// "property". 142static void AddObjCKeyword(llvm::StringRef Name, 143 tok::ObjCKeywordKind ObjCID, 144 IdentifierTable &Table) { 145 Table.get(Name).setObjCKeywordID(ObjCID); 146} 147 148/// AddKeywords - Add all keywords to the symbol table. 149/// 150void IdentifierTable::AddKeywords(const LangOptions &LangOpts) { 151 // Add keywords and tokens for the current language. 152#define KEYWORD(NAME, FLAGS) \ 153 AddKeyword(llvm::StringRef(#NAME), tok::kw_ ## NAME, \ 154 FLAGS, LangOpts, *this); 155#define ALIAS(NAME, TOK, FLAGS) \ 156 AddKeyword(llvm::StringRef(NAME), tok::kw_ ## TOK, \ 157 FLAGS, LangOpts, *this); 158#define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \ 159 if (LangOpts.CXXOperatorNames) \ 160 AddCXXOperatorKeyword(llvm::StringRef(#NAME), tok::ALIAS, *this); 161#define OBJC1_AT_KEYWORD(NAME) \ 162 if (LangOpts.ObjC1) \ 163 AddObjCKeyword(llvm::StringRef(#NAME), tok::objc_##NAME, *this); 164#define OBJC2_AT_KEYWORD(NAME) \ 165 if (LangOpts.ObjC2) \ 166 AddObjCKeyword(llvm::StringRef(#NAME), tok::objc_##NAME, *this); 167#define TESTING_KEYWORD(NAME, FLAGS) 168#include "clang/Basic/TokenKinds.def" 169 170 if (LangOpts.ParseUnknownAnytype) 171 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL, 172 LangOpts, *this); 173} 174 175tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { 176 // We use a perfect hash function here involving the length of the keyword, 177 // the first and third character. For preprocessor ID's there are no 178 // collisions (if there were, the switch below would complain about duplicate 179 // case values). Note that this depends on 'if' being null terminated. 180 181#define HASH(LEN, FIRST, THIRD) \ 182 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) 183#define CASE(LEN, FIRST, THIRD, NAME) \ 184 case HASH(LEN, FIRST, THIRD): \ 185 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME 186 187 unsigned Len = getLength(); 188 if (Len < 2) return tok::pp_not_keyword; 189 const char *Name = getNameStart(); 190 switch (HASH(Len, Name[0], Name[2])) { 191 default: return tok::pp_not_keyword; 192 CASE( 2, 'i', '\0', if); 193 CASE( 4, 'e', 'i', elif); 194 CASE( 4, 'e', 's', else); 195 CASE( 4, 'l', 'n', line); 196 CASE( 4, 's', 'c', sccs); 197 CASE( 5, 'e', 'd', endif); 198 CASE( 5, 'e', 'r', error); 199 CASE( 5, 'i', 'e', ident); 200 CASE( 5, 'i', 'd', ifdef); 201 CASE( 5, 'u', 'd', undef); 202 203 CASE( 6, 'a', 's', assert); 204 CASE( 6, 'd', 'f', define); 205 CASE( 6, 'i', 'n', ifndef); 206 CASE( 6, 'i', 'p', import); 207 CASE( 6, 'p', 'a', pragma); 208 209 CASE( 7, 'd', 'f', defined); 210 CASE( 7, 'i', 'c', include); 211 CASE( 7, 'w', 'r', warning); 212 213 CASE( 8, 'u', 'a', unassert); 214 CASE(12, 'i', 'c', include_next); 215 216 CASE(16, '_', 'i', __include_macros); 217#undef CASE 218#undef HASH 219 } 220} 221 222//===----------------------------------------------------------------------===// 223// Stats Implementation 224//===----------------------------------------------------------------------===// 225 226/// PrintStats - Print statistics about how well the identifier table is doing 227/// at hashing identifiers. 228void IdentifierTable::PrintStats() const { 229 unsigned NumBuckets = HashTable.getNumBuckets(); 230 unsigned NumIdentifiers = HashTable.getNumItems(); 231 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; 232 unsigned AverageIdentifierSize = 0; 233 unsigned MaxIdentifierLength = 0; 234 235 // TODO: Figure out maximum times an identifier had to probe for -stats. 236 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator 237 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { 238 unsigned IdLen = I->getKeyLength(); 239 AverageIdentifierSize += IdLen; 240 if (MaxIdentifierLength < IdLen) 241 MaxIdentifierLength = IdLen; 242 } 243 244 fprintf(stderr, "\n*** Identifier Table Stats:\n"); 245 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); 246 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); 247 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n", 248 NumIdentifiers/(double)NumBuckets); 249 fprintf(stderr, "Ave identifier length: %f\n", 250 (AverageIdentifierSize/(double)NumIdentifiers)); 251 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); 252 253 // Compute statistics about the memory allocated for identifiers. 254 HashTable.getAllocator().PrintStats(); 255} 256 257//===----------------------------------------------------------------------===// 258// SelectorTable Implementation 259//===----------------------------------------------------------------------===// 260 261unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) { 262 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr()); 263} 264 265namespace clang { 266/// MultiKeywordSelector - One of these variable length records is kept for each 267/// selector containing more than one keyword. We use a folding set 268/// to unique aggregate names (keyword selectors in ObjC parlance). Access to 269/// this class is provided strictly through Selector. 270class MultiKeywordSelector 271 : public DeclarationNameExtra, public llvm::FoldingSetNode { 272 MultiKeywordSelector(unsigned nKeys) { 273 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; 274 } 275public: 276 // Constructor for keyword selectors. 277 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) { 278 assert((nKeys > 1) && "not a multi-keyword selector"); 279 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; 280 281 // Fill in the trailing keyword array. 282 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1); 283 for (unsigned i = 0; i != nKeys; ++i) 284 KeyInfo[i] = IIV[i]; 285 } 286 287 // getName - Derive the full selector name and return it. 288 std::string getName() const; 289 290 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; } 291 292 typedef IdentifierInfo *const *keyword_iterator; 293 keyword_iterator keyword_begin() const { 294 return reinterpret_cast<keyword_iterator>(this+1); 295 } 296 keyword_iterator keyword_end() const { 297 return keyword_begin()+getNumArgs(); 298 } 299 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { 300 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); 301 return keyword_begin()[i]; 302 } 303 static void Profile(llvm::FoldingSetNodeID &ID, 304 keyword_iterator ArgTys, unsigned NumArgs) { 305 ID.AddInteger(NumArgs); 306 for (unsigned i = 0; i != NumArgs; ++i) 307 ID.AddPointer(ArgTys[i]); 308 } 309 void Profile(llvm::FoldingSetNodeID &ID) { 310 Profile(ID, keyword_begin(), getNumArgs()); 311 } 312}; 313} // end namespace clang. 314 315unsigned Selector::getNumArgs() const { 316 unsigned IIF = getIdentifierInfoFlag(); 317 if (IIF == ZeroArg) 318 return 0; 319 if (IIF == OneArg) 320 return 1; 321 // We point to a MultiKeywordSelector (pointer doesn't contain any flags). 322 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr); 323 return SI->getNumArgs(); 324} 325 326IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { 327 if (getIdentifierInfoFlag()) { 328 assert(argIndex == 0 && "illegal keyword index"); 329 return getAsIdentifierInfo(); 330 } 331 // We point to a MultiKeywordSelector (pointer doesn't contain any flags). 332 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr); 333 return SI->getIdentifierInfoForSlot(argIndex); 334} 335 336llvm::StringRef Selector::getNameForSlot(unsigned int argIndex) const { 337 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex); 338 return II? II->getName() : llvm::StringRef(); 339} 340 341std::string MultiKeywordSelector::getName() const { 342 llvm::SmallString<256> Str; 343 llvm::raw_svector_ostream OS(Str); 344 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { 345 if (*I) 346 OS << (*I)->getName(); 347 OS << ':'; 348 } 349 350 return OS.str(); 351} 352 353std::string Selector::getAsString() const { 354 if (InfoPtr == 0) 355 return "<null selector>"; 356 357 if (InfoPtr & ArgFlags) { 358 IdentifierInfo *II = getAsIdentifierInfo(); 359 360 // If the number of arguments is 0 then II is guaranteed to not be null. 361 if (getNumArgs() == 0) 362 return II->getName(); 363 364 if (!II) 365 return ":"; 366 367 return II->getName().str() + ":"; 368 } 369 370 // We have a multiple keyword selector (no embedded flags). 371 return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName(); 372} 373 374/// Interpreting the given string using the normal CamelCase 375/// conventions, determine whether the given string starts with the 376/// given "word", which is assumed to end in a lowercase letter. 377static bool startsWithWord(llvm::StringRef name, llvm::StringRef word) { 378 if (name.size() < word.size()) return false; 379 return ((name.size() == word.size() || 380 !islower(name[word.size()])) 381 && name.startswith(word)); 382} 383 384ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { 385 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); 386 if (!first) return OMF_None; 387 388 llvm::StringRef name = first->getName(); 389 if (sel.isUnarySelector()) { 390 if (name == "autorelease") return OMF_autorelease; 391 if (name == "dealloc") return OMF_dealloc; 392 if (name == "release") return OMF_release; 393 if (name == "retain") return OMF_retain; 394 if (name == "retainCount") return OMF_retainCount; 395 if (name == "self") return OMF_self; 396 } 397 398 // The other method families may begin with a prefix of underscores. 399 while (!name.empty() && name.front() == '_') 400 name = name.substr(1); 401 402 if (name.empty()) return OMF_None; 403 switch (name.front()) { 404 case 'a': 405 if (startsWithWord(name, "alloc")) return OMF_alloc; 406 break; 407 case 'c': 408 if (startsWithWord(name, "copy")) return OMF_copy; 409 break; 410 case 'i': 411 if (startsWithWord(name, "init")) return OMF_init; 412 break; 413 case 'm': 414 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy; 415 break; 416 case 'n': 417 if (startsWithWord(name, "new")) return OMF_new; 418 break; 419 default: 420 break; 421 } 422 423 return OMF_None; 424} 425 426namespace { 427 struct SelectorTableImpl { 428 llvm::FoldingSet<MultiKeywordSelector> Table; 429 llvm::BumpPtrAllocator Allocator; 430 }; 431} // end anonymous namespace. 432 433static SelectorTableImpl &getSelectorTableImpl(void *P) { 434 return *static_cast<SelectorTableImpl*>(P); 435} 436 437size_t SelectorTable::getTotalMemory() const { 438 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); 439 return SelTabImpl.Allocator.getTotalMemory(); 440} 441 442Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { 443 if (nKeys < 2) 444 return Selector(IIV[0], nKeys); 445 446 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); 447 448 // Unique selector, to guarantee there is one per name. 449 llvm::FoldingSetNodeID ID; 450 MultiKeywordSelector::Profile(ID, IIV, nKeys); 451 452 void *InsertPos = 0; 453 if (MultiKeywordSelector *SI = 454 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) 455 return Selector(SI); 456 457 // MultiKeywordSelector objects are not allocated with new because they have a 458 // variable size array (for parameter types) at the end of them. 459 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); 460 MultiKeywordSelector *SI = 461 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size, 462 llvm::alignOf<MultiKeywordSelector>()); 463 new (SI) MultiKeywordSelector(nKeys, IIV); 464 SelTabImpl.Table.InsertNode(SI, InsertPos); 465 return Selector(SI); 466} 467 468SelectorTable::SelectorTable() { 469 Impl = new SelectorTableImpl(); 470} 471 472SelectorTable::~SelectorTable() { 473 delete &getSelectorTableImpl(Impl); 474} 475 476const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) { 477 switch (Operator) { 478 case OO_None: 479 case NUM_OVERLOADED_OPERATORS: 480 return 0; 481 482#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 483 case OO_##Name: return Spelling; 484#include "clang/Basic/OperatorKinds.def" 485 } 486 487 return 0; 488} 489 490