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