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