IdentifierTable.cpp 23 KB

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