1 //===--- DeclObjC.h - Classes for representing declarations -----*- C++ -*-===//
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 defines the DeclObjC interface and subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_AST_DECLOBJC_H
15 #define LLVM_CLANG_AST_DECLOBJC_H
16 
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/SelectorLocationsKind.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/Compiler.h"
21 
22 namespace clang {
23 class Expr;
24 class Stmt;
25 class FunctionDecl;
26 class RecordDecl;
27 class ObjCIvarDecl;
28 class ObjCMethodDecl;
29 class ObjCProtocolDecl;
30 class ObjCCategoryDecl;
31 class ObjCPropertyDecl;
32 class ObjCPropertyImplDecl;
33 class CXXCtorInitializer;
34 
35 class ObjCListBase {
36   ObjCListBase(const ObjCListBase &) = delete;
37   void operator=(const ObjCListBase &) = delete;
38 protected:
39   /// List is an array of pointers to objects that are not owned by this object.
40   void **List;
41   unsigned NumElts;
42 
43 public:
ObjCListBase()44   ObjCListBase() : List(nullptr), NumElts(0) {}
size()45   unsigned size() const { return NumElts; }
empty()46   bool empty() const { return NumElts == 0; }
47 
48 protected:
49   void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
50 };
51 
52 
53 /// ObjCList - This is a simple template class used to hold various lists of
54 /// decls etc, which is heavily used by the ObjC front-end.  This only use case
55 /// this supports is setting the list all at once and then reading elements out
56 /// of it.
57 template <typename T>
58 class ObjCList : public ObjCListBase {
59 public:
set(T * const * InList,unsigned Elts,ASTContext & Ctx)60   void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
61     ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
62   }
63 
64   typedef T* const * iterator;
begin()65   iterator begin() const { return (iterator)List; }
end()66   iterator end() const { return (iterator)List+NumElts; }
67 
68   T* operator[](unsigned Idx) const {
69     assert(Idx < NumElts && "Invalid access");
70     return (T*)List[Idx];
71   }
72 };
73 
74 /// \brief A list of Objective-C protocols, along with the source
75 /// locations at which they were referenced.
76 class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
77   SourceLocation *Locations;
78 
79   using ObjCList<ObjCProtocolDecl>::set;
80 
81 public:
ObjCProtocolList()82   ObjCProtocolList() : ObjCList<ObjCProtocolDecl>(), Locations(nullptr) { }
83 
84   typedef const SourceLocation *loc_iterator;
loc_begin()85   loc_iterator loc_begin() const { return Locations; }
loc_end()86   loc_iterator loc_end() const { return Locations + size(); }
87 
88   void set(ObjCProtocolDecl* const* InList, unsigned Elts,
89            const SourceLocation *Locs, ASTContext &Ctx);
90 };
91 
92 
93 /// ObjCMethodDecl - Represents an instance or class method declaration.
94 /// ObjC methods can be declared within 4 contexts: class interfaces,
95 /// categories, protocols, and class implementations. While C++ member
96 /// functions leverage C syntax, Objective-C method syntax is modeled after
97 /// Smalltalk (using colons to specify argument types/expressions).
98 /// Here are some brief examples:
99 ///
100 /// Setter/getter instance methods:
101 /// - (void)setMenu:(NSMenu *)menu;
102 /// - (NSMenu *)menu;
103 ///
104 /// Instance method that takes 2 NSView arguments:
105 /// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
106 ///
107 /// Getter class method:
108 /// + (NSMenu *)defaultMenu;
109 ///
110 /// A selector represents a unique name for a method. The selector names for
111 /// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu.
112 ///
113 class ObjCMethodDecl : public NamedDecl, public DeclContext {
114 public:
115   enum ImplementationControl { None, Required, Optional };
116 private:
117   // The conventional meaning of this method; an ObjCMethodFamily.
118   // This is not serialized; instead, it is computed on demand and
119   // cached.
120   mutable unsigned Family : ObjCMethodFamilyBitWidth;
121 
122   /// instance (true) or class (false) method.
123   unsigned IsInstance : 1;
124   unsigned IsVariadic : 1;
125 
126   /// True if this method is the getter or setter for an explicit property.
127   unsigned IsPropertyAccessor : 1;
128 
129   // Method has a definition.
130   unsigned IsDefined : 1;
131 
132   /// \brief Method redeclaration in the same interface.
133   unsigned IsRedeclaration : 1;
134 
135   /// \brief Is redeclared in the same interface.
136   mutable unsigned HasRedeclaration : 1;
137 
138   // NOTE: VC++ treats enums as signed, avoid using ImplementationControl enum
139   /// \@required/\@optional
140   unsigned DeclImplementation : 2;
141 
142   // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum
143   /// in, inout, etc.
144   unsigned objcDeclQualifier : 6;
145 
146   /// \brief Indicates whether this method has a related result type.
147   unsigned RelatedResultType : 1;
148 
149   /// \brief Whether the locations of the selector identifiers are in a
150   /// "standard" position, a enum SelectorLocationsKind.
151   unsigned SelLocsKind : 2;
152 
153   /// \brief Whether this method overrides any other in the class hierarchy.
154   ///
155   /// A method is said to override any method in the class's
156   /// base classes, its protocols, or its categories' protocols, that has
157   /// the same selector and is of the same kind (class or instance).
158   /// A method in an implementation is not considered as overriding the same
159   /// method in the interface or its categories.
160   unsigned IsOverriding : 1;
161 
162   /// \brief Indicates if the method was a definition but its body was skipped.
163   unsigned HasSkippedBody : 1;
164 
165   // Return type of this method.
166   QualType MethodDeclType;
167 
168   // Type source information for the return type.
169   TypeSourceInfo *ReturnTInfo;
170 
171   /// \brief Array of ParmVarDecls for the formal parameters of this method
172   /// and optionally followed by selector locations.
173   void *ParamsAndSelLocs;
174   unsigned NumParams;
175 
176   /// List of attributes for this method declaration.
177   SourceLocation DeclEndLoc; // the location of the ';' or '{'.
178 
179   // The following are only used for method definitions, null otherwise.
180   LazyDeclStmtPtr Body;
181 
182   /// SelfDecl - Decl for the implicit self parameter. This is lazily
183   /// constructed by createImplicitParams.
184   ImplicitParamDecl *SelfDecl;
185   /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily
186   /// constructed by createImplicitParams.
187   ImplicitParamDecl *CmdDecl;
188 
getSelLocsKind()189   SelectorLocationsKind getSelLocsKind() const {
190     return (SelectorLocationsKind)SelLocsKind;
191   }
hasStandardSelLocs()192   bool hasStandardSelLocs() const {
193     return getSelLocsKind() != SelLoc_NonStandard;
194   }
195 
196   /// \brief Get a pointer to the stored selector identifiers locations array.
197   /// No locations will be stored if HasStandardSelLocs is true.
getStoredSelLocs()198   SourceLocation *getStoredSelLocs() {
199     return reinterpret_cast<SourceLocation*>(getParams() + NumParams);
200   }
getStoredSelLocs()201   const SourceLocation *getStoredSelLocs() const {
202     return reinterpret_cast<const SourceLocation*>(getParams() + NumParams);
203   }
204 
205   /// \brief Get a pointer to the stored selector identifiers locations array.
206   /// No locations will be stored if HasStandardSelLocs is true.
getParams()207   ParmVarDecl **getParams() {
208     return reinterpret_cast<ParmVarDecl **>(ParamsAndSelLocs);
209   }
getParams()210   const ParmVarDecl *const *getParams() const {
211     return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
212   }
213 
214   /// \brief Get the number of stored selector identifiers locations.
215   /// No locations will be stored if HasStandardSelLocs is true.
getNumStoredSelLocs()216   unsigned getNumStoredSelLocs() const {
217     if (hasStandardSelLocs())
218       return 0;
219     return getNumSelectorLocs();
220   }
221 
222   void setParamsAndSelLocs(ASTContext &C,
223                            ArrayRef<ParmVarDecl*> Params,
224                            ArrayRef<SourceLocation> SelLocs);
225 
226   ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
227                  Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
228                  DeclContext *contextDecl, bool isInstance = true,
229                  bool isVariadic = false, bool isPropertyAccessor = false,
230                  bool isImplicitlyDeclared = false, bool isDefined = false,
231                  ImplementationControl impControl = None,
232                  bool HasRelatedResultType = false)
NamedDecl(ObjCMethod,contextDecl,beginLoc,SelInfo)233       : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo),
234         DeclContext(ObjCMethod), Family(InvalidObjCMethodFamily),
235         IsInstance(isInstance), IsVariadic(isVariadic),
236         IsPropertyAccessor(isPropertyAccessor), IsDefined(isDefined),
237         IsRedeclaration(0), HasRedeclaration(0), DeclImplementation(impControl),
238         objcDeclQualifier(OBJC_TQ_None),
239         RelatedResultType(HasRelatedResultType),
240         SelLocsKind(SelLoc_StandardNoSpace), IsOverriding(0), HasSkippedBody(0),
241         MethodDeclType(T), ReturnTInfo(ReturnTInfo), ParamsAndSelLocs(nullptr),
242         NumParams(0), DeclEndLoc(endLoc), Body(), SelfDecl(nullptr),
243         CmdDecl(nullptr) {
244     setImplicit(isImplicitlyDeclared);
245   }
246 
247   /// \brief A definition will return its interface declaration.
248   /// An interface declaration will return its definition.
249   /// Otherwise it will return itself.
250   ObjCMethodDecl *getNextRedeclarationImpl() override;
251 
252 public:
253   static ObjCMethodDecl *
254   Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
255          Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
256          DeclContext *contextDecl, bool isInstance = true,
257          bool isVariadic = false, bool isPropertyAccessor = false,
258          bool isImplicitlyDeclared = false, bool isDefined = false,
259          ImplementationControl impControl = None,
260          bool HasRelatedResultType = false);
261 
262   static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
263 
264   ObjCMethodDecl *getCanonicalDecl() override;
getCanonicalDecl()265   const ObjCMethodDecl *getCanonicalDecl() const {
266     return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
267   }
268 
getObjCDeclQualifier()269   ObjCDeclQualifier getObjCDeclQualifier() const {
270     return ObjCDeclQualifier(objcDeclQualifier);
271   }
setObjCDeclQualifier(ObjCDeclQualifier QV)272   void setObjCDeclQualifier(ObjCDeclQualifier QV) { objcDeclQualifier = QV; }
273 
274   /// \brief Determine whether this method has a result type that is related
275   /// to the message receiver's type.
hasRelatedResultType()276   bool hasRelatedResultType() const { return RelatedResultType; }
277 
278   /// \brief Note whether this method has a related result type.
279   void SetRelatedResultType(bool RRT = true) { RelatedResultType = RRT; }
280 
281   /// \brief True if this is a method redeclaration in the same interface.
isRedeclaration()282   bool isRedeclaration() const { return IsRedeclaration; }
283   void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
284 
285   /// \brief Returns the location where the declarator ends. It will be
286   /// the location of ';' for a method declaration and the location of '{'
287   /// for a method definition.
getDeclaratorEndLoc()288   SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
289 
290   // Location information, modeled after the Stmt API.
getLocStart()291   SourceLocation getLocStart() const LLVM_READONLY { return getLocation(); }
292   SourceLocation getLocEnd() const LLVM_READONLY;
getSourceRange()293   SourceRange getSourceRange() const override LLVM_READONLY {
294     return SourceRange(getLocation(), getLocEnd());
295   }
296 
getSelectorStartLoc()297   SourceLocation getSelectorStartLoc() const {
298     if (isImplicit())
299       return getLocStart();
300     return getSelectorLoc(0);
301   }
getSelectorLoc(unsigned Index)302   SourceLocation getSelectorLoc(unsigned Index) const {
303     assert(Index < getNumSelectorLocs() && "Index out of range!");
304     if (hasStandardSelLocs())
305       return getStandardSelectorLoc(Index, getSelector(),
306                                    getSelLocsKind() == SelLoc_StandardWithSpace,
307                                     parameters(),
308                                    DeclEndLoc);
309     return getStoredSelLocs()[Index];
310   }
311 
312   void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
313 
getNumSelectorLocs()314   unsigned getNumSelectorLocs() const {
315     if (isImplicit())
316       return 0;
317     Selector Sel = getSelector();
318     if (Sel.isUnarySelector())
319       return 1;
320     return Sel.getNumArgs();
321   }
322 
323   ObjCInterfaceDecl *getClassInterface();
getClassInterface()324   const ObjCInterfaceDecl *getClassInterface() const {
325     return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
326   }
327 
getSelector()328   Selector getSelector() const { return getDeclName().getObjCSelector(); }
329 
getReturnType()330   QualType getReturnType() const { return MethodDeclType; }
setReturnType(QualType T)331   void setReturnType(QualType T) { MethodDeclType = T; }
332   SourceRange getReturnTypeSourceRange() const;
333 
334   /// \brief Determine the type of an expression that sends a message to this
335   /// function.
getSendResultType()336   QualType getSendResultType() const {
337     return getReturnType().getNonLValueExprType(getASTContext());
338   }
339 
getReturnTypeSourceInfo()340   TypeSourceInfo *getReturnTypeSourceInfo() const { return ReturnTInfo; }
setReturnTypeSourceInfo(TypeSourceInfo * TInfo)341   void setReturnTypeSourceInfo(TypeSourceInfo *TInfo) { ReturnTInfo = TInfo; }
342 
343   // Iterator access to formal parameters.
param_size()344   unsigned param_size() const { return NumParams; }
345   typedef const ParmVarDecl *const *param_const_iterator;
346   typedef ParmVarDecl *const *param_iterator;
347   typedef llvm::iterator_range<param_iterator> param_range;
348   typedef llvm::iterator_range<param_const_iterator> param_const_range;
349 
params()350   param_range params() { return param_range(param_begin(), param_end()); }
params()351   param_const_range params() const {
352     return param_const_range(param_begin(), param_end());
353   }
354 
param_begin()355   param_const_iterator param_begin() const {
356     return param_const_iterator(getParams());
357   }
param_end()358   param_const_iterator param_end() const {
359     return param_const_iterator(getParams() + NumParams);
360   }
param_begin()361   param_iterator param_begin() { return param_iterator(getParams()); }
param_end()362   param_iterator param_end() { return param_iterator(getParams() + NumParams); }
363 
364   // This method returns and of the parameters which are part of the selector
365   // name mangling requirements.
sel_param_end()366   param_const_iterator sel_param_end() const {
367     return param_begin() + getSelector().getNumArgs();
368   }
369 
370   // ArrayRef access to formal parameters.  This should eventually
371   // replace the iterator interface above.
parameters()372   ArrayRef<ParmVarDecl*> parameters() const {
373     return llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
374                               NumParams);
375   }
376 
377   /// \brief Sets the method's parameters and selector source locations.
378   /// If the method is implicit (not coming from source) \p SelLocs is
379   /// ignored.
380   void setMethodParams(ASTContext &C,
381                        ArrayRef<ParmVarDecl*> Params,
382                        ArrayRef<SourceLocation> SelLocs = llvm::None);
383 
384   // Iterator access to parameter types.
385   typedef std::const_mem_fun_t<QualType, ParmVarDecl> deref_fun;
386   typedef llvm::mapped_iterator<param_const_iterator, deref_fun>
387   param_type_iterator;
388 
param_type_begin()389   param_type_iterator param_type_begin() const {
390     return llvm::map_iterator(param_begin(), deref_fun(&ParmVarDecl::getType));
391   }
param_type_end()392   param_type_iterator param_type_end() const {
393     return llvm::map_iterator(param_end(), deref_fun(&ParmVarDecl::getType));
394   }
395 
396   /// createImplicitParams - Used to lazily create the self and cmd
397   /// implict parameters. This must be called prior to using getSelfDecl()
398   /// or getCmdDecl(). The call is ignored if the implicit paramters
399   /// have already been created.
400   void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
401 
getSelfDecl()402   ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
setSelfDecl(ImplicitParamDecl * SD)403   void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
getCmdDecl()404   ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
setCmdDecl(ImplicitParamDecl * CD)405   void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
406 
407   /// Determines the family of this method.
408   ObjCMethodFamily getMethodFamily() const;
409 
isInstanceMethod()410   bool isInstanceMethod() const { return IsInstance; }
setInstanceMethod(bool isInst)411   void setInstanceMethod(bool isInst) { IsInstance = isInst; }
isVariadic()412   bool isVariadic() const { return IsVariadic; }
setVariadic(bool isVar)413   void setVariadic(bool isVar) { IsVariadic = isVar; }
414 
isClassMethod()415   bool isClassMethod() const { return !IsInstance; }
416 
isPropertyAccessor()417   bool isPropertyAccessor() const { return IsPropertyAccessor; }
setPropertyAccessor(bool isAccessor)418   void setPropertyAccessor(bool isAccessor) { IsPropertyAccessor = isAccessor; }
419 
isDefined()420   bool isDefined() const { return IsDefined; }
setDefined(bool isDefined)421   void setDefined(bool isDefined) { IsDefined = isDefined; }
422 
423   /// \brief Whether this method overrides any other in the class hierarchy.
424   ///
425   /// A method is said to override any method in the class's
426   /// base classes, its protocols, or its categories' protocols, that has
427   /// the same selector and is of the same kind (class or instance).
428   /// A method in an implementation is not considered as overriding the same
429   /// method in the interface or its categories.
isOverriding()430   bool isOverriding() const { return IsOverriding; }
setOverriding(bool isOverriding)431   void setOverriding(bool isOverriding) { IsOverriding = isOverriding; }
432 
433   /// \brief Return overridden methods for the given \p Method.
434   ///
435   /// An ObjC method is considered to override any method in the class's
436   /// base classes (and base's categories), its protocols, or its categories'
437   /// protocols, that has
438   /// the same selector and is of the same kind (class or instance).
439   /// A method in an implementation is not considered as overriding the same
440   /// method in the interface or its categories.
441   void getOverriddenMethods(
442                      SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
443 
444   /// \brief True if the method was a definition but its body was skipped.
hasSkippedBody()445   bool hasSkippedBody() const { return HasSkippedBody; }
446   void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
447 
448   /// \brief Returns the property associated with this method's selector.
449   ///
450   /// Note that even if this particular method is not marked as a property
451   /// accessor, it is still possible for it to match a property declared in a
452   /// superclass. Pass \c false if you only want to check the current class.
453   const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
454 
455   // Related to protocols declared in  \@protocol
setDeclImplementation(ImplementationControl ic)456   void setDeclImplementation(ImplementationControl ic) {
457     DeclImplementation = ic;
458   }
getImplementationControl()459   ImplementationControl getImplementationControl() const {
460     return ImplementationControl(DeclImplementation);
461   }
462 
463   /// Returns true if this specific method declaration is marked with the
464   /// designated initializer attribute.
465   bool isThisDeclarationADesignatedInitializer() const;
466 
467   /// Returns true if the method selector resolves to a designated initializer
468   /// in the class's interface.
469   ///
470   /// \param InitMethod if non-null and the function returns true, it receives
471   /// the method declaration that was marked with the designated initializer
472   /// attribute.
473   bool isDesignatedInitializerForTheInterface(
474       const ObjCMethodDecl **InitMethod = nullptr) const;
475 
476   /// \brief Determine whether this method has a body.
hasBody()477   bool hasBody() const override { return Body.isValid(); }
478 
479   /// \brief Retrieve the body of this method, if it has one.
480   Stmt *getBody() const override;
481 
setLazyBody(uint64_t Offset)482   void setLazyBody(uint64_t Offset) { Body = Offset; }
483 
getCompoundBody()484   CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
setBody(Stmt * B)485   void setBody(Stmt *B) { Body = B; }
486 
487   /// \brief Returns whether this specific method is a definition.
isThisDeclarationADefinition()488   bool isThisDeclarationADefinition() const { return hasBody(); }
489 
490   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)491   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)492   static bool classofKind(Kind K) { return K == ObjCMethod; }
castToDeclContext(const ObjCMethodDecl * D)493   static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
494     return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
495   }
castFromDeclContext(const DeclContext * DC)496   static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
497     return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
498   }
499 
500   friend class ASTDeclReader;
501   friend class ASTDeclWriter;
502 };
503 
504 /// ObjCContainerDecl - Represents a container for method declarations.
505 /// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
506 /// ObjCProtocolDecl, and ObjCImplDecl.
507 ///
508 class ObjCContainerDecl : public NamedDecl, public DeclContext {
509   void anchor() override;
510 
511   SourceLocation AtStart;
512 
513   // These two locations in the range mark the end of the method container.
514   // The first points to the '@' token, and the second to the 'end' token.
515   SourceRange AtEnd;
516 public:
517 
ObjCContainerDecl(Kind DK,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc)518   ObjCContainerDecl(Kind DK, DeclContext *DC,
519                     IdentifierInfo *Id, SourceLocation nameLoc,
520                     SourceLocation atStartLoc)
521     : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK), AtStart(atStartLoc) {}
522 
523   // Iterator access to properties.
524   typedef specific_decl_iterator<ObjCPropertyDecl> prop_iterator;
525   typedef llvm::iterator_range<specific_decl_iterator<ObjCPropertyDecl>>
526     prop_range;
527 
properties()528   prop_range properties() const { return prop_range(prop_begin(), prop_end()); }
prop_begin()529   prop_iterator prop_begin() const {
530     return prop_iterator(decls_begin());
531   }
prop_end()532   prop_iterator prop_end() const {
533     return prop_iterator(decls_end());
534   }
535 
536   // Iterator access to instance/class methods.
537   typedef specific_decl_iterator<ObjCMethodDecl> method_iterator;
538   typedef llvm::iterator_range<specific_decl_iterator<ObjCMethodDecl>>
539     method_range;
540 
methods()541   method_range methods() const {
542     return method_range(meth_begin(), meth_end());
543   }
meth_begin()544   method_iterator meth_begin() const {
545     return method_iterator(decls_begin());
546   }
meth_end()547   method_iterator meth_end() const {
548     return method_iterator(decls_end());
549   }
550 
551   typedef filtered_decl_iterator<ObjCMethodDecl,
552                                  &ObjCMethodDecl::isInstanceMethod>
553     instmeth_iterator;
554   typedef llvm::iterator_range<instmeth_iterator> instmeth_range;
555 
instance_methods()556   instmeth_range instance_methods() const {
557     return instmeth_range(instmeth_begin(), instmeth_end());
558   }
instmeth_begin()559   instmeth_iterator instmeth_begin() const {
560     return instmeth_iterator(decls_begin());
561   }
instmeth_end()562   instmeth_iterator instmeth_end() const {
563     return instmeth_iterator(decls_end());
564   }
565 
566   typedef filtered_decl_iterator<ObjCMethodDecl,
567                                  &ObjCMethodDecl::isClassMethod>
568     classmeth_iterator;
569   typedef llvm::iterator_range<classmeth_iterator> classmeth_range;
570 
class_methods()571   classmeth_range class_methods() const {
572     return classmeth_range(classmeth_begin(), classmeth_end());
573   }
classmeth_begin()574   classmeth_iterator classmeth_begin() const {
575     return classmeth_iterator(decls_begin());
576   }
classmeth_end()577   classmeth_iterator classmeth_end() const {
578     return classmeth_iterator(decls_end());
579   }
580 
581   // Get the local instance/class method declared in this interface.
582   ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
583                             bool AllowHidden = false) const;
584   ObjCMethodDecl *getInstanceMethod(Selector Sel,
585                                     bool AllowHidden = false) const {
586     return getMethod(Sel, true/*isInstance*/, AllowHidden);
587   }
588   ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
589     return getMethod(Sel, false/*isInstance*/, AllowHidden);
590   }
591   bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
592   ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
593 
594   ObjCPropertyDecl *
595   FindPropertyDeclaration(const IdentifierInfo *PropertyId) const;
596 
597   typedef llvm::DenseMap<IdentifierInfo*, ObjCPropertyDecl*> PropertyMap;
598 
599   typedef llvm::DenseMap<const ObjCProtocolDecl *, ObjCPropertyDecl*>
600             ProtocolPropertyMap;
601 
602   typedef llvm::SmallVector<ObjCPropertyDecl*, 8> PropertyDeclOrder;
603 
604   /// This routine collects list of properties to be implemented in the class.
605   /// This includes, class's and its conforming protocols' properties.
606   /// Note, the superclass's properties are not included in the list.
collectPropertiesToImplement(PropertyMap & PM,PropertyDeclOrder & PO)607   virtual void collectPropertiesToImplement(PropertyMap &PM,
608                                             PropertyDeclOrder &PO) const {}
609 
getAtStartLoc()610   SourceLocation getAtStartLoc() const { return AtStart; }
setAtStartLoc(SourceLocation Loc)611   void setAtStartLoc(SourceLocation Loc) { AtStart = Loc; }
612 
613   // Marks the end of the container.
getAtEndRange()614   SourceRange getAtEndRange() const {
615     return AtEnd;
616   }
setAtEndRange(SourceRange atEnd)617   void setAtEndRange(SourceRange atEnd) {
618     AtEnd = atEnd;
619   }
620 
getSourceRange()621   SourceRange getSourceRange() const override LLVM_READONLY {
622     return SourceRange(AtStart, getAtEndRange().getEnd());
623   }
624 
625   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)626   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)627   static bool classofKind(Kind K) {
628     return K >= firstObjCContainer &&
629            K <= lastObjCContainer;
630   }
631 
castToDeclContext(const ObjCContainerDecl * D)632   static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
633     return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
634   }
castFromDeclContext(const DeclContext * DC)635   static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
636     return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
637   }
638 };
639 
640 /// \brief Represents an ObjC class declaration.
641 ///
642 /// For example:
643 ///
644 /// \code
645 ///   // MostPrimitive declares no super class (not particularly useful).
646 ///   \@interface MostPrimitive
647 ///     // no instance variables or methods.
648 ///   \@end
649 ///
650 ///   // NSResponder inherits from NSObject & implements NSCoding (a protocol).
651 ///   \@interface NSResponder : NSObject \<NSCoding>
652 ///   { // instance variables are represented by ObjCIvarDecl.
653 ///     id nextResponder; // nextResponder instance variable.
654 ///   }
655 ///   - (NSResponder *)nextResponder; // return a pointer to NSResponder.
656 ///   - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
657 ///   \@end                                    // to an NSEvent.
658 /// \endcode
659 ///
660 ///   Unlike C/C++, forward class declarations are accomplished with \@class.
661 ///   Unlike C/C++, \@class allows for a list of classes to be forward declared.
662 ///   Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
663 ///   typically inherit from NSObject (an exception is NSProxy).
664 ///
665 class ObjCInterfaceDecl : public ObjCContainerDecl
666                         , public Redeclarable<ObjCInterfaceDecl> {
667   void anchor() override;
668 
669   /// TypeForDecl - This indicates the Type object that represents this
670   /// TypeDecl.  It is a cache maintained by ASTContext::getObjCInterfaceType
671   mutable const Type *TypeForDecl;
672   friend class ASTContext;
673 
674   struct DefinitionData {
675     /// \brief The definition of this class, for quick access from any
676     /// declaration.
677     ObjCInterfaceDecl *Definition;
678 
679     /// Class's super class.
680     ObjCInterfaceDecl *SuperClass;
681 
682     /// Protocols referenced in the \@interface  declaration
683     ObjCProtocolList ReferencedProtocols;
684 
685     /// Protocols reference in both the \@interface and class extensions.
686     ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
687 
688     /// \brief List of categories and class extensions defined for this class.
689     ///
690     /// Categories are stored as a linked list in the AST, since the categories
691     /// and class extensions come long after the initial interface declaration,
692     /// and we avoid dynamically-resized arrays in the AST wherever possible.
693     ObjCCategoryDecl *CategoryList;
694 
695     /// IvarList - List of all ivars defined by this class; including class
696     /// extensions and implementation. This list is built lazily.
697     ObjCIvarDecl *IvarList;
698 
699     /// \brief Indicates that the contents of this Objective-C class will be
700     /// completed by the external AST source when required.
701     mutable bool ExternallyCompleted : 1;
702 
703     /// \brief Indicates that the ivar cache does not yet include ivars
704     /// declared in the implementation.
705     mutable bool IvarListMissingImplementation : 1;
706 
707     /// Indicates that this interface decl contains at least one initializer
708     /// marked with the 'objc_designated_initializer' attribute.
709     bool HasDesignatedInitializers : 1;
710 
711     enum InheritedDesignatedInitializersState {
712       /// We didn't calculate whether the designated initializers should be
713       /// inherited or not.
714       IDI_Unknown = 0,
715       /// Designated initializers are inherited for the super class.
716       IDI_Inherited = 1,
717       /// The class does not inherit designated initializers.
718       IDI_NotInherited = 2
719     };
720     /// One of the \c InheritedDesignatedInitializersState enumeratos.
721     mutable unsigned InheritedDesignatedInitializers : 2;
722 
723     /// \brief The location of the superclass, if any.
724     SourceLocation SuperClassLoc;
725 
726     /// \brief The location of the last location in this declaration, before
727     /// the properties/methods. For example, this will be the '>', '}', or
728     /// identifier,
729     SourceLocation EndLoc;
730 
DefinitionDataDefinitionData731     DefinitionData() : Definition(), SuperClass(), CategoryList(), IvarList(),
732                        ExternallyCompleted(),
733                        IvarListMissingImplementation(true),
734                        HasDesignatedInitializers(),
735                        InheritedDesignatedInitializers(IDI_Unknown) { }
736   };
737 
738   ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, SourceLocation AtLoc,
739                     IdentifierInfo *Id, SourceLocation CLoc,
740                     ObjCInterfaceDecl *PrevDecl, bool IsInternal);
741 
742   void LoadExternalDefinition() const;
743 
744   /// \brief Contains a pointer to the data associated with this class,
745   /// which will be NULL if this class has not yet been defined.
746   ///
747   /// The bit indicates when we don't need to check for out-of-date
748   /// declarations. It will be set unless modules are enabled.
749   llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
750 
data()751   DefinitionData &data() const {
752     assert(Data.getPointer() && "Declaration has no definition!");
753     return *Data.getPointer();
754   }
755 
756   /// \brief Allocate the definition data for this class.
757   void allocateDefinitionData();
758 
759   typedef Redeclarable<ObjCInterfaceDecl> redeclarable_base;
getNextRedeclarationImpl()760   ObjCInterfaceDecl *getNextRedeclarationImpl() override {
761     return getNextRedeclaration();
762   }
getPreviousDeclImpl()763   ObjCInterfaceDecl *getPreviousDeclImpl() override {
764     return getPreviousDecl();
765   }
getMostRecentDeclImpl()766   ObjCInterfaceDecl *getMostRecentDeclImpl() override {
767     return getMostRecentDecl();
768   }
769 
770 public:
771   static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
772                                    SourceLocation atLoc,
773                                    IdentifierInfo *Id,
774                                    ObjCInterfaceDecl *PrevDecl,
775                                    SourceLocation ClassLoc = SourceLocation(),
776                                    bool isInternal = false);
777 
778   static ObjCInterfaceDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
779 
getSourceRange()780   SourceRange getSourceRange() const override LLVM_READONLY {
781     if (isThisDeclarationADefinition())
782       return ObjCContainerDecl::getSourceRange();
783 
784     return SourceRange(getAtStartLoc(), getLocation());
785   }
786 
787   /// \brief Indicate that this Objective-C class is complete, but that
788   /// the external AST source will be responsible for filling in its contents
789   /// when a complete class is required.
790   void setExternallyCompleted();
791 
792   /// Indicate that this interface decl contains at least one initializer
793   /// marked with the 'objc_designated_initializer' attribute.
794   void setHasDesignatedInitializers();
795 
796   /// Returns true if this interface decl contains at least one initializer
797   /// marked with the 'objc_designated_initializer' attribute.
798   bool hasDesignatedInitializers() const;
799 
800   /// Returns true if this interface decl declares a designated initializer
801   /// or it inherites one from its super class.
declaresOrInheritsDesignatedInitializers()802   bool declaresOrInheritsDesignatedInitializers() const {
803     return hasDesignatedInitializers() || inheritsDesignatedInitializers();
804   }
805 
getReferencedProtocols()806   const ObjCProtocolList &getReferencedProtocols() const {
807     assert(hasDefinition() && "Caller did not check for forward reference!");
808     if (data().ExternallyCompleted)
809       LoadExternalDefinition();
810 
811     return data().ReferencedProtocols;
812   }
813 
814   ObjCImplementationDecl *getImplementation() const;
815   void setImplementation(ObjCImplementationDecl *ImplD);
816 
817   ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
818 
819   // Get the local instance/class method declared in a category.
820   ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
821   ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
getCategoryMethod(Selector Sel,bool isInstance)822   ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
823     return isInstance ? getCategoryInstanceMethod(Sel)
824                       : getCategoryClassMethod(Sel);
825   }
826 
827   typedef ObjCProtocolList::iterator protocol_iterator;
828   typedef llvm::iterator_range<protocol_iterator> protocol_range;
829 
protocols()830   protocol_range protocols() const {
831     return protocol_range(protocol_begin(), protocol_end());
832   }
protocol_begin()833   protocol_iterator protocol_begin() const {
834     // FIXME: Should make sure no callers ever do this.
835     if (!hasDefinition())
836       return protocol_iterator();
837 
838     if (data().ExternallyCompleted)
839       LoadExternalDefinition();
840 
841     return data().ReferencedProtocols.begin();
842   }
protocol_end()843   protocol_iterator protocol_end() const {
844     // FIXME: Should make sure no callers ever do this.
845     if (!hasDefinition())
846       return protocol_iterator();
847 
848     if (data().ExternallyCompleted)
849       LoadExternalDefinition();
850 
851     return data().ReferencedProtocols.end();
852   }
853 
854   typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
855   typedef llvm::iterator_range<protocol_loc_iterator> protocol_loc_range;
856 
protocol_locs()857   protocol_loc_range protocol_locs() const {
858     return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
859   }
protocol_loc_begin()860   protocol_loc_iterator protocol_loc_begin() const {
861     // FIXME: Should make sure no callers ever do this.
862     if (!hasDefinition())
863       return protocol_loc_iterator();
864 
865     if (data().ExternallyCompleted)
866       LoadExternalDefinition();
867 
868     return data().ReferencedProtocols.loc_begin();
869   }
870 
protocol_loc_end()871   protocol_loc_iterator protocol_loc_end() const {
872     // FIXME: Should make sure no callers ever do this.
873     if (!hasDefinition())
874       return protocol_loc_iterator();
875 
876     if (data().ExternallyCompleted)
877       LoadExternalDefinition();
878 
879     return data().ReferencedProtocols.loc_end();
880   }
881 
882   typedef ObjCList<ObjCProtocolDecl>::iterator all_protocol_iterator;
883   typedef llvm::iterator_range<all_protocol_iterator> all_protocol_range;
884 
all_referenced_protocols()885   all_protocol_range all_referenced_protocols() const {
886     return all_protocol_range(all_referenced_protocol_begin(),
887                               all_referenced_protocol_end());
888   }
all_referenced_protocol_begin()889   all_protocol_iterator all_referenced_protocol_begin() const {
890     // FIXME: Should make sure no callers ever do this.
891     if (!hasDefinition())
892       return all_protocol_iterator();
893 
894     if (data().ExternallyCompleted)
895       LoadExternalDefinition();
896 
897     return data().AllReferencedProtocols.empty()
898              ? protocol_begin()
899              : data().AllReferencedProtocols.begin();
900   }
all_referenced_protocol_end()901   all_protocol_iterator all_referenced_protocol_end() const {
902     // FIXME: Should make sure no callers ever do this.
903     if (!hasDefinition())
904       return all_protocol_iterator();
905 
906     if (data().ExternallyCompleted)
907       LoadExternalDefinition();
908 
909     return data().AllReferencedProtocols.empty()
910              ? protocol_end()
911              : data().AllReferencedProtocols.end();
912   }
913 
914   typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
915   typedef llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>> ivar_range;
916 
ivars()917   ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
ivar_begin()918   ivar_iterator ivar_begin() const {
919     if (const ObjCInterfaceDecl *Def = getDefinition())
920       return ivar_iterator(Def->decls_begin());
921 
922     // FIXME: Should make sure no callers ever do this.
923     return ivar_iterator();
924   }
ivar_end()925   ivar_iterator ivar_end() const {
926     if (const ObjCInterfaceDecl *Def = getDefinition())
927       return ivar_iterator(Def->decls_end());
928 
929     // FIXME: Should make sure no callers ever do this.
930     return ivar_iterator();
931   }
932 
ivar_size()933   unsigned ivar_size() const {
934     return std::distance(ivar_begin(), ivar_end());
935   }
936 
ivar_empty()937   bool ivar_empty() const { return ivar_begin() == ivar_end(); }
938 
939   ObjCIvarDecl *all_declared_ivar_begin();
all_declared_ivar_begin()940   const ObjCIvarDecl *all_declared_ivar_begin() const {
941     // Even though this modifies IvarList, it's conceptually const:
942     // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
943     return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
944   }
setIvarList(ObjCIvarDecl * ivar)945   void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
946 
947   /// setProtocolList - Set the list of protocols that this interface
948   /// implements.
setProtocolList(ObjCProtocolDecl * const * List,unsigned Num,const SourceLocation * Locs,ASTContext & C)949   void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
950                        const SourceLocation *Locs, ASTContext &C) {
951     data().ReferencedProtocols.set(List, Num, Locs, C);
952   }
953 
954   /// mergeClassExtensionProtocolList - Merge class extension's protocol list
955   /// into the protocol list for this class.
956   void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
957                                        unsigned Num,
958                                        ASTContext &C);
959 
960   /// Produce a name to be used for class's metadata. It comes either via
961   /// objc_runtime_name attribute or class name.
962   StringRef getObjCRuntimeNameAsString() const;
963 
964   /// Returns the designated initializers for the interface.
965   ///
966   /// If this declaration does not have methods marked as designated
967   /// initializers then the interface inherits the designated initializers of
968   /// its super class.
969   void getDesignatedInitializers(
970                   llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const;
971 
972   /// Returns true if the given selector is a designated initializer for the
973   /// interface.
974   ///
975   /// If this declaration does not have methods marked as designated
976   /// initializers then the interface inherits the designated initializers of
977   /// its super class.
978   ///
979   /// \param InitMethod if non-null and the function returns true, it receives
980   /// the method that was marked as a designated initializer.
981   bool
982   isDesignatedInitializer(Selector Sel,
983                           const ObjCMethodDecl **InitMethod = nullptr) const;
984 
985   /// \brief Determine whether this particular declaration of this class is
986   /// actually also a definition.
isThisDeclarationADefinition()987   bool isThisDeclarationADefinition() const {
988     return getDefinition() == this;
989   }
990 
991   /// \brief Determine whether this class has been defined.
hasDefinition()992   bool hasDefinition() const {
993     // If the name of this class is out-of-date, bring it up-to-date, which
994     // might bring in a definition.
995     // Note: a null value indicates that we don't have a definition and that
996     // modules are enabled.
997     if (!Data.getOpaqueValue()) {
998       if (IdentifierInfo *II = getIdentifier()) {
999         if (II->isOutOfDate()) {
1000           updateOutOfDate(*II);
1001         }
1002       }
1003     }
1004 
1005     return Data.getPointer();
1006   }
1007 
1008   /// \brief Retrieve the definition of this class, or NULL if this class
1009   /// has been forward-declared (with \@class) but not yet defined (with
1010   /// \@interface).
getDefinition()1011   ObjCInterfaceDecl *getDefinition() {
1012     return hasDefinition()? Data.getPointer()->Definition : nullptr;
1013   }
1014 
1015   /// \brief Retrieve the definition of this class, or NULL if this class
1016   /// has been forward-declared (with \@class) but not yet defined (with
1017   /// \@interface).
getDefinition()1018   const ObjCInterfaceDecl *getDefinition() const {
1019     return hasDefinition()? Data.getPointer()->Definition : nullptr;
1020   }
1021 
1022   /// \brief Starts the definition of this Objective-C class, taking it from
1023   /// a forward declaration (\@class) to a definition (\@interface).
1024   void startDefinition();
1025 
getSuperClass()1026   ObjCInterfaceDecl *getSuperClass() const {
1027     // FIXME: Should make sure no callers ever do this.
1028     if (!hasDefinition())
1029       return nullptr;
1030 
1031     if (data().ExternallyCompleted)
1032       LoadExternalDefinition();
1033 
1034     return data().SuperClass;
1035   }
1036 
setSuperClass(ObjCInterfaceDecl * superCls)1037   void setSuperClass(ObjCInterfaceDecl * superCls) {
1038     data().SuperClass =
1039       (superCls && superCls->hasDefinition()) ? superCls->getDefinition()
1040                                               : superCls;
1041   }
1042 
1043   /// \brief Iterator that walks over the list of categories, filtering out
1044   /// those that do not meet specific criteria.
1045   ///
1046   /// This class template is used for the various permutations of category
1047   /// and extension iterators.
1048   template<bool (*Filter)(ObjCCategoryDecl *)>
1049   class filtered_category_iterator {
1050     ObjCCategoryDecl *Current;
1051 
1052     void findAcceptableCategory();
1053 
1054   public:
1055     typedef ObjCCategoryDecl *      value_type;
1056     typedef value_type              reference;
1057     typedef value_type              pointer;
1058     typedef std::ptrdiff_t          difference_type;
1059     typedef std::input_iterator_tag iterator_category;
1060 
filtered_category_iterator()1061     filtered_category_iterator() : Current(nullptr) { }
filtered_category_iterator(ObjCCategoryDecl * Current)1062     explicit filtered_category_iterator(ObjCCategoryDecl *Current)
1063       : Current(Current)
1064     {
1065       findAcceptableCategory();
1066     }
1067 
1068     reference operator*() const { return Current; }
1069     pointer operator->() const { return Current; }
1070 
1071     filtered_category_iterator &operator++();
1072 
1073     filtered_category_iterator operator++(int) {
1074       filtered_category_iterator Tmp = *this;
1075       ++(*this);
1076       return Tmp;
1077     }
1078 
1079     friend bool operator==(filtered_category_iterator X,
1080                            filtered_category_iterator Y) {
1081       return X.Current == Y.Current;
1082     }
1083 
1084     friend bool operator!=(filtered_category_iterator X,
1085                            filtered_category_iterator Y) {
1086       return X.Current != Y.Current;
1087     }
1088   };
1089 
1090 private:
1091   /// \brief Test whether the given category is visible.
1092   ///
1093   /// Used in the \c visible_categories_iterator.
1094   static bool isVisibleCategory(ObjCCategoryDecl *Cat);
1095 
1096 public:
1097   /// \brief Iterator that walks over the list of categories and extensions
1098   /// that are visible, i.e., not hidden in a non-imported submodule.
1099   typedef filtered_category_iterator<isVisibleCategory>
1100     visible_categories_iterator;
1101 
1102   typedef llvm::iterator_range<visible_categories_iterator>
1103     visible_categories_range;
1104 
visible_categories()1105   visible_categories_range visible_categories() const {
1106     return visible_categories_range(visible_categories_begin(),
1107                                     visible_categories_end());
1108   }
1109 
1110   /// \brief Retrieve an iterator to the beginning of the visible-categories
1111   /// list.
visible_categories_begin()1112   visible_categories_iterator visible_categories_begin() const {
1113     return visible_categories_iterator(getCategoryListRaw());
1114   }
1115 
1116   /// \brief Retrieve an iterator to the end of the visible-categories list.
visible_categories_end()1117   visible_categories_iterator visible_categories_end() const {
1118     return visible_categories_iterator();
1119   }
1120 
1121   /// \brief Determine whether the visible-categories list is empty.
visible_categories_empty()1122   bool visible_categories_empty() const {
1123     return visible_categories_begin() == visible_categories_end();
1124   }
1125 
1126 private:
1127   /// \brief Test whether the given category... is a category.
1128   ///
1129   /// Used in the \c known_categories_iterator.
isKnownCategory(ObjCCategoryDecl *)1130   static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1131 
1132 public:
1133   /// \brief Iterator that walks over all of the known categories and
1134   /// extensions, including those that are hidden.
1135   typedef filtered_category_iterator<isKnownCategory> known_categories_iterator;
1136   typedef llvm::iterator_range<known_categories_iterator>
1137     known_categories_range;
1138 
known_categories()1139   known_categories_range known_categories() const {
1140     return known_categories_range(known_categories_begin(),
1141                                   known_categories_end());
1142   }
1143 
1144   /// \brief Retrieve an iterator to the beginning of the known-categories
1145   /// list.
known_categories_begin()1146   known_categories_iterator known_categories_begin() const {
1147     return known_categories_iterator(getCategoryListRaw());
1148   }
1149 
1150   /// \brief Retrieve an iterator to the end of the known-categories list.
known_categories_end()1151   known_categories_iterator known_categories_end() const {
1152     return known_categories_iterator();
1153   }
1154 
1155   /// \brief Determine whether the known-categories list is empty.
known_categories_empty()1156   bool known_categories_empty() const {
1157     return known_categories_begin() == known_categories_end();
1158   }
1159 
1160 private:
1161   /// \brief Test whether the given category is a visible extension.
1162   ///
1163   /// Used in the \c visible_extensions_iterator.
1164   static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1165 
1166 public:
1167   /// \brief Iterator that walks over all of the visible extensions, skipping
1168   /// any that are known but hidden.
1169   typedef filtered_category_iterator<isVisibleExtension>
1170     visible_extensions_iterator;
1171 
1172   typedef llvm::iterator_range<visible_extensions_iterator>
1173     visible_extensions_range;
1174 
visible_extensions()1175   visible_extensions_range visible_extensions() const {
1176     return visible_extensions_range(visible_extensions_begin(),
1177                                     visible_extensions_end());
1178   }
1179 
1180   /// \brief Retrieve an iterator to the beginning of the visible-extensions
1181   /// list.
visible_extensions_begin()1182   visible_extensions_iterator visible_extensions_begin() const {
1183     return visible_extensions_iterator(getCategoryListRaw());
1184   }
1185 
1186   /// \brief Retrieve an iterator to the end of the visible-extensions list.
visible_extensions_end()1187   visible_extensions_iterator visible_extensions_end() const {
1188     return visible_extensions_iterator();
1189   }
1190 
1191   /// \brief Determine whether the visible-extensions list is empty.
visible_extensions_empty()1192   bool visible_extensions_empty() const {
1193     return visible_extensions_begin() == visible_extensions_end();
1194   }
1195 
1196 private:
1197   /// \brief Test whether the given category is an extension.
1198   ///
1199   /// Used in the \c known_extensions_iterator.
1200   static bool isKnownExtension(ObjCCategoryDecl *Cat);
1201 
1202 public:
1203   /// \brief Iterator that walks over all of the known extensions.
1204   typedef filtered_category_iterator<isKnownExtension>
1205     known_extensions_iterator;
1206   typedef llvm::iterator_range<known_extensions_iterator>
1207     known_extensions_range;
1208 
known_extensions()1209   known_extensions_range known_extensions() const {
1210     return known_extensions_range(known_extensions_begin(),
1211                                   known_extensions_end());
1212   }
1213 
1214   /// \brief Retrieve an iterator to the beginning of the known-extensions
1215   /// list.
known_extensions_begin()1216   known_extensions_iterator known_extensions_begin() const {
1217     return known_extensions_iterator(getCategoryListRaw());
1218   }
1219 
1220   /// \brief Retrieve an iterator to the end of the known-extensions list.
known_extensions_end()1221   known_extensions_iterator known_extensions_end() const {
1222     return known_extensions_iterator();
1223   }
1224 
1225   /// \brief Determine whether the known-extensions list is empty.
known_extensions_empty()1226   bool known_extensions_empty() const {
1227     return known_extensions_begin() == known_extensions_end();
1228   }
1229 
1230   /// \brief Retrieve the raw pointer to the start of the category/extension
1231   /// list.
getCategoryListRaw()1232   ObjCCategoryDecl* getCategoryListRaw() const {
1233     // FIXME: Should make sure no callers ever do this.
1234     if (!hasDefinition())
1235       return nullptr;
1236 
1237     if (data().ExternallyCompleted)
1238       LoadExternalDefinition();
1239 
1240     return data().CategoryList;
1241   }
1242 
1243   /// \brief Set the raw pointer to the start of the category/extension
1244   /// list.
setCategoryListRaw(ObjCCategoryDecl * category)1245   void setCategoryListRaw(ObjCCategoryDecl *category) {
1246     data().CategoryList = category;
1247   }
1248 
1249   ObjCPropertyDecl
1250     *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId) const;
1251 
1252   void collectPropertiesToImplement(PropertyMap &PM,
1253                                     PropertyDeclOrder &PO) const override;
1254 
1255   /// isSuperClassOf - Return true if this class is the specified class or is a
1256   /// super class of the specified interface class.
isSuperClassOf(const ObjCInterfaceDecl * I)1257   bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1258     // If RHS is derived from LHS it is OK; else it is not OK.
1259     while (I != nullptr) {
1260       if (declaresSameEntity(this, I))
1261         return true;
1262 
1263       I = I->getSuperClass();
1264     }
1265     return false;
1266   }
1267 
1268   /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1269   /// to be incompatible with __weak references. Returns true if it is.
1270   bool isArcWeakrefUnavailable() const;
1271 
1272   /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1273   /// classes must not be auto-synthesized. Returns class decl. if it must not
1274   /// be; 0, otherwise.
1275   const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1276 
1277   ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1278                                        ObjCInterfaceDecl *&ClassDeclared);
lookupInstanceVariable(IdentifierInfo * IVarName)1279   ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1280     ObjCInterfaceDecl *ClassDeclared;
1281     return lookupInstanceVariable(IVarName, ClassDeclared);
1282   }
1283 
1284   ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name);
1285 
1286   // Lookup a method. First, we search locally. If a method isn't
1287   // found, we search referenced protocols and class categories.
1288   ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1289                                bool shallowCategoryLookup = false,
1290                                bool followSuper = true,
1291                                const ObjCCategoryDecl *C = nullptr) const;
1292 
1293   /// Lookup an instance method for a given selector.
lookupInstanceMethod(Selector Sel)1294   ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1295     return lookupMethod(Sel, true/*isInstance*/);
1296   }
1297 
1298   /// Lookup a class method for a given selector.
lookupClassMethod(Selector Sel)1299   ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1300     return lookupMethod(Sel, false/*isInstance*/);
1301   }
1302   ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1303 
1304   /// \brief Lookup a method in the classes implementation hierarchy.
1305   ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1306                                       bool Instance=true) const;
1307 
lookupPrivateClassMethod(const Selector & Sel)1308   ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1309     return lookupPrivateMethod(Sel, false);
1310   }
1311 
1312   /// \brief Lookup a setter or getter in the class hierarchy,
1313   /// including in all categories except for category passed
1314   /// as argument.
lookupPropertyAccessor(const Selector Sel,const ObjCCategoryDecl * Cat)1315   ObjCMethodDecl *lookupPropertyAccessor(const Selector Sel,
1316                                          const ObjCCategoryDecl *Cat) const {
1317     return lookupMethod(Sel, true/*isInstance*/,
1318                         false/*shallowCategoryLookup*/,
1319                         true /* followsSuper */,
1320                         Cat);
1321   }
1322 
getEndOfDefinitionLoc()1323   SourceLocation getEndOfDefinitionLoc() const {
1324     if (!hasDefinition())
1325       return getLocation();
1326 
1327     return data().EndLoc;
1328   }
1329 
setEndOfDefinitionLoc(SourceLocation LE)1330   void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1331 
setSuperClassLoc(SourceLocation Loc)1332   void setSuperClassLoc(SourceLocation Loc) { data().SuperClassLoc = Loc; }
getSuperClassLoc()1333   SourceLocation getSuperClassLoc() const { return data().SuperClassLoc; }
1334 
1335   /// isImplicitInterfaceDecl - check that this is an implicitly declared
1336   /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1337   /// declaration without an \@interface declaration.
isImplicitInterfaceDecl()1338   bool isImplicitInterfaceDecl() const {
1339     return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1340   }
1341 
1342   /// ClassImplementsProtocol - Checks that 'lProto' protocol
1343   /// has been implemented in IDecl class, its super class or categories (if
1344   /// lookupCategory is true).
1345   bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1346                                bool lookupCategory,
1347                                bool RHSIsQualifiedID = false);
1348 
1349   typedef redeclarable_base::redecl_range redecl_range;
1350   typedef redeclarable_base::redecl_iterator redecl_iterator;
1351   using redeclarable_base::redecls_begin;
1352   using redeclarable_base::redecls_end;
1353   using redeclarable_base::redecls;
1354   using redeclarable_base::getPreviousDecl;
1355   using redeclarable_base::getMostRecentDecl;
1356   using redeclarable_base::isFirstDecl;
1357 
1358   /// Retrieves the canonical declaration of this Objective-C class.
getCanonicalDecl()1359   ObjCInterfaceDecl *getCanonicalDecl() override { return getFirstDecl(); }
getCanonicalDecl()1360   const ObjCInterfaceDecl *getCanonicalDecl() const { return getFirstDecl(); }
1361 
1362   // Low-level accessor
getTypeForDecl()1363   const Type *getTypeForDecl() const { return TypeForDecl; }
setTypeForDecl(const Type * TD)1364   void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1365 
classof(const Decl * D)1366   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1367   static bool classofKind(Kind K) { return K == ObjCInterface; }
1368 
1369   friend class ASTReader;
1370   friend class ASTDeclReader;
1371   friend class ASTDeclWriter;
1372 
1373 private:
1374   const ObjCInterfaceDecl *findInterfaceWithDesignatedInitializers() const;
1375   bool inheritsDesignatedInitializers() const;
1376 };
1377 
1378 /// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1379 /// instance variables are identical to C. The only exception is Objective-C
1380 /// supports C++ style access control. For example:
1381 ///
1382 ///   \@interface IvarExample : NSObject
1383 ///   {
1384 ///     id defaultToProtected;
1385 ///   \@public:
1386 ///     id canBePublic; // same as C++.
1387 ///   \@protected:
1388 ///     id canBeProtected; // same as C++.
1389 ///   \@package:
1390 ///     id canBePackage; // framework visibility (not available in C++).
1391 ///   }
1392 ///
1393 class ObjCIvarDecl : public FieldDecl {
1394   void anchor() override;
1395 
1396 public:
1397   enum AccessControl {
1398     None, Private, Protected, Public, Package
1399   };
1400 
1401 private:
ObjCIvarDecl(ObjCContainerDecl * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,AccessControl ac,Expr * BW,bool synthesized)1402   ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1403                SourceLocation IdLoc, IdentifierInfo *Id,
1404                QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1405                bool synthesized)
1406     : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1407                 /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1408       NextIvar(nullptr), DeclAccess(ac), Synthesized(synthesized) {}
1409 
1410 public:
1411   static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1412                               SourceLocation StartLoc, SourceLocation IdLoc,
1413                               IdentifierInfo *Id, QualType T,
1414                               TypeSourceInfo *TInfo,
1415                               AccessControl ac, Expr *BW = nullptr,
1416                               bool synthesized=false);
1417 
1418   static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1419 
1420   /// \brief Return the class interface that this ivar is logically contained
1421   /// in; this is either the interface where the ivar was declared, or the
1422   /// interface the ivar is conceptually a part of in the case of synthesized
1423   /// ivars.
1424   const ObjCInterfaceDecl *getContainingInterface() const;
1425 
getNextIvar()1426   ObjCIvarDecl *getNextIvar() { return NextIvar; }
getNextIvar()1427   const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
setNextIvar(ObjCIvarDecl * ivar)1428   void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1429 
setAccessControl(AccessControl ac)1430   void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1431 
getAccessControl()1432   AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1433 
getCanonicalAccessControl()1434   AccessControl getCanonicalAccessControl() const {
1435     return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1436   }
1437 
setSynthesize(bool synth)1438   void setSynthesize(bool synth) { Synthesized = synth; }
getSynthesize()1439   bool getSynthesize() const { return Synthesized; }
1440 
1441   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)1442   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1443   static bool classofKind(Kind K) { return K == ObjCIvar; }
1444 private:
1445   /// NextIvar - Next Ivar in the list of ivars declared in class; class's
1446   /// extensions and class's implementation
1447   ObjCIvarDecl *NextIvar;
1448 
1449   // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
1450   unsigned DeclAccess : 3;
1451   unsigned Synthesized : 1;
1452 };
1453 
1454 
1455 /// \brief Represents a field declaration created by an \@defs(...).
1456 class ObjCAtDefsFieldDecl : public FieldDecl {
1457   void anchor() override;
ObjCAtDefsFieldDecl(DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,Expr * BW)1458   ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
1459                       SourceLocation IdLoc, IdentifierInfo *Id,
1460                       QualType T, Expr *BW)
1461     : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
1462                 /*TInfo=*/nullptr, // FIXME: Do ObjCAtDefs have declarators ?
1463                 BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
1464 
1465 public:
1466   static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
1467                                      SourceLocation StartLoc,
1468                                      SourceLocation IdLoc, IdentifierInfo *Id,
1469                                      QualType T, Expr *BW);
1470 
1471   static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1472 
1473   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)1474   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1475   static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
1476 };
1477 
1478 /// \brief Represents an Objective-C protocol declaration.
1479 ///
1480 /// Objective-C protocols declare a pure abstract type (i.e., no instance
1481 /// variables are permitted).  Protocols originally drew inspiration from
1482 /// C++ pure virtual functions (a C++ feature with nice semantics and lousy
1483 /// syntax:-). Here is an example:
1484 ///
1485 /// \code
1486 /// \@protocol NSDraggingInfo <refproto1, refproto2>
1487 /// - (NSWindow *)draggingDestinationWindow;
1488 /// - (NSImage *)draggedImage;
1489 /// \@end
1490 /// \endcode
1491 ///
1492 /// This says that NSDraggingInfo requires two methods and requires everything
1493 /// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
1494 /// well.
1495 ///
1496 /// \code
1497 /// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
1498 /// \@end
1499 /// \endcode
1500 ///
1501 /// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
1502 /// protocols are in distinct namespaces. For example, Cocoa defines both
1503 /// an NSObject protocol and class (which isn't allowed in Java). As a result,
1504 /// protocols are referenced using angle brackets as follows:
1505 ///
1506 /// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
1507 ///
1508 class ObjCProtocolDecl : public ObjCContainerDecl,
1509                          public Redeclarable<ObjCProtocolDecl> {
1510   void anchor() override;
1511 
1512   struct DefinitionData {
1513     // \brief The declaration that defines this protocol.
1514     ObjCProtocolDecl *Definition;
1515 
1516     /// \brief Referenced protocols
1517     ObjCProtocolList ReferencedProtocols;
1518   };
1519 
1520   /// \brief Contains a pointer to the data associated with this class,
1521   /// which will be NULL if this class has not yet been defined.
1522   ///
1523   /// The bit indicates when we don't need to check for out-of-date
1524   /// declarations. It will be set unless modules are enabled.
1525   llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1526 
data()1527   DefinitionData &data() const {
1528     assert(Data.getPointer() && "Objective-C protocol has no definition!");
1529     return *Data.getPointer();
1530   }
1531 
1532   ObjCProtocolDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
1533                    SourceLocation nameLoc, SourceLocation atStartLoc,
1534                    ObjCProtocolDecl *PrevDecl);
1535 
1536   void allocateDefinitionData();
1537 
1538   typedef Redeclarable<ObjCProtocolDecl> redeclarable_base;
getNextRedeclarationImpl()1539   ObjCProtocolDecl *getNextRedeclarationImpl() override {
1540     return getNextRedeclaration();
1541   }
getPreviousDeclImpl()1542   ObjCProtocolDecl *getPreviousDeclImpl() override {
1543     return getPreviousDecl();
1544   }
getMostRecentDeclImpl()1545   ObjCProtocolDecl *getMostRecentDeclImpl() override {
1546     return getMostRecentDecl();
1547   }
1548 
1549 public:
1550   static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
1551                                   IdentifierInfo *Id,
1552                                   SourceLocation nameLoc,
1553                                   SourceLocation atStartLoc,
1554                                   ObjCProtocolDecl *PrevDecl);
1555 
1556   static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1557 
getReferencedProtocols()1558   const ObjCProtocolList &getReferencedProtocols() const {
1559     assert(hasDefinition() && "No definition available!");
1560     return data().ReferencedProtocols;
1561   }
1562   typedef ObjCProtocolList::iterator protocol_iterator;
1563   typedef llvm::iterator_range<protocol_iterator> protocol_range;
1564 
protocols()1565   protocol_range protocols() const {
1566     return protocol_range(protocol_begin(), protocol_end());
1567   }
protocol_begin()1568   protocol_iterator protocol_begin() const {
1569     if (!hasDefinition())
1570       return protocol_iterator();
1571 
1572     return data().ReferencedProtocols.begin();
1573   }
protocol_end()1574   protocol_iterator protocol_end() const {
1575     if (!hasDefinition())
1576       return protocol_iterator();
1577 
1578     return data().ReferencedProtocols.end();
1579   }
1580   typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1581   typedef llvm::iterator_range<protocol_loc_iterator> protocol_loc_range;
1582 
protocol_locs()1583   protocol_loc_range protocol_locs() const {
1584     return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1585   }
protocol_loc_begin()1586   protocol_loc_iterator protocol_loc_begin() const {
1587     if (!hasDefinition())
1588       return protocol_loc_iterator();
1589 
1590     return data().ReferencedProtocols.loc_begin();
1591   }
protocol_loc_end()1592   protocol_loc_iterator protocol_loc_end() const {
1593     if (!hasDefinition())
1594       return protocol_loc_iterator();
1595 
1596     return data().ReferencedProtocols.loc_end();
1597   }
protocol_size()1598   unsigned protocol_size() const {
1599     if (!hasDefinition())
1600       return 0;
1601 
1602     return data().ReferencedProtocols.size();
1603   }
1604 
1605   /// setProtocolList - Set the list of protocols that this interface
1606   /// implements.
setProtocolList(ObjCProtocolDecl * const * List,unsigned Num,const SourceLocation * Locs,ASTContext & C)1607   void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1608                        const SourceLocation *Locs, ASTContext &C) {
1609     assert(hasDefinition() && "Protocol is not defined");
1610     data().ReferencedProtocols.set(List, Num, Locs, C);
1611   }
1612 
1613   ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
1614 
1615   // Lookup a method. First, we search locally. If a method isn't
1616   // found, we search referenced protocols and class categories.
1617   ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
lookupInstanceMethod(Selector Sel)1618   ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1619     return lookupMethod(Sel, true/*isInstance*/);
1620   }
lookupClassMethod(Selector Sel)1621   ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1622     return lookupMethod(Sel, false/*isInstance*/);
1623   }
1624 
1625   /// \brief Determine whether this protocol has a definition.
hasDefinition()1626   bool hasDefinition() const {
1627     // If the name of this protocol is out-of-date, bring it up-to-date, which
1628     // might bring in a definition.
1629     // Note: a null value indicates that we don't have a definition and that
1630     // modules are enabled.
1631     if (!Data.getOpaqueValue()) {
1632       if (IdentifierInfo *II = getIdentifier()) {
1633         if (II->isOutOfDate()) {
1634           updateOutOfDate(*II);
1635         }
1636       }
1637     }
1638 
1639     return Data.getPointer();
1640   }
1641 
1642   /// \brief Retrieve the definition of this protocol, if any.
getDefinition()1643   ObjCProtocolDecl *getDefinition() {
1644     return hasDefinition()? Data.getPointer()->Definition : nullptr;
1645   }
1646 
1647   /// \brief Retrieve the definition of this protocol, if any.
getDefinition()1648   const ObjCProtocolDecl *getDefinition() const {
1649     return hasDefinition()? Data.getPointer()->Definition : nullptr;
1650   }
1651 
1652   /// \brief Determine whether this particular declaration is also the
1653   /// definition.
isThisDeclarationADefinition()1654   bool isThisDeclarationADefinition() const {
1655     return getDefinition() == this;
1656   }
1657 
1658   /// \brief Starts the definition of this Objective-C protocol.
1659   void startDefinition();
1660 
1661   /// Produce a name to be used for protocol's metadata. It comes either via
1662   /// objc_runtime_name attribute or protocol name.
1663   StringRef getObjCRuntimeNameAsString() const;
1664 
getSourceRange()1665   SourceRange getSourceRange() const override LLVM_READONLY {
1666     if (isThisDeclarationADefinition())
1667       return ObjCContainerDecl::getSourceRange();
1668 
1669     return SourceRange(getAtStartLoc(), getLocation());
1670   }
1671 
1672   typedef redeclarable_base::redecl_range redecl_range;
1673   typedef redeclarable_base::redecl_iterator redecl_iterator;
1674   using redeclarable_base::redecls_begin;
1675   using redeclarable_base::redecls_end;
1676   using redeclarable_base::redecls;
1677   using redeclarable_base::getPreviousDecl;
1678   using redeclarable_base::getMostRecentDecl;
1679   using redeclarable_base::isFirstDecl;
1680 
1681   /// Retrieves the canonical declaration of this Objective-C protocol.
getCanonicalDecl()1682   ObjCProtocolDecl *getCanonicalDecl() override { return getFirstDecl(); }
getCanonicalDecl()1683   const ObjCProtocolDecl *getCanonicalDecl() const { return getFirstDecl(); }
1684 
1685   void collectPropertiesToImplement(PropertyMap &PM,
1686                                     PropertyDeclOrder &PO) const override;
1687 
1688   void collectInheritedProtocolProperties(const ObjCPropertyDecl *Property,
1689                                           ProtocolPropertyMap &PM) const;
1690 
classof(const Decl * D)1691   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1692   static bool classofKind(Kind K) { return K == ObjCProtocol; }
1693 
1694   friend class ASTReader;
1695   friend class ASTDeclReader;
1696   friend class ASTDeclWriter;
1697 };
1698 
1699 /// ObjCCategoryDecl - Represents a category declaration. A category allows
1700 /// you to add methods to an existing class (without subclassing or modifying
1701 /// the original class interface or implementation:-). Categories don't allow
1702 /// you to add instance data. The following example adds "myMethod" to all
1703 /// NSView's within a process:
1704 ///
1705 /// \@interface NSView (MyViewMethods)
1706 /// - myMethod;
1707 /// \@end
1708 ///
1709 /// Categories also allow you to split the implementation of a class across
1710 /// several files (a feature more naturally supported in C++).
1711 ///
1712 /// Categories were originally inspired by dynamic languages such as Common
1713 /// Lisp and Smalltalk.  More traditional class-based languages (C++, Java)
1714 /// don't support this level of dynamism, which is both powerful and dangerous.
1715 ///
1716 class ObjCCategoryDecl : public ObjCContainerDecl {
1717   void anchor() override;
1718 
1719   /// Interface belonging to this category
1720   ObjCInterfaceDecl *ClassInterface;
1721 
1722   /// referenced protocols in this category.
1723   ObjCProtocolList ReferencedProtocols;
1724 
1725   /// Next category belonging to this class.
1726   /// FIXME: this should not be a singly-linked list.  Move storage elsewhere.
1727   ObjCCategoryDecl *NextClassCategory;
1728 
1729   /// \brief The location of the category name in this declaration.
1730   SourceLocation CategoryNameLoc;
1731 
1732   /// class extension may have private ivars.
1733   SourceLocation IvarLBraceLoc;
1734   SourceLocation IvarRBraceLoc;
1735 
1736   ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1737                    SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
1738                    IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1739                    SourceLocation IvarLBraceLoc=SourceLocation(),
1740                    SourceLocation IvarRBraceLoc=SourceLocation())
ObjCContainerDecl(ObjCCategory,DC,Id,ClassNameLoc,AtLoc)1741     : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1742       ClassInterface(IDecl), NextClassCategory(nullptr),
1743       CategoryNameLoc(CategoryNameLoc),
1744       IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
1745   }
1746 
1747 public:
1748 
1749   static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
1750                                   SourceLocation AtLoc,
1751                                   SourceLocation ClassNameLoc,
1752                                   SourceLocation CategoryNameLoc,
1753                                   IdentifierInfo *Id,
1754                                   ObjCInterfaceDecl *IDecl,
1755                                   SourceLocation IvarLBraceLoc=SourceLocation(),
1756                                   SourceLocation IvarRBraceLoc=SourceLocation());
1757   static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1758 
getClassInterface()1759   ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
getClassInterface()1760   const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
1761 
1762   ObjCCategoryImplDecl *getImplementation() const;
1763   void setImplementation(ObjCCategoryImplDecl *ImplD);
1764 
1765   /// setProtocolList - Set the list of protocols that this interface
1766   /// implements.
setProtocolList(ObjCProtocolDecl * const * List,unsigned Num,const SourceLocation * Locs,ASTContext & C)1767   void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
1768                        const SourceLocation *Locs, ASTContext &C) {
1769     ReferencedProtocols.set(List, Num, Locs, C);
1770   }
1771 
getReferencedProtocols()1772   const ObjCProtocolList &getReferencedProtocols() const {
1773     return ReferencedProtocols;
1774   }
1775 
1776   typedef ObjCProtocolList::iterator protocol_iterator;
1777   typedef llvm::iterator_range<protocol_iterator> protocol_range;
1778 
protocols()1779   protocol_range protocols() const {
1780     return protocol_range(protocol_begin(), protocol_end());
1781   }
protocol_begin()1782   protocol_iterator protocol_begin() const {
1783     return ReferencedProtocols.begin();
1784   }
protocol_end()1785   protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
protocol_size()1786   unsigned protocol_size() const { return ReferencedProtocols.size(); }
1787   typedef ObjCProtocolList::loc_iterator protocol_loc_iterator;
1788   typedef llvm::iterator_range<protocol_loc_iterator> protocol_loc_range;
1789 
protocol_locs()1790   protocol_loc_range protocol_locs() const {
1791     return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1792   }
protocol_loc_begin()1793   protocol_loc_iterator protocol_loc_begin() const {
1794     return ReferencedProtocols.loc_begin();
1795   }
protocol_loc_end()1796   protocol_loc_iterator protocol_loc_end() const {
1797     return ReferencedProtocols.loc_end();
1798   }
1799 
getNextClassCategory()1800   ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
1801 
1802   /// \brief Retrieve the pointer to the next stored category (or extension),
1803   /// which may be hidden.
getNextClassCategoryRaw()1804   ObjCCategoryDecl *getNextClassCategoryRaw() const {
1805     return NextClassCategory;
1806   }
1807 
IsClassExtension()1808   bool IsClassExtension() const { return getIdentifier() == nullptr; }
1809 
1810   typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
1811   typedef llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>> ivar_range;
1812 
ivars()1813   ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
ivar_begin()1814   ivar_iterator ivar_begin() const {
1815     return ivar_iterator(decls_begin());
1816   }
ivar_end()1817   ivar_iterator ivar_end() const {
1818     return ivar_iterator(decls_end());
1819   }
ivar_size()1820   unsigned ivar_size() const {
1821     return std::distance(ivar_begin(), ivar_end());
1822   }
ivar_empty()1823   bool ivar_empty() const {
1824     return ivar_begin() == ivar_end();
1825   }
1826 
getCategoryNameLoc()1827   SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
setCategoryNameLoc(SourceLocation Loc)1828   void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
1829 
setIvarLBraceLoc(SourceLocation Loc)1830   void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
getIvarLBraceLoc()1831   SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
setIvarRBraceLoc(SourceLocation Loc)1832   void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
getIvarRBraceLoc()1833   SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
1834 
classof(const Decl * D)1835   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1836   static bool classofKind(Kind K) { return K == ObjCCategory; }
1837 
1838   friend class ASTDeclReader;
1839   friend class ASTDeclWriter;
1840 };
1841 
1842 class ObjCImplDecl : public ObjCContainerDecl {
1843   void anchor() override;
1844 
1845   /// Class interface for this class/category implementation
1846   ObjCInterfaceDecl *ClassInterface;
1847 
1848 protected:
ObjCImplDecl(Kind DK,DeclContext * DC,ObjCInterfaceDecl * classInterface,SourceLocation nameLoc,SourceLocation atStartLoc)1849   ObjCImplDecl(Kind DK, DeclContext *DC,
1850                ObjCInterfaceDecl *classInterface,
1851                SourceLocation nameLoc, SourceLocation atStartLoc)
1852     : ObjCContainerDecl(DK, DC,
1853                         classInterface? classInterface->getIdentifier()
1854                                       : nullptr,
1855                         nameLoc, atStartLoc),
1856       ClassInterface(classInterface) {}
1857 
1858 public:
getClassInterface()1859   const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
getClassInterface()1860   ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
1861   void setClassInterface(ObjCInterfaceDecl *IFace);
1862 
addInstanceMethod(ObjCMethodDecl * method)1863   void addInstanceMethod(ObjCMethodDecl *method) {
1864     // FIXME: Context should be set correctly before we get here.
1865     method->setLexicalDeclContext(this);
1866     addDecl(method);
1867   }
addClassMethod(ObjCMethodDecl * method)1868   void addClassMethod(ObjCMethodDecl *method) {
1869     // FIXME: Context should be set correctly before we get here.
1870     method->setLexicalDeclContext(this);
1871     addDecl(method);
1872   }
1873 
1874   void addPropertyImplementation(ObjCPropertyImplDecl *property);
1875 
1876   ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId) const;
1877   ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
1878 
1879   // Iterator access to properties.
1880   typedef specific_decl_iterator<ObjCPropertyImplDecl> propimpl_iterator;
1881   typedef llvm::iterator_range<specific_decl_iterator<ObjCPropertyImplDecl>>
1882     propimpl_range;
1883 
property_impls()1884   propimpl_range property_impls() const {
1885     return propimpl_range(propimpl_begin(), propimpl_end());
1886   }
propimpl_begin()1887   propimpl_iterator propimpl_begin() const {
1888     return propimpl_iterator(decls_begin());
1889   }
propimpl_end()1890   propimpl_iterator propimpl_end() const {
1891     return propimpl_iterator(decls_end());
1892   }
1893 
classof(const Decl * D)1894   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1895   static bool classofKind(Kind K) {
1896     return K >= firstObjCImpl && K <= lastObjCImpl;
1897   }
1898 };
1899 
1900 /// ObjCCategoryImplDecl - An object of this class encapsulates a category
1901 /// \@implementation declaration. If a category class has declaration of a
1902 /// property, its implementation must be specified in the category's
1903 /// \@implementation declaration. Example:
1904 /// \@interface I \@end
1905 /// \@interface I(CATEGORY)
1906 ///    \@property int p1, d1;
1907 /// \@end
1908 /// \@implementation I(CATEGORY)
1909 ///  \@dynamic p1,d1;
1910 /// \@end
1911 ///
1912 /// ObjCCategoryImplDecl
1913 class ObjCCategoryImplDecl : public ObjCImplDecl {
1914   void anchor() override;
1915 
1916   // Category name
1917   IdentifierInfo *Id;
1918 
1919   // Category name location
1920   SourceLocation CategoryNameLoc;
1921 
ObjCCategoryImplDecl(DeclContext * DC,IdentifierInfo * Id,ObjCInterfaceDecl * classInterface,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation CategoryNameLoc)1922   ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
1923                        ObjCInterfaceDecl *classInterface,
1924                        SourceLocation nameLoc, SourceLocation atStartLoc,
1925                        SourceLocation CategoryNameLoc)
1926     : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, nameLoc, atStartLoc),
1927       Id(Id), CategoryNameLoc(CategoryNameLoc) {}
1928 public:
1929   static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
1930                                       IdentifierInfo *Id,
1931                                       ObjCInterfaceDecl *classInterface,
1932                                       SourceLocation nameLoc,
1933                                       SourceLocation atStartLoc,
1934                                       SourceLocation CategoryNameLoc);
1935   static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1936 
1937   /// getIdentifier - Get the identifier that names the category
1938   /// interface associated with this implementation.
1939   /// FIXME: This is a bad API, we are hiding NamedDecl::getIdentifier()
1940   /// with a different meaning. For example:
1941   /// ((NamedDecl *)SomeCategoryImplDecl)->getIdentifier()
1942   /// returns the class interface name, whereas
1943   /// ((ObjCCategoryImplDecl *)SomeCategoryImplDecl)->getIdentifier()
1944   /// returns the category name.
getIdentifier()1945   IdentifierInfo *getIdentifier() const {
1946     return Id;
1947   }
setIdentifier(IdentifierInfo * II)1948   void setIdentifier(IdentifierInfo *II) { Id = II; }
1949 
1950   ObjCCategoryDecl *getCategoryDecl() const;
1951 
getCategoryNameLoc()1952   SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
1953 
1954   /// getName - Get the name of identifier for the class interface associated
1955   /// with this implementation as a StringRef.
1956   //
1957   // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
1958   // meaning.
getName()1959   StringRef getName() const { return Id ? Id->getName() : StringRef(); }
1960 
1961   /// @brief Get the name of the class associated with this interface.
1962   //
1963   // FIXME: Deprecated, move clients to getName().
getNameAsString()1964   std::string getNameAsString() const {
1965     return getName();
1966   }
1967 
classof(const Decl * D)1968   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1969   static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
1970 
1971   friend class ASTDeclReader;
1972   friend class ASTDeclWriter;
1973 };
1974 
1975 raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
1976 
1977 /// ObjCImplementationDecl - Represents a class definition - this is where
1978 /// method definitions are specified. For example:
1979 ///
1980 /// @code
1981 /// \@implementation MyClass
1982 /// - (void)myMethod { /* do something */ }
1983 /// \@end
1984 /// @endcode
1985 ///
1986 /// In a non-fragile runtime, instance variables can appear in the class
1987 /// interface, class extensions (nameless categories), and in the implementation
1988 /// itself, as well as being synthesized as backing storage for properties.
1989 ///
1990 /// In a fragile runtime, instance variables are specified in the class
1991 /// interface, \em not in the implementation. Nevertheless (for legacy reasons),
1992 /// we allow instance variables to be specified in the implementation. When
1993 /// specified, they need to be \em identical to the interface.
1994 class ObjCImplementationDecl : public ObjCImplDecl {
1995   void anchor() override;
1996   /// Implementation Class's super class.
1997   ObjCInterfaceDecl *SuperClass;
1998   SourceLocation SuperLoc;
1999 
2000   /// \@implementation may have private ivars.
2001   SourceLocation IvarLBraceLoc;
2002   SourceLocation IvarRBraceLoc;
2003 
2004   /// Support for ivar initialization.
2005   /// \brief The arguments used to initialize the ivars
2006   LazyCXXCtorInitializersPtr IvarInitializers;
2007   unsigned NumIvarInitializers;
2008 
2009   /// Do the ivars of this class require initialization other than
2010   /// zero-initialization?
2011   bool HasNonZeroConstructors : 1;
2012 
2013   /// Do the ivars of this class require non-trivial destruction?
2014   bool HasDestructors : 1;
2015 
2016   ObjCImplementationDecl(DeclContext *DC,
2017                          ObjCInterfaceDecl *classInterface,
2018                          ObjCInterfaceDecl *superDecl,
2019                          SourceLocation nameLoc, SourceLocation atStartLoc,
2020                          SourceLocation superLoc = SourceLocation(),
2021                          SourceLocation IvarLBraceLoc=SourceLocation(),
2022                          SourceLocation IvarRBraceLoc=SourceLocation())
ObjCImplDecl(ObjCImplementation,DC,classInterface,nameLoc,atStartLoc)2023     : ObjCImplDecl(ObjCImplementation, DC, classInterface, nameLoc, atStartLoc),
2024        SuperClass(superDecl), SuperLoc(superLoc), IvarLBraceLoc(IvarLBraceLoc),
2025        IvarRBraceLoc(IvarRBraceLoc),
2026        IvarInitializers(nullptr), NumIvarInitializers(0),
2027        HasNonZeroConstructors(false), HasDestructors(false) {}
2028 public:
2029   static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
2030                                         ObjCInterfaceDecl *classInterface,
2031                                         ObjCInterfaceDecl *superDecl,
2032                                         SourceLocation nameLoc,
2033                                         SourceLocation atStartLoc,
2034                                      SourceLocation superLoc = SourceLocation(),
2035                                         SourceLocation IvarLBraceLoc=SourceLocation(),
2036                                         SourceLocation IvarRBraceLoc=SourceLocation());
2037 
2038   static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2039 
2040   /// init_iterator - Iterates through the ivar initializer list.
2041   typedef CXXCtorInitializer **init_iterator;
2042 
2043   /// init_const_iterator - Iterates through the ivar initializer list.
2044   typedef CXXCtorInitializer * const * init_const_iterator;
2045 
2046   typedef llvm::iterator_range<init_iterator> init_range;
2047   typedef llvm::iterator_range<init_const_iterator> init_const_range;
2048 
inits()2049   init_range inits() { return init_range(init_begin(), init_end()); }
inits()2050   init_const_range inits() const {
2051     return init_const_range(init_begin(), init_end());
2052   }
2053 
2054   /// init_begin() - Retrieve an iterator to the first initializer.
init_begin()2055   init_iterator init_begin() {
2056     const auto *ConstThis = this;
2057     return const_cast<init_iterator>(ConstThis->init_begin());
2058   }
2059   /// begin() - Retrieve an iterator to the first initializer.
2060   init_const_iterator init_begin() const;
2061 
2062   /// init_end() - Retrieve an iterator past the last initializer.
init_end()2063   init_iterator       init_end()       {
2064     return init_begin() + NumIvarInitializers;
2065   }
2066   /// end() - Retrieve an iterator past the last initializer.
init_end()2067   init_const_iterator init_end() const {
2068     return init_begin() + NumIvarInitializers;
2069   }
2070   /// getNumArgs - Number of ivars which must be initialized.
getNumIvarInitializers()2071   unsigned getNumIvarInitializers() const {
2072     return NumIvarInitializers;
2073   }
2074 
setNumIvarInitializers(unsigned numNumIvarInitializers)2075   void setNumIvarInitializers(unsigned numNumIvarInitializers) {
2076     NumIvarInitializers = numNumIvarInitializers;
2077   }
2078 
2079   void setIvarInitializers(ASTContext &C,
2080                            CXXCtorInitializer ** initializers,
2081                            unsigned numInitializers);
2082 
2083   /// Do any of the ivars of this class (not counting its base classes)
2084   /// require construction other than zero-initialization?
hasNonZeroConstructors()2085   bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
setHasNonZeroConstructors(bool val)2086   void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
2087 
2088   /// Do any of the ivars of this class (not counting its base classes)
2089   /// require non-trivial destruction?
hasDestructors()2090   bool hasDestructors() const { return HasDestructors; }
setHasDestructors(bool val)2091   void setHasDestructors(bool val) { HasDestructors = val; }
2092 
2093   /// getIdentifier - Get the identifier that names the class
2094   /// interface associated with this implementation.
getIdentifier()2095   IdentifierInfo *getIdentifier() const {
2096     return getClassInterface()->getIdentifier();
2097   }
2098 
2099   /// getName - Get the name of identifier for the class interface associated
2100   /// with this implementation as a StringRef.
2101   //
2102   // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
2103   // meaning.
getName()2104   StringRef getName() const {
2105     assert(getIdentifier() && "Name is not a simple identifier");
2106     return getIdentifier()->getName();
2107   }
2108 
2109   /// @brief Get the name of the class associated with this interface.
2110   //
2111   // FIXME: Move to StringRef API.
getNameAsString()2112   std::string getNameAsString() const {
2113     return getName();
2114   }
2115 
2116   /// Produce a name to be used for class's metadata. It comes either via
2117   /// class's objc_runtime_name attribute or class name.
2118   StringRef getObjCRuntimeNameAsString() const;
2119 
getSuperClass()2120   const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
getSuperClass()2121   ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
getSuperClassLoc()2122   SourceLocation getSuperClassLoc() const { return SuperLoc; }
2123 
setSuperClass(ObjCInterfaceDecl * superCls)2124   void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
2125 
setIvarLBraceLoc(SourceLocation Loc)2126   void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
getIvarLBraceLoc()2127   SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
setIvarRBraceLoc(SourceLocation Loc)2128   void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
getIvarRBraceLoc()2129   SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2130 
2131   typedef specific_decl_iterator<ObjCIvarDecl> ivar_iterator;
2132   typedef llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>> ivar_range;
2133 
ivars()2134   ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
ivar_begin()2135   ivar_iterator ivar_begin() const {
2136     return ivar_iterator(decls_begin());
2137   }
ivar_end()2138   ivar_iterator ivar_end() const {
2139     return ivar_iterator(decls_end());
2140   }
ivar_size()2141   unsigned ivar_size() const {
2142     return std::distance(ivar_begin(), ivar_end());
2143   }
ivar_empty()2144   bool ivar_empty() const {
2145     return ivar_begin() == ivar_end();
2146   }
2147 
classof(const Decl * D)2148   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2149   static bool classofKind(Kind K) { return K == ObjCImplementation; }
2150 
2151   friend class ASTDeclReader;
2152   friend class ASTDeclWriter;
2153 };
2154 
2155 raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
2156 
2157 /// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
2158 /// declared as \@compatibility_alias alias class.
2159 class ObjCCompatibleAliasDecl : public NamedDecl {
2160   void anchor() override;
2161   /// Class that this is an alias of.
2162   ObjCInterfaceDecl *AliasedClass;
2163 
ObjCCompatibleAliasDecl(DeclContext * DC,SourceLocation L,IdentifierInfo * Id,ObjCInterfaceDecl * aliasedClass)2164   ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2165                           ObjCInterfaceDecl* aliasedClass)
2166     : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
2167 public:
2168   static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
2169                                          SourceLocation L, IdentifierInfo *Id,
2170                                          ObjCInterfaceDecl* aliasedClass);
2171 
2172   static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
2173                                                      unsigned ID);
2174 
getClassInterface()2175   const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
getClassInterface()2176   ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
setClassInterface(ObjCInterfaceDecl * D)2177   void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
2178 
classof(const Decl * D)2179   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2180   static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
2181 
2182 };
2183 
2184 /// \brief Represents one property declaration in an Objective-C interface.
2185 ///
2186 /// For example:
2187 /// \code{.mm}
2188 /// \@property (assign, readwrite) int MyProperty;
2189 /// \endcode
2190 class ObjCPropertyDecl : public NamedDecl {
2191   void anchor() override;
2192 public:
2193   enum PropertyAttributeKind {
2194     OBJC_PR_noattr    = 0x00,
2195     OBJC_PR_readonly  = 0x01,
2196     OBJC_PR_getter    = 0x02,
2197     OBJC_PR_assign    = 0x04,
2198     OBJC_PR_readwrite = 0x08,
2199     OBJC_PR_retain    = 0x10,
2200     OBJC_PR_copy      = 0x20,
2201     OBJC_PR_nonatomic = 0x40,
2202     OBJC_PR_setter    = 0x80,
2203     OBJC_PR_atomic    = 0x100,
2204     OBJC_PR_weak      = 0x200,
2205     OBJC_PR_strong    = 0x400,
2206     OBJC_PR_unsafe_unretained = 0x800
2207     // Adding a property should change NumPropertyAttrsBits
2208   };
2209 
2210   enum {
2211     /// \brief Number of bits fitting all the property attributes.
2212     NumPropertyAttrsBits = 12
2213   };
2214 
2215   enum SetterKind { Assign, Retain, Copy, Weak };
2216   enum PropertyControl { None, Required, Optional };
2217 private:
2218   SourceLocation AtLoc;   // location of \@property
2219   SourceLocation LParenLoc; // location of '(' starting attribute list or null.
2220   TypeSourceInfo *DeclType;
2221   unsigned PropertyAttributes : NumPropertyAttrsBits;
2222   unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
2223   // \@required/\@optional
2224   unsigned PropertyImplementation : 2;
2225 
2226   Selector GetterName;    // getter name of NULL if no getter
2227   Selector SetterName;    // setter name of NULL if no setter
2228 
2229   ObjCMethodDecl *GetterMethodDecl; // Declaration of getter instance method
2230   ObjCMethodDecl *SetterMethodDecl; // Declaration of setter instance method
2231   ObjCIvarDecl *PropertyIvarDecl;   // Synthesize ivar for this property
2232 
ObjCPropertyDecl(DeclContext * DC,SourceLocation L,IdentifierInfo * Id,SourceLocation AtLocation,SourceLocation LParenLocation,TypeSourceInfo * T)2233   ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2234                    SourceLocation AtLocation,  SourceLocation LParenLocation,
2235                    TypeSourceInfo *T)
2236     : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
2237       LParenLoc(LParenLocation), DeclType(T),
2238       PropertyAttributes(OBJC_PR_noattr),
2239       PropertyAttributesAsWritten(OBJC_PR_noattr),
2240       PropertyImplementation(None),
2241       GetterName(Selector()),
2242       SetterName(Selector()),
2243       GetterMethodDecl(nullptr), SetterMethodDecl(nullptr),
2244       PropertyIvarDecl(nullptr) {}
2245 
2246 public:
2247   static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
2248                                   SourceLocation L,
2249                                   IdentifierInfo *Id, SourceLocation AtLocation,
2250                                   SourceLocation LParenLocation,
2251                                   TypeSourceInfo *T,
2252                                   PropertyControl propControl = None);
2253 
2254   static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2255 
getAtLoc()2256   SourceLocation getAtLoc() const { return AtLoc; }
setAtLoc(SourceLocation L)2257   void setAtLoc(SourceLocation L) { AtLoc = L; }
2258 
getLParenLoc()2259   SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)2260   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2261 
getTypeSourceInfo()2262   TypeSourceInfo *getTypeSourceInfo() const { return DeclType; }
getType()2263   QualType getType() const { return DeclType->getType(); }
setType(TypeSourceInfo * T)2264   void setType(TypeSourceInfo *T) { DeclType = T; }
2265 
getPropertyAttributes()2266   PropertyAttributeKind getPropertyAttributes() const {
2267     return PropertyAttributeKind(PropertyAttributes);
2268   }
setPropertyAttributes(PropertyAttributeKind PRVal)2269   void setPropertyAttributes(PropertyAttributeKind PRVal) {
2270     PropertyAttributes |= PRVal;
2271   }
2272 
getPropertyAttributesAsWritten()2273   PropertyAttributeKind getPropertyAttributesAsWritten() const {
2274     return PropertyAttributeKind(PropertyAttributesAsWritten);
2275   }
2276 
hasWrittenStorageAttribute()2277   bool hasWrittenStorageAttribute() const {
2278     return PropertyAttributesAsWritten & (OBJC_PR_assign | OBJC_PR_copy |
2279         OBJC_PR_unsafe_unretained | OBJC_PR_retain | OBJC_PR_strong |
2280         OBJC_PR_weak);
2281   }
2282 
setPropertyAttributesAsWritten(PropertyAttributeKind PRVal)2283   void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
2284     PropertyAttributesAsWritten = PRVal;
2285   }
2286 
makeitReadWriteAttribute()2287  void makeitReadWriteAttribute() {
2288     PropertyAttributes &= ~OBJC_PR_readonly;
2289     PropertyAttributes |= OBJC_PR_readwrite;
2290  }
2291 
2292   // Helper methods for accessing attributes.
2293 
2294   /// isReadOnly - Return true iff the property has a setter.
isReadOnly()2295   bool isReadOnly() const {
2296     return (PropertyAttributes & OBJC_PR_readonly);
2297   }
2298 
2299   /// isAtomic - Return true if the property is atomic.
isAtomic()2300   bool isAtomic() const {
2301     return (PropertyAttributes & OBJC_PR_atomic);
2302   }
2303 
2304   /// isRetaining - Return true if the property retains its value.
isRetaining()2305   bool isRetaining() const {
2306     return (PropertyAttributes &
2307             (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
2308   }
2309 
2310   /// getSetterKind - Return the method used for doing assignment in
2311   /// the property setter. This is only valid if the property has been
2312   /// defined to have a setter.
getSetterKind()2313   SetterKind getSetterKind() const {
2314     if (PropertyAttributes & OBJC_PR_strong)
2315       return getType()->isBlockPointerType() ? Copy : Retain;
2316     if (PropertyAttributes & OBJC_PR_retain)
2317       return Retain;
2318     if (PropertyAttributes & OBJC_PR_copy)
2319       return Copy;
2320     if (PropertyAttributes & OBJC_PR_weak)
2321       return Weak;
2322     return Assign;
2323   }
2324 
getGetterName()2325   Selector getGetterName() const { return GetterName; }
setGetterName(Selector Sel)2326   void setGetterName(Selector Sel) { GetterName = Sel; }
2327 
getSetterName()2328   Selector getSetterName() const { return SetterName; }
setSetterName(Selector Sel)2329   void setSetterName(Selector Sel) { SetterName = Sel; }
2330 
getGetterMethodDecl()2331   ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
setGetterMethodDecl(ObjCMethodDecl * gDecl)2332   void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
2333 
getSetterMethodDecl()2334   ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
setSetterMethodDecl(ObjCMethodDecl * gDecl)2335   void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
2336 
2337   // Related to \@optional/\@required declared in \@protocol
setPropertyImplementation(PropertyControl pc)2338   void setPropertyImplementation(PropertyControl pc) {
2339     PropertyImplementation = pc;
2340   }
getPropertyImplementation()2341   PropertyControl getPropertyImplementation() const {
2342     return PropertyControl(PropertyImplementation);
2343   }
2344 
setPropertyIvarDecl(ObjCIvarDecl * Ivar)2345   void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
2346     PropertyIvarDecl = Ivar;
2347   }
getPropertyIvarDecl()2348   ObjCIvarDecl *getPropertyIvarDecl() const {
2349     return PropertyIvarDecl;
2350   }
2351 
getSourceRange()2352   SourceRange getSourceRange() const override LLVM_READONLY {
2353     return SourceRange(AtLoc, getLocation());
2354   }
2355 
2356   /// Get the default name of the synthesized ivar.
2357   IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
2358 
2359   /// Lookup a property by name in the specified DeclContext.
2360   static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
2361                                             const IdentifierInfo *propertyID);
2362 
classof(const Decl * D)2363   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2364   static bool classofKind(Kind K) { return K == ObjCProperty; }
2365 };
2366 
2367 /// ObjCPropertyImplDecl - Represents implementation declaration of a property
2368 /// in a class or category implementation block. For example:
2369 /// \@synthesize prop1 = ivar1;
2370 ///
2371 class ObjCPropertyImplDecl : public Decl {
2372 public:
2373   enum Kind {
2374     Synthesize,
2375     Dynamic
2376   };
2377 private:
2378   SourceLocation AtLoc;   // location of \@synthesize or \@dynamic
2379 
2380   /// \brief For \@synthesize, the location of the ivar, if it was written in
2381   /// the source code.
2382   ///
2383   /// \code
2384   /// \@synthesize int a = b
2385   /// \endcode
2386   SourceLocation IvarLoc;
2387 
2388   /// Property declaration being implemented
2389   ObjCPropertyDecl *PropertyDecl;
2390 
2391   /// Null for \@dynamic. Required for \@synthesize.
2392   ObjCIvarDecl *PropertyIvarDecl;
2393 
2394   /// Null for \@dynamic. Non-null if property must be copy-constructed in
2395   /// getter.
2396   Expr *GetterCXXConstructor;
2397 
2398   /// Null for \@dynamic. Non-null if property has assignment operator to call
2399   /// in Setter synthesis.
2400   Expr *SetterCXXAssignment;
2401 
ObjCPropertyImplDecl(DeclContext * DC,SourceLocation atLoc,SourceLocation L,ObjCPropertyDecl * property,Kind PK,ObjCIvarDecl * ivarDecl,SourceLocation ivarLoc)2402   ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2403                        ObjCPropertyDecl *property,
2404                        Kind PK,
2405                        ObjCIvarDecl *ivarDecl,
2406                        SourceLocation ivarLoc)
2407     : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2408       IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl),
2409       GetterCXXConstructor(nullptr), SetterCXXAssignment(nullptr) {
2410     assert (PK == Dynamic || PropertyIvarDecl);
2411   }
2412 
2413 public:
2414   static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2415                                       SourceLocation atLoc, SourceLocation L,
2416                                       ObjCPropertyDecl *property,
2417                                       Kind PK,
2418                                       ObjCIvarDecl *ivarDecl,
2419                                       SourceLocation ivarLoc);
2420 
2421   static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2422 
2423   SourceRange getSourceRange() const override LLVM_READONLY;
2424 
getLocStart()2425   SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; }
setAtLoc(SourceLocation Loc)2426   void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2427 
getPropertyDecl()2428   ObjCPropertyDecl *getPropertyDecl() const {
2429     return PropertyDecl;
2430   }
setPropertyDecl(ObjCPropertyDecl * Prop)2431   void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2432 
getPropertyImplementation()2433   Kind getPropertyImplementation() const {
2434     return PropertyIvarDecl ? Synthesize : Dynamic;
2435   }
2436 
getPropertyIvarDecl()2437   ObjCIvarDecl *getPropertyIvarDecl() const {
2438     return PropertyIvarDecl;
2439   }
getPropertyIvarDeclLoc()2440   SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2441 
setPropertyIvarDecl(ObjCIvarDecl * Ivar,SourceLocation IvarLoc)2442   void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2443                            SourceLocation IvarLoc) {
2444     PropertyIvarDecl = Ivar;
2445     this->IvarLoc = IvarLoc;
2446   }
2447 
2448   /// \brief For \@synthesize, returns true if an ivar name was explicitly
2449   /// specified.
2450   ///
2451   /// \code
2452   /// \@synthesize int a = b; // true
2453   /// \@synthesize int a; // false
2454   /// \endcode
isIvarNameSpecified()2455   bool isIvarNameSpecified() const {
2456     return IvarLoc.isValid() && IvarLoc != getLocation();
2457   }
2458 
getGetterCXXConstructor()2459   Expr *getGetterCXXConstructor() const {
2460     return GetterCXXConstructor;
2461   }
setGetterCXXConstructor(Expr * getterCXXConstructor)2462   void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2463     GetterCXXConstructor = getterCXXConstructor;
2464   }
2465 
getSetterCXXAssignment()2466   Expr *getSetterCXXAssignment() const {
2467     return SetterCXXAssignment;
2468   }
setSetterCXXAssignment(Expr * setterCXXAssignment)2469   void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2470     SetterCXXAssignment = setterCXXAssignment;
2471   }
2472 
classof(const Decl * D)2473   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Decl::Kind K)2474   static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2475 
2476   friend class ASTDeclReader;
2477 };
2478 
2479 template<bool (*Filter)(ObjCCategoryDecl *)>
2480 void
2481 ObjCInterfaceDecl::filtered_category_iterator<Filter>::
findAcceptableCategory()2482 findAcceptableCategory() {
2483   while (Current && !Filter(Current))
2484     Current = Current->getNextClassCategoryRaw();
2485 }
2486 
2487 template<bool (*Filter)(ObjCCategoryDecl *)>
2488 inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2489 ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2490   Current = Current->getNextClassCategoryRaw();
2491   findAcceptableCategory();
2492   return *this;
2493 }
2494 
isVisibleCategory(ObjCCategoryDecl * Cat)2495 inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2496   return !Cat->isHidden();
2497 }
2498 
isVisibleExtension(ObjCCategoryDecl * Cat)2499 inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2500   return Cat->IsClassExtension() && !Cat->isHidden();
2501 }
2502 
isKnownExtension(ObjCCategoryDecl * Cat)2503 inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2504   return Cat->IsClassExtension();
2505 }
2506 
2507 }  // end namespace clang
2508 #endif
2509