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