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/CharInfo.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/OperatorKinds.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
28 //===----------------------------------------------------------------------===//
29 // IdentifierInfo Implementation
30 //===----------------------------------------------------------------------===//
32 IdentifierInfo::IdentifierInfo() {
33 TokenID = tok::identifier;
38 IsFutureCompatKeyword = false;
40 IsCPPOperatorKeyword = false;
41 NeedsHandleIdentifier = false;
43 ChangedAfterLoad = false;
44 RevertedTokenID = false;
46 IsModulesImport = false;
47 FETokenInfo = nullptr;
51 //===----------------------------------------------------------------------===//
52 // IdentifierTable Implementation
53 //===----------------------------------------------------------------------===//
55 IdentifierIterator::~IdentifierIterator() { }
57 IdentifierInfoLookup::~IdentifierInfoLookup() {}
60 /// \brief A simple identifier lookup iterator that represents an
61 /// empty sequence of identifiers.
62 class EmptyLookupIterator : public IdentifierIterator
65 StringRef Next() override { return StringRef(); }
69 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
70 return new EmptyLookupIterator();
73 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
75 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
76 IdentifierInfoLookup* externalLookup)
77 : HashTable(8192), // Start with space for 8K identifiers.
78 ExternalLookup(externalLookup) {
80 // Populate the identifier table with info about keywords for the current
82 AddKeywords(LangOpts);
85 // Add the '_experimental_modules_import' contextual keyword.
86 get("import").setModulesImport(true);
89 //===----------------------------------------------------------------------===//
90 // Language Keyword Implementation
91 //===----------------------------------------------------------------------===//
93 // Constants for TokenKinds.def
109 KEYNOOPENCL = 0x02000,
110 WCHARSUPPORT = 0x04000,
111 HALFSUPPORT = 0x08000,
112 KEYALL = (0xffff & ~KEYNOMS18 &
113 ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
116 /// \brief How a keyword is treated in the selected standard.
118 KS_Disabled, // Disabled
119 KS_Extension, // Is an extension
120 KS_Enabled, // Enabled
121 KS_Future // Is a keyword in future standard
125 /// \brief Translates flags as specified in TokenKinds.def into keyword status
126 /// in the given language standard.
127 static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
129 if (Flags == KEYALL) return KS_Enabled;
130 if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
131 if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
132 if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
133 if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
134 if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
135 if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
136 if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
137 if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
138 if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
139 if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
140 if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled;
141 if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
142 if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
143 // We treat bridge casts as objective-C keywords so we can warn on them
145 if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled;
146 if (LangOpts.CPlusPlus && (Flags & KEYCXX11)) return KS_Future;
150 /// AddKeyword - This method is used to associate a token ID with specific
151 /// identifiers because they are language keywords. This causes the lexer to
152 /// automatically map matching identifiers to specialized token codes.
153 static void AddKeyword(StringRef Keyword,
154 tok::TokenKind TokenCode, unsigned Flags,
155 const LangOptions &LangOpts, IdentifierTable &Table) {
156 KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
158 // Don't add this keyword under MSVCCompat.
159 if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
160 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
163 // Don't add this keyword under OpenCL.
164 if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
167 // Don't add this keyword if disabled in this language.
168 if (AddResult == KS_Disabled) return;
170 IdentifierInfo &Info =
171 Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
172 Info.setIsExtensionToken(AddResult == KS_Extension);
173 Info.setIsFutureCompatKeyword(AddResult == KS_Future);
176 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
178 static void AddCXXOperatorKeyword(StringRef Keyword,
179 tok::TokenKind TokenCode,
180 IdentifierTable &Table) {
181 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
182 Info.setIsCPlusPlusOperatorKeyword();
185 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
187 static void AddObjCKeyword(StringRef Name,
188 tok::ObjCKeywordKind ObjCID,
189 IdentifierTable &Table) {
190 Table.get(Name).setObjCKeywordID(ObjCID);
193 /// AddKeywords - Add all keywords to the symbol table.
195 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
196 // Add keywords and tokens for the current language.
197 #define KEYWORD(NAME, FLAGS) \
198 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
199 FLAGS, LangOpts, *this);
200 #define ALIAS(NAME, TOK, FLAGS) \
201 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
202 FLAGS, LangOpts, *this);
203 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
204 if (LangOpts.CXXOperatorNames) \
205 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
206 #define OBJC1_AT_KEYWORD(NAME) \
207 if (LangOpts.ObjC1) \
208 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
209 #define OBJC2_AT_KEYWORD(NAME) \
210 if (LangOpts.ObjC2) \
211 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
212 #define TESTING_KEYWORD(NAME, FLAGS)
213 #include "clang/Basic/TokenKinds.def"
215 if (LangOpts.ParseUnknownAnytype)
216 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
219 // FIXME: __declspec isn't really a CUDA extension, however it is required for
220 // supporting cuda_builtin_vars.h, which uses __declspec(property). Once that
221 // has been rewritten in terms of something more generic, remove this code.
223 AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
226 /// \brief Checks if the specified token kind represents a keyword in the
227 /// specified language.
228 /// \returns Status of the keyword in the language.
229 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
232 #define KEYWORD(NAME, FLAGS) \
233 case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
234 #include "clang/Basic/TokenKinds.def"
235 default: return KS_Disabled;
239 /// \brief Returns true if the identifier represents a keyword in the
240 /// specified language.
241 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) {
242 switch (getTokenKwStatus(LangOpts, getTokenID())) {
251 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
252 // We use a perfect hash function here involving the length of the keyword,
253 // the first and third character. For preprocessor ID's there are no
254 // collisions (if there were, the switch below would complain about duplicate
255 // case values). Note that this depends on 'if' being null terminated.
257 #define HASH(LEN, FIRST, THIRD) \
258 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
259 #define CASE(LEN, FIRST, THIRD, NAME) \
260 case HASH(LEN, FIRST, THIRD): \
261 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
263 unsigned Len = getLength();
264 if (Len < 2) return tok::pp_not_keyword;
265 const char *Name = getNameStart();
266 switch (HASH(Len, Name[0], Name[2])) {
267 default: return tok::pp_not_keyword;
268 CASE( 2, 'i', '\0', if);
269 CASE( 4, 'e', 'i', elif);
270 CASE( 4, 'e', 's', else);
271 CASE( 4, 'l', 'n', line);
272 CASE( 4, 's', 'c', sccs);
273 CASE( 5, 'e', 'd', endif);
274 CASE( 5, 'e', 'r', error);
275 CASE( 5, 'i', 'e', ident);
276 CASE( 5, 'i', 'd', ifdef);
277 CASE( 5, 'u', 'd', undef);
279 CASE( 6, 'a', 's', assert);
280 CASE( 6, 'd', 'f', define);
281 CASE( 6, 'i', 'n', ifndef);
282 CASE( 6, 'i', 'p', import);
283 CASE( 6, 'p', 'a', pragma);
285 CASE( 7, 'd', 'f', defined);
286 CASE( 7, 'i', 'c', include);
287 CASE( 7, 'w', 'r', warning);
289 CASE( 8, 'u', 'a', unassert);
290 CASE(12, 'i', 'c', include_next);
292 CASE(14, '_', 'p', __public_macro);
294 CASE(15, '_', 'p', __private_macro);
296 CASE(16, '_', 'i', __include_macros);
302 //===----------------------------------------------------------------------===//
303 // Stats Implementation
304 //===----------------------------------------------------------------------===//
306 /// PrintStats - Print statistics about how well the identifier table is doing
307 /// at hashing identifiers.
308 void IdentifierTable::PrintStats() const {
309 unsigned NumBuckets = HashTable.getNumBuckets();
310 unsigned NumIdentifiers = HashTable.getNumItems();
311 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
312 unsigned AverageIdentifierSize = 0;
313 unsigned MaxIdentifierLength = 0;
315 // TODO: Figure out maximum times an identifier had to probe for -stats.
316 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
317 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
318 unsigned IdLen = I->getKeyLength();
319 AverageIdentifierSize += IdLen;
320 if (MaxIdentifierLength < IdLen)
321 MaxIdentifierLength = IdLen;
324 fprintf(stderr, "\n*** Identifier Table Stats:\n");
325 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
326 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
327 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
328 NumIdentifiers/(double)NumBuckets);
329 fprintf(stderr, "Ave identifier length: %f\n",
330 (AverageIdentifierSize/(double)NumIdentifiers));
331 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
333 // Compute statistics about the memory allocated for identifiers.
334 HashTable.getAllocator().PrintStats();
337 //===----------------------------------------------------------------------===//
338 // SelectorTable Implementation
339 //===----------------------------------------------------------------------===//
341 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
342 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
346 /// MultiKeywordSelector - One of these variable length records is kept for each
347 /// selector containing more than one keyword. We use a folding set
348 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
349 /// this class is provided strictly through Selector.
350 class MultiKeywordSelector
351 : public DeclarationNameExtra, public llvm::FoldingSetNode {
352 MultiKeywordSelector(unsigned nKeys) {
353 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
356 // Constructor for keyword selectors.
357 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
358 assert((nKeys > 1) && "not a multi-keyword selector");
359 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
361 // Fill in the trailing keyword array.
362 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
363 for (unsigned i = 0; i != nKeys; ++i)
367 // getName - Derive the full selector name and return it.
368 std::string getName() const;
370 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
372 typedef IdentifierInfo *const *keyword_iterator;
373 keyword_iterator keyword_begin() const {
374 return reinterpret_cast<keyword_iterator>(this+1);
376 keyword_iterator keyword_end() const {
377 return keyword_begin()+getNumArgs();
379 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
380 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
381 return keyword_begin()[i];
383 static void Profile(llvm::FoldingSetNodeID &ID,
384 keyword_iterator ArgTys, unsigned NumArgs) {
385 ID.AddInteger(NumArgs);
386 for (unsigned i = 0; i != NumArgs; ++i)
387 ID.AddPointer(ArgTys[i]);
389 void Profile(llvm::FoldingSetNodeID &ID) {
390 Profile(ID, keyword_begin(), getNumArgs());
393 } // end namespace clang.
395 unsigned Selector::getNumArgs() const {
396 unsigned IIF = getIdentifierInfoFlag();
401 // We point to a MultiKeywordSelector.
402 MultiKeywordSelector *SI = getMultiKeywordSelector();
403 return SI->getNumArgs();
406 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
407 if (getIdentifierInfoFlag() < MultiArg) {
408 assert(argIndex == 0 && "illegal keyword index");
409 return getAsIdentifierInfo();
411 // We point to a MultiKeywordSelector.
412 MultiKeywordSelector *SI = getMultiKeywordSelector();
413 return SI->getIdentifierInfoForSlot(argIndex);
416 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
417 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
418 return II? II->getName() : StringRef();
421 std::string MultiKeywordSelector::getName() const {
422 SmallString<256> Str;
423 llvm::raw_svector_ostream OS(Str);
424 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
426 OS << (*I)->getName();
433 std::string Selector::getAsString() const {
435 return "<null selector>";
437 if (getIdentifierInfoFlag() < MultiArg) {
438 IdentifierInfo *II = getAsIdentifierInfo();
440 // If the number of arguments is 0 then II is guaranteed to not be null.
441 if (getNumArgs() == 0)
442 return II->getName();
447 return II->getName().str() + ":";
450 // We have a multiple keyword selector.
451 return getMultiKeywordSelector()->getName();
454 void Selector::print(llvm::raw_ostream &OS) const {
458 /// Interpreting the given string using the normal CamelCase
459 /// conventions, determine whether the given string starts with the
460 /// given "word", which is assumed to end in a lowercase letter.
461 static bool startsWithWord(StringRef name, StringRef word) {
462 if (name.size() < word.size()) return false;
463 return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
464 name.startswith(word));
467 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
468 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
469 if (!first) return OMF_None;
471 StringRef name = first->getName();
472 if (sel.isUnarySelector()) {
473 if (name == "autorelease") return OMF_autorelease;
474 if (name == "dealloc") return OMF_dealloc;
475 if (name == "finalize") return OMF_finalize;
476 if (name == "release") return OMF_release;
477 if (name == "retain") return OMF_retain;
478 if (name == "retainCount") return OMF_retainCount;
479 if (name == "self") return OMF_self;
480 if (name == "initialize") return OMF_initialize;
483 if (name == "performSelector") return OMF_performSelector;
485 // The other method families may begin with a prefix of underscores.
486 while (!name.empty() && name.front() == '_')
487 name = name.substr(1);
489 if (name.empty()) return OMF_None;
490 switch (name.front()) {
492 if (startsWithWord(name, "alloc")) return OMF_alloc;
495 if (startsWithWord(name, "copy")) return OMF_copy;
498 if (startsWithWord(name, "init")) return OMF_init;
501 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
504 if (startsWithWord(name, "new")) return OMF_new;
513 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
514 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
515 if (!first) return OIT_None;
517 StringRef name = first->getName();
519 if (name.empty()) return OIT_None;
520 switch (name.front()) {
522 if (startsWithWord(name, "array")) return OIT_Array;
525 if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
526 if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
529 if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
530 if (startsWithWord(name, "standard")) return OIT_Singleton;
532 if (startsWithWord(name, "init")) return OIT_Init;
539 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
540 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
541 if (!first) return SFF_None;
543 StringRef name = first->getName();
545 switch (name.front()) {
547 if (name == "appendFormat") return SFF_NSString;
551 if (name == "initWithFormat") return SFF_NSString;
555 if (name == "localizedStringWithFormat") return SFF_NSString;
559 if (name == "stringByAppendingFormat" ||
560 name == "stringWithFormat") return SFF_NSString;
567 struct SelectorTableImpl {
568 llvm::FoldingSet<MultiKeywordSelector> Table;
569 llvm::BumpPtrAllocator Allocator;
571 } // end anonymous namespace.
573 static SelectorTableImpl &getSelectorTableImpl(void *P) {
574 return *static_cast<SelectorTableImpl*>(P);
578 SelectorTable::constructSetterName(StringRef Name) {
579 SmallString<64> SetterName("set");
581 SetterName[3] = toUppercase(SetterName[3]);
586 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
587 SelectorTable &SelTable,
588 const IdentifierInfo *Name) {
589 IdentifierInfo *SetterName =
590 &Idents.get(constructSetterName(Name->getName()));
591 return SelTable.getUnarySelector(SetterName);
594 size_t SelectorTable::getTotalMemory() const {
595 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
596 return SelTabImpl.Allocator.getTotalMemory();
599 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
601 return Selector(IIV[0], nKeys);
603 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
605 // Unique selector, to guarantee there is one per name.
606 llvm::FoldingSetNodeID ID;
607 MultiKeywordSelector::Profile(ID, IIV, nKeys);
609 void *InsertPos = nullptr;
610 if (MultiKeywordSelector *SI =
611 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
614 // MultiKeywordSelector objects are not allocated with new because they have a
615 // variable size array (for parameter types) at the end of them.
616 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
617 MultiKeywordSelector *SI =
618 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
619 llvm::alignOf<MultiKeywordSelector>());
620 new (SI) MultiKeywordSelector(nKeys, IIV);
621 SelTabImpl.Table.InsertNode(SI, InsertPos);
625 SelectorTable::SelectorTable() {
626 Impl = new SelectorTableImpl();
629 SelectorTable::~SelectorTable() {
630 delete &getSelectorTableImpl(Impl);
633 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
636 case NUM_OVERLOADED_OPERATORS:
639 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
640 case OO_##Name: return Spelling;
641 #include "clang/Basic/OperatorKinds.def"
644 llvm_unreachable("Invalid OverloadedOperatorKind!");