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