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