xref: /freebsd/contrib/llvm-project/clang/include/clang/Basic/IdentifierTable.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- IdentifierTable.h - Hash table for identifier lookup -----*- C++ -*-===//
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 /// \file
10 /// Defines the clang::IdentifierInfo, clang::IdentifierTable, and
11 /// clang::Selector interfaces.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
16 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
17 
18 #include "clang/Basic/Builtins.h"
19 #include "clang/Basic/DiagnosticIDs.h"
20 #include "clang/Basic/LLVM.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/TokenKinds.h"
23 #include "llvm/ADT/DenseMapInfo.h"
24 #include "llvm/ADT/FoldingSet.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/ADT/PointerUnion.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/PointerLikeTypeTraits.h"
32 #include "llvm/Support/type_traits.h"
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <cstring>
37 #include <string>
38 #include <utility>
39 
40 namespace clang {
41 
42 class DeclarationName;
43 class DeclarationNameTable;
44 class IdentifierInfo;
45 class LangOptions;
46 class MultiKeywordSelector;
47 class SourceLocation;
48 
49 enum class ReservedIdentifierStatus {
50   NotReserved = 0,
51   StartsWithUnderscoreAtGlobalScope,
52   StartsWithUnderscoreAndIsExternC,
53   StartsWithDoubleUnderscore,
54   StartsWithUnderscoreFollowedByCapitalLetter,
55   ContainsDoubleUnderscore,
56 };
57 
58 enum class ReservedLiteralSuffixIdStatus {
59   NotReserved = 0,
60   NotStartsWithUnderscore,
61   ContainsDoubleUnderscore,
62 };
63 
64 /// Determine whether an identifier is reserved for use as a name at global
65 /// scope. Such identifiers might be implementation-specific global functions
66 /// or variables.
isReservedAtGlobalScope(ReservedIdentifierStatus Status)67 inline bool isReservedAtGlobalScope(ReservedIdentifierStatus Status) {
68   return Status != ReservedIdentifierStatus::NotReserved;
69 }
70 
71 /// Determine whether an identifier is reserved in all contexts. Such
72 /// identifiers might be implementation-specific keywords or macros, for
73 /// example.
isReservedInAllContexts(ReservedIdentifierStatus Status)74 inline bool isReservedInAllContexts(ReservedIdentifierStatus Status) {
75   return Status != ReservedIdentifierStatus::NotReserved &&
76          Status != ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope &&
77          Status != ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
78 }
79 
80 /// IdentifierInfo and other related classes are aligned to
81 /// 8 bytes so that DeclarationName can use the lower 3 bits
82 /// of a pointer to one of these classes.
83 enum { IdentifierInfoAlignment = 8 };
84 
85 static constexpr int InterestingIdentifierBits = 16;
86 
87 /// The "layout" of InterestingIdentifier is:
88 ///  - ObjCKeywordKind enumerators
89 ///  - NotableIdentifierKind enumerators
90 ///  - Builtin::ID enumerators
91 ///  - NotInterestingIdentifier
92 enum class InterestingIdentifier {
93 #define OBJC_AT_KEYWORD(X) objc_##X,
94 #include "clang/Basic/TokenKinds.def"
95   NUM_OBJC_KEYWORDS,
96 
97 #define NOTABLE_IDENTIFIER(X) X,
98 #include "clang/Basic/TokenKinds.def"
99   NUM_OBJC_KEYWORDS_AND_NOTABLE_IDENTIFIERS,
100 
101   NotBuiltin,
102 #define GET_BUILTIN_ENUMERATORS
103 #include "clang/Basic/Builtins.inc"
104 #undef GET_BUILTIN_ENUMERATORS
105   FirstTSBuiltin,
106 
107   NotInterestingIdentifier = 65534
108 };
109 
110 /// One of these records is kept for each identifier that
111 /// is lexed.  This contains information about whether the token was \#define'd,
112 /// is a language keyword, or if it is a front-end token of some sort (e.g. a
113 /// variable or function name).  The preprocessor keeps this information in a
114 /// set, and all tok::identifier tokens have a pointer to one of these.
115 /// It is aligned to 8 bytes because DeclarationName needs the lower 3 bits.
116 class alignas(IdentifierInfoAlignment) IdentifierInfo {
117   friend class IdentifierTable;
118 
119   // Front-end token ID or tok::identifier.
120   LLVM_PREFERRED_TYPE(tok::TokenKind)
121   unsigned TokenID : 9;
122 
123   LLVM_PREFERRED_TYPE(InterestingIdentifier)
124   unsigned InterestingIdentifierID : InterestingIdentifierBits;
125 
126   // True if there is a #define for this.
127   LLVM_PREFERRED_TYPE(bool)
128   unsigned HasMacro : 1;
129 
130   // True if there was a #define for this.
131   LLVM_PREFERRED_TYPE(bool)
132   unsigned HadMacro : 1;
133 
134   // True if the identifier is a language extension.
135   LLVM_PREFERRED_TYPE(bool)
136   unsigned IsExtension : 1;
137 
138   // True if the identifier is a keyword in a newer or proposed Standard.
139   LLVM_PREFERRED_TYPE(bool)
140   unsigned IsFutureCompatKeyword : 1;
141 
142   // True if the identifier is poisoned.
143   LLVM_PREFERRED_TYPE(bool)
144   unsigned IsPoisoned : 1;
145 
146   // True if the identifier is a C++ operator keyword.
147   LLVM_PREFERRED_TYPE(bool)
148   unsigned IsCPPOperatorKeyword : 1;
149 
150   // Internal bit set by the member function RecomputeNeedsHandleIdentifier.
151   // See comment about RecomputeNeedsHandleIdentifier for more info.
152   LLVM_PREFERRED_TYPE(bool)
153   unsigned NeedsHandleIdentifier : 1;
154 
155   // True if the identifier was loaded (at least partially) from an AST file.
156   LLVM_PREFERRED_TYPE(bool)
157   unsigned IsFromAST : 1;
158 
159   // True if the identifier has changed from the definition
160   // loaded from an AST file.
161   LLVM_PREFERRED_TYPE(bool)
162   unsigned ChangedAfterLoad : 1;
163 
164   // True if the identifier's frontend information has changed from the
165   // definition loaded from an AST file.
166   LLVM_PREFERRED_TYPE(bool)
167   unsigned FEChangedAfterLoad : 1;
168 
169   // True if revertTokenIDToIdentifier was called.
170   LLVM_PREFERRED_TYPE(bool)
171   unsigned RevertedTokenID : 1;
172 
173   // True if there may be additional information about
174   // this identifier stored externally.
175   LLVM_PREFERRED_TYPE(bool)
176   unsigned OutOfDate : 1;
177 
178   // True if this is the 'import' contextual keyword.
179   LLVM_PREFERRED_TYPE(bool)
180   unsigned IsModulesImport : 1;
181 
182   // True if this is a mangled OpenMP variant name.
183   LLVM_PREFERRED_TYPE(bool)
184   unsigned IsMangledOpenMPVariantName : 1;
185 
186   // True if this is a deprecated macro.
187   LLVM_PREFERRED_TYPE(bool)
188   unsigned IsDeprecatedMacro : 1;
189 
190   // True if this macro is unsafe in headers.
191   LLVM_PREFERRED_TYPE(bool)
192   unsigned IsRestrictExpansion : 1;
193 
194   // True if this macro is final.
195   LLVM_PREFERRED_TYPE(bool)
196   unsigned IsFinal : 1;
197 
198   // True if this identifier would be a keyword in C++ mode.
199   LLVM_PREFERRED_TYPE(bool)
200   unsigned IsKeywordInCpp : 1;
201 
202   // 21 bits left in a 64-bit word.
203 
204   // Managed by the language front-end.
205   void *FETokenInfo = nullptr;
206 
207   llvm::StringMapEntry<IdentifierInfo *> *Entry = nullptr;
208 
IdentifierInfo()209   IdentifierInfo()
210       : TokenID(tok::identifier),
211         InterestingIdentifierID(llvm::to_underlying(
212             InterestingIdentifier::NotInterestingIdentifier)),
213         HasMacro(false), HadMacro(false), IsExtension(false),
214         IsFutureCompatKeyword(false), IsPoisoned(false),
215         IsCPPOperatorKeyword(false), NeedsHandleIdentifier(false),
216         IsFromAST(false), ChangedAfterLoad(false), FEChangedAfterLoad(false),
217         RevertedTokenID(false), OutOfDate(false), IsModulesImport(false),
218         IsMangledOpenMPVariantName(false), IsDeprecatedMacro(false),
219         IsRestrictExpansion(false), IsFinal(false), IsKeywordInCpp(false) {}
220 
221 public:
222   IdentifierInfo(const IdentifierInfo &) = delete;
223   IdentifierInfo &operator=(const IdentifierInfo &) = delete;
224   IdentifierInfo(IdentifierInfo &&) = delete;
225   IdentifierInfo &operator=(IdentifierInfo &&) = delete;
226 
227   /// Return true if this is the identifier for the specified string.
228   ///
229   /// This is intended to be used for string literals only: II->isStr("foo").
230   template <std::size_t StrLen>
isStr(const char (& Str)[StrLen])231   bool isStr(const char (&Str)[StrLen]) const {
232     return getLength() == StrLen-1 &&
233            memcmp(getNameStart(), Str, StrLen-1) == 0;
234   }
235 
236   /// Return true if this is the identifier for the specified StringRef.
isStr(llvm::StringRef Str)237   bool isStr(llvm::StringRef Str) const {
238     llvm::StringRef ThisStr(getNameStart(), getLength());
239     return ThisStr == Str;
240   }
241 
242   /// Return the beginning of the actual null-terminated string for this
243   /// identifier.
getNameStart()244   const char *getNameStart() const { return Entry->getKeyData(); }
245 
246   /// Efficiently return the length of this identifier info.
getLength()247   unsigned getLength() const { return Entry->getKeyLength(); }
248 
249   /// Return the actual identifier string.
getName()250   StringRef getName() const {
251     return StringRef(getNameStart(), getLength());
252   }
253 
254   /// Return true if this identifier is \#defined to some other value.
255   /// \note The current definition may be in a module and not currently visible.
hasMacroDefinition()256   bool hasMacroDefinition() const {
257     return HasMacro;
258   }
setHasMacroDefinition(bool Val)259   void setHasMacroDefinition(bool Val) {
260     if (HasMacro == Val) return;
261 
262     HasMacro = Val;
263     if (Val) {
264       NeedsHandleIdentifier = true;
265       HadMacro = true;
266     } else {
267       // If this is a final macro, make the deprecation and header unsafe bits
268       // stick around after the undefinition so they apply to any redefinitions.
269       if (!IsFinal) {
270         // Because calling the setters of these calls recomputes, just set them
271         // manually to avoid recomputing a bunch of times.
272         IsDeprecatedMacro = false;
273         IsRestrictExpansion = false;
274       }
275       RecomputeNeedsHandleIdentifier();
276     }
277   }
278   /// Returns true if this identifier was \#defined to some value at any
279   /// moment. In this case there should be an entry for the identifier in the
280   /// macro history table in Preprocessor.
hadMacroDefinition()281   bool hadMacroDefinition() const {
282     return HadMacro;
283   }
284 
isDeprecatedMacro()285   bool isDeprecatedMacro() const { return IsDeprecatedMacro; }
286 
setIsDeprecatedMacro(bool Val)287   void setIsDeprecatedMacro(bool Val) {
288     if (IsDeprecatedMacro == Val)
289       return;
290     IsDeprecatedMacro = Val;
291     if (Val)
292       NeedsHandleIdentifier = true;
293     else
294       RecomputeNeedsHandleIdentifier();
295   }
296 
isRestrictExpansion()297   bool isRestrictExpansion() const { return IsRestrictExpansion; }
298 
setIsRestrictExpansion(bool Val)299   void setIsRestrictExpansion(bool Val) {
300     if (IsRestrictExpansion == Val)
301       return;
302     IsRestrictExpansion = Val;
303     if (Val)
304       NeedsHandleIdentifier = true;
305     else
306       RecomputeNeedsHandleIdentifier();
307   }
308 
isFinal()309   bool isFinal() const { return IsFinal; }
310 
setIsFinal(bool Val)311   void setIsFinal(bool Val) { IsFinal = Val; }
312 
313   /// If this is a source-language token (e.g. 'for'), this API
314   /// can be used to cause the lexer to map identifiers to source-language
315   /// tokens.
getTokenID()316   tok::TokenKind getTokenID() const { return (tok::TokenKind)TokenID; }
317 
318   /// True if revertTokenIDToIdentifier() was called.
hasRevertedTokenIDToIdentifier()319   bool hasRevertedTokenIDToIdentifier() const { return RevertedTokenID; }
320 
321   /// Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2
322   /// compatibility.
323   ///
324   /// TokenID is normally read-only but there are 2 instances where we revert it
325   /// to tok::identifier for libstdc++ 4.2. Keep track of when this happens
326   /// using this method so we can inform serialization about it.
revertTokenIDToIdentifier()327   void revertTokenIDToIdentifier() {
328     assert(TokenID != tok::identifier && "Already at tok::identifier");
329     TokenID = tok::identifier;
330     RevertedTokenID = true;
331   }
revertIdentifierToTokenID(tok::TokenKind TK)332   void revertIdentifierToTokenID(tok::TokenKind TK) {
333     assert(TokenID == tok::identifier && "Should be at tok::identifier");
334     TokenID = TK;
335     RevertedTokenID = false;
336   }
337 
338   /// Return the preprocessor keyword ID for this identifier.
339   ///
340   /// For example, "define" will return tok::pp_define.
341   tok::PPKeywordKind getPPKeywordID() const;
342 
343   /// Return the Objective-C keyword ID for the this identifier.
344   ///
345   /// For example, 'class' will return tok::objc_class if ObjC is enabled.
getObjCKeywordID()346   tok::ObjCKeywordKind getObjCKeywordID() const {
347     assert(0 == llvm::to_underlying(InterestingIdentifier::objc_not_keyword));
348     auto Value = static_cast<InterestingIdentifier>(InterestingIdentifierID);
349     if (Value < InterestingIdentifier::NUM_OBJC_KEYWORDS)
350       return static_cast<tok::ObjCKeywordKind>(InterestingIdentifierID);
351     return tok::objc_not_keyword;
352   }
setObjCKeywordID(tok::ObjCKeywordKind ID)353   void setObjCKeywordID(tok::ObjCKeywordKind ID) {
354     assert(0 == llvm::to_underlying(InterestingIdentifier::objc_not_keyword));
355     InterestingIdentifierID = ID;
356     assert(getObjCKeywordID() == ID && "ID too large for field!");
357   }
358 
359   /// Return a value indicating whether this is a builtin function.
getBuiltinID()360   unsigned getBuiltinID() const {
361     auto Value = static_cast<InterestingIdentifier>(InterestingIdentifierID);
362     if (Value >
363             InterestingIdentifier::NUM_OBJC_KEYWORDS_AND_NOTABLE_IDENTIFIERS &&
364         Value != InterestingIdentifier::NotInterestingIdentifier) {
365       auto FirstBuiltin =
366           llvm::to_underlying(InterestingIdentifier::NotBuiltin);
367       return static_cast<Builtin::ID>(InterestingIdentifierID - FirstBuiltin);
368     }
369     return Builtin::ID::NotBuiltin;
370   }
setBuiltinID(unsigned ID)371   void setBuiltinID(unsigned ID) {
372     assert(ID != Builtin::ID::NotBuiltin);
373     auto FirstBuiltin = llvm::to_underlying(InterestingIdentifier::NotBuiltin);
374     InterestingIdentifierID = ID + FirstBuiltin;
375     assert(getBuiltinID() == ID && "ID too large for field!");
376   }
clearBuiltinID()377   void clearBuiltinID() {
378     InterestingIdentifierID =
379         llvm::to_underlying(InterestingIdentifier::NotInterestingIdentifier);
380   }
381 
getNotableIdentifierID()382   tok::NotableIdentifierKind getNotableIdentifierID() const {
383     auto Value = static_cast<InterestingIdentifier>(InterestingIdentifierID);
384     if (Value > InterestingIdentifier::NUM_OBJC_KEYWORDS &&
385         Value <
386             InterestingIdentifier::NUM_OBJC_KEYWORDS_AND_NOTABLE_IDENTIFIERS) {
387       auto FirstNotableIdentifier =
388           1 + llvm::to_underlying(InterestingIdentifier::NUM_OBJC_KEYWORDS);
389       return static_cast<tok::NotableIdentifierKind>(InterestingIdentifierID -
390                                                      FirstNotableIdentifier);
391     }
392     return tok::not_notable;
393   }
setNotableIdentifierID(unsigned ID)394   void setNotableIdentifierID(unsigned ID) {
395     assert(ID != tok::not_notable);
396     auto FirstNotableIdentifier =
397         1 + llvm::to_underlying(InterestingIdentifier::NUM_OBJC_KEYWORDS);
398     InterestingIdentifierID = ID + FirstNotableIdentifier;
399     assert(getNotableIdentifierID() == ID && "ID too large for field!");
400   }
401 
getObjCOrBuiltinID()402   unsigned getObjCOrBuiltinID() const { return InterestingIdentifierID; }
setObjCOrBuiltinID(unsigned ID)403   void setObjCOrBuiltinID(unsigned ID) { InterestingIdentifierID = ID; }
404 
405   /// get/setExtension - Initialize information about whether or not this
406   /// language token is an extension.  This controls extension warnings, and is
407   /// only valid if a custom token ID is set.
isExtensionToken()408   bool isExtensionToken() const { return IsExtension; }
setIsExtensionToken(bool Val)409   void setIsExtensionToken(bool Val) {
410     IsExtension = Val;
411     if (Val)
412       NeedsHandleIdentifier = true;
413     else
414       RecomputeNeedsHandleIdentifier();
415   }
416 
417   /// is/setIsFutureCompatKeyword - Initialize information about whether or not
418   /// this language token is a keyword in a newer or proposed Standard. This
419   /// controls compatibility warnings, and is only true when not parsing the
420   /// corresponding Standard. Once a compatibility problem has been diagnosed
421   /// with this keyword, the flag will be cleared.
isFutureCompatKeyword()422   bool isFutureCompatKeyword() const { return IsFutureCompatKeyword; }
setIsFutureCompatKeyword(bool Val)423   void setIsFutureCompatKeyword(bool Val) {
424     IsFutureCompatKeyword = Val;
425     if (Val)
426       NeedsHandleIdentifier = true;
427     else
428       RecomputeNeedsHandleIdentifier();
429   }
430 
431   /// setIsPoisoned - Mark this identifier as poisoned.  After poisoning, the
432   /// Preprocessor will emit an error every time this token is used.
433   void setIsPoisoned(bool Value = true) {
434     IsPoisoned = Value;
435     if (Value)
436       NeedsHandleIdentifier = true;
437     else
438       RecomputeNeedsHandleIdentifier();
439   }
440 
441   /// Return true if this token has been poisoned.
isPoisoned()442   bool isPoisoned() const { return IsPoisoned; }
443 
444   /// isCPlusPlusOperatorKeyword/setIsCPlusPlusOperatorKeyword controls whether
445   /// this identifier is a C++ alternate representation of an operator.
446   void setIsCPlusPlusOperatorKeyword(bool Val = true) {
447     IsCPPOperatorKeyword = Val;
448   }
isCPlusPlusOperatorKeyword()449   bool isCPlusPlusOperatorKeyword() const { return IsCPPOperatorKeyword; }
450 
451   /// Return true if this identifier would be a keyword in C++ mode.
IsKeywordInCPlusPlus()452   bool IsKeywordInCPlusPlus() const { return IsKeywordInCpp; }
453   void setIsKeywordInCPlusPlus(bool Val = true) { IsKeywordInCpp = Val; }
454 
455   /// Return true if this token is a keyword in the specified language.
456   bool isKeyword(const LangOptions &LangOpts) const;
457 
458   /// Return true if this token is a C++ keyword in the specified
459   /// language.
460   bool isCPlusPlusKeyword(const LangOptions &LangOpts) const;
461 
462   /// Get and set FETokenInfo. The language front-end is allowed to associate
463   /// arbitrary metadata with this token.
getFETokenInfo()464   void *getFETokenInfo() const { return FETokenInfo; }
setFETokenInfo(void * T)465   void setFETokenInfo(void *T) { FETokenInfo = T; }
466 
467   /// Return true if the Preprocessor::HandleIdentifier must be called
468   /// on a token of this identifier.
469   ///
470   /// If this returns false, we know that HandleIdentifier will not affect
471   /// the token.
isHandleIdentifierCase()472   bool isHandleIdentifierCase() const { return NeedsHandleIdentifier; }
473   void setHandleIdentifierCase(bool Val = true) { NeedsHandleIdentifier = Val; }
474 
475   /// Return true if the identifier in its current state was loaded
476   /// from an AST file.
isFromAST()477   bool isFromAST() const { return IsFromAST; }
478 
setIsFromAST()479   void setIsFromAST() { IsFromAST = true; }
480 
481   /// Determine whether this identifier has changed since it was loaded
482   /// from an AST file.
hasChangedSinceDeserialization()483   bool hasChangedSinceDeserialization() const {
484     return ChangedAfterLoad;
485   }
486 
487   /// Note that this identifier has changed since it was loaded from
488   /// an AST file.
setChangedSinceDeserialization()489   void setChangedSinceDeserialization() {
490     ChangedAfterLoad = true;
491   }
492 
493   /// Determine whether the frontend token information for this
494   /// identifier has changed since it was loaded from an AST file.
hasFETokenInfoChangedSinceDeserialization()495   bool hasFETokenInfoChangedSinceDeserialization() const {
496     return FEChangedAfterLoad;
497   }
498 
499   /// Note that the frontend token information for this identifier has
500   /// changed since it was loaded from an AST file.
setFETokenInfoChangedSinceDeserialization()501   void setFETokenInfoChangedSinceDeserialization() {
502     FEChangedAfterLoad = true;
503   }
504 
505   /// Determine whether the information for this identifier is out of
506   /// date with respect to the external source.
isOutOfDate()507   bool isOutOfDate() const { return OutOfDate; }
508 
509   /// Set whether the information for this identifier is out of
510   /// date with respect to the external source.
setOutOfDate(bool OOD)511   void setOutOfDate(bool OOD) {
512     OutOfDate = OOD;
513     if (OOD)
514       NeedsHandleIdentifier = true;
515     else
516       RecomputeNeedsHandleIdentifier();
517   }
518 
519   /// Determine whether this is the contextual keyword \c import.
isModulesImport()520   bool isModulesImport() const { return IsModulesImport; }
521 
522   /// Set whether this identifier is the contextual keyword \c import.
setModulesImport(bool I)523   void setModulesImport(bool I) {
524     IsModulesImport = I;
525     if (I)
526       NeedsHandleIdentifier = true;
527     else
528       RecomputeNeedsHandleIdentifier();
529   }
530 
531   /// Determine whether this is the mangled name of an OpenMP variant.
isMangledOpenMPVariantName()532   bool isMangledOpenMPVariantName() const { return IsMangledOpenMPVariantName; }
533 
534   /// Set whether this is the mangled name of an OpenMP variant.
setMangledOpenMPVariantName(bool I)535   void setMangledOpenMPVariantName(bool I) { IsMangledOpenMPVariantName = I; }
536 
537   /// Return true if this identifier is an editor placeholder.
538   ///
539   /// Editor placeholders are produced by the code-completion engine and are
540   /// represented as characters between '<#' and '#>' in the source code. An
541   /// example of auto-completed call with a placeholder parameter is shown
542   /// below:
543   /// \code
544   ///   function(<#int x#>);
545   /// \endcode
isEditorPlaceholder()546   bool isEditorPlaceholder() const {
547     return getName().starts_with("<#") && getName().ends_with("#>");
548   }
549 
550   /// Determine whether \p this is a name reserved for the implementation (C99
551   /// 7.1.3, C++ [lib.global.names]).
552   ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const;
553 
554   /// Determine whether \p this is a name reserved for future standardization or
555   /// the implementation (C++ [usrlit.suffix]).
556   ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const;
557 
558   /// If the identifier is an "uglified" reserved name, return a cleaned form.
559   /// e.g. _Foo => Foo. Otherwise, just returns the name.
560   StringRef deuglifiedName() const;
isPlaceholder()561   bool isPlaceholder() const {
562     return getLength() == 1 && getNameStart()[0] == '_';
563   }
564 
565   /// Provide less than operator for lexicographical sorting.
566   bool operator<(const IdentifierInfo &RHS) const {
567     return getName() < RHS.getName();
568   }
569 
570 private:
571   /// The Preprocessor::HandleIdentifier does several special (but rare)
572   /// things to identifiers of various sorts.  For example, it changes the
573   /// \c for keyword token from tok::identifier to tok::for.
574   ///
575   /// This method is very tied to the definition of HandleIdentifier.  Any
576   /// change to it should be reflected here.
RecomputeNeedsHandleIdentifier()577   void RecomputeNeedsHandleIdentifier() {
578     NeedsHandleIdentifier = isPoisoned() || hasMacroDefinition() ||
579                             isExtensionToken() || isFutureCompatKeyword() ||
580                             isOutOfDate() || isModulesImport();
581   }
582 };
583 
584 /// An RAII object for [un]poisoning an identifier within a scope.
585 ///
586 /// \p II is allowed to be null, in which case objects of this type have
587 /// no effect.
588 class PoisonIdentifierRAIIObject {
589   IdentifierInfo *const II;
590   const bool OldValue;
591 
592 public:
PoisonIdentifierRAIIObject(IdentifierInfo * II,bool NewValue)593   PoisonIdentifierRAIIObject(IdentifierInfo *II, bool NewValue)
594     : II(II), OldValue(II ? II->isPoisoned() : false) {
595     if(II)
596       II->setIsPoisoned(NewValue);
597   }
598 
~PoisonIdentifierRAIIObject()599   ~PoisonIdentifierRAIIObject() {
600     if(II)
601       II->setIsPoisoned(OldValue);
602   }
603 };
604 
605 /// An iterator that walks over all of the known identifiers
606 /// in the lookup table.
607 ///
608 /// Since this iterator uses an abstract interface via virtual
609 /// functions, it uses an object-oriented interface rather than the
610 /// more standard C++ STL iterator interface. In this OO-style
611 /// iteration, the single function \c Next() provides dereference,
612 /// advance, and end-of-sequence checking in a single
613 /// operation. Subclasses of this iterator type will provide the
614 /// actual functionality.
615 class IdentifierIterator {
616 protected:
617   IdentifierIterator() = default;
618 
619 public:
620   IdentifierIterator(const IdentifierIterator &) = delete;
621   IdentifierIterator &operator=(const IdentifierIterator &) = delete;
622 
623   virtual ~IdentifierIterator();
624 
625   /// Retrieve the next string in the identifier table and
626   /// advances the iterator for the following string.
627   ///
628   /// \returns The next string in the identifier table. If there is
629   /// no such string, returns an empty \c StringRef.
630   virtual StringRef Next() = 0;
631 };
632 
633 /// Provides lookups to, and iteration over, IdentiferInfo objects.
634 class IdentifierInfoLookup {
635 public:
636   virtual ~IdentifierInfoLookup();
637 
638   /// Return the IdentifierInfo for the specified named identifier.
639   ///
640   /// Unlike the version in IdentifierTable, this returns a pointer instead
641   /// of a reference.  If the pointer is null then the IdentifierInfo cannot
642   /// be found.
643   virtual IdentifierInfo* get(StringRef Name) = 0;
644 
645   /// Retrieve an iterator into the set of all identifiers
646   /// known to this identifier lookup source.
647   ///
648   /// This routine provides access to all of the identifiers known to
649   /// the identifier lookup, allowing access to the contents of the
650   /// identifiers without introducing the overhead of constructing
651   /// IdentifierInfo objects for each.
652   ///
653   /// \returns A new iterator into the set of known identifiers. The
654   /// caller is responsible for deleting this iterator.
655   virtual IdentifierIterator *getIdentifiers();
656 };
657 
658 /// Implements an efficient mapping from strings to IdentifierInfo nodes.
659 ///
660 /// This has no other purpose, but this is an extremely performance-critical
661 /// piece of the code, as each occurrence of every identifier goes through
662 /// here when lexed.
663 class IdentifierTable {
664   // Shark shows that using MallocAllocator is *much* slower than using this
665   // BumpPtrAllocator!
666   using HashTableTy = llvm::StringMap<IdentifierInfo *, llvm::BumpPtrAllocator>;
667   HashTableTy HashTable;
668 
669   IdentifierInfoLookup* ExternalLookup;
670 
671 public:
672   /// Create the identifier table.
673   explicit IdentifierTable(IdentifierInfoLookup *ExternalLookup = nullptr);
674 
675   /// Create the identifier table, populating it with info about the
676   /// language keywords for the language specified by \p LangOpts.
677   explicit IdentifierTable(const LangOptions &LangOpts,
678                            IdentifierInfoLookup *ExternalLookup = nullptr);
679 
680   /// Set the external identifier lookup mechanism.
setExternalIdentifierLookup(IdentifierInfoLookup * IILookup)681   void setExternalIdentifierLookup(IdentifierInfoLookup *IILookup) {
682     ExternalLookup = IILookup;
683   }
684 
685   /// Retrieve the external identifier lookup object, if any.
getExternalIdentifierLookup()686   IdentifierInfoLookup *getExternalIdentifierLookup() const {
687     return ExternalLookup;
688   }
689 
getAllocator()690   llvm::BumpPtrAllocator& getAllocator() {
691     return HashTable.getAllocator();
692   }
693 
694   /// Return the identifier token info for the specified named
695   /// identifier.
get(StringRef Name)696   IdentifierInfo &get(StringRef Name) {
697     auto &Entry = *HashTable.try_emplace(Name, nullptr).first;
698 
699     IdentifierInfo *&II = Entry.second;
700     if (II) return *II;
701 
702     // No entry; if we have an external lookup, look there first.
703     if (ExternalLookup) {
704       II = ExternalLookup->get(Name);
705       if (II)
706         return *II;
707     }
708 
709     // Lookups failed, make a new IdentifierInfo.
710     void *Mem = getAllocator().Allocate<IdentifierInfo>();
711     II = new (Mem) IdentifierInfo();
712 
713     // Make sure getName() knows how to find the IdentifierInfo
714     // contents.
715     II->Entry = &Entry;
716 
717     return *II;
718   }
719 
get(StringRef Name,tok::TokenKind TokenCode)720   IdentifierInfo &get(StringRef Name, tok::TokenKind TokenCode) {
721     IdentifierInfo &II = get(Name);
722     II.TokenID = TokenCode;
723     assert(II.TokenID == (unsigned) TokenCode && "TokenCode too large");
724     return II;
725   }
726 
727   /// Gets an IdentifierInfo for the given name without consulting
728   ///        external sources.
729   ///
730   /// This is a version of get() meant for external sources that want to
731   /// introduce or modify an identifier. If they called get(), they would
732   /// likely end up in a recursion.
getOwn(StringRef Name)733   IdentifierInfo &getOwn(StringRef Name) {
734     auto &Entry = *HashTable.try_emplace(Name).first;
735 
736     IdentifierInfo *&II = Entry.second;
737     if (II)
738       return *II;
739 
740     // Lookups failed, make a new IdentifierInfo.
741     void *Mem = getAllocator().Allocate<IdentifierInfo>();
742     II = new (Mem) IdentifierInfo();
743 
744     // Make sure getName() knows how to find the IdentifierInfo
745     // contents.
746     II->Entry = &Entry;
747 
748     // If this is the 'import' contextual keyword, mark it as such.
749     if (Name == "import")
750       II->setModulesImport(true);
751 
752     return *II;
753   }
754 
755   using iterator = HashTableTy::const_iterator;
756   using const_iterator = HashTableTy::const_iterator;
757 
begin()758   iterator begin() const { return HashTable.begin(); }
end()759   iterator end() const   { return HashTable.end(); }
size()760   unsigned size() const  { return HashTable.size(); }
761 
find(StringRef Name)762   iterator find(StringRef Name) const { return HashTable.find(Name); }
763 
764   /// Print some statistics to stderr that indicate how well the
765   /// hashing is doing.
766   void PrintStats() const;
767 
768   /// Populate the identifier table with info about the language keywords
769   /// for the language specified by \p LangOpts.
770   void AddKeywords(const LangOptions &LangOpts);
771 
772   /// Returns the correct diagnostic to issue for a future-compat diagnostic
773   /// warning. Note, this function assumes the identifier passed has already
774   /// been determined to be a future compatible keyword.
775   diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
776                                      const LangOptions &LangOpts);
777 };
778 
779 /// A family of Objective-C methods.
780 ///
781 /// These families have no inherent meaning in the language, but are
782 /// nonetheless central enough in the existing implementations to
783 /// merit direct AST support.  While, in theory, arbitrary methods can
784 /// be considered to form families, we focus here on the methods
785 /// involving allocation and retain-count management, as these are the
786 /// most "core" and the most likely to be useful to diverse clients
787 /// without extra information.
788 ///
789 /// Both selectors and actual method declarations may be classified
790 /// into families.  Method families may impose additional restrictions
791 /// beyond their selector name; for example, a method called '_init'
792 /// that returns void is not considered to be in the 'init' family
793 /// (but would be if it returned 'id').  It is also possible to
794 /// explicitly change or remove a method's family.  Therefore the
795 /// method's family should be considered the single source of truth.
796 enum ObjCMethodFamily {
797   /// No particular method family.
798   OMF_None,
799 
800   // Selectors in these families may have arbitrary arity, may be
801   // written with arbitrary leading underscores, and may have
802   // additional CamelCase "words" in their first selector chunk
803   // following the family name.
804   OMF_alloc,
805   OMF_copy,
806   OMF_init,
807   OMF_mutableCopy,
808   OMF_new,
809 
810   // These families are singletons consisting only of the nullary
811   // selector with the given name.
812   OMF_autorelease,
813   OMF_dealloc,
814   OMF_finalize,
815   OMF_release,
816   OMF_retain,
817   OMF_retainCount,
818   OMF_self,
819   OMF_initialize,
820 
821   // performSelector families
822   OMF_performSelector
823 };
824 
825 /// Enough bits to store any enumerator in ObjCMethodFamily or
826 /// InvalidObjCMethodFamily.
827 enum { ObjCMethodFamilyBitWidth = 4 };
828 
829 /// An invalid value of ObjCMethodFamily.
830 enum { InvalidObjCMethodFamily = (1 << ObjCMethodFamilyBitWidth) - 1 };
831 
832 /// A family of Objective-C methods.
833 ///
834 /// These are family of methods whose result type is initially 'id', but
835 /// but are candidate for the result type to be changed to 'instancetype'.
836 enum ObjCInstanceTypeFamily {
837   OIT_None,
838   OIT_Array,
839   OIT_Dictionary,
840   OIT_Singleton,
841   OIT_Init,
842   OIT_ReturnsSelf
843 };
844 
845 enum ObjCStringFormatFamily {
846   SFF_None,
847   SFF_NSString,
848   SFF_CFString
849 };
850 
851 namespace detail {
852 
853 /// DeclarationNameExtra is used as a base of various uncommon special names.
854 /// This class is needed since DeclarationName has not enough space to store
855 /// the kind of every possible names. Therefore the kind of common names is
856 /// stored directly in DeclarationName, and the kind of uncommon names is
857 /// stored in DeclarationNameExtra. It is aligned to 8 bytes because
858 /// DeclarationName needs the lower 3 bits to store the kind of common names.
859 /// DeclarationNameExtra is tightly coupled to DeclarationName and any change
860 /// here is very likely to require changes in DeclarationName(Table).
861 class alignas(IdentifierInfoAlignment) DeclarationNameExtra {
862   friend class clang::DeclarationName;
863   friend class clang::DeclarationNameTable;
864 
865 protected:
866   /// The kind of "extra" information stored in the DeclarationName. See
867   /// @c ExtraKindOrNumArgs for an explanation of how these enumerator values
868   /// are used. Note that DeclarationName depends on the numerical values
869   /// of the enumerators in this enum. See DeclarationName::StoredNameKind
870   /// for more info.
871   enum ExtraKind {
872     CXXDeductionGuideName,
873     CXXLiteralOperatorName,
874     CXXUsingDirective,
875     ObjCMultiArgSelector
876   };
877 
878   /// ExtraKindOrNumArgs has one of the following meaning:
879   ///  * The kind of an uncommon C++ special name. This DeclarationNameExtra
880   ///    is in this case in fact either a CXXDeductionGuideNameExtra or
881   ///    a CXXLiteralOperatorIdName.
882   ///
883   ///  * It may be also name common to C++ using-directives (CXXUsingDirective),
884   ///
885   ///  * Otherwise it is ObjCMultiArgSelector+NumArgs, where NumArgs is
886   ///    the number of arguments in the Objective-C selector, in which
887   ///    case the DeclarationNameExtra is also a MultiKeywordSelector.
888   unsigned ExtraKindOrNumArgs;
889 
DeclarationNameExtra(ExtraKind Kind)890   DeclarationNameExtra(ExtraKind Kind) : ExtraKindOrNumArgs(Kind) {}
DeclarationNameExtra(unsigned NumArgs)891   DeclarationNameExtra(unsigned NumArgs)
892       : ExtraKindOrNumArgs(ObjCMultiArgSelector + NumArgs) {}
893 
894   /// Return the corresponding ExtraKind.
getKind()895   ExtraKind getKind() const {
896     return static_cast<ExtraKind>(ExtraKindOrNumArgs >
897                                           (unsigned)ObjCMultiArgSelector
898                                       ? (unsigned)ObjCMultiArgSelector
899                                       : ExtraKindOrNumArgs);
900   }
901 
902   /// Return the number of arguments in an ObjC selector. Only valid when this
903   /// is indeed an ObjCMultiArgSelector.
getNumArgs()904   unsigned getNumArgs() const {
905     assert(ExtraKindOrNumArgs >= (unsigned)ObjCMultiArgSelector &&
906            "getNumArgs called but this is not an ObjC selector!");
907     return ExtraKindOrNumArgs - (unsigned)ObjCMultiArgSelector;
908   }
909 };
910 
911 } // namespace detail
912 
913 /// One of these variable length records is kept for each
914 /// selector containing more than one keyword. We use a folding set
915 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
916 /// this class is provided strictly through Selector.
917 class alignas(IdentifierInfoAlignment) MultiKeywordSelector
918     : public detail::DeclarationNameExtra,
919       public llvm::FoldingSetNode {
MultiKeywordSelector(unsigned nKeys)920   MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
921 
922 public:
923   // Constructor for keyword selectors.
MultiKeywordSelector(unsigned nKeys,const IdentifierInfo ** IIV)924   MultiKeywordSelector(unsigned nKeys, const IdentifierInfo **IIV)
925       : DeclarationNameExtra(nKeys) {
926     assert((nKeys > 1) && "not a multi-keyword selector");
927 
928     // Fill in the trailing keyword array.
929     const IdentifierInfo **KeyInfo =
930         reinterpret_cast<const IdentifierInfo **>(this + 1);
931     for (unsigned i = 0; i != nKeys; ++i)
932       KeyInfo[i] = IIV[i];
933   }
934 
935   // getName - Derive the full selector name and return it.
936   std::string getName() const;
937 
938   using DeclarationNameExtra::getNumArgs;
939 
940   using keyword_iterator = const IdentifierInfo *const *;
941 
keyword_begin()942   keyword_iterator keyword_begin() const {
943     return reinterpret_cast<keyword_iterator>(this + 1);
944   }
945 
keyword_end()946   keyword_iterator keyword_end() const {
947     return keyword_begin() + getNumArgs();
948   }
949 
getIdentifierInfoForSlot(unsigned i)950   const IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
951     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
952     return keyword_begin()[i];
953   }
954 
Profile(llvm::FoldingSetNodeID & ID,keyword_iterator ArgTys,unsigned NumArgs)955   static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
956                       unsigned NumArgs) {
957     ID.AddInteger(NumArgs);
958     for (unsigned i = 0; i != NumArgs; ++i)
959       ID.AddPointer(ArgTys[i]);
960   }
961 
Profile(llvm::FoldingSetNodeID & ID)962   void Profile(llvm::FoldingSetNodeID &ID) {
963     Profile(ID, keyword_begin(), getNumArgs());
964   }
965 };
966 
967 /// Smart pointer class that efficiently represents Objective-C method
968 /// names.
969 ///
970 /// This class will either point to an IdentifierInfo or a
971 /// MultiKeywordSelector (which is private). This enables us to optimize
972 /// selectors that take no arguments and selectors that take 1 argument, which
973 /// accounts for 78% of all selectors in Cocoa.h.
974 class Selector {
975   friend class Diagnostic;
976   friend class SelectorTable; // only the SelectorTable can create these
977   friend class DeclarationName; // and the AST's DeclarationName.
978 
979   enum IdentifierInfoFlag {
980     // Empty selector = 0. Note that these enumeration values must
981     // correspond to the enumeration values of DeclarationName::StoredNameKind
982     ZeroArg = 0x01,
983     OneArg = 0x02,
984     // IMPORTANT NOTE: see comments in InfoPtr (below) about this enumerator
985     // value.
986     MultiArg = 0x07,
987   };
988 
989   /// IMPORTANT NOTE: the order of the types in this PointerUnion are
990   /// important! The DeclarationName class has bidirectional conversion
991   /// to/from Selector through an opaque pointer (void *) which corresponds
992   /// to this PointerIntPair. The discriminator bit from the PointerUnion
993   /// corresponds to the high bit in the MultiArg enumerator. So while this
994   /// PointerIntPair only has two bits for the integer (and we mask off the
995   /// high bit in `MultiArg` when it is used), that discrimator bit is
996   /// still necessary for the opaque conversion. The discriminator bit
997   /// from the PointerUnion and the two integer bits from the
998   /// PointerIntPair are also exposed via the DeclarationName::StoredNameKind
999   /// enumeration; see the comments in DeclarationName.h for more details.
1000   /// Do not reorder or add any arguments to this template
1001   /// without thoroughly understanding how tightly coupled these classes are.
1002   llvm::PointerIntPair<
1003       llvm::PointerUnion<const IdentifierInfo *, MultiKeywordSelector *>, 2>
1004       InfoPtr;
1005 
Selector(const IdentifierInfo * II,unsigned nArgs)1006   Selector(const IdentifierInfo *II, unsigned nArgs) {
1007     assert(nArgs < 2 && "nArgs not equal to 0/1");
1008     InfoPtr.setPointerAndInt(II, nArgs + 1);
1009   }
1010 
Selector(MultiKeywordSelector * SI)1011   Selector(MultiKeywordSelector *SI) {
1012     // IMPORTANT NOTE: we mask off the upper bit of this value because we only
1013     // reserve two bits for the integer in the PointerIntPair. See the comments
1014     // in `InfoPtr` for more details.
1015     InfoPtr.setPointerAndInt(SI, MultiArg & 0b11);
1016   }
1017 
getAsIdentifierInfo()1018   const IdentifierInfo *getAsIdentifierInfo() const {
1019     return dyn_cast_if_present<const IdentifierInfo *>(InfoPtr.getPointer());
1020   }
1021 
getMultiKeywordSelector()1022   MultiKeywordSelector *getMultiKeywordSelector() const {
1023     return cast<MultiKeywordSelector *>(InfoPtr.getPointer());
1024   }
1025 
getIdentifierInfoFlag()1026   unsigned getIdentifierInfoFlag() const {
1027     unsigned new_flags = InfoPtr.getInt();
1028     // IMPORTANT NOTE: We have to reconstitute this data rather than use the
1029     // value directly from the PointerIntPair. See the comments in `InfoPtr`
1030     // for more details.
1031     if (isa<MultiKeywordSelector *>(InfoPtr.getPointer()))
1032       new_flags |= MultiArg;
1033     return new_flags;
1034   }
1035 
1036   static ObjCMethodFamily getMethodFamilyImpl(Selector sel);
1037 
1038   static ObjCStringFormatFamily getStringFormatFamilyImpl(Selector sel);
1039 
1040 public:
1041   /// The default ctor should only be used when creating data structures that
1042   ///  will contain selectors.
1043   Selector() = default;
Selector(uintptr_t V)1044   explicit Selector(uintptr_t V) {
1045     InfoPtr.setFromOpaqueValue(reinterpret_cast<void *>(V));
1046   }
1047 
1048   /// operator==/!= - Indicate whether the specified selectors are identical.
1049   bool operator==(Selector RHS) const {
1050     return InfoPtr.getOpaqueValue() == RHS.InfoPtr.getOpaqueValue();
1051   }
1052   bool operator!=(Selector RHS) const {
1053     return InfoPtr.getOpaqueValue() != RHS.InfoPtr.getOpaqueValue();
1054   }
1055 
getAsOpaquePtr()1056   void *getAsOpaquePtr() const { return InfoPtr.getOpaqueValue(); }
1057 
1058   /// Determine whether this is the empty selector.
isNull()1059   bool isNull() const { return InfoPtr.getOpaqueValue() == nullptr; }
1060 
1061   // Predicates to identify the selector type.
isKeywordSelector()1062   bool isKeywordSelector() const { return InfoPtr.getInt() != ZeroArg; }
1063 
isUnarySelector()1064   bool isUnarySelector() const { return InfoPtr.getInt() == ZeroArg; }
1065 
1066   /// If this selector is the specific keyword selector described by Names.
1067   bool isKeywordSelector(ArrayRef<StringRef> Names) const;
1068 
1069   /// If this selector is the specific unary selector described by Name.
1070   bool isUnarySelector(StringRef Name) const;
1071 
1072   unsigned getNumArgs() const;
1073 
1074   /// Retrieve the identifier at a given position in the selector.
1075   ///
1076   /// Note that the identifier pointer returned may be NULL. Clients that only
1077   /// care about the text of the identifier string, and not the specific,
1078   /// uniqued identifier pointer, should use \c getNameForSlot(), which returns
1079   /// an empty string when the identifier pointer would be NULL.
1080   ///
1081   /// \param argIndex The index for which we want to retrieve the identifier.
1082   /// This index shall be less than \c getNumArgs() unless this is a keyword
1083   /// selector, in which case 0 is the only permissible value.
1084   ///
1085   /// \returns the uniqued identifier for this slot, or NULL if this slot has
1086   /// no corresponding identifier.
1087   const IdentifierInfo *getIdentifierInfoForSlot(unsigned argIndex) const;
1088 
1089   /// Retrieve the name at a given position in the selector.
1090   ///
1091   /// \param argIndex The index for which we want to retrieve the name.
1092   /// This index shall be less than \c getNumArgs() unless this is a keyword
1093   /// selector, in which case 0 is the only permissible value.
1094   ///
1095   /// \returns the name for this slot, which may be the empty string if no
1096   /// name was supplied.
1097   StringRef getNameForSlot(unsigned argIndex) const;
1098 
1099   /// Derive the full selector name (e.g. "foo:bar:") and return
1100   /// it as an std::string.
1101   std::string getAsString() const;
1102 
1103   /// Prints the full selector name (e.g. "foo:bar:").
1104   void print(llvm::raw_ostream &OS) const;
1105 
1106   void dump() const;
1107 
1108   /// Derive the conventional family of this method.
getMethodFamily()1109   ObjCMethodFamily getMethodFamily() const {
1110     return getMethodFamilyImpl(*this);
1111   }
1112 
getStringFormatFamily()1113   ObjCStringFormatFamily getStringFormatFamily() const {
1114     return getStringFormatFamilyImpl(*this);
1115   }
1116 
getEmptyMarker()1117   static Selector getEmptyMarker() {
1118     return Selector(uintptr_t(-1));
1119   }
1120 
getTombstoneMarker()1121   static Selector getTombstoneMarker() {
1122     return Selector(uintptr_t(-2));
1123   }
1124 
1125   static ObjCInstanceTypeFamily getInstTypeMethodFamily(Selector sel);
1126 };
1127 
1128 /// This table allows us to fully hide how we implement
1129 /// multi-keyword caching.
1130 class SelectorTable {
1131   // Actually a SelectorTableImpl
1132   void *Impl;
1133 
1134 public:
1135   SelectorTable();
1136   SelectorTable(const SelectorTable &) = delete;
1137   SelectorTable &operator=(const SelectorTable &) = delete;
1138   ~SelectorTable();
1139 
1140   /// Can create any sort of selector.
1141   ///
1142   /// \p NumArgs indicates whether this is a no argument selector "foo", a
1143   /// single argument selector "foo:" or multi-argument "foo:bar:".
1144   Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV);
1145 
getUnarySelector(const IdentifierInfo * ID)1146   Selector getUnarySelector(const IdentifierInfo *ID) {
1147     return Selector(ID, 1);
1148   }
1149 
getNullarySelector(const IdentifierInfo * ID)1150   Selector getNullarySelector(const IdentifierInfo *ID) {
1151     return Selector(ID, 0);
1152   }
1153 
1154   /// Return the total amount of memory allocated for managing selectors.
1155   size_t getTotalMemory() const;
1156 
1157   /// Return the default setter name for the given identifier.
1158   ///
1159   /// This is "set" + \p Name where the initial character of \p Name
1160   /// has been capitalized.
1161   static SmallString<64> constructSetterName(StringRef Name);
1162 
1163   /// Return the default setter selector for the given identifier.
1164   ///
1165   /// This is "set" + \p Name where the initial character of \p Name
1166   /// has been capitalized.
1167   static Selector constructSetterSelector(IdentifierTable &Idents,
1168                                           SelectorTable &SelTable,
1169                                           const IdentifierInfo *Name);
1170 
1171   /// Return the property name for the given setter selector.
1172   static std::string getPropertyNameFromSetterSelector(Selector Sel);
1173 };
1174 
1175 /// A simple pair of identifier info and location.
1176 class IdentifierLoc {
1177   SourceLocation Loc;
1178   IdentifierInfo *II = nullptr;
1179 
1180 public:
1181   IdentifierLoc() = default;
IdentifierLoc(SourceLocation L,IdentifierInfo * Ident)1182   IdentifierLoc(SourceLocation L, IdentifierInfo *Ident) : Loc(L), II(Ident) {}
1183 
setLoc(SourceLocation L)1184   void setLoc(SourceLocation L) { Loc = L; }
setIdentifierInfo(IdentifierInfo * Ident)1185   void setIdentifierInfo(IdentifierInfo *Ident) { II = Ident; }
getLoc()1186   SourceLocation getLoc() const { return Loc; }
getIdentifierInfo()1187   IdentifierInfo *getIdentifierInfo() const { return II; }
1188 
1189   bool operator==(const IdentifierLoc &X) const {
1190     return Loc == X.Loc && II == X.II;
1191   }
1192 
1193   bool operator!=(const IdentifierLoc &X) const {
1194     return Loc != X.Loc || II != X.II;
1195   }
1196 };
1197 }  // namespace clang
1198 
1199 namespace llvm {
1200 
1201 /// Define DenseMapInfo so that Selectors can be used as keys in DenseMap and
1202 /// DenseSets.
1203 template <>
1204 struct DenseMapInfo<clang::Selector> {
1205   static clang::Selector getEmptyKey() {
1206     return clang::Selector::getEmptyMarker();
1207   }
1208 
1209   static clang::Selector getTombstoneKey() {
1210     return clang::Selector::getTombstoneMarker();
1211   }
1212 
1213   static unsigned getHashValue(clang::Selector S);
1214 
1215   static bool isEqual(clang::Selector LHS, clang::Selector RHS) {
1216     return LHS == RHS;
1217   }
1218 };
1219 
1220 template<>
1221 struct PointerLikeTypeTraits<clang::Selector> {
1222   static const void *getAsVoidPointer(clang::Selector P) {
1223     return P.getAsOpaquePtr();
1224   }
1225 
1226   static clang::Selector getFromVoidPointer(const void *P) {
1227     return clang::Selector(reinterpret_cast<uintptr_t>(P));
1228   }
1229 
1230   static constexpr int NumLowBitsAvailable = 0;
1231 };
1232 
1233 } // namespace llvm
1234 
1235 #endif // LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
1236