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/SmallString.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/ErrorHandling.h"
25 using namespace clang;
27 //===----------------------------------------------------------------------===//
28 // IdentifierInfo Implementation
29 //===----------------------------------------------------------------------===//
31 IdentifierInfo::IdentifierInfo() {
32 TokenID = tok::identifier;
36 IsCXX11CompatKeyword = false;
38 IsCPPOperatorKeyword = false;
39 NeedsHandleIdentifier = false;
41 ChangedAfterLoad = false;
42 RevertedTokenID = false;
44 IsModulesImport = false;
49 //===----------------------------------------------------------------------===//
50 // IdentifierTable Implementation
51 //===----------------------------------------------------------------------===//
53 IdentifierIterator::~IdentifierIterator() { }
55 IdentifierInfoLookup::~IdentifierInfoLookup() {}
58 /// \brief A simple identifier lookup iterator that represents an
59 /// empty sequence of identifiers.
60 class EmptyLookupIterator : public IdentifierIterator
63 virtual StringRef Next() { return StringRef(); }
67 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const {
68 return new EmptyLookupIterator();
71 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
73 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
74 IdentifierInfoLookup* externalLookup)
75 : HashTable(8192), // Start with space for 8K identifiers.
76 ExternalLookup(externalLookup) {
78 // Populate the identifier table with info about keywords for the current
80 AddKeywords(LangOpts);
83 // Add the '_experimental_modules_import' contextual keyword.
84 get("__experimental_modules_import").setModulesImport(true);
87 //===----------------------------------------------------------------------===//
88 // Language Keyword Implementation
89 //===----------------------------------------------------------------------===//
91 // Constants for TokenKinds.def
110 /// AddKeyword - This method is used to associate a token ID with specific
111 /// identifiers because they are language keywords. This causes the lexer to
112 /// automatically map matching identifiers to specialized token codes.
114 /// The C90/C99/CPP/CPP0x flags are set to 3 if the token is a keyword in a
115 /// future language standard, set to 2 if the token should be enabled in the
116 /// specified language, set to 1 if it is an extension in the specified
117 /// language, and set to 0 if disabled in the specified language.
118 static void AddKeyword(StringRef Keyword,
119 tok::TokenKind TokenCode, unsigned Flags,
120 const LangOptions &LangOpts, IdentifierTable &Table) {
121 unsigned AddResult = 0;
122 if (Flags == KEYALL) AddResult = 2;
123 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
124 else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2;
125 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
126 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1;
127 else if (LangOpts.MicrosoftExt && (Flags & KEYMS)) AddResult = 1;
128 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1;
129 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
130 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2;
131 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2;
132 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2;
133 else if (LangOpts.C11 && (Flags & KEYC11)) AddResult = 2;
134 // We treat bridge casts as objective-C keywords so we can warn on them
136 else if (LangOpts.ObjC2 && (Flags & KEYARC)) AddResult = 2;
137 else if (LangOpts.CPlusPlus && (Flags & KEYCXX0X)) AddResult = 3;
139 // Don't add this keyword if disabled in this language.
140 if (AddResult == 0) return;
142 IdentifierInfo &Info =
143 Table.get(Keyword, AddResult == 3 ? tok::identifier : TokenCode);
144 Info.setIsExtensionToken(AddResult == 1);
145 Info.setIsCXX11CompatKeyword(AddResult == 3);
148 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
150 static void AddCXXOperatorKeyword(StringRef Keyword,
151 tok::TokenKind TokenCode,
152 IdentifierTable &Table) {
153 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
154 Info.setIsCPlusPlusOperatorKeyword();
157 /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
159 static void AddObjCKeyword(StringRef Name,
160 tok::ObjCKeywordKind ObjCID,
161 IdentifierTable &Table) {
162 Table.get(Name).setObjCKeywordID(ObjCID);
165 /// AddKeywords - Add all keywords to the symbol table.
167 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
168 // Add keywords and tokens for the current language.
169 #define KEYWORD(NAME, FLAGS) \
170 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
171 FLAGS, LangOpts, *this);
172 #define ALIAS(NAME, TOK, FLAGS) \
173 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
174 FLAGS, LangOpts, *this);
175 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
176 if (LangOpts.CXXOperatorNames) \
177 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
178 #define OBJC1_AT_KEYWORD(NAME) \
179 if (LangOpts.ObjC1) \
180 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
181 #define OBJC2_AT_KEYWORD(NAME) \
182 if (LangOpts.ObjC2) \
183 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
184 #define TESTING_KEYWORD(NAME, FLAGS)
185 #include "clang/Basic/TokenKinds.def"
187 if (LangOpts.ParseUnknownAnytype)
188 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
192 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
193 // We use a perfect hash function here involving the length of the keyword,
194 // the first and third character. For preprocessor ID's there are no
195 // collisions (if there were, the switch below would complain about duplicate
196 // case values). Note that this depends on 'if' being null terminated.
198 #define HASH(LEN, FIRST, THIRD) \
199 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
200 #define CASE(LEN, FIRST, THIRD, NAME) \
201 case HASH(LEN, FIRST, THIRD): \
202 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
204 unsigned Len = getLength();
205 if (Len < 2) return tok::pp_not_keyword;
206 const char *Name = getNameStart();
207 switch (HASH(Len, Name[0], Name[2])) {
208 default: return tok::pp_not_keyword;
209 CASE( 2, 'i', '\0', if);
210 CASE( 4, 'e', 'i', elif);
211 CASE( 4, 'e', 's', else);
212 CASE( 4, 'l', 'n', line);
213 CASE( 4, 's', 'c', sccs);
214 CASE( 5, 'e', 'd', endif);
215 CASE( 5, 'e', 'r', error);
216 CASE( 5, 'i', 'e', ident);
217 CASE( 5, 'i', 'd', ifdef);
218 CASE( 5, 'u', 'd', undef);
220 CASE( 6, 'a', 's', assert);
221 CASE( 6, 'd', 'f', define);
222 CASE( 6, 'i', 'n', ifndef);
223 CASE( 6, 'i', 'p', import);
224 CASE( 6, 'p', 'a', pragma);
226 CASE( 7, 'd', 'f', defined);
227 CASE( 7, 'i', 'c', include);
228 CASE( 7, 'w', 'r', warning);
230 CASE( 8, 'u', 'a', unassert);
231 CASE(12, 'i', 'c', include_next);
233 CASE(14, '_', 'p', __public_macro);
235 CASE(15, '_', 'p', __private_macro);
237 CASE(16, '_', 'i', __include_macros);
243 //===----------------------------------------------------------------------===//
244 // Stats Implementation
245 //===----------------------------------------------------------------------===//
247 /// PrintStats - Print statistics about how well the identifier table is doing
248 /// at hashing identifiers.
249 void IdentifierTable::PrintStats() const {
250 unsigned NumBuckets = HashTable.getNumBuckets();
251 unsigned NumIdentifiers = HashTable.getNumItems();
252 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
253 unsigned AverageIdentifierSize = 0;
254 unsigned MaxIdentifierLength = 0;
256 // TODO: Figure out maximum times an identifier had to probe for -stats.
257 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
258 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
259 unsigned IdLen = I->getKeyLength();
260 AverageIdentifierSize += IdLen;
261 if (MaxIdentifierLength < IdLen)
262 MaxIdentifierLength = IdLen;
265 fprintf(stderr, "\n*** Identifier Table Stats:\n");
266 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
267 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
268 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
269 NumIdentifiers/(double)NumBuckets);
270 fprintf(stderr, "Ave identifier length: %f\n",
271 (AverageIdentifierSize/(double)NumIdentifiers));
272 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
274 // Compute statistics about the memory allocated for identifiers.
275 HashTable.getAllocator().PrintStats();
278 //===----------------------------------------------------------------------===//
279 // SelectorTable Implementation
280 //===----------------------------------------------------------------------===//
282 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
283 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
287 /// MultiKeywordSelector - One of these variable length records is kept for each
288 /// selector containing more than one keyword. We use a folding set
289 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
290 /// this class is provided strictly through Selector.
291 class MultiKeywordSelector
292 : public DeclarationNameExtra, public llvm::FoldingSetNode {
293 MultiKeywordSelector(unsigned nKeys) {
294 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
297 // Constructor for keyword selectors.
298 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
299 assert((nKeys > 1) && "not a multi-keyword selector");
300 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
302 // Fill in the trailing keyword array.
303 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
304 for (unsigned i = 0; i != nKeys; ++i)
308 // getName - Derive the full selector name and return it.
309 std::string getName() const;
311 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
313 typedef IdentifierInfo *const *keyword_iterator;
314 keyword_iterator keyword_begin() const {
315 return reinterpret_cast<keyword_iterator>(this+1);
317 keyword_iterator keyword_end() const {
318 return keyword_begin()+getNumArgs();
320 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
321 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
322 return keyword_begin()[i];
324 static void Profile(llvm::FoldingSetNodeID &ID,
325 keyword_iterator ArgTys, unsigned NumArgs) {
326 ID.AddInteger(NumArgs);
327 for (unsigned i = 0; i != NumArgs; ++i)
328 ID.AddPointer(ArgTys[i]);
330 void Profile(llvm::FoldingSetNodeID &ID) {
331 Profile(ID, keyword_begin(), getNumArgs());
334 } // end namespace clang.
336 unsigned Selector::getNumArgs() const {
337 unsigned IIF = getIdentifierInfoFlag();
342 // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
343 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
344 return SI->getNumArgs();
347 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
348 if (getIdentifierInfoFlag()) {
349 assert(argIndex == 0 && "illegal keyword index");
350 return getAsIdentifierInfo();
352 // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
353 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
354 return SI->getIdentifierInfoForSlot(argIndex);
357 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
358 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
359 return II? II->getName() : StringRef();
362 std::string MultiKeywordSelector::getName() const {
363 SmallString<256> Str;
364 llvm::raw_svector_ostream OS(Str);
365 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
367 OS << (*I)->getName();
374 std::string Selector::getAsString() const {
376 return "<null selector>";
378 if (InfoPtr & ArgFlags) {
379 IdentifierInfo *II = getAsIdentifierInfo();
381 // If the number of arguments is 0 then II is guaranteed to not be null.
382 if (getNumArgs() == 0)
383 return II->getName();
388 return II->getName().str() + ":";
391 // We have a multiple keyword selector (no embedded flags).
392 return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
395 /// Interpreting the given string using the normal CamelCase
396 /// conventions, determine whether the given string starts with the
397 /// given "word", which is assumed to end in a lowercase letter.
398 static bool startsWithWord(StringRef name, StringRef word) {
399 if (name.size() < word.size()) return false;
400 return ((name.size() == word.size() ||
401 !islower(name[word.size()]))
402 && name.startswith(word));
405 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
406 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
407 if (!first) return OMF_None;
409 StringRef name = first->getName();
410 if (sel.isUnarySelector()) {
411 if (name == "autorelease") return OMF_autorelease;
412 if (name == "dealloc") return OMF_dealloc;
413 if (name == "finalize") return OMF_finalize;
414 if (name == "release") return OMF_release;
415 if (name == "retain") return OMF_retain;
416 if (name == "retainCount") return OMF_retainCount;
417 if (name == "self") return OMF_self;
420 if (name == "performSelector") return OMF_performSelector;
422 // The other method families may begin with a prefix of underscores.
423 while (!name.empty() && name.front() == '_')
424 name = name.substr(1);
426 if (name.empty()) return OMF_None;
427 switch (name.front()) {
429 if (startsWithWord(name, "alloc")) return OMF_alloc;
432 if (startsWithWord(name, "copy")) return OMF_copy;
435 if (startsWithWord(name, "init")) return OMF_init;
438 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
441 if (startsWithWord(name, "new")) return OMF_new;
451 struct SelectorTableImpl {
452 llvm::FoldingSet<MultiKeywordSelector> Table;
453 llvm::BumpPtrAllocator Allocator;
455 } // end anonymous namespace.
457 static SelectorTableImpl &getSelectorTableImpl(void *P) {
458 return *static_cast<SelectorTableImpl*>(P);
462 SelectorTable::constructSetterName(IdentifierTable &Idents,
463 SelectorTable &SelTable,
464 const IdentifierInfo *Name) {
465 SmallString<100> SelectorName;
466 SelectorName = "set";
467 SelectorName += Name->getName();
468 SelectorName[3] = toupper(SelectorName[3]);
469 IdentifierInfo *SetterName = &Idents.get(SelectorName);
470 return SelTable.getUnarySelector(SetterName);
473 size_t SelectorTable::getTotalMemory() const {
474 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
475 return SelTabImpl.Allocator.getTotalMemory();
478 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
480 return Selector(IIV[0], nKeys);
482 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
484 // Unique selector, to guarantee there is one per name.
485 llvm::FoldingSetNodeID ID;
486 MultiKeywordSelector::Profile(ID, IIV, nKeys);
489 if (MultiKeywordSelector *SI =
490 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
493 // MultiKeywordSelector objects are not allocated with new because they have a
494 // variable size array (for parameter types) at the end of them.
495 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
496 MultiKeywordSelector *SI =
497 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
498 llvm::alignOf<MultiKeywordSelector>());
499 new (SI) MultiKeywordSelector(nKeys, IIV);
500 SelTabImpl.Table.InsertNode(SI, InsertPos);
504 SelectorTable::SelectorTable() {
505 Impl = new SelectorTableImpl();
508 SelectorTable::~SelectorTable() {
509 delete &getSelectorTableImpl(Impl);
512 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
515 case NUM_OVERLOADED_OPERATORS:
518 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
519 case OO_##Name: return Spelling;
520 #include "clang/Basic/OperatorKinds.def"
523 llvm_unreachable("Invalid OverloadedOperatorKind!");