1 //===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IdentifierInfo, IdentifierVisitor, and
11 // IdentifierTable interfaces.
13 //===----------------------------------------------------------------------===//
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"
24 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // IdentifierInfo Implementation
28 //===----------------------------------------------------------------------===//
30 IdentifierInfo::IdentifierInfo() {
31 TokenID = tok::identifier;
35 IsCXX11CompatKeyword = false;
37 IsCPPOperatorKeyword = false;
38 NeedsHandleIdentifier = false;
40 RevertedTokenID = false;
45 //===----------------------------------------------------------------------===//
46 // IdentifierTable Implementation
47 //===----------------------------------------------------------------------===//
49 IdentifierIterator::~IdentifierIterator() { }
51 IdentifierInfoLookup::~IdentifierInfoLookup() {}
54 /// \brief A simple identifier lookup iterator that represents an
55 /// empty sequence of identifiers.
56 class EmptyLookupIterator : public IdentifierIterator
59 virtual StringRef Next() { return StringRef(); }
63 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const {
64 return new EmptyLookupIterator();
67 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
69 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
70 IdentifierInfoLookup* externalLookup)
71 : HashTable(8192), // Start with space for 8K identifiers.
72 ExternalLookup(externalLookup) {
74 // Populate the identifier table with info about keywords for the current
76 AddKeywords(LangOpts);
79 //===----------------------------------------------------------------------===//
80 // Language Keyword Implementation
81 //===----------------------------------------------------------------------===//
83 // Constants for TokenKinds.def
102 /// AddKeyword - This method is used to associate a token ID with specific
103 /// identifiers because they are language keywords. This causes the lexer to
104 /// automatically map matching identifiers to specialized token codes.
106 /// The C90/C99/CPP/CPP0x flags are set to 3 if the token is a keyword in a
107 /// future language standard, set to 2 if the token should be enabled in the
108 /// specified langauge, set to 1 if it is an extension in the specified
109 /// language, and set to 0 if disabled in the specified language.
110 static void AddKeyword(StringRef Keyword,
111 tok::TokenKind TokenCode, unsigned Flags,
112 const LangOptions &LangOpts, IdentifierTable &Table) {
113 unsigned AddResult = 0;
114 if (Flags == KEYALL) AddResult = 2;
115 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
116 else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2;
117 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
118 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1;
119 else if (LangOpts.MicrosoftExt && (Flags & KEYMS)) AddResult = 1;
120 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1;
121 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
122 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2;
123 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2;
124 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2;
125 else if (LangOpts.C1X && (Flags & KEYC1X)) AddResult = 2;
126 else if (LangOpts.ObjCAutoRefCount && (Flags & KEYARC)) AddResult = 2;
127 else if (LangOpts.CPlusPlus && (Flags & KEYCXX0X)) AddResult = 3;
129 // Don't add this keyword if disabled in this language.
130 if (AddResult == 0) return;
132 IdentifierInfo &Info =
133 Table.get(Keyword, AddResult == 3 ? tok::identifier : TokenCode);
134 Info.setIsExtensionToken(AddResult == 1);
135 Info.setIsCXX11CompatKeyword(AddResult == 3);
138 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
140 static void AddCXXOperatorKeyword(StringRef Keyword,
141 tok::TokenKind TokenCode,
142 IdentifierTable &Table) {
143 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
144 Info.setIsCPlusPlusOperatorKeyword();
147 /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
149 static void AddObjCKeyword(StringRef Name,
150 tok::ObjCKeywordKind ObjCID,
151 IdentifierTable &Table) {
152 Table.get(Name).setObjCKeywordID(ObjCID);
155 /// AddKeywords - Add all keywords to the symbol table.
157 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
158 // Add keywords and tokens for the current language.
159 #define KEYWORD(NAME, FLAGS) \
160 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
161 FLAGS, LangOpts, *this);
162 #define ALIAS(NAME, TOK, FLAGS) \
163 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
164 FLAGS, LangOpts, *this);
165 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
166 if (LangOpts.CXXOperatorNames) \
167 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
168 #define OBJC1_AT_KEYWORD(NAME) \
169 if (LangOpts.ObjC1) \
170 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
171 #define OBJC2_AT_KEYWORD(NAME) \
172 if (LangOpts.ObjC2) \
173 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
174 #define TESTING_KEYWORD(NAME, FLAGS)
175 #include "clang/Basic/TokenKinds.def"
177 if (LangOpts.ParseUnknownAnytype)
178 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
182 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
183 // We use a perfect hash function here involving the length of the keyword,
184 // the first and third character. For preprocessor ID's there are no
185 // collisions (if there were, the switch below would complain about duplicate
186 // case values). Note that this depends on 'if' being null terminated.
188 #define HASH(LEN, FIRST, THIRD) \
189 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
190 #define CASE(LEN, FIRST, THIRD, NAME) \
191 case HASH(LEN, FIRST, THIRD): \
192 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
194 unsigned Len = getLength();
195 if (Len < 2) return tok::pp_not_keyword;
196 const char *Name = getNameStart();
197 switch (HASH(Len, Name[0], Name[2])) {
198 default: return tok::pp_not_keyword;
199 CASE( 2, 'i', '\0', if);
200 CASE( 4, 'e', 'i', elif);
201 CASE( 4, 'e', 's', else);
202 CASE( 4, 'l', 'n', line);
203 CASE( 4, 's', 'c', sccs);
204 CASE( 5, 'e', 'd', endif);
205 CASE( 5, 'e', 'r', error);
206 CASE( 5, 'i', 'e', ident);
207 CASE( 5, 'i', 'd', ifdef);
208 CASE( 5, 'u', 'd', undef);
210 CASE( 6, 'a', 's', assert);
211 CASE( 6, 'd', 'f', define);
212 CASE( 6, 'i', 'n', ifndef);
213 CASE( 6, 'i', 'p', import);
214 CASE( 6, 'p', 'a', pragma);
216 CASE( 7, 'd', 'f', defined);
217 CASE( 7, 'i', 'c', include);
218 CASE( 7, 'w', 'r', warning);
220 CASE( 8, 'u', 'a', unassert);
221 CASE(12, 'i', 'c', include_next);
223 CASE(16, '_', 'i', __include_macros);
224 CASE(16, '_', 'e', __export_macro__);
230 //===----------------------------------------------------------------------===//
231 // Stats Implementation
232 //===----------------------------------------------------------------------===//
234 /// PrintStats - Print statistics about how well the identifier table is doing
235 /// at hashing identifiers.
236 void IdentifierTable::PrintStats() const {
237 unsigned NumBuckets = HashTable.getNumBuckets();
238 unsigned NumIdentifiers = HashTable.getNumItems();
239 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
240 unsigned AverageIdentifierSize = 0;
241 unsigned MaxIdentifierLength = 0;
243 // TODO: Figure out maximum times an identifier had to probe for -stats.
244 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
245 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
246 unsigned IdLen = I->getKeyLength();
247 AverageIdentifierSize += IdLen;
248 if (MaxIdentifierLength < IdLen)
249 MaxIdentifierLength = IdLen;
252 fprintf(stderr, "\n*** Identifier Table Stats:\n");
253 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
254 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
255 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
256 NumIdentifiers/(double)NumBuckets);
257 fprintf(stderr, "Ave identifier length: %f\n",
258 (AverageIdentifierSize/(double)NumIdentifiers));
259 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
261 // Compute statistics about the memory allocated for identifiers.
262 HashTable.getAllocator().PrintStats();
265 //===----------------------------------------------------------------------===//
266 // SelectorTable Implementation
267 //===----------------------------------------------------------------------===//
269 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
270 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
274 /// MultiKeywordSelector - One of these variable length records is kept for each
275 /// selector containing more than one keyword. We use a folding set
276 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
277 /// this class is provided strictly through Selector.
278 class MultiKeywordSelector
279 : public DeclarationNameExtra, public llvm::FoldingSetNode {
280 MultiKeywordSelector(unsigned nKeys) {
281 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
284 // Constructor for keyword selectors.
285 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
286 assert((nKeys > 1) && "not a multi-keyword selector");
287 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
289 // Fill in the trailing keyword array.
290 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
291 for (unsigned i = 0; i != nKeys; ++i)
295 // getName - Derive the full selector name and return it.
296 std::string getName() const;
298 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
300 typedef IdentifierInfo *const *keyword_iterator;
301 keyword_iterator keyword_begin() const {
302 return reinterpret_cast<keyword_iterator>(this+1);
304 keyword_iterator keyword_end() const {
305 return keyword_begin()+getNumArgs();
307 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
308 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
309 return keyword_begin()[i];
311 static void Profile(llvm::FoldingSetNodeID &ID,
312 keyword_iterator ArgTys, unsigned NumArgs) {
313 ID.AddInteger(NumArgs);
314 for (unsigned i = 0; i != NumArgs; ++i)
315 ID.AddPointer(ArgTys[i]);
317 void Profile(llvm::FoldingSetNodeID &ID) {
318 Profile(ID, keyword_begin(), getNumArgs());
321 } // end namespace clang.
323 unsigned Selector::getNumArgs() const {
324 unsigned IIF = getIdentifierInfoFlag();
329 // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
330 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
331 return SI->getNumArgs();
334 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
335 if (getIdentifierInfoFlag()) {
336 assert(argIndex == 0 && "illegal keyword index");
337 return getAsIdentifierInfo();
339 // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
340 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
341 return SI->getIdentifierInfoForSlot(argIndex);
344 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
345 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
346 return II? II->getName() : StringRef();
349 std::string MultiKeywordSelector::getName() const {
350 llvm::SmallString<256> Str;
351 llvm::raw_svector_ostream OS(Str);
352 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
354 OS << (*I)->getName();
361 std::string Selector::getAsString() const {
363 return "<null selector>";
365 if (InfoPtr & ArgFlags) {
366 IdentifierInfo *II = getAsIdentifierInfo();
368 // If the number of arguments is 0 then II is guaranteed to not be null.
369 if (getNumArgs() == 0)
370 return II->getName();
375 return II->getName().str() + ":";
378 // We have a multiple keyword selector (no embedded flags).
379 return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
382 /// Interpreting the given string using the normal CamelCase
383 /// conventions, determine whether the given string starts with the
384 /// given "word", which is assumed to end in a lowercase letter.
385 static bool startsWithWord(StringRef name, StringRef word) {
386 if (name.size() < word.size()) return false;
387 return ((name.size() == word.size() ||
388 !islower(name[word.size()]))
389 && name.startswith(word));
392 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
393 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
394 if (!first) return OMF_None;
396 StringRef name = first->getName();
397 if (sel.isUnarySelector()) {
398 if (name == "autorelease") return OMF_autorelease;
399 if (name == "dealloc") return OMF_dealloc;
400 if (name == "finalize") return OMF_finalize;
401 if (name == "release") return OMF_release;
402 if (name == "retain") return OMF_retain;
403 if (name == "retainCount") return OMF_retainCount;
404 if (name == "self") return OMF_self;
407 if (name == "performSelector") return OMF_performSelector;
409 // The other method families may begin with a prefix of underscores.
410 while (!name.empty() && name.front() == '_')
411 name = name.substr(1);
413 if (name.empty()) return OMF_None;
414 switch (name.front()) {
416 if (startsWithWord(name, "alloc")) return OMF_alloc;
419 if (startsWithWord(name, "copy")) return OMF_copy;
422 if (startsWithWord(name, "init")) return OMF_init;
425 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
428 if (startsWithWord(name, "new")) return OMF_new;
438 struct SelectorTableImpl {
439 llvm::FoldingSet<MultiKeywordSelector> Table;
440 llvm::BumpPtrAllocator Allocator;
442 } // end anonymous namespace.
444 static SelectorTableImpl &getSelectorTableImpl(void *P) {
445 return *static_cast<SelectorTableImpl*>(P);
448 size_t SelectorTable::getTotalMemory() const {
449 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
450 return SelTabImpl.Allocator.getTotalMemory();
453 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
455 return Selector(IIV[0], nKeys);
457 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
459 // Unique selector, to guarantee there is one per name.
460 llvm::FoldingSetNodeID ID;
461 MultiKeywordSelector::Profile(ID, IIV, nKeys);
464 if (MultiKeywordSelector *SI =
465 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
468 // MultiKeywordSelector objects are not allocated with new because they have a
469 // variable size array (for parameter types) at the end of them.
470 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
471 MultiKeywordSelector *SI =
472 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
473 llvm::alignOf<MultiKeywordSelector>());
474 new (SI) MultiKeywordSelector(nKeys, IIV);
475 SelTabImpl.Table.InsertNode(SI, InsertPos);
479 SelectorTable::SelectorTable() {
480 Impl = new SelectorTableImpl();
483 SelectorTable::~SelectorTable() {
484 delete &getSelectorTableImpl(Impl);
487 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
490 case NUM_OVERLOADED_OPERATORS:
493 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
494 case OO_##Name: return Spelling;
495 #include "clang/Basic/OperatorKinds.def"