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