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