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