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