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