xref: /freebsd/contrib/llvm-project/clang/lib/Basic/IdentifierTable.cpp (revision 3e8eb5c7f4909209c042403ddee340b2ee7003a5)
1 //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the IdentifierInfo, IdentifierVisitor, and
10 // IdentifierTable interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/IdentifierTable.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/OperatorKinds.h"
18 #include "clang/Basic/Specifiers.h"
19 #include "clang/Basic/TargetBuiltins.h"
20 #include "clang/Basic/TokenKinds.h"
21 #include "llvm/ADT/DenseMapInfo.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cassert>
30 #include <cstdio>
31 #include <cstring>
32 #include <string>
33 
34 using namespace clang;
35 
36 // A check to make sure the ObjCOrBuiltinID has sufficient room to store the
37 // largest possible target/aux-target combination. If we exceed this, we likely
38 // need to just change the ObjCOrBuiltinIDBits value in IdentifierTable.h.
39 static_assert(2 * LargestBuiltinID < (2 << (ObjCOrBuiltinIDBits - 1)),
40               "Insufficient ObjCOrBuiltinID Bits");
41 
42 //===----------------------------------------------------------------------===//
43 // IdentifierTable Implementation
44 //===----------------------------------------------------------------------===//
45 
46 IdentifierIterator::~IdentifierIterator() = default;
47 
48 IdentifierInfoLookup::~IdentifierInfoLookup() = default;
49 
50 namespace {
51 
52 /// A simple identifier lookup iterator that represents an
53 /// empty sequence of identifiers.
54 class EmptyLookupIterator : public IdentifierIterator
55 {
56 public:
57   StringRef Next() override { return StringRef(); }
58 };
59 
60 } // namespace
61 
62 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
63   return new EmptyLookupIterator();
64 }
65 
66 IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
67     : HashTable(8192), // Start with space for 8K identifiers.
68       ExternalLookup(ExternalLookup) {}
69 
70 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
71                                  IdentifierInfoLookup *ExternalLookup)
72     : IdentifierTable(ExternalLookup) {
73   // Populate the identifier table with info about keywords for the current
74   // language.
75   AddKeywords(LangOpts);
76 }
77 
78 //===----------------------------------------------------------------------===//
79 // Language Keyword Implementation
80 //===----------------------------------------------------------------------===//
81 
82 // Constants for TokenKinds.def
83 namespace {
84 
85   enum {
86     KEYC99        = 0x1,
87     KEYCXX        = 0x2,
88     KEYCXX11      = 0x4,
89     KEYGNU        = 0x8,
90     KEYMS         = 0x10,
91     BOOLSUPPORT   = 0x20,
92     KEYALTIVEC    = 0x40,
93     KEYNOCXX      = 0x80,
94     KEYBORLAND    = 0x100,
95     KEYOPENCLC    = 0x200,
96     KEYC11        = 0x400,
97     KEYNOMS18     = 0x800,
98     KEYNOOPENCL   = 0x1000,
99     WCHARSUPPORT  = 0x2000,
100     HALFSUPPORT   = 0x4000,
101     CHAR8SUPPORT  = 0x8000,
102     KEYCONCEPTS   = 0x10000,
103     KEYOBJC       = 0x20000,
104     KEYZVECTOR    = 0x40000,
105     KEYCOROUTINES = 0x80000,
106     KEYMODULES    = 0x100000,
107     KEYCXX20      = 0x200000,
108     KEYOPENCLCXX  = 0x400000,
109     KEYMSCOMPAT   = 0x800000,
110     KEYSYCL       = 0x1000000,
111     KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
112     KEYALL = (0x1ffffff & ~KEYNOMS18 &
113               ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
114   };
115 
116   /// How a keyword is treated in the selected standard.
117   enum KeywordStatus {
118     KS_Disabled,    // Disabled
119     KS_Extension,   // Is an extension
120     KS_Enabled,     // Enabled
121     KS_Future       // Is a keyword in future standard
122   };
123 
124 } // namespace
125 
126 /// Translates flags as specified in TokenKinds.def into keyword status
127 /// in the given language standard.
128 static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
129                                       unsigned Flags) {
130   if (Flags == KEYALL) return KS_Enabled;
131   if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
132   if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
133   if (LangOpts.CPlusPlus20 && (Flags & KEYCXX20)) return KS_Enabled;
134   if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
135   if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
136   if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
137   if (LangOpts.MSVCCompat && (Flags & KEYMSCOMPAT)) return KS_Enabled;
138   if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
139   if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
140   if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
141   if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
142   if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
143   if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
144   if (LangOpts.ZVector && (Flags & KEYZVECTOR)) return KS_Enabled;
145   if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLC))
146     return KS_Enabled;
147   if (LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLCXX)) return KS_Enabled;
148   if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
149   if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
150   // We treat bridge casts as objective-C keywords so we can warn on them
151   // in non-arc mode.
152   if (LangOpts.ObjC && (Flags & KEYOBJC)) return KS_Enabled;
153   if (LangOpts.CPlusPlus20 && (Flags & KEYCONCEPTS)) return KS_Enabled;
154   if (LangOpts.Coroutines && (Flags & KEYCOROUTINES)) return KS_Enabled;
155   if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
156   if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
157   if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus20 && (Flags & CHAR8SUPPORT))
158     return KS_Future;
159   if (LangOpts.isSYCL() && (Flags & KEYSYCL))
160     return KS_Enabled;
161   return KS_Disabled;
162 }
163 
164 /// AddKeyword - This method is used to associate a token ID with specific
165 /// identifiers because they are language keywords.  This causes the lexer to
166 /// automatically map matching identifiers to specialized token codes.
167 static void AddKeyword(StringRef Keyword,
168                        tok::TokenKind TokenCode, unsigned Flags,
169                        const LangOptions &LangOpts, IdentifierTable &Table) {
170   KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
171 
172   // Don't add this keyword under MSVCCompat.
173   if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
174       !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
175     return;
176 
177   // Don't add this keyword under OpenCL.
178   if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
179     return;
180 
181   // Don't add this keyword if disabled in this language.
182   if (AddResult == KS_Disabled) return;
183 
184   IdentifierInfo &Info =
185       Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
186   Info.setIsExtensionToken(AddResult == KS_Extension);
187   Info.setIsFutureCompatKeyword(AddResult == KS_Future);
188 }
189 
190 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
191 /// representations.
192 static void AddCXXOperatorKeyword(StringRef Keyword,
193                                   tok::TokenKind TokenCode,
194                                   IdentifierTable &Table) {
195   IdentifierInfo &Info = Table.get(Keyword, TokenCode);
196   Info.setIsCPlusPlusOperatorKeyword();
197 }
198 
199 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
200 /// or "property".
201 static void AddObjCKeyword(StringRef Name,
202                            tok::ObjCKeywordKind ObjCID,
203                            IdentifierTable &Table) {
204   Table.get(Name).setObjCKeywordID(ObjCID);
205 }
206 
207 /// AddKeywords - Add all keywords to the symbol table.
208 ///
209 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
210   // Add keywords and tokens for the current language.
211 #define KEYWORD(NAME, FLAGS) \
212   AddKeyword(StringRef(#NAME), tok::kw_ ## NAME,  \
213              FLAGS, LangOpts, *this);
214 #define ALIAS(NAME, TOK, FLAGS) \
215   AddKeyword(StringRef(NAME), tok::kw_ ## TOK,  \
216              FLAGS, LangOpts, *this);
217 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
218   if (LangOpts.CXXOperatorNames)          \
219     AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
220 #define OBJC_AT_KEYWORD(NAME)  \
221   if (LangOpts.ObjC)           \
222     AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
223 #define TESTING_KEYWORD(NAME, FLAGS)
224 #include "clang/Basic/TokenKinds.def"
225 
226   if (LangOpts.ParseUnknownAnytype)
227     AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
228                LangOpts, *this);
229 
230   if (LangOpts.DeclSpecKeyword)
231     AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
232 
233   if (LangOpts.IEEE128)
234     AddKeyword("__ieee128", tok::kw___float128, KEYALL, LangOpts, *this);
235 
236   // Add the 'import' contextual keyword.
237   get("import").setModulesImport(true);
238 }
239 
240 /// Checks if the specified token kind represents a keyword in the
241 /// specified language.
242 /// \returns Status of the keyword in the language.
243 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
244                                       tok::TokenKind K) {
245   switch (K) {
246 #define KEYWORD(NAME, FLAGS) \
247   case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
248 #include "clang/Basic/TokenKinds.def"
249   default: return KS_Disabled;
250   }
251 }
252 
253 /// Returns true if the identifier represents a keyword in the
254 /// specified language.
255 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
256   switch (getTokenKwStatus(LangOpts, getTokenID())) {
257   case KS_Enabled:
258   case KS_Extension:
259     return true;
260   default:
261     return false;
262   }
263 }
264 
265 /// Returns true if the identifier represents a C++ keyword in the
266 /// specified language.
267 bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
268   if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
269     return false;
270   // This is a C++ keyword if this identifier is not a keyword when checked
271   // using LangOptions without C++ support.
272   LangOptions LangOptsNoCPP = LangOpts;
273   LangOptsNoCPP.CPlusPlus = false;
274   LangOptsNoCPP.CPlusPlus11 = false;
275   LangOptsNoCPP.CPlusPlus20 = false;
276   return !isKeyword(LangOptsNoCPP);
277 }
278 
279 ReservedIdentifierStatus
280 IdentifierInfo::isReserved(const LangOptions &LangOpts) const {
281   StringRef Name = getName();
282 
283   // '_' is a reserved identifier, but its use is so common (e.g. to store
284   // ignored values) that we don't warn on it.
285   if (Name.size() <= 1)
286     return ReservedIdentifierStatus::NotReserved;
287 
288   // [lex.name] p3
289   if (Name[0] == '_') {
290 
291     // Each name that begins with an underscore followed by an uppercase letter
292     // or another underscore is reserved.
293     if (Name[1] == '_')
294       return ReservedIdentifierStatus::StartsWithDoubleUnderscore;
295 
296     if ('A' <= Name[1] && Name[1] <= 'Z')
297       return ReservedIdentifierStatus::
298           StartsWithUnderscoreFollowedByCapitalLetter;
299 
300     // This is a bit misleading: it actually means it's only reserved if we're
301     // at global scope because it starts with an underscore.
302     return ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope;
303   }
304 
305   // Each name that contains a double underscore (__) is reserved.
306   if (LangOpts.CPlusPlus && Name.contains("__"))
307     return ReservedIdentifierStatus::ContainsDoubleUnderscore;
308 
309   return ReservedIdentifierStatus::NotReserved;
310 }
311 
312 StringRef IdentifierInfo::deuglifiedName() const {
313   StringRef Name = getName();
314   if (Name.size() >= 2 && Name.front() == '_' &&
315       (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
316     return Name.ltrim('_');
317   return Name;
318 }
319 
320 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
321   // We use a perfect hash function here involving the length of the keyword,
322   // the first and third character.  For preprocessor ID's there are no
323   // collisions (if there were, the switch below would complain about duplicate
324   // case values).  Note that this depends on 'if' being null terminated.
325 
326 #define HASH(LEN, FIRST, THIRD) \
327   (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
328 #define CASE(LEN, FIRST, THIRD, NAME) \
329   case HASH(LEN, FIRST, THIRD): \
330     return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
331 
332   unsigned Len = getLength();
333   if (Len < 2) return tok::pp_not_keyword;
334   const char *Name = getNameStart();
335   switch (HASH(Len, Name[0], Name[2])) {
336   default: return tok::pp_not_keyword;
337   CASE( 2, 'i', '\0', if);
338   CASE( 4, 'e', 'i', elif);
339   CASE( 4, 'e', 's', else);
340   CASE( 4, 'l', 'n', line);
341   CASE( 4, 's', 'c', sccs);
342   CASE( 5, 'e', 'd', endif);
343   CASE( 5, 'e', 'r', error);
344   CASE( 5, 'i', 'e', ident);
345   CASE( 5, 'i', 'd', ifdef);
346   CASE( 5, 'u', 'd', undef);
347 
348   CASE( 6, 'a', 's', assert);
349   CASE( 6, 'd', 'f', define);
350   CASE( 6, 'i', 'n', ifndef);
351   CASE( 6, 'i', 'p', import);
352   CASE( 6, 'p', 'a', pragma);
353 
354   CASE( 7, 'd', 'f', defined);
355   CASE( 7, 'e', 'i', elifdef);
356   CASE( 7, 'i', 'c', include);
357   CASE( 7, 'w', 'r', warning);
358 
359   CASE( 8, 'e', 'i', elifndef);
360   CASE( 8, 'u', 'a', unassert);
361   CASE(12, 'i', 'c', include_next);
362 
363   CASE(14, '_', 'p', __public_macro);
364 
365   CASE(15, '_', 'p', __private_macro);
366 
367   CASE(16, '_', 'i', __include_macros);
368 #undef CASE
369 #undef HASH
370   }
371 }
372 
373 //===----------------------------------------------------------------------===//
374 // Stats Implementation
375 //===----------------------------------------------------------------------===//
376 
377 /// PrintStats - Print statistics about how well the identifier table is doing
378 /// at hashing identifiers.
379 void IdentifierTable::PrintStats() const {
380   unsigned NumBuckets = HashTable.getNumBuckets();
381   unsigned NumIdentifiers = HashTable.getNumItems();
382   unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
383   unsigned AverageIdentifierSize = 0;
384   unsigned MaxIdentifierLength = 0;
385 
386   // TODO: Figure out maximum times an identifier had to probe for -stats.
387   for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
388        I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
389     unsigned IdLen = I->getKeyLength();
390     AverageIdentifierSize += IdLen;
391     if (MaxIdentifierLength < IdLen)
392       MaxIdentifierLength = IdLen;
393   }
394 
395   fprintf(stderr, "\n*** Identifier Table Stats:\n");
396   fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
397   fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
398   fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
399           NumIdentifiers/(double)NumBuckets);
400   fprintf(stderr, "Ave identifier length: %f\n",
401           (AverageIdentifierSize/(double)NumIdentifiers));
402   fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
403 
404   // Compute statistics about the memory allocated for identifiers.
405   HashTable.getAllocator().PrintStats();
406 }
407 
408 //===----------------------------------------------------------------------===//
409 // SelectorTable Implementation
410 //===----------------------------------------------------------------------===//
411 
412 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
413   return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
414 }
415 
416 namespace clang {
417 
418 /// One of these variable length records is kept for each
419 /// selector containing more than one keyword. We use a folding set
420 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
421 /// this class is provided strictly through Selector.
422 class alignas(IdentifierInfoAlignment) MultiKeywordSelector
423     : public detail::DeclarationNameExtra,
424       public llvm::FoldingSetNode {
425   MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
426 
427 public:
428   // Constructor for keyword selectors.
429   MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
430       : DeclarationNameExtra(nKeys) {
431     assert((nKeys > 1) && "not a multi-keyword selector");
432 
433     // Fill in the trailing keyword array.
434     IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
435     for (unsigned i = 0; i != nKeys; ++i)
436       KeyInfo[i] = IIV[i];
437   }
438 
439   // getName - Derive the full selector name and return it.
440   std::string getName() const;
441 
442   using DeclarationNameExtra::getNumArgs;
443 
444   using keyword_iterator = IdentifierInfo *const *;
445 
446   keyword_iterator keyword_begin() const {
447     return reinterpret_cast<keyword_iterator>(this + 1);
448   }
449 
450   keyword_iterator keyword_end() const {
451     return keyword_begin() + getNumArgs();
452   }
453 
454   IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
455     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
456     return keyword_begin()[i];
457   }
458 
459   static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
460                       unsigned NumArgs) {
461     ID.AddInteger(NumArgs);
462     for (unsigned i = 0; i != NumArgs; ++i)
463       ID.AddPointer(ArgTys[i]);
464   }
465 
466   void Profile(llvm::FoldingSetNodeID &ID) {
467     Profile(ID, keyword_begin(), getNumArgs());
468   }
469 };
470 
471 } // namespace clang.
472 
473 bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
474   assert(!Names.empty() && "must have >= 1 selector slots");
475   if (getNumArgs() != Names.size())
476     return false;
477   for (unsigned I = 0, E = Names.size(); I != E; ++I) {
478     if (getNameForSlot(I) != Names[I])
479       return false;
480   }
481   return true;
482 }
483 
484 bool Selector::isUnarySelector(StringRef Name) const {
485   return isUnarySelector() && getNameForSlot(0) == Name;
486 }
487 
488 unsigned Selector::getNumArgs() const {
489   unsigned IIF = getIdentifierInfoFlag();
490   if (IIF <= ZeroArg)
491     return 0;
492   if (IIF == OneArg)
493     return 1;
494   // We point to a MultiKeywordSelector.
495   MultiKeywordSelector *SI = getMultiKeywordSelector();
496   return SI->getNumArgs();
497 }
498 
499 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
500   if (getIdentifierInfoFlag() < MultiArg) {
501     assert(argIndex == 0 && "illegal keyword index");
502     return getAsIdentifierInfo();
503   }
504 
505   // We point to a MultiKeywordSelector.
506   MultiKeywordSelector *SI = getMultiKeywordSelector();
507   return SI->getIdentifierInfoForSlot(argIndex);
508 }
509 
510 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
511   IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
512   return II ? II->getName() : StringRef();
513 }
514 
515 std::string MultiKeywordSelector::getName() const {
516   SmallString<256> Str;
517   llvm::raw_svector_ostream OS(Str);
518   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
519     if (*I)
520       OS << (*I)->getName();
521     OS << ':';
522   }
523 
524   return std::string(OS.str());
525 }
526 
527 std::string Selector::getAsString() const {
528   if (InfoPtr == 0)
529     return "<null selector>";
530 
531   if (getIdentifierInfoFlag() < MultiArg) {
532     IdentifierInfo *II = getAsIdentifierInfo();
533 
534     if (getNumArgs() == 0) {
535       assert(II && "If the number of arguments is 0 then II is guaranteed to "
536                    "not be null.");
537       return std::string(II->getName());
538     }
539 
540     if (!II)
541       return ":";
542 
543     return II->getName().str() + ":";
544   }
545 
546   // We have a multiple keyword selector.
547   return getMultiKeywordSelector()->getName();
548 }
549 
550 void Selector::print(llvm::raw_ostream &OS) const {
551   OS << getAsString();
552 }
553 
554 LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
555 
556 /// Interpreting the given string using the normal CamelCase
557 /// conventions, determine whether the given string starts with the
558 /// given "word", which is assumed to end in a lowercase letter.
559 static bool startsWithWord(StringRef name, StringRef word) {
560   if (name.size() < word.size()) return false;
561   return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
562           name.startswith(word));
563 }
564 
565 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
566   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
567   if (!first) return OMF_None;
568 
569   StringRef name = first->getName();
570   if (sel.isUnarySelector()) {
571     if (name == "autorelease") return OMF_autorelease;
572     if (name == "dealloc") return OMF_dealloc;
573     if (name == "finalize") return OMF_finalize;
574     if (name == "release") return OMF_release;
575     if (name == "retain") return OMF_retain;
576     if (name == "retainCount") return OMF_retainCount;
577     if (name == "self") return OMF_self;
578     if (name == "initialize") return OMF_initialize;
579   }
580 
581   if (name == "performSelector" || name == "performSelectorInBackground" ||
582       name == "performSelectorOnMainThread")
583     return OMF_performSelector;
584 
585   // The other method families may begin with a prefix of underscores.
586   while (!name.empty() && name.front() == '_')
587     name = name.substr(1);
588 
589   if (name.empty()) return OMF_None;
590   switch (name.front()) {
591   case 'a':
592     if (startsWithWord(name, "alloc")) return OMF_alloc;
593     break;
594   case 'c':
595     if (startsWithWord(name, "copy")) return OMF_copy;
596     break;
597   case 'i':
598     if (startsWithWord(name, "init")) return OMF_init;
599     break;
600   case 'm':
601     if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
602     break;
603   case 'n':
604     if (startsWithWord(name, "new")) return OMF_new;
605     break;
606   default:
607     break;
608   }
609 
610   return OMF_None;
611 }
612 
613 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
614   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
615   if (!first) return OIT_None;
616 
617   StringRef name = first->getName();
618 
619   if (name.empty()) return OIT_None;
620   switch (name.front()) {
621     case 'a':
622       if (startsWithWord(name, "array")) return OIT_Array;
623       break;
624     case 'd':
625       if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
626       if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
627       break;
628     case 's':
629       if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
630       if (startsWithWord(name, "standard")) return OIT_Singleton;
631       break;
632     case 'i':
633       if (startsWithWord(name, "init")) return OIT_Init;
634       break;
635     default:
636       break;
637   }
638   return OIT_None;
639 }
640 
641 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
642   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
643   if (!first) return SFF_None;
644 
645   StringRef name = first->getName();
646 
647   switch (name.front()) {
648     case 'a':
649       if (name == "appendFormat") return SFF_NSString;
650       break;
651 
652     case 'i':
653       if (name == "initWithFormat") return SFF_NSString;
654       break;
655 
656     case 'l':
657       if (name == "localizedStringWithFormat") return SFF_NSString;
658       break;
659 
660     case 's':
661       if (name == "stringByAppendingFormat" ||
662           name == "stringWithFormat") return SFF_NSString;
663       break;
664   }
665   return SFF_None;
666 }
667 
668 namespace {
669 
670 struct SelectorTableImpl {
671   llvm::FoldingSet<MultiKeywordSelector> Table;
672   llvm::BumpPtrAllocator Allocator;
673 };
674 
675 } // namespace
676 
677 static SelectorTableImpl &getSelectorTableImpl(void *P) {
678   return *static_cast<SelectorTableImpl*>(P);
679 }
680 
681 SmallString<64>
682 SelectorTable::constructSetterName(StringRef Name) {
683   SmallString<64> SetterName("set");
684   SetterName += Name;
685   SetterName[3] = toUppercase(SetterName[3]);
686   return SetterName;
687 }
688 
689 Selector
690 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
691                                        SelectorTable &SelTable,
692                                        const IdentifierInfo *Name) {
693   IdentifierInfo *SetterName =
694     &Idents.get(constructSetterName(Name->getName()));
695   return SelTable.getUnarySelector(SetterName);
696 }
697 
698 std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
699   StringRef Name = Sel.getNameForSlot(0);
700   assert(Name.startswith("set") && "invalid setter name");
701   return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
702 }
703 
704 size_t SelectorTable::getTotalMemory() const {
705   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
706   return SelTabImpl.Allocator.getTotalMemory();
707 }
708 
709 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
710   if (nKeys < 2)
711     return Selector(IIV[0], nKeys);
712 
713   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
714 
715   // Unique selector, to guarantee there is one per name.
716   llvm::FoldingSetNodeID ID;
717   MultiKeywordSelector::Profile(ID, IIV, nKeys);
718 
719   void *InsertPos = nullptr;
720   if (MultiKeywordSelector *SI =
721         SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
722     return Selector(SI);
723 
724   // MultiKeywordSelector objects are not allocated with new because they have a
725   // variable size array (for parameter types) at the end of them.
726   unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
727   MultiKeywordSelector *SI =
728       (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
729           Size, alignof(MultiKeywordSelector));
730   new (SI) MultiKeywordSelector(nKeys, IIV);
731   SelTabImpl.Table.InsertNode(SI, InsertPos);
732   return Selector(SI);
733 }
734 
735 SelectorTable::SelectorTable() {
736   Impl = new SelectorTableImpl();
737 }
738 
739 SelectorTable::~SelectorTable() {
740   delete &getSelectorTableImpl(Impl);
741 }
742 
743 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
744   switch (Operator) {
745   case OO_None:
746   case NUM_OVERLOADED_OPERATORS:
747     return nullptr;
748 
749 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
750   case OO_##Name: return Spelling;
751 #include "clang/Basic/OperatorKinds.def"
752   }
753 
754   llvm_unreachable("Invalid OverloadedOperatorKind!");
755 }
756 
757 StringRef clang::getNullabilitySpelling(NullabilityKind kind,
758                                         bool isContextSensitive) {
759   switch (kind) {
760   case NullabilityKind::NonNull:
761     return isContextSensitive ? "nonnull" : "_Nonnull";
762 
763   case NullabilityKind::Nullable:
764     return isContextSensitive ? "nullable" : "_Nullable";
765 
766   case NullabilityKind::NullableResult:
767     assert(!isContextSensitive &&
768            "_Nullable_result isn't supported as context-sensitive keyword");
769     return "_Nullable_result";
770 
771   case NullabilityKind::Unspecified:
772     return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
773   }
774   llvm_unreachable("Unknown nullability kind.");
775 }
776