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