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