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(alignof(ParmVarDecl *) >= alignof(SourceLocation),
804                 "Alignment not sufficient for SourceLocation");
805 
806   unsigned Size = sizeof(ParmVarDecl *) * NumParams +
807                   sizeof(SourceLocation) * SelLocs.size();
808   ParamsAndSelLocs = C.Allocate(Size);
809   std::copy(Params.begin(), Params.end(), getParams());
810   std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
811 }
812 
813 void ObjCMethodDecl::getSelectorLocs(
814                                SmallVectorImpl<SourceLocation> &SelLocs) const {
815   for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
816     SelLocs.push_back(getSelectorLoc(i));
817 }
818 
819 void ObjCMethodDecl::setMethodParams(ASTContext &C,
820                                      ArrayRef<ParmVarDecl*> Params,
821                                      ArrayRef<SourceLocation> SelLocs) {
822   assert((!SelLocs.empty() || isImplicit()) &&
823          "No selector locs for non-implicit method");
824   if (isImplicit())
825     return setParamsAndSelLocs(C, Params, llvm::None);
826 
827   SelLocsKind = hasStandardSelectorLocs(getSelector(), SelLocs, Params,
828                                         DeclEndLoc);
829   if (SelLocsKind != SelLoc_NonStandard)
830     return setParamsAndSelLocs(C, Params, llvm::None);
831 
832   setParamsAndSelLocs(C, Params, SelLocs);
833 }
834 
835 /// \brief A definition will return its interface declaration.
836 /// An interface declaration will return its definition.
837 /// Otherwise it will return itself.
838 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() {
839   ASTContext &Ctx = getASTContext();
840   ObjCMethodDecl *Redecl = nullptr;
841   if (HasRedeclaration)
842     Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
843   if (Redecl)
844     return Redecl;
845 
846   Decl *CtxD = cast<Decl>(getDeclContext());
847 
848   if (!CtxD->isInvalidDecl()) {
849     if (ObjCInterfaceDecl *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
850       if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
851         if (!ImplD->isInvalidDecl())
852           Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
853 
854     } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
855       if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
856         if (!ImplD->isInvalidDecl())
857           Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
858 
859     } else if (ObjCImplementationDecl *ImplD =
860                  dyn_cast<ObjCImplementationDecl>(CtxD)) {
861       if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
862         if (!IFD->isInvalidDecl())
863           Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
864 
865     } else if (ObjCCategoryImplDecl *CImplD =
866                  dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
867       if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
868         if (!CatD->isInvalidDecl())
869           Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
870     }
871   }
872 
873   if (!Redecl && isRedeclaration()) {
874     // This is the last redeclaration, go back to the first method.
875     return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
876                                                     isInstanceMethod());
877   }
878 
879   return Redecl ? Redecl : this;
880 }
881 
882 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
883   Decl *CtxD = cast<Decl>(getDeclContext());
884 
885   if (ObjCImplementationDecl *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
886     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
887       if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
888                                               isInstanceMethod()))
889         return MD;
890 
891   } else if (ObjCCategoryImplDecl *CImplD =
892                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
893     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
894       if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
895                                                isInstanceMethod()))
896         return MD;
897   }
898 
899   if (isRedeclaration()) {
900     // It is possible that we have not done deserializing the ObjCMethod yet.
901     ObjCMethodDecl *MD =
902         cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
903                                                  isInstanceMethod());
904     return MD ? MD : this;
905   }
906 
907   return this;
908 }
909 
910 SourceLocation ObjCMethodDecl::getLocEnd() const {
911   if (Stmt *Body = getBody())
912     return Body->getLocEnd();
913   return DeclEndLoc;
914 }
915 
916 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
917   ObjCMethodFamily family = static_cast<ObjCMethodFamily>(Family);
918   if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
919     return family;
920 
921   // Check for an explicit attribute.
922   if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
923     // The unfortunate necessity of mapping between enums here is due
924     // to the attributes framework.
925     switch (attr->getFamily()) {
926     case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
927     case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
928     case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
929     case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
930     case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
931     case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
932     }
933     Family = static_cast<unsigned>(family);
934     return family;
935   }
936 
937   family = getSelector().getMethodFamily();
938   switch (family) {
939   case OMF_None: break;
940 
941   // init only has a conventional meaning for an instance method, and
942   // it has to return an object.
943   case OMF_init:
944     if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
945       family = OMF_None;
946     break;
947 
948   // alloc/copy/new have a conventional meaning for both class and
949   // instance methods, but they require an object return.
950   case OMF_alloc:
951   case OMF_copy:
952   case OMF_mutableCopy:
953   case OMF_new:
954     if (!getReturnType()->isObjCObjectPointerType())
955       family = OMF_None;
956     break;
957 
958   // These selectors have a conventional meaning only for instance methods.
959   case OMF_dealloc:
960   case OMF_finalize:
961   case OMF_retain:
962   case OMF_release:
963   case OMF_autorelease:
964   case OMF_retainCount:
965   case OMF_self:
966     if (!isInstanceMethod())
967       family = OMF_None;
968     break;
969 
970   case OMF_initialize:
971     if (isInstanceMethod() || !getReturnType()->isVoidType())
972       family = OMF_None;
973     break;
974 
975   case OMF_performSelector:
976     if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
977       family = OMF_None;
978     else {
979       unsigned noParams = param_size();
980       if (noParams < 1 || noParams > 3)
981         family = OMF_None;
982       else {
983         ObjCMethodDecl::param_type_iterator it = param_type_begin();
984         QualType ArgT = (*it);
985         if (!ArgT->isObjCSelType()) {
986           family = OMF_None;
987           break;
988         }
989         while (--noParams) {
990           it++;
991           ArgT = (*it);
992           if (!ArgT->isObjCIdType()) {
993             family = OMF_None;
994             break;
995           }
996         }
997       }
998     }
999     break;
1000 
1001   }
1002 
1003   // Cache the result.
1004   Family = static_cast<unsigned>(family);
1005   return family;
1006 }
1007 
1008 QualType ObjCMethodDecl::getSelfType(ASTContext &Context,
1009                                      const ObjCInterfaceDecl *OID,
1010                                      bool &selfIsPseudoStrong,
1011                                      bool &selfIsConsumed) {
1012   QualType selfTy;
1013   selfIsPseudoStrong = false;
1014   selfIsConsumed = false;
1015   if (isInstanceMethod()) {
1016     // There may be no interface context due to error in declaration
1017     // of the interface (which has been reported). Recover gracefully.
1018     if (OID) {
1019       selfTy = Context.getObjCInterfaceType(OID);
1020       selfTy = Context.getObjCObjectPointerType(selfTy);
1021     } else {
1022       selfTy = Context.getObjCIdType();
1023     }
1024   } else // we have a factory method.
1025     selfTy = Context.getObjCClassType();
1026 
1027   if (Context.getLangOpts().ObjCAutoRefCount) {
1028     if (isInstanceMethod()) {
1029       selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
1030 
1031       // 'self' is always __strong.  It's actually pseudo-strong except
1032       // in init methods (or methods labeled ns_consumes_self), though.
1033       Qualifiers qs;
1034       qs.setObjCLifetime(Qualifiers::OCL_Strong);
1035       selfTy = Context.getQualifiedType(selfTy, qs);
1036 
1037       // In addition, 'self' is const unless this is an init method.
1038       if (getMethodFamily() != OMF_init && !selfIsConsumed) {
1039         selfTy = selfTy.withConst();
1040         selfIsPseudoStrong = true;
1041       }
1042     }
1043     else {
1044       assert(isClassMethod());
1045       // 'self' is always const in class methods.
1046       selfTy = selfTy.withConst();
1047       selfIsPseudoStrong = true;
1048     }
1049   }
1050   return selfTy;
1051 }
1052 
1053 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
1054                                           const ObjCInterfaceDecl *OID) {
1055   bool selfIsPseudoStrong, selfIsConsumed;
1056   QualType selfTy =
1057     getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed);
1058   ImplicitParamDecl *self
1059     = ImplicitParamDecl::Create(Context, this, SourceLocation(),
1060                                 &Context.Idents.get("self"), selfTy);
1061   setSelfDecl(self);
1062 
1063   if (selfIsConsumed)
1064     self->addAttr(NSConsumedAttr::CreateImplicit(Context));
1065 
1066   if (selfIsPseudoStrong)
1067     self->setARCPseudoStrong(true);
1068 
1069   setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
1070                                        &Context.Idents.get("_cmd"),
1071                                        Context.getObjCSelType()));
1072 }
1073 
1074 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
1075   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
1076     return ID;
1077   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1078     return CD->getClassInterface();
1079   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
1080     return IMD->getClassInterface();
1081   if (isa<ObjCProtocolDecl>(getDeclContext()))
1082     return nullptr;
1083   llvm_unreachable("unknown method context");
1084 }
1085 
1086 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const {
1087   const auto *TSI = getReturnTypeSourceInfo();
1088   if (TSI)
1089     return TSI->getTypeLoc().getSourceRange();
1090   return SourceRange();
1091 }
1092 
1093 QualType ObjCMethodDecl::getSendResultType() const {
1094   ASTContext &Ctx = getASTContext();
1095   return getReturnType().getNonLValueExprType(Ctx)
1096            .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result);
1097 }
1098 
1099 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const {
1100   // FIXME: Handle related result types here.
1101 
1102   return getReturnType().getNonLValueExprType(getASTContext())
1103            .substObjCMemberType(receiverType, getDeclContext(),
1104                                 ObjCSubstitutionContext::Result);
1105 }
1106 
1107 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
1108                                             const ObjCMethodDecl *Method,
1109                                SmallVectorImpl<const ObjCMethodDecl *> &Methods,
1110                                             bool MovedToSuper) {
1111   if (!Container)
1112     return;
1113 
1114   // In categories look for overriden methods from protocols. A method from
1115   // category is not "overriden" since it is considered as the "same" method
1116   // (same USR) as the one from the interface.
1117   if (const ObjCCategoryDecl *
1118         Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1119     // Check whether we have a matching method at this category but only if we
1120     // are at the super class level.
1121     if (MovedToSuper)
1122       if (ObjCMethodDecl *
1123             Overridden = Container->getMethod(Method->getSelector(),
1124                                               Method->isInstanceMethod(),
1125                                               /*AllowHidden=*/true))
1126         if (Method != Overridden) {
1127           // We found an override at this category; there is no need to look
1128           // into its protocols.
1129           Methods.push_back(Overridden);
1130           return;
1131         }
1132 
1133     for (const auto *P : Category->protocols())
1134       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1135     return;
1136   }
1137 
1138   // Check whether we have a matching method at this level.
1139   if (const ObjCMethodDecl *
1140         Overridden = Container->getMethod(Method->getSelector(),
1141                                           Method->isInstanceMethod(),
1142                                           /*AllowHidden=*/true))
1143     if (Method != Overridden) {
1144       // We found an override at this level; there is no need to look
1145       // into other protocols or categories.
1146       Methods.push_back(Overridden);
1147       return;
1148     }
1149 
1150   if (const ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
1151     for (const auto *P : Protocol->protocols())
1152       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1153   }
1154 
1155   if (const ObjCInterfaceDecl *
1156         Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1157     for (const auto *P : Interface->protocols())
1158       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1159 
1160     for (const auto *Cat : Interface->known_categories())
1161       CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper);
1162 
1163     if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1164       return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1165                                              /*MovedToSuper=*/true);
1166   }
1167 }
1168 
1169 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1170                                             const ObjCMethodDecl *Method,
1171                              SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1172   CollectOverriddenMethodsRecurse(Container, Method, Methods,
1173                                   /*MovedToSuper=*/false);
1174 }
1175 
1176 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1177                           SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1178   assert(Method->isOverriding());
1179 
1180   if (const ObjCProtocolDecl *
1181         ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1182     CollectOverriddenMethods(ProtD, Method, overridden);
1183 
1184   } else if (const ObjCImplDecl *
1185                IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1186     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1187     if (!ID)
1188       return;
1189     // Start searching for overridden methods using the method from the
1190     // interface as starting point.
1191     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1192                                                     Method->isInstanceMethod(),
1193                                                     /*AllowHidden=*/true))
1194       Method = IFaceMeth;
1195     CollectOverriddenMethods(ID, Method, overridden);
1196 
1197   } else if (const ObjCCategoryDecl *
1198                CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1199     const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1200     if (!ID)
1201       return;
1202     // Start searching for overridden methods using the method from the
1203     // interface as starting point.
1204     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1205                                                      Method->isInstanceMethod(),
1206                                                      /*AllowHidden=*/true))
1207       Method = IFaceMeth;
1208     CollectOverriddenMethods(ID, Method, overridden);
1209 
1210   } else {
1211     CollectOverriddenMethods(
1212                   dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1213                   Method, overridden);
1214   }
1215 }
1216 
1217 void ObjCMethodDecl::getOverriddenMethods(
1218                     SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1219   const ObjCMethodDecl *Method = this;
1220 
1221   if (Method->isRedeclaration()) {
1222     Method = cast<ObjCContainerDecl>(Method->getDeclContext())->
1223                    getMethod(Method->getSelector(), Method->isInstanceMethod());
1224   }
1225 
1226   if (Method->isOverriding()) {
1227     collectOverriddenMethodsSlow(Method, Overridden);
1228     assert(!Overridden.empty() &&
1229            "ObjCMethodDecl's overriding bit is not as expected");
1230   }
1231 }
1232 
1233 const ObjCPropertyDecl *
1234 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1235   Selector Sel = getSelector();
1236   unsigned NumArgs = Sel.getNumArgs();
1237   if (NumArgs > 1)
1238     return nullptr;
1239 
1240   if (isPropertyAccessor()) {
1241     const ObjCContainerDecl *Container = cast<ObjCContainerDecl>(getParent());
1242     bool IsGetter = (NumArgs == 0);
1243     bool IsInstance = isInstanceMethod();
1244 
1245     /// Local function that attempts to find a matching property within the
1246     /// given Objective-C container.
1247     auto findMatchingProperty =
1248       [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * {
1249       if (IsInstance) {
1250         for (const auto *I : Container->instance_properties()) {
1251           Selector NextSel = IsGetter ? I->getGetterName()
1252                                       : I->getSetterName();
1253           if (NextSel == Sel)
1254             return I;
1255         }
1256       } else {
1257         for (const auto *I : Container->class_properties()) {
1258           Selector NextSel = IsGetter ? I->getGetterName()
1259                                       : I->getSetterName();
1260           if (NextSel == Sel)
1261             return I;
1262         }
1263       }
1264 
1265       return nullptr;
1266     };
1267 
1268     // Look in the container we were given.
1269     if (const auto *Found = findMatchingProperty(Container))
1270       return Found;
1271 
1272     // If we're in a category or extension, look in the main class.
1273     const ObjCInterfaceDecl *ClassDecl = nullptr;
1274     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1275       ClassDecl = Category->getClassInterface();
1276       if (const auto *Found = findMatchingProperty(ClassDecl))
1277         return Found;
1278     } else {
1279       // Determine whether the container is a class.
1280       ClassDecl = dyn_cast<ObjCInterfaceDecl>(Container);
1281     }
1282 
1283     // If we have a class, check its visible extensions.
1284     if (ClassDecl) {
1285       for (const auto *Ext : ClassDecl->visible_extensions()) {
1286         if (Ext == Container)
1287           continue;
1288 
1289         if (const auto *Found = findMatchingProperty(Ext))
1290           return Found;
1291       }
1292     }
1293 
1294     llvm_unreachable("Marked as a property accessor but no property found!");
1295   }
1296 
1297   if (!CheckOverrides)
1298     return nullptr;
1299 
1300   typedef SmallVector<const ObjCMethodDecl *, 8> OverridesTy;
1301   OverridesTy Overrides;
1302   getOverriddenMethods(Overrides);
1303   for (OverridesTy::const_iterator I = Overrides.begin(), E = Overrides.end();
1304        I != E; ++I) {
1305     if (const ObjCPropertyDecl *Prop = (*I)->findPropertyDecl(false))
1306       return Prop;
1307   }
1308 
1309   return nullptr;
1310 }
1311 
1312 //===----------------------------------------------------------------------===//
1313 // ObjCTypeParamDecl
1314 //===----------------------------------------------------------------------===//
1315 
1316 void ObjCTypeParamDecl::anchor() { }
1317 
1318 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc,
1319                                              ObjCTypeParamVariance variance,
1320                                              SourceLocation varianceLoc,
1321                                              unsigned index,
1322                                              SourceLocation nameLoc,
1323                                              IdentifierInfo *name,
1324                                              SourceLocation colonLoc,
1325                                              TypeSourceInfo *boundInfo) {
1326   auto *TPDecl =
1327     new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index,
1328                                     nameLoc, name, colonLoc, boundInfo);
1329   QualType TPType = ctx.getObjCTypeParamType(TPDecl, {});
1330   TPDecl->setTypeForDecl(TPType.getTypePtr());
1331   return TPDecl;
1332 }
1333 
1334 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx,
1335                                                          unsigned ID) {
1336   return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr,
1337                                          ObjCTypeParamVariance::Invariant,
1338                                          SourceLocation(), 0, SourceLocation(),
1339                                          nullptr, SourceLocation(), nullptr);
1340 }
1341 
1342 SourceRange ObjCTypeParamDecl::getSourceRange() const {
1343   SourceLocation startLoc = VarianceLoc;
1344   if (startLoc.isInvalid())
1345     startLoc = getLocation();
1346 
1347   if (hasExplicitBound()) {
1348     return SourceRange(startLoc,
1349                        getTypeSourceInfo()->getTypeLoc().getEndLoc());
1350   }
1351 
1352   return SourceRange(startLoc);
1353 }
1354 
1355 //===----------------------------------------------------------------------===//
1356 // ObjCTypeParamList
1357 //===----------------------------------------------------------------------===//
1358 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc,
1359                                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1360                                      SourceLocation rAngleLoc)
1361   : NumParams(typeParams.size())
1362 {
1363   Brackets.Begin = lAngleLoc.getRawEncoding();
1364   Brackets.End = rAngleLoc.getRawEncoding();
1365   std::copy(typeParams.begin(), typeParams.end(), begin());
1366 }
1367 
1368 
1369 ObjCTypeParamList *ObjCTypeParamList::create(
1370                      ASTContext &ctx,
1371                      SourceLocation lAngleLoc,
1372                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1373                      SourceLocation rAngleLoc) {
1374   void *mem =
1375       ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()),
1376                    alignof(ObjCTypeParamList));
1377   return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc);
1378 }
1379 
1380 void ObjCTypeParamList::gatherDefaultTypeArgs(
1381        SmallVectorImpl<QualType> &typeArgs) const {
1382   typeArgs.reserve(size());
1383   for (auto typeParam : *this)
1384     typeArgs.push_back(typeParam->getUnderlyingType());
1385 }
1386 
1387 //===----------------------------------------------------------------------===//
1388 // ObjCInterfaceDecl
1389 //===----------------------------------------------------------------------===//
1390 
1391 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1392                                              DeclContext *DC,
1393                                              SourceLocation atLoc,
1394                                              IdentifierInfo *Id,
1395                                              ObjCTypeParamList *typeParamList,
1396                                              ObjCInterfaceDecl *PrevDecl,
1397                                              SourceLocation ClassLoc,
1398                                              bool isInternal){
1399   ObjCInterfaceDecl *Result = new (C, DC)
1400       ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl,
1401                         isInternal);
1402   Result->Data.setInt(!C.getLangOpts().Modules);
1403   C.getObjCInterfaceType(Result, PrevDecl);
1404   return Result;
1405 }
1406 
1407 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1408                                                          unsigned ID) {
1409   ObjCInterfaceDecl *Result = new (C, ID) ObjCInterfaceDecl(C, nullptr,
1410                                                             SourceLocation(),
1411                                                             nullptr,
1412                                                             nullptr,
1413                                                             SourceLocation(),
1414                                                             nullptr, false);
1415   Result->Data.setInt(!C.getLangOpts().Modules);
1416   return Result;
1417 }
1418 
1419 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1420                                      SourceLocation AtLoc, IdentifierInfo *Id,
1421                                      ObjCTypeParamList *typeParamList,
1422                                      SourceLocation CLoc,
1423                                      ObjCInterfaceDecl *PrevDecl,
1424                                      bool IsInternal)
1425     : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1426       redeclarable_base(C), TypeForDecl(nullptr), TypeParamList(nullptr),
1427       Data() {
1428   setPreviousDecl(PrevDecl);
1429 
1430   // Copy the 'data' pointer over.
1431   if (PrevDecl)
1432     Data = PrevDecl->Data;
1433 
1434   setImplicit(IsInternal);
1435 
1436   setTypeParamList(typeParamList);
1437 }
1438 
1439 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1440   assert(data().ExternallyCompleted && "Class is not externally completed");
1441   data().ExternallyCompleted = false;
1442   getASTContext().getExternalSource()->CompleteType(
1443                                         const_cast<ObjCInterfaceDecl *>(this));
1444 }
1445 
1446 void ObjCInterfaceDecl::setExternallyCompleted() {
1447   assert(getASTContext().getExternalSource() &&
1448          "Class can't be externally completed without an external source");
1449   assert(hasDefinition() &&
1450          "Forward declarations can't be externally completed");
1451   data().ExternallyCompleted = true;
1452 }
1453 
1454 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1455   // Check for a complete definition and recover if not so.
1456   if (!isThisDeclarationADefinition())
1457     return;
1458   data().HasDesignatedInitializers = true;
1459 }
1460 
1461 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1462   // Check for a complete definition and recover if not so.
1463   if (!isThisDeclarationADefinition())
1464     return false;
1465   if (data().ExternallyCompleted)
1466     LoadExternalDefinition();
1467 
1468   return data().HasDesignatedInitializers;
1469 }
1470 
1471 StringRef
1472 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1473   if (ObjCRuntimeNameAttr *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1474     return ObjCRTName->getMetadataName();
1475 
1476   return getName();
1477 }
1478 
1479 StringRef
1480 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1481   if (ObjCInterfaceDecl *ID =
1482       const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1483     return ID->getObjCRuntimeNameAsString();
1484 
1485   return getName();
1486 }
1487 
1488 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1489   if (const ObjCInterfaceDecl *Def = getDefinition()) {
1490     if (data().ExternallyCompleted)
1491       LoadExternalDefinition();
1492 
1493     return getASTContext().getObjCImplementation(
1494              const_cast<ObjCInterfaceDecl*>(Def));
1495   }
1496 
1497   // FIXME: Should make sure no callers ever do this.
1498   return nullptr;
1499 }
1500 
1501 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1502   getASTContext().setObjCImplementation(getDefinition(), ImplD);
1503 }
1504 
1505 namespace {
1506   struct SynthesizeIvarChunk {
1507     uint64_t Size;
1508     ObjCIvarDecl *Ivar;
1509     SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1510       : Size(size), Ivar(ivar) {}
1511   };
1512 
1513   bool operator<(const SynthesizeIvarChunk & LHS,
1514                  const SynthesizeIvarChunk &RHS) {
1515       return LHS.Size < RHS.Size;
1516   }
1517 }
1518 
1519 /// all_declared_ivar_begin - return first ivar declared in this class,
1520 /// its extensions and its implementation. Lazily build the list on first
1521 /// access.
1522 ///
1523 /// Caveat: The list returned by this method reflects the current
1524 /// state of the parser. The cache will be updated for every ivar
1525 /// added by an extension or the implementation when they are
1526 /// encountered.
1527 /// See also ObjCIvarDecl::Create().
1528 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1529   // FIXME: Should make sure no callers ever do this.
1530   if (!hasDefinition())
1531     return nullptr;
1532 
1533   ObjCIvarDecl *curIvar = nullptr;
1534   if (!data().IvarList) {
1535     if (!ivar_empty()) {
1536       ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1537       data().IvarList = *I; ++I;
1538       for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1539         curIvar->setNextIvar(*I);
1540     }
1541 
1542     for (const auto *Ext : known_extensions()) {
1543       if (!Ext->ivar_empty()) {
1544         ObjCCategoryDecl::ivar_iterator
1545           I = Ext->ivar_begin(),
1546           E = Ext->ivar_end();
1547         if (!data().IvarList) {
1548           data().IvarList = *I; ++I;
1549           curIvar = data().IvarList;
1550         }
1551         for ( ;I != E; curIvar = *I, ++I)
1552           curIvar->setNextIvar(*I);
1553       }
1554     }
1555     data().IvarListMissingImplementation = true;
1556   }
1557 
1558   // cached and complete!
1559   if (!data().IvarListMissingImplementation)
1560       return data().IvarList;
1561 
1562   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1563     data().IvarListMissingImplementation = false;
1564     if (!ImplDecl->ivar_empty()) {
1565       SmallVector<SynthesizeIvarChunk, 16> layout;
1566       for (auto *IV : ImplDecl->ivars()) {
1567         if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1568           layout.push_back(SynthesizeIvarChunk(
1569                              IV->getASTContext().getTypeSize(IV->getType()), IV));
1570           continue;
1571         }
1572         if (!data().IvarList)
1573           data().IvarList = IV;
1574         else
1575           curIvar->setNextIvar(IV);
1576         curIvar = IV;
1577       }
1578 
1579       if (!layout.empty()) {
1580         // Order synthesized ivars by their size.
1581         std::stable_sort(layout.begin(), layout.end());
1582         unsigned Ix = 0, EIx = layout.size();
1583         if (!data().IvarList) {
1584           data().IvarList = layout[0].Ivar; Ix++;
1585           curIvar = data().IvarList;
1586         }
1587         for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1588           curIvar->setNextIvar(layout[Ix].Ivar);
1589       }
1590     }
1591   }
1592   return data().IvarList;
1593 }
1594 
1595 /// FindCategoryDeclaration - Finds category declaration in the list of
1596 /// categories for this class and returns it. Name of the category is passed
1597 /// in 'CategoryId'. If category not found, return 0;
1598 ///
1599 ObjCCategoryDecl *
1600 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1601   // FIXME: Should make sure no callers ever do this.
1602   if (!hasDefinition())
1603     return nullptr;
1604 
1605   if (data().ExternallyCompleted)
1606     LoadExternalDefinition();
1607 
1608   for (auto *Cat : visible_categories())
1609     if (Cat->getIdentifier() == CategoryId)
1610       return Cat;
1611 
1612   return nullptr;
1613 }
1614 
1615 ObjCMethodDecl *
1616 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1617   for (const auto *Cat : visible_categories()) {
1618     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1619       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1620         return MD;
1621   }
1622 
1623   return nullptr;
1624 }
1625 
1626 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1627   for (const auto *Cat : visible_categories()) {
1628     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1629       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1630         return MD;
1631   }
1632 
1633   return nullptr;
1634 }
1635 
1636 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1637 /// has been implemented in IDecl class, its super class or categories (if
1638 /// lookupCategory is true).
1639 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1640                                     bool lookupCategory,
1641                                     bool RHSIsQualifiedID) {
1642   if (!hasDefinition())
1643     return false;
1644 
1645   ObjCInterfaceDecl *IDecl = this;
1646   // 1st, look up the class.
1647   for (auto *PI : IDecl->protocols()){
1648     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1649       return true;
1650     // This is dubious and is added to be compatible with gcc.  In gcc, it is
1651     // also allowed assigning a protocol-qualified 'id' type to a LHS object
1652     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1653     // object. This IMO, should be a bug.
1654     // FIXME: Treat this as an extension, and flag this as an error when GCC
1655     // extensions are not enabled.
1656     if (RHSIsQualifiedID &&
1657         getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1658       return true;
1659   }
1660 
1661   // 2nd, look up the category.
1662   if (lookupCategory)
1663     for (const auto *Cat : visible_categories()) {
1664       for (auto *PI : Cat->protocols())
1665         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1666           return true;
1667     }
1668 
1669   // 3rd, look up the super class(s)
1670   if (IDecl->getSuperClass())
1671     return
1672   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1673                                                   RHSIsQualifiedID);
1674 
1675   return false;
1676 }
1677 
1678 //===----------------------------------------------------------------------===//
1679 // ObjCIvarDecl
1680 //===----------------------------------------------------------------------===//
1681 
1682 void ObjCIvarDecl::anchor() { }
1683 
1684 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1685                                    SourceLocation StartLoc,
1686                                    SourceLocation IdLoc, IdentifierInfo *Id,
1687                                    QualType T, TypeSourceInfo *TInfo,
1688                                    AccessControl ac, Expr *BW,
1689                                    bool synthesized) {
1690   if (DC) {
1691     // Ivar's can only appear in interfaces, implementations (via synthesized
1692     // properties), and class extensions (via direct declaration, or synthesized
1693     // properties).
1694     //
1695     // FIXME: This should really be asserting this:
1696     //   (isa<ObjCCategoryDecl>(DC) &&
1697     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1698     // but unfortunately we sometimes place ivars into non-class extension
1699     // categories on error. This breaks an AST invariant, and should not be
1700     // fixed.
1701     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
1702             isa<ObjCCategoryDecl>(DC)) &&
1703            "Invalid ivar decl context!");
1704     // Once a new ivar is created in any of class/class-extension/implementation
1705     // decl contexts, the previously built IvarList must be rebuilt.
1706     ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1707     if (!ID) {
1708       if (ObjCImplementationDecl *IM = dyn_cast<ObjCImplementationDecl>(DC))
1709         ID = IM->getClassInterface();
1710       else
1711         ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1712     }
1713     ID->setIvarList(nullptr);
1714   }
1715 
1716   return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1717                                   synthesized);
1718 }
1719 
1720 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1721   return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1722                                   nullptr, QualType(), nullptr,
1723                                   ObjCIvarDecl::None, nullptr, false);
1724 }
1725 
1726 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1727   const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
1728 
1729   switch (DC->getKind()) {
1730   default:
1731   case ObjCCategoryImpl:
1732   case ObjCProtocol:
1733     llvm_unreachable("invalid ivar container!");
1734 
1735     // Ivars can only appear in class extension categories.
1736   case ObjCCategory: {
1737     const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
1738     assert(CD->IsClassExtension() && "invalid container for ivar!");
1739     return CD->getClassInterface();
1740   }
1741 
1742   case ObjCImplementation:
1743     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1744 
1745   case ObjCInterface:
1746     return cast<ObjCInterfaceDecl>(DC);
1747   }
1748 }
1749 
1750 QualType ObjCIvarDecl::getUsageType(QualType objectType) const {
1751   return getType().substObjCMemberType(objectType, getDeclContext(),
1752                                        ObjCSubstitutionContext::Property);
1753 }
1754 
1755 //===----------------------------------------------------------------------===//
1756 // ObjCAtDefsFieldDecl
1757 //===----------------------------------------------------------------------===//
1758 
1759 void ObjCAtDefsFieldDecl::anchor() { }
1760 
1761 ObjCAtDefsFieldDecl
1762 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1763                              SourceLocation StartLoc,  SourceLocation IdLoc,
1764                              IdentifierInfo *Id, QualType T, Expr *BW) {
1765   return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1766 }
1767 
1768 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1769                                                              unsigned ID) {
1770   return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1771                                          SourceLocation(), nullptr, QualType(),
1772                                          nullptr);
1773 }
1774 
1775 //===----------------------------------------------------------------------===//
1776 // ObjCProtocolDecl
1777 //===----------------------------------------------------------------------===//
1778 
1779 void ObjCProtocolDecl::anchor() { }
1780 
1781 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1782                                    IdentifierInfo *Id, SourceLocation nameLoc,
1783                                    SourceLocation atStartLoc,
1784                                    ObjCProtocolDecl *PrevDecl)
1785     : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1786       redeclarable_base(C), Data() {
1787   setPreviousDecl(PrevDecl);
1788   if (PrevDecl)
1789     Data = PrevDecl->Data;
1790 }
1791 
1792 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1793                                            IdentifierInfo *Id,
1794                                            SourceLocation nameLoc,
1795                                            SourceLocation atStartLoc,
1796                                            ObjCProtocolDecl *PrevDecl) {
1797   ObjCProtocolDecl *Result =
1798       new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1799   Result->Data.setInt(!C.getLangOpts().Modules);
1800   return Result;
1801 }
1802 
1803 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1804                                                        unsigned ID) {
1805   ObjCProtocolDecl *Result =
1806       new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1807                                    SourceLocation(), nullptr);
1808   Result->Data.setInt(!C.getLangOpts().Modules);
1809   return Result;
1810 }
1811 
1812 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1813   ObjCProtocolDecl *PDecl = this;
1814 
1815   if (Name == getIdentifier())
1816     return PDecl;
1817 
1818   for (auto *I : protocols())
1819     if ((PDecl = I->lookupProtocolNamed(Name)))
1820       return PDecl;
1821 
1822   return nullptr;
1823 }
1824 
1825 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1826 // it inherited.
1827 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1828                                                bool isInstance) const {
1829   ObjCMethodDecl *MethodDecl = nullptr;
1830 
1831   // If there is no definition or the definition is hidden, we don't find
1832   // anything.
1833   const ObjCProtocolDecl *Def = getDefinition();
1834   if (!Def || Def->isHidden())
1835     return nullptr;
1836 
1837   if ((MethodDecl = getMethod(Sel, isInstance)))
1838     return MethodDecl;
1839 
1840   for (const auto *I : protocols())
1841     if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1842       return MethodDecl;
1843   return nullptr;
1844 }
1845 
1846 void ObjCProtocolDecl::allocateDefinitionData() {
1847   assert(!Data.getPointer() && "Protocol already has a definition!");
1848   Data.setPointer(new (getASTContext()) DefinitionData);
1849   Data.getPointer()->Definition = this;
1850 }
1851 
1852 void ObjCProtocolDecl::startDefinition() {
1853   allocateDefinitionData();
1854 
1855   // Update all of the declarations with a pointer to the definition.
1856   for (auto RD : redecls())
1857     RD->Data = this->Data;
1858 }
1859 
1860 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1861                                                     PropertyDeclOrder &PO) const {
1862 
1863   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1864     for (auto *Prop : PDecl->properties()) {
1865       // Insert into PM if not there already.
1866       PM.insert(std::make_pair(
1867           std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()),
1868           Prop));
1869       PO.push_back(Prop);
1870     }
1871     // Scan through protocol's protocols.
1872     for (const auto *PI : PDecl->protocols())
1873       PI->collectPropertiesToImplement(PM, PO);
1874   }
1875 }
1876 
1877 
1878 void ObjCProtocolDecl::collectInheritedProtocolProperties(
1879                                                 const ObjCPropertyDecl *Property,
1880                                                 ProtocolPropertyMap &PM) const {
1881   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1882     bool MatchFound = false;
1883     for (auto *Prop : PDecl->properties()) {
1884       if (Prop == Property)
1885         continue;
1886       if (Prop->getIdentifier() == Property->getIdentifier()) {
1887         PM[PDecl] = Prop;
1888         MatchFound = true;
1889         break;
1890       }
1891     }
1892     // Scan through protocol's protocols which did not have a matching property.
1893     if (!MatchFound)
1894       for (const auto *PI : PDecl->protocols())
1895         PI->collectInheritedProtocolProperties(Property, PM);
1896   }
1897 }
1898 
1899 StringRef
1900 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
1901   if (ObjCRuntimeNameAttr *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1902     return ObjCRTName->getMetadataName();
1903 
1904   return getName();
1905 }
1906 
1907 //===----------------------------------------------------------------------===//
1908 // ObjCCategoryDecl
1909 //===----------------------------------------------------------------------===//
1910 
1911 void ObjCCategoryDecl::anchor() { }
1912 
1913 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
1914                                    SourceLocation ClassNameLoc,
1915                                    SourceLocation CategoryNameLoc,
1916                                    IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
1917                                    ObjCTypeParamList *typeParamList,
1918                                    SourceLocation IvarLBraceLoc,
1919                                    SourceLocation IvarRBraceLoc)
1920   : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
1921     ClassInterface(IDecl), TypeParamList(nullptr),
1922     NextClassCategory(nullptr), CategoryNameLoc(CategoryNameLoc),
1923     IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc)
1924 {
1925   setTypeParamList(typeParamList);
1926 }
1927 
1928 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
1929                                            SourceLocation AtLoc,
1930                                            SourceLocation ClassNameLoc,
1931                                            SourceLocation CategoryNameLoc,
1932                                            IdentifierInfo *Id,
1933                                            ObjCInterfaceDecl *IDecl,
1934                                            ObjCTypeParamList *typeParamList,
1935                                            SourceLocation IvarLBraceLoc,
1936                                            SourceLocation IvarRBraceLoc) {
1937   ObjCCategoryDecl *CatDecl =
1938       new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
1939                                    IDecl, typeParamList, IvarLBraceLoc,
1940                                    IvarRBraceLoc);
1941   if (IDecl) {
1942     // Link this category into its class's category list.
1943     CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
1944     if (IDecl->hasDefinition()) {
1945       IDecl->setCategoryListRaw(CatDecl);
1946       if (ASTMutationListener *L = C.getASTMutationListener())
1947         L->AddedObjCCategoryToInterface(CatDecl, IDecl);
1948     }
1949   }
1950 
1951   return CatDecl;
1952 }
1953 
1954 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
1955                                                        unsigned ID) {
1956   return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
1957                                       SourceLocation(), SourceLocation(),
1958                                       nullptr, nullptr, nullptr);
1959 }
1960 
1961 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
1962   return getASTContext().getObjCImplementation(
1963                                            const_cast<ObjCCategoryDecl*>(this));
1964 }
1965 
1966 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
1967   getASTContext().setObjCImplementation(this, ImplD);
1968 }
1969 
1970 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) {
1971   TypeParamList = TPL;
1972   if (!TPL)
1973     return;
1974   // Set the declaration context of each of the type parameters.
1975   for (auto typeParam : *TypeParamList)
1976     typeParam->setDeclContext(this);
1977 }
1978 
1979 
1980 //===----------------------------------------------------------------------===//
1981 // ObjCCategoryImplDecl
1982 //===----------------------------------------------------------------------===//
1983 
1984 void ObjCCategoryImplDecl::anchor() { }
1985 
1986 ObjCCategoryImplDecl *
1987 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
1988                              IdentifierInfo *Id,
1989                              ObjCInterfaceDecl *ClassInterface,
1990                              SourceLocation nameLoc,
1991                              SourceLocation atStartLoc,
1992                              SourceLocation CategoryNameLoc) {
1993   if (ClassInterface && ClassInterface->hasDefinition())
1994     ClassInterface = ClassInterface->getDefinition();
1995   return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
1996                                           atStartLoc, CategoryNameLoc);
1997 }
1998 
1999 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
2000                                                                unsigned ID) {
2001   return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2002                                           SourceLocation(), SourceLocation(),
2003                                           SourceLocation());
2004 }
2005 
2006 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
2007   // The class interface might be NULL if we are working with invalid code.
2008   if (const ObjCInterfaceDecl *ID = getClassInterface())
2009     return ID->FindCategoryDeclaration(getIdentifier());
2010   return nullptr;
2011 }
2012 
2013 
2014 void ObjCImplDecl::anchor() { }
2015 
2016 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
2017   // FIXME: The context should be correct before we get here.
2018   property->setLexicalDeclContext(this);
2019   addDecl(property);
2020 }
2021 
2022 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
2023   ASTContext &Ctx = getASTContext();
2024 
2025   if (ObjCImplementationDecl *ImplD
2026         = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
2027     if (IFace)
2028       Ctx.setObjCImplementation(IFace, ImplD);
2029 
2030   } else if (ObjCCategoryImplDecl *ImplD =
2031              dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
2032     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
2033       Ctx.setObjCImplementation(CD, ImplD);
2034   }
2035 
2036   ClassInterface = IFace;
2037 }
2038 
2039 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2040 /// properties implemented in this \@implementation block and returns
2041 /// the implemented property that uses it.
2042 ///
2043 ObjCPropertyImplDecl *ObjCImplDecl::
2044 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
2045   for (auto *PID : property_impls())
2046     if (PID->getPropertyIvarDecl() &&
2047         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
2048       return PID;
2049   return nullptr;
2050 }
2051 
2052 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2053 /// added to the list of those properties \@synthesized/\@dynamic in this
2054 /// category \@implementation block.
2055 ///
2056 ObjCPropertyImplDecl *ObjCImplDecl::
2057 FindPropertyImplDecl(IdentifierInfo *Id,
2058                      ObjCPropertyQueryKind QueryKind) const {
2059   ObjCPropertyImplDecl *ClassPropImpl = nullptr;
2060   for (auto *PID : property_impls())
2061     // If queryKind is unknown, we return the instance property if one
2062     // exists; otherwise we return the class property.
2063     if (PID->getPropertyDecl()->getIdentifier() == Id) {
2064       if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
2065            !PID->getPropertyDecl()->isClassProperty()) ||
2066           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
2067            PID->getPropertyDecl()->isClassProperty()) ||
2068           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
2069            !PID->getPropertyDecl()->isClassProperty()))
2070         return PID;
2071 
2072       if (PID->getPropertyDecl()->isClassProperty())
2073         ClassPropImpl = PID;
2074     }
2075 
2076   if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
2077     // We can't find the instance property, return the class property.
2078     return ClassPropImpl;
2079 
2080   return nullptr;
2081 }
2082 
2083 raw_ostream &clang::operator<<(raw_ostream &OS,
2084                                const ObjCCategoryImplDecl &CID) {
2085   OS << CID.getName();
2086   return OS;
2087 }
2088 
2089 //===----------------------------------------------------------------------===//
2090 // ObjCImplementationDecl
2091 //===----------------------------------------------------------------------===//
2092 
2093 void ObjCImplementationDecl::anchor() { }
2094 
2095 ObjCImplementationDecl *
2096 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
2097                                ObjCInterfaceDecl *ClassInterface,
2098                                ObjCInterfaceDecl *SuperDecl,
2099                                SourceLocation nameLoc,
2100                                SourceLocation atStartLoc,
2101                                SourceLocation superLoc,
2102                                SourceLocation IvarLBraceLoc,
2103                                SourceLocation IvarRBraceLoc) {
2104   if (ClassInterface && ClassInterface->hasDefinition())
2105     ClassInterface = ClassInterface->getDefinition();
2106   return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
2107                                             nameLoc, atStartLoc, superLoc,
2108                                             IvarLBraceLoc, IvarRBraceLoc);
2109 }
2110 
2111 ObjCImplementationDecl *
2112 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2113   return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2114                                             SourceLocation(), SourceLocation());
2115 }
2116 
2117 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2118                                              CXXCtorInitializer ** initializers,
2119                                                  unsigned numInitializers) {
2120   if (numInitializers > 0) {
2121     NumIvarInitializers = numInitializers;
2122     CXXCtorInitializer **ivarInitializers =
2123     new (C) CXXCtorInitializer*[NumIvarInitializers];
2124     memcpy(ivarInitializers, initializers,
2125            numInitializers * sizeof(CXXCtorInitializer*));
2126     IvarInitializers = ivarInitializers;
2127   }
2128 }
2129 
2130 ObjCImplementationDecl::init_const_iterator
2131 ObjCImplementationDecl::init_begin() const {
2132   return IvarInitializers.get(getASTContext().getExternalSource());
2133 }
2134 
2135 raw_ostream &clang::operator<<(raw_ostream &OS,
2136                                const ObjCImplementationDecl &ID) {
2137   OS << ID.getName();
2138   return OS;
2139 }
2140 
2141 //===----------------------------------------------------------------------===//
2142 // ObjCCompatibleAliasDecl
2143 //===----------------------------------------------------------------------===//
2144 
2145 void ObjCCompatibleAliasDecl::anchor() { }
2146 
2147 ObjCCompatibleAliasDecl *
2148 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
2149                                 SourceLocation L,
2150                                 IdentifierInfo *Id,
2151                                 ObjCInterfaceDecl* AliasedClass) {
2152   return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
2153 }
2154 
2155 ObjCCompatibleAliasDecl *
2156 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2157   return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2158                                              nullptr, nullptr);
2159 }
2160 
2161 //===----------------------------------------------------------------------===//
2162 // ObjCPropertyDecl
2163 //===----------------------------------------------------------------------===//
2164 
2165 void ObjCPropertyDecl::anchor() { }
2166 
2167 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
2168                                            SourceLocation L,
2169                                            IdentifierInfo *Id,
2170                                            SourceLocation AtLoc,
2171                                            SourceLocation LParenLoc,
2172                                            QualType T,
2173                                            TypeSourceInfo *TSI,
2174                                            PropertyControl propControl) {
2175   return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
2176                                       propControl);
2177 }
2178 
2179 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
2180                                                        unsigned ID) {
2181   return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2182                                       SourceLocation(), SourceLocation(),
2183                                       QualType(), nullptr, None);
2184 }
2185 
2186 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const {
2187   return DeclType.substObjCMemberType(objectType, getDeclContext(),
2188                                       ObjCSubstitutionContext::Property);
2189 }
2190 
2191 //===----------------------------------------------------------------------===//
2192 // ObjCPropertyImplDecl
2193 //===----------------------------------------------------------------------===//
2194 
2195 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
2196                                                    DeclContext *DC,
2197                                                    SourceLocation atLoc,
2198                                                    SourceLocation L,
2199                                                    ObjCPropertyDecl *property,
2200                                                    Kind PK,
2201                                                    ObjCIvarDecl *ivar,
2202                                                    SourceLocation ivarLoc) {
2203   return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
2204                                           ivarLoc);
2205 }
2206 
2207 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
2208                                                                unsigned ID) {
2209   return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2210                                           SourceLocation(), nullptr, Dynamic,
2211                                           nullptr, SourceLocation());
2212 }
2213 
2214 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
2215   SourceLocation EndLoc = getLocation();
2216   if (IvarLoc.isValid())
2217     EndLoc = IvarLoc;
2218 
2219   return SourceRange(AtLoc, EndLoc);
2220 }
2221