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 <cstdio>
20 
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // IdentifierInfo Implementation
25 //===----------------------------------------------------------------------===//
26 
27 IdentifierInfo::IdentifierInfo() {
28   TokenID = tok::identifier;
29   ObjCOrBuiltinID = 0;
30   HasMacro = false;
31   IsExtension = false;
32   IsPoisoned = false;
33   IsCPPOperatorKeyword = false;
34   NeedsHandleIdentifier = false;
35   FETokenInfo = 0;
36   Entry = 0;
37 }
38 
39 //===----------------------------------------------------------------------===//
40 // IdentifierTable Implementation
41 //===----------------------------------------------------------------------===//
42 
43 IdentifierInfoLookup::~IdentifierInfoLookup() {}
44 
45 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
46 
47 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
48                                  IdentifierInfoLookup* externalLookup)
49   : HashTable(8192), // Start with space for 8K identifiers.
50     ExternalLookup(externalLookup) {
51 
52   // Populate the identifier table with info about keywords for the current
53   // language.
54   AddKeywords(LangOpts);
55 }
56 
57 //===----------------------------------------------------------------------===//
58 // Language Keyword Implementation
59 //===----------------------------------------------------------------------===//
60 
61 // Constants for TokenKinds.def
62 namespace {
63   enum {
64     KEYALL = 1,
65     KEYC99 = 2,
66     KEYCXX = 4,
67     KEYCXX0X = 8,
68     KEYGNU = 16,
69     KEYMS = 32,
70     BOOLSUPPORT = 64
71   };
72 }
73 
74 /// AddKeyword - This method is used to associate a token ID with specific
75 /// identifiers because they are language keywords.  This causes the lexer to
76 /// automatically map matching identifiers to specialized token codes.
77 ///
78 /// The C90/C99/CPP/CPP0x flags are set to 0 if the token should be
79 /// enabled in the specified langauge, set to 1 if it is an extension
80 /// in the specified language, and set to 2 if disabled in the
81 /// specified language.
82 static void AddKeyword(const char *Keyword, unsigned KWLen,
83                        tok::TokenKind TokenCode, unsigned Flags,
84                        const LangOptions &LangOpts, IdentifierTable &Table) {
85   unsigned AddResult = 0;
86   if (Flags & KEYALL) AddResult = 2;
87   else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
88   else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2;
89   else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
90   else if (LangOpts.GNUMode && (Flags & KEYGNU)) AddResult = 1;
91   else if (LangOpts.Microsoft && (Flags & KEYMS)) AddResult = 1;
92   else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
93 
94   // Don't add this keyword if disabled in this language.
95   if (AddResult == 0) return;
96 
97   IdentifierInfo &Info = Table.get(Keyword, Keyword+KWLen);
98   Info.setTokenID(TokenCode);
99   Info.setIsExtensionToken(AddResult == 1);
100 }
101 
102 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
103 /// representations.
104 static void AddCXXOperatorKeyword(const char *Keyword, unsigned KWLen,
105                                   tok::TokenKind TokenCode,
106                                   IdentifierTable &Table) {
107   IdentifierInfo &Info = Table.get(Keyword, Keyword + KWLen);
108   Info.setTokenID(TokenCode);
109   Info.setIsCPlusPlusOperatorKeyword();
110 }
111 
112 /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
113 /// "property".
114 static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID,
115                            const char *Name, unsigned NameLen,
116                            IdentifierTable &Table) {
117   Table.get(Name, Name+NameLen).setObjCKeywordID(ObjCID);
118 }
119 
120 /// AddKeywords - Add all keywords to the symbol table.
121 ///
122 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
123   // Add keywords and tokens for the current language.
124 #define KEYWORD(NAME, FLAGS) \
125   AddKeyword(#NAME, strlen(#NAME), tok::kw_ ## NAME,  \
126              FLAGS, LangOpts, *this);
127 #define ALIAS(NAME, TOK, FLAGS) \
128   AddKeyword(NAME, strlen(NAME), tok::kw_ ## TOK,  \
129              FLAGS, LangOpts, *this);
130 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
131   if (LangOpts.CXXOperatorNames)          \
132     AddCXXOperatorKeyword(#NAME, strlen(#NAME), tok::ALIAS, *this);
133 #define OBJC1_AT_KEYWORD(NAME) \
134   if (LangOpts.ObjC1)          \
135     AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
136 #define OBJC2_AT_KEYWORD(NAME) \
137   if (LangOpts.ObjC2)          \
138     AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
139 #include "clang/Basic/TokenKinds.def"
140 }
141 
142 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
143   // We use a perfect hash function here involving the length of the keyword,
144   // the first and third character.  For preprocessor ID's there are no
145   // collisions (if there were, the switch below would complain about duplicate
146   // case values).  Note that this depends on 'if' being null terminated.
147 
148 #define HASH(LEN, FIRST, THIRD) \
149   (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
150 #define CASE(LEN, FIRST, THIRD, NAME) \
151   case HASH(LEN, FIRST, THIRD): \
152     return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
153 
154   unsigned Len = getLength();
155   if (Len < 2) return tok::pp_not_keyword;
156   const char *Name = getName();
157   switch (HASH(Len, Name[0], Name[2])) {
158   default: return tok::pp_not_keyword;
159   CASE( 2, 'i', '\0', if);
160   CASE( 4, 'e', 'i', elif);
161   CASE( 4, 'e', 's', else);
162   CASE( 4, 'l', 'n', line);
163   CASE( 4, 's', 'c', sccs);
164   CASE( 5, 'e', 'd', endif);
165   CASE( 5, 'e', 'r', error);
166   CASE( 5, 'i', 'e', ident);
167   CASE( 5, 'i', 'd', ifdef);
168   CASE( 5, 'u', 'd', undef);
169 
170   CASE( 6, 'a', 's', assert);
171   CASE( 6, 'd', 'f', define);
172   CASE( 6, 'i', 'n', ifndef);
173   CASE( 6, 'i', 'p', import);
174   CASE( 6, 'p', 'a', pragma);
175 
176   CASE( 7, 'd', 'f', defined);
177   CASE( 7, 'i', 'c', include);
178   CASE( 7, 'w', 'r', warning);
179 
180   CASE( 8, 'u', 'a', unassert);
181   CASE(12, 'i', 'c', include_next);
182 
183   CASE(16, '_', 'i', __include_macros);
184 #undef CASE
185 #undef HASH
186   }
187 }
188 
189 //===----------------------------------------------------------------------===//
190 // Stats Implementation
191 //===----------------------------------------------------------------------===//
192 
193 /// PrintStats - Print statistics about how well the identifier table is doing
194 /// at hashing identifiers.
195 void IdentifierTable::PrintStats() const {
196   unsigned NumBuckets = HashTable.getNumBuckets();
197   unsigned NumIdentifiers = HashTable.getNumItems();
198   unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
199   unsigned AverageIdentifierSize = 0;
200   unsigned MaxIdentifierLength = 0;
201 
202   // TODO: Figure out maximum times an identifier had to probe for -stats.
203   for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
204        I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
205     unsigned IdLen = I->getKeyLength();
206     AverageIdentifierSize += IdLen;
207     if (MaxIdentifierLength < IdLen)
208       MaxIdentifierLength = IdLen;
209   }
210 
211   fprintf(stderr, "\n*** Identifier Table Stats:\n");
212   fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
213   fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
214   fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
215           NumIdentifiers/(double)NumBuckets);
216   fprintf(stderr, "Ave identifier length: %f\n",
217           (AverageIdentifierSize/(double)NumIdentifiers));
218   fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
219 
220   // Compute statistics about the memory allocated for identifiers.
221   HashTable.getAllocator().PrintStats();
222 }
223 
224 //===----------------------------------------------------------------------===//
225 // SelectorTable Implementation
226 //===----------------------------------------------------------------------===//
227 
228 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
229   return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
230 }
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 
248     // Fill in the trailing keyword array.
249     IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
250     for (unsigned i = 0; i != nKeys; ++i)
251       KeyInfo[i] = IIV[i];
252   }
253 
254   // getName - Derive the full selector name and return it.
255   std::string getName() const;
256 
257   unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
258 
259   typedef IdentifierInfo *const *keyword_iterator;
260   keyword_iterator keyword_begin() const {
261     return reinterpret_cast<keyword_iterator>(this+1);
262   }
263   keyword_iterator keyword_end() const {
264     return keyword_begin()+getNumArgs();
265   }
266   IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
267     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
268     return keyword_begin()[i];
269   }
270   static void Profile(llvm::FoldingSetNodeID &ID,
271                       keyword_iterator ArgTys, unsigned NumArgs) {
272     ID.AddInteger(NumArgs);
273     for (unsigned i = 0; i != NumArgs; ++i)
274       ID.AddPointer(ArgTys[i]);
275   }
276   void Profile(llvm::FoldingSetNodeID &ID) {
277     Profile(ID, keyword_begin(), getNumArgs());
278   }
279 };
280 } // end namespace clang.
281 
282 unsigned Selector::getNumArgs() const {
283   unsigned IIF = getIdentifierInfoFlag();
284   if (IIF == ZeroArg)
285     return 0;
286   if (IIF == OneArg)
287     return 1;
288   // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
289   MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
290   return SI->getNumArgs();
291 }
292 
293 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
294   if (getIdentifierInfoFlag()) {
295     assert(argIndex == 0 && "illegal keyword index");
296     return getAsIdentifierInfo();
297   }
298   // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
299   MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
300   return SI->getIdentifierInfoForSlot(argIndex);
301 }
302 
303 std::string MultiKeywordSelector::getName() const {
304   std::string Result;
305   unsigned Length = 0;
306   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
307     if (*I)
308       Length += (*I)->getLength();
309     ++Length;  // :
310   }
311 
312   Result.reserve(Length);
313 
314   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
315     if (*I)
316       Result.insert(Result.end(), (*I)->getName(),
317                     (*I)->getName()+(*I)->getLength());
318     Result.push_back(':');
319   }
320 
321   return Result;
322 }
323 
324 std::string Selector::getAsString() const {
325   if (InfoPtr == 0)
326     return "<null selector>";
327 
328   if (InfoPtr & ArgFlags) {
329     IdentifierInfo *II = getAsIdentifierInfo();
330 
331     // If the number of arguments is 0 then II is guaranteed to not be null.
332     if (getNumArgs() == 0)
333       return II->getName();
334 
335     std::string Res = II ? II->getName() : "";
336     Res += ":";
337     return Res;
338   }
339 
340   // We have a multiple keyword selector (no embedded flags).
341   return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
342 }
343 
344 
345 namespace {
346   struct SelectorTableImpl {
347     llvm::FoldingSet<MultiKeywordSelector> Table;
348     llvm::BumpPtrAllocator Allocator;
349   };
350 } // end anonymous namespace.
351 
352 static SelectorTableImpl &getSelectorTableImpl(void *P) {
353   return *static_cast<SelectorTableImpl*>(P);
354 }
355 
356 
357 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
358   if (nKeys < 2)
359     return Selector(IIV[0], nKeys);
360 
361   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
362 
363   // Unique selector, to guarantee there is one per name.
364   llvm::FoldingSetNodeID ID;
365   MultiKeywordSelector::Profile(ID, IIV, nKeys);
366 
367   void *InsertPos = 0;
368   if (MultiKeywordSelector *SI =
369         SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
370     return Selector(SI);
371 
372   // MultiKeywordSelector objects are not allocated with new because they have a
373   // variable size array (for parameter types) at the end of them.
374   unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
375   MultiKeywordSelector *SI =
376     (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
377                                          llvm::alignof<MultiKeywordSelector>());
378   new (SI) MultiKeywordSelector(nKeys, IIV);
379   SelTabImpl.Table.InsertNode(SI, InsertPos);
380   return Selector(SI);
381 }
382 
383 SelectorTable::SelectorTable() {
384   Impl = new SelectorTableImpl();
385 }
386 
387 SelectorTable::~SelectorTable() {
388   delete &getSelectorTableImpl(Impl);
389 }
390 
391