1 //===--- DeclObjC.cpp - ObjC Declaration AST Node Implementation ----------===//
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 implements the Objective-C related Decl classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/Stmt.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // ObjCListBase
25 //===----------------------------------------------------------------------===//
26 
27 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
28   List = nullptr;
29   if (Elts == 0) return;  // Setting to an empty list is a noop.
30 
31 
32   List = new (Ctx) void*[Elts];
33   NumElts = Elts;
34   memcpy(List, InList, sizeof(void*)*Elts);
35 }
36 
37 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts,
38                            const SourceLocation *Locs, ASTContext &Ctx) {
39   if (Elts == 0)
40     return;
41 
42   Locations = new (Ctx) SourceLocation[Elts];
43   memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
44   set(InList, Elts, Ctx);
45 }
46 
47 //===----------------------------------------------------------------------===//
48 // ObjCInterfaceDecl
49 //===----------------------------------------------------------------------===//
50 
51 void ObjCContainerDecl::anchor() { }
52 
53 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
54 ///
55 ObjCIvarDecl *
56 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
57   lookup_result R = lookup(Id);
58   for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end();
59        Ivar != IvarEnd; ++Ivar) {
60     if (ObjCIvarDecl *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
61       return ivar;
62   }
63   return nullptr;
64 }
65 
66 // Get the local instance/class method declared in this interface.
67 ObjCMethodDecl *
68 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance,
69                              bool AllowHidden) const {
70   // If this context is a hidden protocol definition, don't find any
71   // methods there.
72   if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
73     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
74       if (Def->isHidden() && !AllowHidden)
75         return nullptr;
76   }
77 
78   // Since instance & class methods can have the same name, the loop below
79   // ensures we get the correct method.
80   //
81   // @interface Whatever
82   // - (int) class_method;
83   // + (float) class_method;
84   // @end
85   //
86   lookup_result R = lookup(Sel);
87   for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
88        Meth != MethEnd; ++Meth) {
89     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
90     if (MD && MD->isInstanceMethod() == isInstance)
91       return MD;
92   }
93   return nullptr;
94 }
95 
96 /// \brief This routine returns 'true' if a user declared setter method was
97 /// found in the class, its protocols, its super classes or categories.
98 /// It also returns 'true' if one of its categories has declared a 'readwrite'
99 /// property.  This is because, user must provide a setter method for the
100 /// category's 'readwrite' property.
101 bool ObjCContainerDecl::HasUserDeclaredSetterMethod(
102     const ObjCPropertyDecl *Property) const {
103   Selector Sel = Property->getSetterName();
104   lookup_result R = lookup(Sel);
105   for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
106        Meth != MethEnd; ++Meth) {
107     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
108     if (MD && MD->isInstanceMethod() && !MD->isImplicit())
109       return true;
110   }
111 
112   if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
113     // Also look into categories, including class extensions, looking
114     // for a user declared instance method.
115     for (const auto *Cat : ID->visible_categories()) {
116       if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel))
117         if (!MD->isImplicit())
118           return true;
119       if (Cat->IsClassExtension())
120         continue;
121       // Also search through the categories looking for a 'readwrite'
122       // declaration of this property. If one found, presumably a setter will
123       // be provided (properties declared in categories will not get
124       // auto-synthesized).
125       for (const auto *P : Cat->properties())
126         if (P->getIdentifier() == Property->getIdentifier()) {
127           if (P->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite)
128             return true;
129           break;
130         }
131     }
132 
133     // Also look into protocols, for a user declared instance method.
134     for (const auto *Proto : ID->all_referenced_protocols())
135       if (Proto->HasUserDeclaredSetterMethod(Property))
136         return true;
137 
138     // And in its super class.
139     ObjCInterfaceDecl *OSC = ID->getSuperClass();
140     while (OSC) {
141       if (OSC->HasUserDeclaredSetterMethod(Property))
142         return true;
143       OSC = OSC->getSuperClass();
144     }
145   }
146   if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(this))
147     for (const auto *PI : PD->protocols())
148       if (PI->HasUserDeclaredSetterMethod(Property))
149         return true;
150   return false;
151 }
152 
153 ObjCPropertyDecl *
154 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
155                                    const IdentifierInfo *propertyID,
156                                    ObjCPropertyQueryKind queryKind) {
157   // If this context is a hidden protocol definition, don't find any
158   // property.
159   if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(DC)) {
160     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
161       if (Def->isHidden())
162         return nullptr;
163   }
164 
165   // If context is class, then lookup property in its extensions.
166   // This comes before property is looked up in primary class.
167   if (auto *IDecl = dyn_cast<ObjCInterfaceDecl>(DC)) {
168     for (const auto *Ext : IDecl->known_extensions())
169       if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl(Ext,
170                                                        propertyID,
171                                                        queryKind))
172         return PD;
173   }
174 
175   DeclContext::lookup_result R = DC->lookup(propertyID);
176   ObjCPropertyDecl *classProp = nullptr;
177   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
178        ++I)
179     if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I)) {
180       // If queryKind is unknown, we return the instance property if one
181       // exists; otherwise we return the class property.
182       if ((queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
183            !PD->isClassProperty()) ||
184           (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
185            PD->isClassProperty()) ||
186           (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
187            !PD->isClassProperty()))
188         return PD;
189 
190       if (PD->isClassProperty())
191         classProp = PD;
192     }
193 
194   if (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
195     // We can't find the instance property, return the class property.
196     return classProp;
197 
198   return nullptr;
199 }
200 
201 IdentifierInfo *
202 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const {
203   SmallString<128> ivarName;
204   {
205     llvm::raw_svector_ostream os(ivarName);
206     os << '_' << getIdentifier()->getName();
207   }
208   return &Ctx.Idents.get(ivarName.str());
209 }
210 
211 /// FindPropertyDeclaration - Finds declaration of the property given its name
212 /// in 'PropertyId' and returns it. It returns 0, if not found.
213 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration(
214     const IdentifierInfo *PropertyId,
215     ObjCPropertyQueryKind QueryKind) const {
216   // Don't find properties within hidden protocol definitions.
217   if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
218     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
219       if (Def->isHidden())
220         return nullptr;
221   }
222 
223   // Search the extensions of a class first; they override what's in
224   // the class itself.
225   if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) {
226     for (const auto *Ext : ClassDecl->visible_extensions()) {
227       if (auto *P = Ext->FindPropertyDeclaration(PropertyId, QueryKind))
228         return P;
229     }
230   }
231 
232   if (ObjCPropertyDecl *PD =
233         ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId,
234                                            QueryKind))
235     return PD;
236 
237   switch (getKind()) {
238     default:
239       break;
240     case Decl::ObjCProtocol: {
241       const ObjCProtocolDecl *PID = cast<ObjCProtocolDecl>(this);
242       for (const auto *I : PID->protocols())
243         if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
244                                                              QueryKind))
245           return P;
246       break;
247     }
248     case Decl::ObjCInterface: {
249       const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(this);
250       // Look through categories (but not extensions; they were handled above).
251       for (const auto *Cat : OID->visible_categories()) {
252         if (!Cat->IsClassExtension())
253           if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(
254                                              PropertyId, QueryKind))
255             return P;
256       }
257 
258       // Look through protocols.
259       for (const auto *I : OID->all_referenced_protocols())
260         if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
261                                                              QueryKind))
262           return P;
263 
264       // Finally, check the super class.
265       if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
266         return superClass->FindPropertyDeclaration(PropertyId, QueryKind);
267       break;
268     }
269     case Decl::ObjCCategory: {
270       const ObjCCategoryDecl *OCD = cast<ObjCCategoryDecl>(this);
271       // Look through protocols.
272       if (!OCD->IsClassExtension())
273         for (const auto *I : OCD->protocols())
274           if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
275                                                                QueryKind))
276             return P;
277       break;
278     }
279   }
280   return nullptr;
281 }
282 
283 void ObjCInterfaceDecl::anchor() { }
284 
285 ObjCTypeParamList *ObjCInterfaceDecl::getTypeParamList() const {
286   // If this particular declaration has a type parameter list, return it.
287   if (ObjCTypeParamList *written = getTypeParamListAsWritten())
288     return written;
289 
290   // If there is a definition, return its type parameter list.
291   if (const ObjCInterfaceDecl *def = getDefinition())
292     return def->getTypeParamListAsWritten();
293 
294   // Otherwise, look at previous declarations to determine whether any
295   // of them has a type parameter list, skipping over those
296   // declarations that do not.
297   for (auto decl = getMostRecentDecl(); decl; decl = decl->getPreviousDecl()) {
298     if (ObjCTypeParamList *written = decl->getTypeParamListAsWritten())
299       return written;
300   }
301 
302   return nullptr;
303 }
304 
305 void ObjCInterfaceDecl::setTypeParamList(ObjCTypeParamList *TPL) {
306   TypeParamList = TPL;
307   if (!TPL)
308     return;
309   // Set the declaration context of each of the type parameters.
310   for (auto typeParam : *TypeParamList)
311     typeParam->setDeclContext(this);
312 }
313 
314 ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const {
315   // FIXME: Should make sure no callers ever do this.
316   if (!hasDefinition())
317     return nullptr;
318 
319   if (data().ExternallyCompleted)
320     LoadExternalDefinition();
321 
322   if (const ObjCObjectType *superType = getSuperClassType()) {
323     if (ObjCInterfaceDecl *superDecl = superType->getInterface()) {
324       if (ObjCInterfaceDecl *superDef = superDecl->getDefinition())
325         return superDef;
326 
327       return superDecl;
328     }
329   }
330 
331   return nullptr;
332 }
333 
334 SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const {
335   if (TypeSourceInfo *superTInfo = getSuperClassTInfo())
336     return superTInfo->getTypeLoc().getLocStart();
337 
338   return SourceLocation();
339 }
340 
341 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
342 /// with name 'PropertyId' in the primary class; including those in protocols
343 /// (direct or indirect) used by the primary class.
344 ///
345 ObjCPropertyDecl *
346 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
347                        IdentifierInfo *PropertyId,
348                        ObjCPropertyQueryKind QueryKind) const {
349   // FIXME: Should make sure no callers ever do this.
350   if (!hasDefinition())
351     return nullptr;
352 
353   if (data().ExternallyCompleted)
354     LoadExternalDefinition();
355 
356   if (ObjCPropertyDecl *PD =
357       ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId,
358                                          QueryKind))
359     return PD;
360 
361   // Look through protocols.
362   for (const auto *I : all_referenced_protocols())
363     if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
364                                                          QueryKind))
365       return P;
366 
367   return nullptr;
368 }
369 
370 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM,
371                                                      PropertyDeclOrder &PO) const {
372   for (auto *Prop : properties()) {
373     PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
374     PO.push_back(Prop);
375   }
376   for (const auto *Ext : known_extensions()) {
377     const ObjCCategoryDecl *ClassExt = Ext;
378     for (auto *Prop : ClassExt->properties()) {
379       PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
380       PO.push_back(Prop);
381     }
382   }
383   for (const auto *PI : all_referenced_protocols())
384     PI->collectPropertiesToImplement(PM, PO);
385   // Note, the properties declared only in class extensions are still copied
386   // into the main @interface's property list, and therefore we don't
387   // explicitly, have to search class extension properties.
388 }
389 
390 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const {
391   const ObjCInterfaceDecl *Class = this;
392   while (Class) {
393     if (Class->hasAttr<ArcWeakrefUnavailableAttr>())
394       return true;
395     Class = Class->getSuperClass();
396   }
397   return false;
398 }
399 
400 const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const {
401   const ObjCInterfaceDecl *Class = this;
402   while (Class) {
403     if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
404       return Class;
405     Class = Class->getSuperClass();
406   }
407   return nullptr;
408 }
409 
410 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
411                               ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
412                               ASTContext &C)
413 {
414   if (data().ExternallyCompleted)
415     LoadExternalDefinition();
416 
417   if (data().AllReferencedProtocols.empty() &&
418       data().ReferencedProtocols.empty()) {
419     data().AllReferencedProtocols.set(ExtList, ExtNum, C);
420     return;
421   }
422 
423   // Check for duplicate protocol in class's protocol list.
424   // This is O(n*m). But it is extremely rare and number of protocols in
425   // class or its extension are very few.
426   SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
427   for (unsigned i = 0; i < ExtNum; i++) {
428     bool protocolExists = false;
429     ObjCProtocolDecl *ProtoInExtension = ExtList[i];
430     for (auto *Proto : all_referenced_protocols()) {
431       if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
432         protocolExists = true;
433         break;
434       }
435     }
436     // Do we want to warn on a protocol in extension class which
437     // already exist in the class? Probably not.
438     if (!protocolExists)
439       ProtocolRefs.push_back(ProtoInExtension);
440   }
441 
442   if (ProtocolRefs.empty())
443     return;
444 
445   // Merge ProtocolRefs into class's protocol list;
446   ProtocolRefs.append(all_referenced_protocol_begin(),
447                       all_referenced_protocol_end());
448 
449   data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
450 }
451 
452 const ObjCInterfaceDecl *
453 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const {
454   const ObjCInterfaceDecl *IFace = this;
455   while (IFace) {
456     if (IFace->hasDesignatedInitializers())
457       return IFace;
458     if (!IFace->inheritsDesignatedInitializers())
459       break;
460     IFace = IFace->getSuperClass();
461   }
462   return nullptr;
463 }
464 
465 static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) {
466   for (const auto *MD : D->instance_methods()) {
467     if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
468       return true;
469   }
470   for (const auto *Ext : D->visible_extensions()) {
471     for (const auto *MD : Ext->instance_methods()) {
472       if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
473         return true;
474     }
475   }
476   if (const auto *ImplD = D->getImplementation()) {
477     for (const auto *MD : ImplD->instance_methods()) {
478       if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
479         return true;
480     }
481   }
482   return false;
483 }
484 
485 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const {
486   switch (data().InheritedDesignatedInitializers) {
487   case DefinitionData::IDI_Inherited:
488     return true;
489   case DefinitionData::IDI_NotInherited:
490     return false;
491   case DefinitionData::IDI_Unknown: {
492     // If the class introduced initializers we conservatively assume that we
493     // don't know if any of them is a designated initializer to avoid possible
494     // misleading warnings.
495     if (isIntroducingInitializers(this)) {
496       data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited;
497     } else {
498       if (auto SuperD = getSuperClass()) {
499         data().InheritedDesignatedInitializers =
500           SuperD->declaresOrInheritsDesignatedInitializers() ?
501             DefinitionData::IDI_Inherited :
502             DefinitionData::IDI_NotInherited;
503       } else {
504         data().InheritedDesignatedInitializers =
505           DefinitionData::IDI_NotInherited;
506       }
507     }
508     assert(data().InheritedDesignatedInitializers
509              != DefinitionData::IDI_Unknown);
510     return data().InheritedDesignatedInitializers ==
511         DefinitionData::IDI_Inherited;
512   }
513   }
514 
515   llvm_unreachable("unexpected InheritedDesignatedInitializers value");
516 }
517 
518 void ObjCInterfaceDecl::getDesignatedInitializers(
519     llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const {
520   // Check for a complete definition and recover if not so.
521   if (!isThisDeclarationADefinition())
522     return;
523   if (data().ExternallyCompleted)
524     LoadExternalDefinition();
525 
526   const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
527   if (!IFace)
528     return;
529 
530   for (const auto *MD : IFace->instance_methods())
531     if (MD->isThisDeclarationADesignatedInitializer())
532       Methods.push_back(MD);
533   for (const auto *Ext : IFace->visible_extensions()) {
534     for (const auto *MD : Ext->instance_methods())
535       if (MD->isThisDeclarationADesignatedInitializer())
536         Methods.push_back(MD);
537   }
538 }
539 
540 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel,
541                                       const ObjCMethodDecl **InitMethod) const {
542   // Check for a complete definition and recover if not so.
543   if (!isThisDeclarationADefinition())
544     return false;
545   if (data().ExternallyCompleted)
546     LoadExternalDefinition();
547 
548   const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
549   if (!IFace)
550     return false;
551 
552   if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) {
553     if (MD->isThisDeclarationADesignatedInitializer()) {
554       if (InitMethod)
555         *InitMethod = MD;
556       return true;
557     }
558   }
559   for (const auto *Ext : IFace->visible_extensions()) {
560     if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) {
561       if (MD->isThisDeclarationADesignatedInitializer()) {
562         if (InitMethod)
563           *InitMethod = MD;
564         return true;
565       }
566     }
567   }
568   return false;
569 }
570 
571 void ObjCInterfaceDecl::allocateDefinitionData() {
572   assert(!hasDefinition() && "ObjC class already has a definition");
573   Data.setPointer(new (getASTContext()) DefinitionData());
574   Data.getPointer()->Definition = this;
575 
576   // Make the type point at the definition, now that we have one.
577   if (TypeForDecl)
578     cast<ObjCInterfaceType>(TypeForDecl)->Decl = this;
579 }
580 
581 void ObjCInterfaceDecl::startDefinition() {
582   allocateDefinitionData();
583 
584   // Update all of the declarations with a pointer to the definition.
585   for (auto RD : redecls()) {
586     if (RD != this)
587       RD->Data = Data;
588   }
589 }
590 
591 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
592                                               ObjCInterfaceDecl *&clsDeclared) {
593   // FIXME: Should make sure no callers ever do this.
594   if (!hasDefinition())
595     return nullptr;
596 
597   if (data().ExternallyCompleted)
598     LoadExternalDefinition();
599 
600   ObjCInterfaceDecl* ClassDecl = this;
601   while (ClassDecl != nullptr) {
602     if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
603       clsDeclared = ClassDecl;
604       return I;
605     }
606 
607     for (const auto *Ext : ClassDecl->visible_extensions()) {
608       if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) {
609         clsDeclared = ClassDecl;
610         return I;
611       }
612     }
613 
614     ClassDecl = ClassDecl->getSuperClass();
615   }
616   return nullptr;
617 }
618 
619 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
620 /// class whose name is passed as argument. If it is not one of the super classes
621 /// the it returns NULL.
622 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
623                                         const IdentifierInfo*ICName) {
624   // FIXME: Should make sure no callers ever do this.
625   if (!hasDefinition())
626     return nullptr;
627 
628   if (data().ExternallyCompleted)
629     LoadExternalDefinition();
630 
631   ObjCInterfaceDecl* ClassDecl = this;
632   while (ClassDecl != nullptr) {
633     if (ClassDecl->getIdentifier() == ICName)
634       return ClassDecl;
635     ClassDecl = ClassDecl->getSuperClass();
636   }
637   return nullptr;
638 }
639 
640 ObjCProtocolDecl *
641 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) {
642   for (auto *P : all_referenced_protocols())
643     if (P->lookupProtocolNamed(Name))
644       return P;
645   ObjCInterfaceDecl *SuperClass = getSuperClass();
646   return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr;
647 }
648 
649 /// lookupMethod - This method returns an instance/class method by looking in
650 /// the class, its categories, and its super classes (using a linear search).
651 /// When argument category "C" is specified, any implicit method found
652 /// in this category is ignored.
653 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
654                                                 bool isInstance,
655                                                 bool shallowCategoryLookup,
656                                                 bool followSuper,
657                                                 const ObjCCategoryDecl *C) const
658 {
659   // FIXME: Should make sure no callers ever do this.
660   if (!hasDefinition())
661     return nullptr;
662 
663   const ObjCInterfaceDecl* ClassDecl = this;
664   ObjCMethodDecl *MethodDecl = nullptr;
665 
666   if (data().ExternallyCompleted)
667     LoadExternalDefinition();
668 
669   while (ClassDecl) {
670     // 1. Look through primary class.
671     if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
672       return MethodDecl;
673 
674     // 2. Didn't find one yet - now look through categories.
675     for (const auto *Cat : ClassDecl->visible_categories())
676       if ((MethodDecl = Cat->getMethod(Sel, isInstance)))
677         if (C != Cat || !MethodDecl->isImplicit())
678           return MethodDecl;
679 
680     // 3. Didn't find one yet - look through primary class's protocols.
681     for (const auto *I : ClassDecl->protocols())
682       if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
683         return MethodDecl;
684 
685     // 4. Didn't find one yet - now look through categories' protocols
686     if (!shallowCategoryLookup)
687       for (const auto *Cat : ClassDecl->visible_categories()) {
688         // Didn't find one yet - look through protocols.
689         const ObjCList<ObjCProtocolDecl> &Protocols =
690           Cat->getReferencedProtocols();
691         for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
692              E = Protocols.end(); I != E; ++I)
693           if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
694             if (C != Cat || !MethodDecl->isImplicit())
695               return MethodDecl;
696       }
697 
698 
699     if (!followSuper)
700       return nullptr;
701 
702     // 5. Get to the super class (if any).
703     ClassDecl = ClassDecl->getSuperClass();
704   }
705   return nullptr;
706 }
707 
708 // Will search "local" class/category implementations for a method decl.
709 // If failed, then we search in class's root for an instance method.
710 // Returns 0 if no method is found.
711 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
712                                    const Selector &Sel,
713                                    bool Instance) const {
714   // FIXME: Should make sure no callers ever do this.
715   if (!hasDefinition())
716     return nullptr;
717 
718   if (data().ExternallyCompleted)
719     LoadExternalDefinition();
720 
721   ObjCMethodDecl *Method = nullptr;
722   if (ObjCImplementationDecl *ImpDecl = getImplementation())
723     Method = Instance ? ImpDecl->getInstanceMethod(Sel)
724                       : ImpDecl->getClassMethod(Sel);
725 
726   // Look through local category implementations associated with the class.
727   if (!Method)
728     Method = getCategoryMethod(Sel, Instance);
729 
730   // Before we give up, check if the selector is an instance method.
731   // But only in the root. This matches gcc's behavior and what the
732   // runtime expects.
733   if (!Instance && !Method && !getSuperClass()) {
734     Method = lookupInstanceMethod(Sel);
735     // Look through local category implementations associated
736     // with the root class.
737     if (!Method)
738       Method = lookupPrivateMethod(Sel, true);
739   }
740 
741   if (!Method && getSuperClass())
742     return getSuperClass()->lookupPrivateMethod(Sel, Instance);
743   return Method;
744 }
745 
746 //===----------------------------------------------------------------------===//
747 // ObjCMethodDecl
748 //===----------------------------------------------------------------------===//
749 
750 ObjCMethodDecl *ObjCMethodDecl::Create(
751     ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
752     Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
753     DeclContext *contextDecl, bool isInstance, bool isVariadic,
754     bool isPropertyAccessor, bool isImplicitlyDeclared, bool isDefined,
755     ImplementationControl impControl, bool HasRelatedResultType) {
756   return new (C, contextDecl) ObjCMethodDecl(
757       beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance,
758       isVariadic, isPropertyAccessor, isImplicitlyDeclared, isDefined,
759       impControl, HasRelatedResultType);
760 }
761 
762 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
763   return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(),
764                                     Selector(), QualType(), nullptr, nullptr);
765 }
766 
767 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const {
768   return getMethodFamily() == OMF_init &&
769       hasAttr<ObjCDesignatedInitializerAttr>();
770 }
771 
772 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface(
773     const ObjCMethodDecl **InitMethod) const {
774   if (getMethodFamily() != OMF_init)
775     return false;
776   const DeclContext *DC = getDeclContext();
777   if (isa<ObjCProtocolDecl>(DC))
778     return false;
779   if (const ObjCInterfaceDecl *ID = getClassInterface())
780     return ID->isDesignatedInitializer(getSelector(), InitMethod);
781   return false;
782 }
783 
784 Stmt *ObjCMethodDecl::getBody() const {
785   return Body.get(getASTContext().getExternalSource());
786 }
787 
788 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
789   assert(PrevMethod);
790   getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
791   IsRedeclaration = true;
792   PrevMethod->HasRedeclaration = true;
793 }
794 
795 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
796                                          ArrayRef<ParmVarDecl*> Params,
797                                          ArrayRef<SourceLocation> SelLocs) {
798   ParamsAndSelLocs = nullptr;
799   NumParams = Params.size();
800   if (Params.empty() && SelLocs.empty())
801     return;
802 
803   static_assert(llvm::AlignOf<ParmVarDecl *>::Alignment >=
804                     llvm::AlignOf<SourceLocation>::Alignment,
805                 "Alignment not sufficient for SourceLocation");
806 
807   unsigned Size = sizeof(ParmVarDecl *) * NumParams +
808                   sizeof(SourceLocation) * SelLocs.size();
809   ParamsAndSelLocs = C.Allocate(Size);
810   std::copy(Params.begin(), Params.end(), getParams());
811   std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
812 }
813 
814 void ObjCMethodDecl::getSelectorLocs(
815                                SmallVectorImpl<SourceLocation> &SelLocs) const {
816   for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
817     SelLocs.push_back(getSelectorLoc(i));
818 }
819 
820 void ObjCMethodDecl::setMethodParams(ASTContext &C,
821                                      ArrayRef<ParmVarDecl*> Params,
822                                      ArrayRef<SourceLocation> SelLocs) {
823   assert((!SelLocs.empty() || isImplicit()) &&
824          "No selector locs for non-implicit method");
825   if (isImplicit())
826     return setParamsAndSelLocs(C, Params, llvm::None);
827 
828   SelLocsKind = hasStandardSelectorLocs(getSelector(), SelLocs, Params,
829                                         DeclEndLoc);
830   if (SelLocsKind != SelLoc_NonStandard)
831     return setParamsAndSelLocs(C, Params, llvm::None);
832 
833   setParamsAndSelLocs(C, Params, SelLocs);
834 }
835 
836 /// \brief A definition will return its interface declaration.
837 /// An interface declaration will return its definition.
838 /// Otherwise it will return itself.
839 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() {
840   ASTContext &Ctx = getASTContext();
841   ObjCMethodDecl *Redecl = nullptr;
842   if (HasRedeclaration)
843     Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
844   if (Redecl)
845     return Redecl;
846 
847   Decl *CtxD = cast<Decl>(getDeclContext());
848 
849   if (!CtxD->isInvalidDecl()) {
850     if (ObjCInterfaceDecl *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
851       if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
852         if (!ImplD->isInvalidDecl())
853           Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
854 
855     } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
856       if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
857         if (!ImplD->isInvalidDecl())
858           Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
859 
860     } else if (ObjCImplementationDecl *ImplD =
861                  dyn_cast<ObjCImplementationDecl>(CtxD)) {
862       if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
863         if (!IFD->isInvalidDecl())
864           Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
865 
866     } else if (ObjCCategoryImplDecl *CImplD =
867                  dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
868       if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
869         if (!CatD->isInvalidDecl())
870           Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
871     }
872   }
873 
874   if (!Redecl && isRedeclaration()) {
875     // This is the last redeclaration, go back to the first method.
876     return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
877                                                     isInstanceMethod());
878   }
879 
880   return Redecl ? Redecl : this;
881 }
882 
883 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
884   Decl *CtxD = cast<Decl>(getDeclContext());
885 
886   if (ObjCImplementationDecl *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
887     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
888       if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
889                                               isInstanceMethod()))
890         return MD;
891 
892   } else if (ObjCCategoryImplDecl *CImplD =
893                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
894     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
895       if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
896                                                isInstanceMethod()))
897         return MD;
898   }
899 
900   if (isRedeclaration()) {
901     // It is possible that we have not done deserializing the ObjCMethod yet.
902     ObjCMethodDecl *MD =
903         cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
904                                                  isInstanceMethod());
905     return MD ? MD : this;
906   }
907 
908   return this;
909 }
910 
911 SourceLocation ObjCMethodDecl::getLocEnd() const {
912   if (Stmt *Body = getBody())
913     return Body->getLocEnd();
914   return DeclEndLoc;
915 }
916 
917 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
918   ObjCMethodFamily family = static_cast<ObjCMethodFamily>(Family);
919   if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
920     return family;
921 
922   // Check for an explicit attribute.
923   if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
924     // The unfortunate necessity of mapping between enums here is due
925     // to the attributes framework.
926     switch (attr->getFamily()) {
927     case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
928     case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
929     case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
930     case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
931     case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
932     case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
933     }
934     Family = static_cast<unsigned>(family);
935     return family;
936   }
937 
938   family = getSelector().getMethodFamily();
939   switch (family) {
940   case OMF_None: break;
941 
942   // init only has a conventional meaning for an instance method, and
943   // it has to return an object.
944   case OMF_init:
945     if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
946       family = OMF_None;
947     break;
948 
949   // alloc/copy/new have a conventional meaning for both class and
950   // instance methods, but they require an object return.
951   case OMF_alloc:
952   case OMF_copy:
953   case OMF_mutableCopy:
954   case OMF_new:
955     if (!getReturnType()->isObjCObjectPointerType())
956       family = OMF_None;
957     break;
958 
959   // These selectors have a conventional meaning only for instance methods.
960   case OMF_dealloc:
961   case OMF_finalize:
962   case OMF_retain:
963   case OMF_release:
964   case OMF_autorelease:
965   case OMF_retainCount:
966   case OMF_self:
967     if (!isInstanceMethod())
968       family = OMF_None;
969     break;
970 
971   case OMF_initialize:
972     if (isInstanceMethod() || !getReturnType()->isVoidType())
973       family = OMF_None;
974     break;
975 
976   case OMF_performSelector:
977     if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
978       family = OMF_None;
979     else {
980       unsigned noParams = param_size();
981       if (noParams < 1 || noParams > 3)
982         family = OMF_None;
983       else {
984         ObjCMethodDecl::param_type_iterator it = param_type_begin();
985         QualType ArgT = (*it);
986         if (!ArgT->isObjCSelType()) {
987           family = OMF_None;
988           break;
989         }
990         while (--noParams) {
991           it++;
992           ArgT = (*it);
993           if (!ArgT->isObjCIdType()) {
994             family = OMF_None;
995             break;
996           }
997         }
998       }
999     }
1000     break;
1001 
1002   }
1003 
1004   // Cache the result.
1005   Family = static_cast<unsigned>(family);
1006   return family;
1007 }
1008 
1009 QualType ObjCMethodDecl::getSelfType(ASTContext &Context,
1010                                      const ObjCInterfaceDecl *OID,
1011                                      bool &selfIsPseudoStrong,
1012                                      bool &selfIsConsumed) {
1013   QualType selfTy;
1014   selfIsPseudoStrong = false;
1015   selfIsConsumed = false;
1016   if (isInstanceMethod()) {
1017     // There may be no interface context due to error in declaration
1018     // of the interface (which has been reported). Recover gracefully.
1019     if (OID) {
1020       selfTy = Context.getObjCInterfaceType(OID);
1021       selfTy = Context.getObjCObjectPointerType(selfTy);
1022     } else {
1023       selfTy = Context.getObjCIdType();
1024     }
1025   } else // we have a factory method.
1026     selfTy = Context.getObjCClassType();
1027 
1028   if (Context.getLangOpts().ObjCAutoRefCount) {
1029     if (isInstanceMethod()) {
1030       selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
1031 
1032       // 'self' is always __strong.  It's actually pseudo-strong except
1033       // in init methods (or methods labeled ns_consumes_self), though.
1034       Qualifiers qs;
1035       qs.setObjCLifetime(Qualifiers::OCL_Strong);
1036       selfTy = Context.getQualifiedType(selfTy, qs);
1037 
1038       // In addition, 'self' is const unless this is an init method.
1039       if (getMethodFamily() != OMF_init && !selfIsConsumed) {
1040         selfTy = selfTy.withConst();
1041         selfIsPseudoStrong = true;
1042       }
1043     }
1044     else {
1045       assert(isClassMethod());
1046       // 'self' is always const in class methods.
1047       selfTy = selfTy.withConst();
1048       selfIsPseudoStrong = true;
1049     }
1050   }
1051   return selfTy;
1052 }
1053 
1054 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
1055                                           const ObjCInterfaceDecl *OID) {
1056   bool selfIsPseudoStrong, selfIsConsumed;
1057   QualType selfTy =
1058     getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed);
1059   ImplicitParamDecl *self
1060     = ImplicitParamDecl::Create(Context, this, SourceLocation(),
1061                                 &Context.Idents.get("self"), selfTy);
1062   setSelfDecl(self);
1063 
1064   if (selfIsConsumed)
1065     self->addAttr(NSConsumedAttr::CreateImplicit(Context));
1066 
1067   if (selfIsPseudoStrong)
1068     self->setARCPseudoStrong(true);
1069 
1070   setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
1071                                        &Context.Idents.get("_cmd"),
1072                                        Context.getObjCSelType()));
1073 }
1074 
1075 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
1076   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
1077     return ID;
1078   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1079     return CD->getClassInterface();
1080   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
1081     return IMD->getClassInterface();
1082   if (isa<ObjCProtocolDecl>(getDeclContext()))
1083     return nullptr;
1084   llvm_unreachable("unknown method context");
1085 }
1086 
1087 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const {
1088   const auto *TSI = getReturnTypeSourceInfo();
1089   if (TSI)
1090     return TSI->getTypeLoc().getSourceRange();
1091   return SourceRange();
1092 }
1093 
1094 QualType ObjCMethodDecl::getSendResultType() const {
1095   ASTContext &Ctx = getASTContext();
1096   return getReturnType().getNonLValueExprType(Ctx)
1097            .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result);
1098 }
1099 
1100 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const {
1101   // FIXME: Handle related result types here.
1102 
1103   return getReturnType().getNonLValueExprType(getASTContext())
1104            .substObjCMemberType(receiverType, getDeclContext(),
1105                                 ObjCSubstitutionContext::Result);
1106 }
1107 
1108 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
1109                                             const ObjCMethodDecl *Method,
1110                                SmallVectorImpl<const ObjCMethodDecl *> &Methods,
1111                                             bool MovedToSuper) {
1112   if (!Container)
1113     return;
1114 
1115   // In categories look for overriden methods from protocols. A method from
1116   // category is not "overriden" since it is considered as the "same" method
1117   // (same USR) as the one from the interface.
1118   if (const ObjCCategoryDecl *
1119         Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1120     // Check whether we have a matching method at this category but only if we
1121     // are at the super class level.
1122     if (MovedToSuper)
1123       if (ObjCMethodDecl *
1124             Overridden = Container->getMethod(Method->getSelector(),
1125                                               Method->isInstanceMethod(),
1126                                               /*AllowHidden=*/true))
1127         if (Method != Overridden) {
1128           // We found an override at this category; there is no need to look
1129           // into its protocols.
1130           Methods.push_back(Overridden);
1131           return;
1132         }
1133 
1134     for (const auto *P : Category->protocols())
1135       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1136     return;
1137   }
1138 
1139   // Check whether we have a matching method at this level.
1140   if (const ObjCMethodDecl *
1141         Overridden = Container->getMethod(Method->getSelector(),
1142                                           Method->isInstanceMethod(),
1143                                           /*AllowHidden=*/true))
1144     if (Method != Overridden) {
1145       // We found an override at this level; there is no need to look
1146       // into other protocols or categories.
1147       Methods.push_back(Overridden);
1148       return;
1149     }
1150 
1151   if (const ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
1152     for (const auto *P : Protocol->protocols())
1153       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1154   }
1155 
1156   if (const ObjCInterfaceDecl *
1157         Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1158     for (const auto *P : Interface->protocols())
1159       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1160 
1161     for (const auto *Cat : Interface->known_categories())
1162       CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper);
1163 
1164     if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1165       return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1166                                              /*MovedToSuper=*/true);
1167   }
1168 }
1169 
1170 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1171                                             const ObjCMethodDecl *Method,
1172                              SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1173   CollectOverriddenMethodsRecurse(Container, Method, Methods,
1174                                   /*MovedToSuper=*/false);
1175 }
1176 
1177 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1178                           SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1179   assert(Method->isOverriding());
1180 
1181   if (const ObjCProtocolDecl *
1182         ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1183     CollectOverriddenMethods(ProtD, Method, overridden);
1184 
1185   } else if (const ObjCImplDecl *
1186                IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1187     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1188     if (!ID)
1189       return;
1190     // Start searching for overridden methods using the method from the
1191     // interface as starting point.
1192     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1193                                                     Method->isInstanceMethod(),
1194                                                     /*AllowHidden=*/true))
1195       Method = IFaceMeth;
1196     CollectOverriddenMethods(ID, Method, overridden);
1197 
1198   } else if (const ObjCCategoryDecl *
1199                CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1200     const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1201     if (!ID)
1202       return;
1203     // Start searching for overridden methods using the method from the
1204     // interface as starting point.
1205     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1206                                                      Method->isInstanceMethod(),
1207                                                      /*AllowHidden=*/true))
1208       Method = IFaceMeth;
1209     CollectOverriddenMethods(ID, Method, overridden);
1210 
1211   } else {
1212     CollectOverriddenMethods(
1213                   dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1214                   Method, overridden);
1215   }
1216 }
1217 
1218 void ObjCMethodDecl::getOverriddenMethods(
1219                     SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1220   const ObjCMethodDecl *Method = this;
1221 
1222   if (Method->isRedeclaration()) {
1223     Method = cast<ObjCContainerDecl>(Method->getDeclContext())->
1224                    getMethod(Method->getSelector(), Method->isInstanceMethod());
1225   }
1226 
1227   if (Method->isOverriding()) {
1228     collectOverriddenMethodsSlow(Method, Overridden);
1229     assert(!Overridden.empty() &&
1230            "ObjCMethodDecl's overriding bit is not as expected");
1231   }
1232 }
1233 
1234 const ObjCPropertyDecl *
1235 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1236   Selector Sel = getSelector();
1237   unsigned NumArgs = Sel.getNumArgs();
1238   if (NumArgs > 1)
1239     return nullptr;
1240 
1241   if (isPropertyAccessor()) {
1242     const ObjCContainerDecl *Container = cast<ObjCContainerDecl>(getParent());
1243     bool IsGetter = (NumArgs == 0);
1244     bool IsInstance = isInstanceMethod();
1245 
1246     /// Local function that attempts to find a matching property within the
1247     /// given Objective-C container.
1248     auto findMatchingProperty =
1249       [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * {
1250       if (IsInstance) {
1251         for (const auto *I : Container->instance_properties()) {
1252           Selector NextSel = IsGetter ? I->getGetterName()
1253                                       : I->getSetterName();
1254           if (NextSel == Sel)
1255             return I;
1256         }
1257       } else {
1258         for (const auto *I : Container->class_properties()) {
1259           Selector NextSel = IsGetter ? I->getGetterName()
1260                                       : I->getSetterName();
1261           if (NextSel == Sel)
1262             return I;
1263         }
1264       }
1265 
1266       return nullptr;
1267     };
1268 
1269     // Look in the container we were given.
1270     if (const auto *Found = findMatchingProperty(Container))
1271       return Found;
1272 
1273     // If we're in a category or extension, look in the main class.
1274     const ObjCInterfaceDecl *ClassDecl = nullptr;
1275     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1276       ClassDecl = Category->getClassInterface();
1277       if (const auto *Found = findMatchingProperty(ClassDecl))
1278         return Found;
1279     } else {
1280       // Determine whether the container is a class.
1281       ClassDecl = dyn_cast<ObjCInterfaceDecl>(Container);
1282     }
1283 
1284     // If we have a class, check its visible extensions.
1285     if (ClassDecl) {
1286       for (const auto *Ext : ClassDecl->visible_extensions()) {
1287         if (Ext == Container)
1288           continue;
1289 
1290         if (const auto *Found = findMatchingProperty(Ext))
1291           return Found;
1292       }
1293     }
1294 
1295     llvm_unreachable("Marked as a property accessor but no property found!");
1296   }
1297 
1298   if (!CheckOverrides)
1299     return nullptr;
1300 
1301   typedef SmallVector<const ObjCMethodDecl *, 8> OverridesTy;
1302   OverridesTy Overrides;
1303   getOverriddenMethods(Overrides);
1304   for (OverridesTy::const_iterator I = Overrides.begin(), E = Overrides.end();
1305        I != E; ++I) {
1306     if (const ObjCPropertyDecl *Prop = (*I)->findPropertyDecl(false))
1307       return Prop;
1308   }
1309 
1310   return nullptr;
1311 }
1312 
1313 //===----------------------------------------------------------------------===//
1314 // ObjCTypeParamDecl
1315 //===----------------------------------------------------------------------===//
1316 
1317 void ObjCTypeParamDecl::anchor() { }
1318 
1319 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc,
1320                                              ObjCTypeParamVariance variance,
1321                                              SourceLocation varianceLoc,
1322                                              unsigned index,
1323                                              SourceLocation nameLoc,
1324                                              IdentifierInfo *name,
1325                                              SourceLocation colonLoc,
1326                                              TypeSourceInfo *boundInfo) {
1327   auto *TPDecl =
1328     new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index,
1329                                     nameLoc, name, colonLoc, boundInfo);
1330   QualType TPType = ctx.getObjCTypeParamType(TPDecl, {});
1331   TPDecl->setTypeForDecl(TPType.getTypePtr());
1332   return TPDecl;
1333 }
1334 
1335 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx,
1336                                                          unsigned ID) {
1337   return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr,
1338                                          ObjCTypeParamVariance::Invariant,
1339                                          SourceLocation(), 0, SourceLocation(),
1340                                          nullptr, SourceLocation(), nullptr);
1341 }
1342 
1343 SourceRange ObjCTypeParamDecl::getSourceRange() const {
1344   SourceLocation startLoc = VarianceLoc;
1345   if (startLoc.isInvalid())
1346     startLoc = getLocation();
1347 
1348   if (hasExplicitBound()) {
1349     return SourceRange(startLoc,
1350                        getTypeSourceInfo()->getTypeLoc().getEndLoc());
1351   }
1352 
1353   return SourceRange(startLoc);
1354 }
1355 
1356 //===----------------------------------------------------------------------===//
1357 // ObjCTypeParamList
1358 //===----------------------------------------------------------------------===//
1359 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc,
1360                                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1361                                      SourceLocation rAngleLoc)
1362   : NumParams(typeParams.size())
1363 {
1364   Brackets.Begin = lAngleLoc.getRawEncoding();
1365   Brackets.End = rAngleLoc.getRawEncoding();
1366   std::copy(typeParams.begin(), typeParams.end(), begin());
1367 }
1368 
1369 
1370 ObjCTypeParamList *ObjCTypeParamList::create(
1371                      ASTContext &ctx,
1372                      SourceLocation lAngleLoc,
1373                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1374                      SourceLocation rAngleLoc) {
1375   void *mem =
1376       ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()),
1377                    llvm::alignOf<ObjCTypeParamList>());
1378   return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc);
1379 }
1380 
1381 void ObjCTypeParamList::gatherDefaultTypeArgs(
1382        SmallVectorImpl<QualType> &typeArgs) const {
1383   typeArgs.reserve(size());
1384   for (auto typeParam : *this)
1385     typeArgs.push_back(typeParam->getUnderlyingType());
1386 }
1387 
1388 //===----------------------------------------------------------------------===//
1389 // ObjCInterfaceDecl
1390 //===----------------------------------------------------------------------===//
1391 
1392 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1393                                              DeclContext *DC,
1394                                              SourceLocation atLoc,
1395                                              IdentifierInfo *Id,
1396                                              ObjCTypeParamList *typeParamList,
1397                                              ObjCInterfaceDecl *PrevDecl,
1398                                              SourceLocation ClassLoc,
1399                                              bool isInternal){
1400   ObjCInterfaceDecl *Result = new (C, DC)
1401       ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl,
1402                         isInternal);
1403   Result->Data.setInt(!C.getLangOpts().Modules);
1404   C.getObjCInterfaceType(Result, PrevDecl);
1405   return Result;
1406 }
1407 
1408 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1409                                                          unsigned ID) {
1410   ObjCInterfaceDecl *Result = new (C, ID) ObjCInterfaceDecl(C, nullptr,
1411                                                             SourceLocation(),
1412                                                             nullptr,
1413                                                             nullptr,
1414                                                             SourceLocation(),
1415                                                             nullptr, false);
1416   Result->Data.setInt(!C.getLangOpts().Modules);
1417   return Result;
1418 }
1419 
1420 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1421                                      SourceLocation AtLoc, IdentifierInfo *Id,
1422                                      ObjCTypeParamList *typeParamList,
1423                                      SourceLocation CLoc,
1424                                      ObjCInterfaceDecl *PrevDecl,
1425                                      bool IsInternal)
1426     : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1427       redeclarable_base(C), TypeForDecl(nullptr), TypeParamList(nullptr),
1428       Data() {
1429   setPreviousDecl(PrevDecl);
1430 
1431   // Copy the 'data' pointer over.
1432   if (PrevDecl)
1433     Data = PrevDecl->Data;
1434 
1435   setImplicit(IsInternal);
1436 
1437   setTypeParamList(typeParamList);
1438 }
1439 
1440 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1441   assert(data().ExternallyCompleted && "Class is not externally completed");
1442   data().ExternallyCompleted = false;
1443   getASTContext().getExternalSource()->CompleteType(
1444                                         const_cast<ObjCInterfaceDecl *>(this));
1445 }
1446 
1447 void ObjCInterfaceDecl::setExternallyCompleted() {
1448   assert(getASTContext().getExternalSource() &&
1449          "Class can't be externally completed without an external source");
1450   assert(hasDefinition() &&
1451          "Forward declarations can't be externally completed");
1452   data().ExternallyCompleted = true;
1453 }
1454 
1455 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1456   // Check for a complete definition and recover if not so.
1457   if (!isThisDeclarationADefinition())
1458     return;
1459   data().HasDesignatedInitializers = true;
1460 }
1461 
1462 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1463   // Check for a complete definition and recover if not so.
1464   if (!isThisDeclarationADefinition())
1465     return false;
1466   if (data().ExternallyCompleted)
1467     LoadExternalDefinition();
1468 
1469   return data().HasDesignatedInitializers;
1470 }
1471 
1472 StringRef
1473 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1474   if (ObjCRuntimeNameAttr *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1475     return ObjCRTName->getMetadataName();
1476 
1477   return getName();
1478 }
1479 
1480 StringRef
1481 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1482   if (ObjCInterfaceDecl *ID =
1483       const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1484     return ID->getObjCRuntimeNameAsString();
1485 
1486   return getName();
1487 }
1488 
1489 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1490   if (const ObjCInterfaceDecl *Def = getDefinition()) {
1491     if (data().ExternallyCompleted)
1492       LoadExternalDefinition();
1493 
1494     return getASTContext().getObjCImplementation(
1495              const_cast<ObjCInterfaceDecl*>(Def));
1496   }
1497 
1498   // FIXME: Should make sure no callers ever do this.
1499   return nullptr;
1500 }
1501 
1502 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1503   getASTContext().setObjCImplementation(getDefinition(), ImplD);
1504 }
1505 
1506 namespace {
1507   struct SynthesizeIvarChunk {
1508     uint64_t Size;
1509     ObjCIvarDecl *Ivar;
1510     SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1511       : Size(size), Ivar(ivar) {}
1512   };
1513 
1514   bool operator<(const SynthesizeIvarChunk & LHS,
1515                  const SynthesizeIvarChunk &RHS) {
1516       return LHS.Size < RHS.Size;
1517   }
1518 }
1519 
1520 /// all_declared_ivar_begin - return first ivar declared in this class,
1521 /// its extensions and its implementation. Lazily build the list on first
1522 /// access.
1523 ///
1524 /// Caveat: The list returned by this method reflects the current
1525 /// state of the parser. The cache will be updated for every ivar
1526 /// added by an extension or the implementation when they are
1527 /// encountered.
1528 /// See also ObjCIvarDecl::Create().
1529 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1530   // FIXME: Should make sure no callers ever do this.
1531   if (!hasDefinition())
1532     return nullptr;
1533 
1534   ObjCIvarDecl *curIvar = nullptr;
1535   if (!data().IvarList) {
1536     if (!ivar_empty()) {
1537       ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1538       data().IvarList = *I; ++I;
1539       for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1540         curIvar->setNextIvar(*I);
1541     }
1542 
1543     for (const auto *Ext : known_extensions()) {
1544       if (!Ext->ivar_empty()) {
1545         ObjCCategoryDecl::ivar_iterator
1546           I = Ext->ivar_begin(),
1547           E = Ext->ivar_end();
1548         if (!data().IvarList) {
1549           data().IvarList = *I; ++I;
1550           curIvar = data().IvarList;
1551         }
1552         for ( ;I != E; curIvar = *I, ++I)
1553           curIvar->setNextIvar(*I);
1554       }
1555     }
1556     data().IvarListMissingImplementation = true;
1557   }
1558 
1559   // cached and complete!
1560   if (!data().IvarListMissingImplementation)
1561       return data().IvarList;
1562 
1563   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1564     data().IvarListMissingImplementation = false;
1565     if (!ImplDecl->ivar_empty()) {
1566       SmallVector<SynthesizeIvarChunk, 16> layout;
1567       for (auto *IV : ImplDecl->ivars()) {
1568         if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1569           layout.push_back(SynthesizeIvarChunk(
1570                              IV->getASTContext().getTypeSize(IV->getType()), IV));
1571           continue;
1572         }
1573         if (!data().IvarList)
1574           data().IvarList = IV;
1575         else
1576           curIvar->setNextIvar(IV);
1577         curIvar = IV;
1578       }
1579 
1580       if (!layout.empty()) {
1581         // Order synthesized ivars by their size.
1582         std::stable_sort(layout.begin(), layout.end());
1583         unsigned Ix = 0, EIx = layout.size();
1584         if (!data().IvarList) {
1585           data().IvarList = layout[0].Ivar; Ix++;
1586           curIvar = data().IvarList;
1587         }
1588         for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1589           curIvar->setNextIvar(layout[Ix].Ivar);
1590       }
1591     }
1592   }
1593   return data().IvarList;
1594 }
1595 
1596 /// FindCategoryDeclaration - Finds category declaration in the list of
1597 /// categories for this class and returns it. Name of the category is passed
1598 /// in 'CategoryId'. If category not found, return 0;
1599 ///
1600 ObjCCategoryDecl *
1601 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1602   // FIXME: Should make sure no callers ever do this.
1603   if (!hasDefinition())
1604     return nullptr;
1605 
1606   if (data().ExternallyCompleted)
1607     LoadExternalDefinition();
1608 
1609   for (auto *Cat : visible_categories())
1610     if (Cat->getIdentifier() == CategoryId)
1611       return Cat;
1612 
1613   return nullptr;
1614 }
1615 
1616 ObjCMethodDecl *
1617 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1618   for (const auto *Cat : visible_categories()) {
1619     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1620       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1621         return MD;
1622   }
1623 
1624   return nullptr;
1625 }
1626 
1627 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1628   for (const auto *Cat : visible_categories()) {
1629     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1630       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1631         return MD;
1632   }
1633 
1634   return nullptr;
1635 }
1636 
1637 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1638 /// has been implemented in IDecl class, its super class or categories (if
1639 /// lookupCategory is true).
1640 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1641                                     bool lookupCategory,
1642                                     bool RHSIsQualifiedID) {
1643   if (!hasDefinition())
1644     return false;
1645 
1646   ObjCInterfaceDecl *IDecl = this;
1647   // 1st, look up the class.
1648   for (auto *PI : IDecl->protocols()){
1649     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1650       return true;
1651     // This is dubious and is added to be compatible with gcc.  In gcc, it is
1652     // also allowed assigning a protocol-qualified 'id' type to a LHS object
1653     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1654     // object. This IMO, should be a bug.
1655     // FIXME: Treat this as an extension, and flag this as an error when GCC
1656     // extensions are not enabled.
1657     if (RHSIsQualifiedID &&
1658         getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1659       return true;
1660   }
1661 
1662   // 2nd, look up the category.
1663   if (lookupCategory)
1664     for (const auto *Cat : visible_categories()) {
1665       for (auto *PI : Cat->protocols())
1666         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1667           return true;
1668     }
1669 
1670   // 3rd, look up the super class(s)
1671   if (IDecl->getSuperClass())
1672     return
1673   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1674                                                   RHSIsQualifiedID);
1675 
1676   return false;
1677 }
1678 
1679 //===----------------------------------------------------------------------===//
1680 // ObjCIvarDecl
1681 //===----------------------------------------------------------------------===//
1682 
1683 void ObjCIvarDecl::anchor() { }
1684 
1685 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1686                                    SourceLocation StartLoc,
1687                                    SourceLocation IdLoc, IdentifierInfo *Id,
1688                                    QualType T, TypeSourceInfo *TInfo,
1689                                    AccessControl ac, Expr *BW,
1690                                    bool synthesized) {
1691   if (DC) {
1692     // Ivar's can only appear in interfaces, implementations (via synthesized
1693     // properties), and class extensions (via direct declaration, or synthesized
1694     // properties).
1695     //
1696     // FIXME: This should really be asserting this:
1697     //   (isa<ObjCCategoryDecl>(DC) &&
1698     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1699     // but unfortunately we sometimes place ivars into non-class extension
1700     // categories on error. This breaks an AST invariant, and should not be
1701     // fixed.
1702     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
1703             isa<ObjCCategoryDecl>(DC)) &&
1704            "Invalid ivar decl context!");
1705     // Once a new ivar is created in any of class/class-extension/implementation
1706     // decl contexts, the previously built IvarList must be rebuilt.
1707     ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1708     if (!ID) {
1709       if (ObjCImplementationDecl *IM = dyn_cast<ObjCImplementationDecl>(DC))
1710         ID = IM->getClassInterface();
1711       else
1712         ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1713     }
1714     ID->setIvarList(nullptr);
1715   }
1716 
1717   return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1718                                   synthesized);
1719 }
1720 
1721 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1722   return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1723                                   nullptr, QualType(), nullptr,
1724                                   ObjCIvarDecl::None, nullptr, false);
1725 }
1726 
1727 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1728   const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
1729 
1730   switch (DC->getKind()) {
1731   default:
1732   case ObjCCategoryImpl:
1733   case ObjCProtocol:
1734     llvm_unreachable("invalid ivar container!");
1735 
1736     // Ivars can only appear in class extension categories.
1737   case ObjCCategory: {
1738     const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
1739     assert(CD->IsClassExtension() && "invalid container for ivar!");
1740     return CD->getClassInterface();
1741   }
1742 
1743   case ObjCImplementation:
1744     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1745 
1746   case ObjCInterface:
1747     return cast<ObjCInterfaceDecl>(DC);
1748   }
1749 }
1750 
1751 QualType ObjCIvarDecl::getUsageType(QualType objectType) const {
1752   return getType().substObjCMemberType(objectType, getDeclContext(),
1753                                        ObjCSubstitutionContext::Property);
1754 }
1755 
1756 //===----------------------------------------------------------------------===//
1757 // ObjCAtDefsFieldDecl
1758 //===----------------------------------------------------------------------===//
1759 
1760 void ObjCAtDefsFieldDecl::anchor() { }
1761 
1762 ObjCAtDefsFieldDecl
1763 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1764                              SourceLocation StartLoc,  SourceLocation IdLoc,
1765                              IdentifierInfo *Id, QualType T, Expr *BW) {
1766   return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1767 }
1768 
1769 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1770                                                              unsigned ID) {
1771   return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1772                                          SourceLocation(), nullptr, QualType(),
1773                                          nullptr);
1774 }
1775 
1776 //===----------------------------------------------------------------------===//
1777 // ObjCProtocolDecl
1778 //===----------------------------------------------------------------------===//
1779 
1780 void ObjCProtocolDecl::anchor() { }
1781 
1782 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1783                                    IdentifierInfo *Id, SourceLocation nameLoc,
1784                                    SourceLocation atStartLoc,
1785                                    ObjCProtocolDecl *PrevDecl)
1786     : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1787       redeclarable_base(C), Data() {
1788   setPreviousDecl(PrevDecl);
1789   if (PrevDecl)
1790     Data = PrevDecl->Data;
1791 }
1792 
1793 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1794                                            IdentifierInfo *Id,
1795                                            SourceLocation nameLoc,
1796                                            SourceLocation atStartLoc,
1797                                            ObjCProtocolDecl *PrevDecl) {
1798   ObjCProtocolDecl *Result =
1799       new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1800   Result->Data.setInt(!C.getLangOpts().Modules);
1801   return Result;
1802 }
1803 
1804 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1805                                                        unsigned ID) {
1806   ObjCProtocolDecl *Result =
1807       new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1808                                    SourceLocation(), nullptr);
1809   Result->Data.setInt(!C.getLangOpts().Modules);
1810   return Result;
1811 }
1812 
1813 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1814   ObjCProtocolDecl *PDecl = this;
1815 
1816   if (Name == getIdentifier())
1817     return PDecl;
1818 
1819   for (auto *I : protocols())
1820     if ((PDecl = I->lookupProtocolNamed(Name)))
1821       return PDecl;
1822 
1823   return nullptr;
1824 }
1825 
1826 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1827 // it inherited.
1828 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1829                                                bool isInstance) const {
1830   ObjCMethodDecl *MethodDecl = nullptr;
1831 
1832   // If there is no definition or the definition is hidden, we don't find
1833   // anything.
1834   const ObjCProtocolDecl *Def = getDefinition();
1835   if (!Def || Def->isHidden())
1836     return nullptr;
1837 
1838   if ((MethodDecl = getMethod(Sel, isInstance)))
1839     return MethodDecl;
1840 
1841   for (const auto *I : protocols())
1842     if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1843       return MethodDecl;
1844   return nullptr;
1845 }
1846 
1847 void ObjCProtocolDecl::allocateDefinitionData() {
1848   assert(!Data.getPointer() && "Protocol already has a definition!");
1849   Data.setPointer(new (getASTContext()) DefinitionData);
1850   Data.getPointer()->Definition = this;
1851 }
1852 
1853 void ObjCProtocolDecl::startDefinition() {
1854   allocateDefinitionData();
1855 
1856   // Update all of the declarations with a pointer to the definition.
1857   for (auto RD : redecls())
1858     RD->Data = this->Data;
1859 }
1860 
1861 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1862                                                     PropertyDeclOrder &PO) const {
1863 
1864   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1865     for (auto *Prop : PDecl->properties()) {
1866       // Insert into PM if not there already.
1867       PM.insert(std::make_pair(
1868           std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()),
1869           Prop));
1870       PO.push_back(Prop);
1871     }
1872     // Scan through protocol's protocols.
1873     for (const auto *PI : PDecl->protocols())
1874       PI->collectPropertiesToImplement(PM, PO);
1875   }
1876 }
1877 
1878 
1879 void ObjCProtocolDecl::collectInheritedProtocolProperties(
1880                                                 const ObjCPropertyDecl *Property,
1881                                                 ProtocolPropertyMap &PM) const {
1882   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1883     bool MatchFound = false;
1884     for (auto *Prop : PDecl->properties()) {
1885       if (Prop == Property)
1886         continue;
1887       if (Prop->getIdentifier() == Property->getIdentifier()) {
1888         PM[PDecl] = Prop;
1889         MatchFound = true;
1890         break;
1891       }
1892     }
1893     // Scan through protocol's protocols which did not have a matching property.
1894     if (!MatchFound)
1895       for (const auto *PI : PDecl->protocols())
1896         PI->collectInheritedProtocolProperties(Property, PM);
1897   }
1898 }
1899 
1900 StringRef
1901 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
1902   if (ObjCRuntimeNameAttr *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1903     return ObjCRTName->getMetadataName();
1904 
1905   return getName();
1906 }
1907 
1908 //===----------------------------------------------------------------------===//
1909 // ObjCCategoryDecl
1910 //===----------------------------------------------------------------------===//
1911 
1912 void ObjCCategoryDecl::anchor() { }
1913 
1914 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1915                                    SourceLocation ClassNameLoc,
1916                                    SourceLocation CategoryNameLoc,
1917                                    IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1918                                    ObjCTypeParamList *typeParamList,
1919                                    SourceLocation IvarLBraceLoc,
1920                                    SourceLocation IvarRBraceLoc)
1921   : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1922     ClassInterface(IDecl), TypeParamList(nullptr),
1923     NextClassCategory(nullptr), CategoryNameLoc(CategoryNameLoc),
1924     IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc)
1925 {
1926   setTypeParamList(typeParamList);
1927 }
1928 
1929 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
1930                                            SourceLocation AtLoc,
1931                                            SourceLocation ClassNameLoc,
1932                                            SourceLocation CategoryNameLoc,
1933                                            IdentifierInfo *Id,
1934                                            ObjCInterfaceDecl *IDecl,
1935                                            ObjCTypeParamList *typeParamList,
1936                                            SourceLocation IvarLBraceLoc,
1937                                            SourceLocation IvarRBraceLoc) {
1938   ObjCCategoryDecl *CatDecl =
1939       new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
1940                                    IDecl, typeParamList, IvarLBraceLoc,
1941                                    IvarRBraceLoc);
1942   if (IDecl) {
1943     // Link this category into its class's category list.
1944     CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
1945     if (IDecl->hasDefinition()) {
1946       IDecl->setCategoryListRaw(CatDecl);
1947       if (ASTMutationListener *L = C.getASTMutationListener())
1948         L->AddedObjCCategoryToInterface(CatDecl, IDecl);
1949     }
1950   }
1951 
1952   return CatDecl;
1953 }
1954 
1955 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
1956                                                        unsigned ID) {
1957   return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
1958                                       SourceLocation(), SourceLocation(),
1959                                       nullptr, nullptr, nullptr);
1960 }
1961 
1962 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
1963   return getASTContext().getObjCImplementation(
1964                                            const_cast<ObjCCategoryDecl*>(this));
1965 }
1966 
1967 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
1968   getASTContext().setObjCImplementation(this, ImplD);
1969 }
1970 
1971 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) {
1972   TypeParamList = TPL;
1973   if (!TPL)
1974     return;
1975   // Set the declaration context of each of the type parameters.
1976   for (auto typeParam : *TypeParamList)
1977     typeParam->setDeclContext(this);
1978 }
1979 
1980 
1981 //===----------------------------------------------------------------------===//
1982 // ObjCCategoryImplDecl
1983 //===----------------------------------------------------------------------===//
1984 
1985 void ObjCCategoryImplDecl::anchor() { }
1986 
1987 ObjCCategoryImplDecl *
1988 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
1989                              IdentifierInfo *Id,
1990                              ObjCInterfaceDecl *ClassInterface,
1991                              SourceLocation nameLoc,
1992                              SourceLocation atStartLoc,
1993                              SourceLocation CategoryNameLoc) {
1994   if (ClassInterface && ClassInterface->hasDefinition())
1995     ClassInterface = ClassInterface->getDefinition();
1996   return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
1997                                           atStartLoc, CategoryNameLoc);
1998 }
1999 
2000 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
2001                                                                unsigned ID) {
2002   return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2003                                           SourceLocation(), SourceLocation(),
2004                                           SourceLocation());
2005 }
2006 
2007 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
2008   // The class interface might be NULL if we are working with invalid code.
2009   if (const ObjCInterfaceDecl *ID = getClassInterface())
2010     return ID->FindCategoryDeclaration(getIdentifier());
2011   return nullptr;
2012 }
2013 
2014 
2015 void ObjCImplDecl::anchor() { }
2016 
2017 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
2018   // FIXME: The context should be correct before we get here.
2019   property->setLexicalDeclContext(this);
2020   addDecl(property);
2021 }
2022 
2023 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
2024   ASTContext &Ctx = getASTContext();
2025 
2026   if (ObjCImplementationDecl *ImplD
2027         = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
2028     if (IFace)
2029       Ctx.setObjCImplementation(IFace, ImplD);
2030 
2031   } else if (ObjCCategoryImplDecl *ImplD =
2032              dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
2033     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
2034       Ctx.setObjCImplementation(CD, ImplD);
2035   }
2036 
2037   ClassInterface = IFace;
2038 }
2039 
2040 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2041 /// properties implemented in this \@implementation block and returns
2042 /// the implemented property that uses it.
2043 ///
2044 ObjCPropertyImplDecl *ObjCImplDecl::
2045 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
2046   for (auto *PID : property_impls())
2047     if (PID->getPropertyIvarDecl() &&
2048         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
2049       return PID;
2050   return nullptr;
2051 }
2052 
2053 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2054 /// added to the list of those properties \@synthesized/\@dynamic in this
2055 /// category \@implementation block.
2056 ///
2057 ObjCPropertyImplDecl *ObjCImplDecl::
2058 FindPropertyImplDecl(IdentifierInfo *Id,
2059                      ObjCPropertyQueryKind QueryKind) const {
2060   ObjCPropertyImplDecl *ClassPropImpl = nullptr;
2061   for (auto *PID : property_impls())
2062     // If queryKind is unknown, we return the instance property if one
2063     // exists; otherwise we return the class property.
2064     if (PID->getPropertyDecl()->getIdentifier() == Id) {
2065       if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
2066            !PID->getPropertyDecl()->isClassProperty()) ||
2067           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
2068            PID->getPropertyDecl()->isClassProperty()) ||
2069           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
2070            !PID->getPropertyDecl()->isClassProperty()))
2071         return PID;
2072 
2073       if (PID->getPropertyDecl()->isClassProperty())
2074         ClassPropImpl = PID;
2075     }
2076 
2077   if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
2078     // We can't find the instance property, return the class property.
2079     return ClassPropImpl;
2080 
2081   return nullptr;
2082 }
2083 
2084 raw_ostream &clang::operator<<(raw_ostream &OS,
2085                                const ObjCCategoryImplDecl &CID) {
2086   OS << CID.getName();
2087   return OS;
2088 }
2089 
2090 //===----------------------------------------------------------------------===//
2091 // ObjCImplementationDecl
2092 //===----------------------------------------------------------------------===//
2093 
2094 void ObjCImplementationDecl::anchor() { }
2095 
2096 ObjCImplementationDecl *
2097 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
2098                                ObjCInterfaceDecl *ClassInterface,
2099                                ObjCInterfaceDecl *SuperDecl,
2100                                SourceLocation nameLoc,
2101                                SourceLocation atStartLoc,
2102                                SourceLocation superLoc,
2103                                SourceLocation IvarLBraceLoc,
2104                                SourceLocation IvarRBraceLoc) {
2105   if (ClassInterface && ClassInterface->hasDefinition())
2106     ClassInterface = ClassInterface->getDefinition();
2107   return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
2108                                             nameLoc, atStartLoc, superLoc,
2109                                             IvarLBraceLoc, IvarRBraceLoc);
2110 }
2111 
2112 ObjCImplementationDecl *
2113 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2114   return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2115                                             SourceLocation(), SourceLocation());
2116 }
2117 
2118 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2119                                              CXXCtorInitializer ** initializers,
2120                                                  unsigned numInitializers) {
2121   if (numInitializers > 0) {
2122     NumIvarInitializers = numInitializers;
2123     CXXCtorInitializer **ivarInitializers =
2124     new (C) CXXCtorInitializer*[NumIvarInitializers];
2125     memcpy(ivarInitializers, initializers,
2126            numInitializers * sizeof(CXXCtorInitializer*));
2127     IvarInitializers = ivarInitializers;
2128   }
2129 }
2130 
2131 ObjCImplementationDecl::init_const_iterator
2132 ObjCImplementationDecl::init_begin() const {
2133   return IvarInitializers.get(getASTContext().getExternalSource());
2134 }
2135 
2136 raw_ostream &clang::operator<<(raw_ostream &OS,
2137                                const ObjCImplementationDecl &ID) {
2138   OS << ID.getName();
2139   return OS;
2140 }
2141 
2142 //===----------------------------------------------------------------------===//
2143 // ObjCCompatibleAliasDecl
2144 //===----------------------------------------------------------------------===//
2145 
2146 void ObjCCompatibleAliasDecl::anchor() { }
2147 
2148 ObjCCompatibleAliasDecl *
2149 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
2150                                 SourceLocation L,
2151                                 IdentifierInfo *Id,
2152                                 ObjCInterfaceDecl* AliasedClass) {
2153   return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
2154 }
2155 
2156 ObjCCompatibleAliasDecl *
2157 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2158   return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2159                                              nullptr, nullptr);
2160 }
2161 
2162 //===----------------------------------------------------------------------===//
2163 // ObjCPropertyDecl
2164 //===----------------------------------------------------------------------===//
2165 
2166 void ObjCPropertyDecl::anchor() { }
2167 
2168 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
2169                                            SourceLocation L,
2170                                            IdentifierInfo *Id,
2171                                            SourceLocation AtLoc,
2172                                            SourceLocation LParenLoc,
2173                                            QualType T,
2174                                            TypeSourceInfo *TSI,
2175                                            PropertyControl propControl) {
2176   return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
2177                                       propControl);
2178 }
2179 
2180 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
2181                                                        unsigned ID) {
2182   return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2183                                       SourceLocation(), SourceLocation(),
2184                                       QualType(), nullptr, None);
2185 }
2186 
2187 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const {
2188   return DeclType.substObjCMemberType(objectType, getDeclContext(),
2189                                       ObjCSubstitutionContext::Property);
2190 }
2191 
2192 //===----------------------------------------------------------------------===//
2193 // ObjCPropertyImplDecl
2194 //===----------------------------------------------------------------------===//
2195 
2196 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
2197                                                    DeclContext *DC,
2198                                                    SourceLocation atLoc,
2199                                                    SourceLocation L,
2200                                                    ObjCPropertyDecl *property,
2201                                                    Kind PK,
2202                                                    ObjCIvarDecl *ivar,
2203                                                    SourceLocation ivarLoc) {
2204   return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
2205                                           ivarLoc);
2206 }
2207 
2208 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
2209                                                                unsigned ID) {
2210   return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2211                                           SourceLocation(), nullptr, Dynamic,
2212                                           nullptr, SourceLocation());
2213 }
2214 
2215 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
2216   SourceLocation EndLoc = getLocation();
2217   if (IvarLoc.isValid())
2218     EndLoc = IvarLoc;
2219 
2220   return SourceRange(AtLoc, EndLoc);
2221 }
2222