IdentifierTable.cpp 18 KB

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