IdentifierTable.cpp 16 KB

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