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