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