IdentifierTable.cpp 17 KB

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