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