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