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