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