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