1 //===- DeclObjC.cpp - ObjC Declaration AST Node Implementation ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Objective-C related Decl classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/DeclObjC.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/Stmt.h"
20 #include "clang/AST/Type.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Basic/IdentifierTable.h"
23 #include "clang/Basic/LLVM.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/SourceLocation.h"
26 #include "llvm/ADT/None.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdint>
35 #include <cstring>
36 #include <queue>
37 #include <utility>
38 
39 using namespace clang;
40 
41 //===----------------------------------------------------------------------===//
42 // ObjCListBase
43 //===----------------------------------------------------------------------===//
44 
set(void * const * InList,unsigned Elts,ASTContext & Ctx)45 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
46   List = nullptr;
47   if (Elts == 0) return;  // Setting to an empty list is a noop.
48 
49   List = new (Ctx) void*[Elts];
50   NumElts = Elts;
51   memcpy(List, InList, sizeof(void*)*Elts);
52 }
53 
set(ObjCProtocolDecl * const * InList,unsigned Elts,const SourceLocation * Locs,ASTContext & Ctx)54 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts,
55                            const SourceLocation *Locs, ASTContext &Ctx) {
56   if (Elts == 0)
57     return;
58 
59   Locations = new (Ctx) SourceLocation[Elts];
60   memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
61   set(InList, Elts, Ctx);
62 }
63 
64 //===----------------------------------------------------------------------===//
65 // ObjCInterfaceDecl
66 //===----------------------------------------------------------------------===//
67 
ObjCContainerDecl(Kind DK,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc)68 ObjCContainerDecl::ObjCContainerDecl(Kind DK, DeclContext *DC,
69                                      IdentifierInfo *Id, SourceLocation nameLoc,
70                                      SourceLocation atStartLoc)
71     : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK) {
72   setAtStartLoc(atStartLoc);
73 }
74 
anchor()75 void ObjCContainerDecl::anchor() {}
76 
77 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
78 ///
79 ObjCIvarDecl *
getIvarDecl(IdentifierInfo * Id) const80 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
81   lookup_result R = lookup(Id);
82   for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end();
83        Ivar != IvarEnd; ++Ivar) {
84     if (auto *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
85       return ivar;
86   }
87   return nullptr;
88 }
89 
90 // Get the local instance/class method declared in this interface.
91 ObjCMethodDecl *
getMethod(Selector Sel,bool isInstance,bool AllowHidden) const92 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance,
93                              bool AllowHidden) const {
94   // If this context is a hidden protocol definition, don't find any
95   // methods there.
96   if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
97     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
98       if (!Def->isUnconditionallyVisible() && !AllowHidden)
99         return nullptr;
100   }
101 
102   // Since instance & class methods can have the same name, the loop below
103   // ensures we get the correct method.
104   //
105   // @interface Whatever
106   // - (int) class_method;
107   // + (float) class_method;
108   // @end
109   lookup_result R = lookup(Sel);
110   for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
111        Meth != MethEnd; ++Meth) {
112     auto *MD = dyn_cast<ObjCMethodDecl>(*Meth);
113     if (MD && MD->isInstanceMethod() == isInstance)
114       return MD;
115   }
116   return nullptr;
117 }
118 
119 /// This routine returns 'true' if a user declared setter method was
120 /// found in the class, its protocols, its super classes or categories.
121 /// It also returns 'true' if one of its categories has declared a 'readwrite'
122 /// property.  This is because, user must provide a setter method for the
123 /// category's 'readwrite' property.
HasUserDeclaredSetterMethod(const ObjCPropertyDecl * Property) const124 bool ObjCContainerDecl::HasUserDeclaredSetterMethod(
125     const ObjCPropertyDecl *Property) const {
126   Selector Sel = Property->getSetterName();
127   lookup_result R = lookup(Sel);
128   for (lookup_iterator Meth = R.begin(), MethEnd = R.end();
129        Meth != MethEnd; ++Meth) {
130     auto *MD = dyn_cast<ObjCMethodDecl>(*Meth);
131     if (MD && MD->isInstanceMethod() && !MD->isImplicit())
132       return true;
133   }
134 
135   if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
136     // Also look into categories, including class extensions, looking
137     // for a user declared instance method.
138     for (const auto *Cat : ID->visible_categories()) {
139       if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel))
140         if (!MD->isImplicit())
141           return true;
142       if (Cat->IsClassExtension())
143         continue;
144       // Also search through the categories looking for a 'readwrite'
145       // declaration of this property. If one found, presumably a setter will
146       // be provided (properties declared in categories will not get
147       // auto-synthesized).
148       for (const auto *P : Cat->properties())
149         if (P->getIdentifier() == Property->getIdentifier()) {
150           if (P->getPropertyAttributes() &
151               ObjCPropertyAttribute::kind_readwrite)
152             return true;
153           break;
154         }
155     }
156 
157     // Also look into protocols, for a user declared instance method.
158     for (const auto *Proto : ID->all_referenced_protocols())
159       if (Proto->HasUserDeclaredSetterMethod(Property))
160         return true;
161 
162     // And in its super class.
163     ObjCInterfaceDecl *OSC = ID->getSuperClass();
164     while (OSC) {
165       if (OSC->HasUserDeclaredSetterMethod(Property))
166         return true;
167       OSC = OSC->getSuperClass();
168     }
169   }
170   if (const auto *PD = dyn_cast<ObjCProtocolDecl>(this))
171     for (const auto *PI : PD->protocols())
172       if (PI->HasUserDeclaredSetterMethod(Property))
173         return true;
174   return false;
175 }
176 
177 ObjCPropertyDecl *
findPropertyDecl(const DeclContext * DC,const IdentifierInfo * propertyID,ObjCPropertyQueryKind queryKind)178 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
179                                    const IdentifierInfo *propertyID,
180                                    ObjCPropertyQueryKind queryKind) {
181   // If this context is a hidden protocol definition, don't find any
182   // property.
183   if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(DC)) {
184     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
185       if (!Def->isUnconditionallyVisible())
186         return nullptr;
187   }
188 
189   // If context is class, then lookup property in its visible extensions.
190   // This comes before property is looked up in primary class.
191   if (auto *IDecl = dyn_cast<ObjCInterfaceDecl>(DC)) {
192     for (const auto *Ext : IDecl->visible_extensions())
193       if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl(Ext,
194                                                        propertyID,
195                                                        queryKind))
196         return PD;
197   }
198 
199   DeclContext::lookup_result R = DC->lookup(propertyID);
200   ObjCPropertyDecl *classProp = nullptr;
201   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
202        ++I)
203     if (auto *PD = dyn_cast<ObjCPropertyDecl>(*I)) {
204       // If queryKind is unknown, we return the instance property if one
205       // exists; otherwise we return the class property.
206       if ((queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
207            !PD->isClassProperty()) ||
208           (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
209            PD->isClassProperty()) ||
210           (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
211            !PD->isClassProperty()))
212         return PD;
213 
214       if (PD->isClassProperty())
215         classProp = PD;
216     }
217 
218   if (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
219     // We can't find the instance property, return the class property.
220     return classProp;
221 
222   return nullptr;
223 }
224 
225 IdentifierInfo *
getDefaultSynthIvarName(ASTContext & Ctx) const226 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const {
227   SmallString<128> ivarName;
228   {
229     llvm::raw_svector_ostream os(ivarName);
230     os << '_' << getIdentifier()->getName();
231   }
232   return &Ctx.Idents.get(ivarName.str());
233 }
234 
235 /// FindPropertyDeclaration - Finds declaration of the property given its name
236 /// in 'PropertyId' and returns it. It returns 0, if not found.
FindPropertyDeclaration(const IdentifierInfo * PropertyId,ObjCPropertyQueryKind QueryKind) const237 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration(
238     const IdentifierInfo *PropertyId,
239     ObjCPropertyQueryKind QueryKind) const {
240   // Don't find properties within hidden protocol definitions.
241   if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
242     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
243       if (!Def->isUnconditionallyVisible())
244         return nullptr;
245   }
246 
247   // Search the extensions of a class first; they override what's in
248   // the class itself.
249   if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) {
250     for (const auto *Ext : ClassDecl->visible_extensions()) {
251       if (auto *P = Ext->FindPropertyDeclaration(PropertyId, QueryKind))
252         return P;
253     }
254   }
255 
256   if (ObjCPropertyDecl *PD =
257         ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId,
258                                            QueryKind))
259     return PD;
260 
261   switch (getKind()) {
262     default:
263       break;
264     case Decl::ObjCProtocol: {
265       const auto *PID = cast<ObjCProtocolDecl>(this);
266       for (const auto *I : PID->protocols())
267         if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
268                                                              QueryKind))
269           return P;
270       break;
271     }
272     case Decl::ObjCInterface: {
273       const auto *OID = cast<ObjCInterfaceDecl>(this);
274       // Look through categories (but not extensions; they were handled above).
275       for (const auto *Cat : OID->visible_categories()) {
276         if (!Cat->IsClassExtension())
277           if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(
278                                              PropertyId, QueryKind))
279             return P;
280       }
281 
282       // Look through protocols.
283       for (const auto *I : OID->all_referenced_protocols())
284         if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
285                                                              QueryKind))
286           return P;
287 
288       // Finally, check the super class.
289       if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
290         return superClass->FindPropertyDeclaration(PropertyId, QueryKind);
291       break;
292     }
293     case Decl::ObjCCategory: {
294       const auto *OCD = cast<ObjCCategoryDecl>(this);
295       // Look through protocols.
296       if (!OCD->IsClassExtension())
297         for (const auto *I : OCD->protocols())
298           if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
299                                                                QueryKind))
300             return P;
301       break;
302     }
303   }
304   return nullptr;
305 }
306 
anchor()307 void ObjCInterfaceDecl::anchor() {}
308 
getTypeParamList() const309 ObjCTypeParamList *ObjCInterfaceDecl::getTypeParamList() const {
310   // If this particular declaration has a type parameter list, return it.
311   if (ObjCTypeParamList *written = getTypeParamListAsWritten())
312     return written;
313 
314   // If there is a definition, return its type parameter list.
315   if (const ObjCInterfaceDecl *def = getDefinition())
316     return def->getTypeParamListAsWritten();
317 
318   // Otherwise, look at previous declarations to determine whether any
319   // of them has a type parameter list, skipping over those
320   // declarations that do not.
321   for (const ObjCInterfaceDecl *decl = getMostRecentDecl(); decl;
322        decl = decl->getPreviousDecl()) {
323     if (ObjCTypeParamList *written = decl->getTypeParamListAsWritten())
324       return written;
325   }
326 
327   return nullptr;
328 }
329 
setTypeParamList(ObjCTypeParamList * TPL)330 void ObjCInterfaceDecl::setTypeParamList(ObjCTypeParamList *TPL) {
331   TypeParamList = TPL;
332   if (!TPL)
333     return;
334   // Set the declaration context of each of the type parameters.
335   for (auto *typeParam : *TypeParamList)
336     typeParam->setDeclContext(this);
337 }
338 
getSuperClass() const339 ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const {
340   // FIXME: Should make sure no callers ever do this.
341   if (!hasDefinition())
342     return nullptr;
343 
344   if (data().ExternallyCompleted)
345     LoadExternalDefinition();
346 
347   if (const ObjCObjectType *superType = getSuperClassType()) {
348     if (ObjCInterfaceDecl *superDecl = superType->getInterface()) {
349       if (ObjCInterfaceDecl *superDef = superDecl->getDefinition())
350         return superDef;
351 
352       return superDecl;
353     }
354   }
355 
356   return nullptr;
357 }
358 
getSuperClassLoc() const359 SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const {
360   if (TypeSourceInfo *superTInfo = getSuperClassTInfo())
361     return superTInfo->getTypeLoc().getBeginLoc();
362 
363   return SourceLocation();
364 }
365 
366 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
367 /// with name 'PropertyId' in the primary class; including those in protocols
368 /// (direct or indirect) used by the primary class.
369 ObjCPropertyDecl *
FindPropertyVisibleInPrimaryClass(IdentifierInfo * PropertyId,ObjCPropertyQueryKind QueryKind) const370 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
371                        IdentifierInfo *PropertyId,
372                        ObjCPropertyQueryKind QueryKind) const {
373   // FIXME: Should make sure no callers ever do this.
374   if (!hasDefinition())
375     return nullptr;
376 
377   if (data().ExternallyCompleted)
378     LoadExternalDefinition();
379 
380   if (ObjCPropertyDecl *PD =
381       ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId,
382                                          QueryKind))
383     return PD;
384 
385   // Look through protocols.
386   for (const auto *I : all_referenced_protocols())
387     if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId,
388                                                          QueryKind))
389       return P;
390 
391   return nullptr;
392 }
393 
collectPropertiesToImplement(PropertyMap & PM,PropertyDeclOrder & PO) const394 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM,
395                                                      PropertyDeclOrder &PO) const {
396   for (auto *Prop : properties()) {
397     PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
398     PO.push_back(Prop);
399   }
400   for (const auto *Ext : known_extensions()) {
401     const ObjCCategoryDecl *ClassExt = Ext;
402     for (auto *Prop : ClassExt->properties()) {
403       PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
404       PO.push_back(Prop);
405     }
406   }
407   for (const auto *PI : all_referenced_protocols())
408     PI->collectPropertiesToImplement(PM, PO);
409   // Note, the properties declared only in class extensions are still copied
410   // into the main @interface's property list, and therefore we don't
411   // explicitly, have to search class extension properties.
412 }
413 
isArcWeakrefUnavailable() const414 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const {
415   const ObjCInterfaceDecl *Class = this;
416   while (Class) {
417     if (Class->hasAttr<ArcWeakrefUnavailableAttr>())
418       return true;
419     Class = Class->getSuperClass();
420   }
421   return false;
422 }
423 
isObjCRequiresPropertyDefs() const424 const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const {
425   const ObjCInterfaceDecl *Class = this;
426   while (Class) {
427     if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
428       return Class;
429     Class = Class->getSuperClass();
430   }
431   return nullptr;
432 }
433 
mergeClassExtensionProtocolList(ObjCProtocolDecl * const * ExtList,unsigned ExtNum,ASTContext & C)434 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
435                               ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
436                               ASTContext &C) {
437   if (data().ExternallyCompleted)
438     LoadExternalDefinition();
439 
440   if (data().AllReferencedProtocols.empty() &&
441       data().ReferencedProtocols.empty()) {
442     data().AllReferencedProtocols.set(ExtList, ExtNum, C);
443     return;
444   }
445 
446   // Check for duplicate protocol in class's protocol list.
447   // This is O(n*m). But it is extremely rare and number of protocols in
448   // class or its extension are very few.
449   SmallVector<ObjCProtocolDecl *, 8> ProtocolRefs;
450   for (unsigned i = 0; i < ExtNum; i++) {
451     bool protocolExists = false;
452     ObjCProtocolDecl *ProtoInExtension = ExtList[i];
453     for (auto *Proto : all_referenced_protocols()) {
454       if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
455         protocolExists = true;
456         break;
457       }
458     }
459     // Do we want to warn on a protocol in extension class which
460     // already exist in the class? Probably not.
461     if (!protocolExists)
462       ProtocolRefs.push_back(ProtoInExtension);
463   }
464 
465   if (ProtocolRefs.empty())
466     return;
467 
468   // Merge ProtocolRefs into class's protocol list;
469   ProtocolRefs.append(all_referenced_protocol_begin(),
470                       all_referenced_protocol_end());
471 
472   data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
473 }
474 
475 const ObjCInterfaceDecl *
findInterfaceWithDesignatedInitializers() const476 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const {
477   const ObjCInterfaceDecl *IFace = this;
478   while (IFace) {
479     if (IFace->hasDesignatedInitializers())
480       return IFace;
481     if (!IFace->inheritsDesignatedInitializers())
482       break;
483     IFace = IFace->getSuperClass();
484   }
485   return nullptr;
486 }
487 
isIntroducingInitializers(const ObjCInterfaceDecl * D)488 static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) {
489   for (const auto *MD : D->instance_methods()) {
490     if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
491       return true;
492   }
493   for (const auto *Ext : D->visible_extensions()) {
494     for (const auto *MD : Ext->instance_methods()) {
495       if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
496         return true;
497     }
498   }
499   if (const auto *ImplD = D->getImplementation()) {
500     for (const auto *MD : ImplD->instance_methods()) {
501       if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
502         return true;
503     }
504   }
505   return false;
506 }
507 
inheritsDesignatedInitializers() const508 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const {
509   switch (data().InheritedDesignatedInitializers) {
510   case DefinitionData::IDI_Inherited:
511     return true;
512   case DefinitionData::IDI_NotInherited:
513     return false;
514   case DefinitionData::IDI_Unknown:
515     // If the class introduced initializers we conservatively assume that we
516     // don't know if any of them is a designated initializer to avoid possible
517     // misleading warnings.
518     if (isIntroducingInitializers(this)) {
519       data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited;
520     } else {
521       if (auto SuperD = getSuperClass()) {
522         data().InheritedDesignatedInitializers =
523           SuperD->declaresOrInheritsDesignatedInitializers() ?
524             DefinitionData::IDI_Inherited :
525             DefinitionData::IDI_NotInherited;
526       } else {
527         data().InheritedDesignatedInitializers =
528           DefinitionData::IDI_NotInherited;
529       }
530     }
531     assert(data().InheritedDesignatedInitializers
532              != DefinitionData::IDI_Unknown);
533     return data().InheritedDesignatedInitializers ==
534         DefinitionData::IDI_Inherited;
535   }
536 
537   llvm_unreachable("unexpected InheritedDesignatedInitializers value");
538 }
539 
getDesignatedInitializers(llvm::SmallVectorImpl<const ObjCMethodDecl * > & Methods) const540 void ObjCInterfaceDecl::getDesignatedInitializers(
541     llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const {
542   // Check for a complete definition and recover if not so.
543   if (!isThisDeclarationADefinition())
544     return;
545   if (data().ExternallyCompleted)
546     LoadExternalDefinition();
547 
548   const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
549   if (!IFace)
550     return;
551 
552   for (const auto *MD : IFace->instance_methods())
553     if (MD->isThisDeclarationADesignatedInitializer())
554       Methods.push_back(MD);
555   for (const auto *Ext : IFace->visible_extensions()) {
556     for (const auto *MD : Ext->instance_methods())
557       if (MD->isThisDeclarationADesignatedInitializer())
558         Methods.push_back(MD);
559   }
560 }
561 
isDesignatedInitializer(Selector Sel,const ObjCMethodDecl ** InitMethod) const562 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel,
563                                       const ObjCMethodDecl **InitMethod) const {
564   bool HasCompleteDef = isThisDeclarationADefinition();
565   // During deserialization the data record for the ObjCInterfaceDecl could
566   // be made invariant by reusing the canonical decl. Take this into account
567   // when checking for the complete definition.
568   if (!HasCompleteDef && getCanonicalDecl()->hasDefinition() &&
569       getCanonicalDecl()->getDefinition() == getDefinition())
570     HasCompleteDef = true;
571 
572   // Check for a complete definition and recover if not so.
573   if (!HasCompleteDef)
574     return false;
575 
576   if (data().ExternallyCompleted)
577     LoadExternalDefinition();
578 
579   const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
580   if (!IFace)
581     return false;
582 
583   if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) {
584     if (MD->isThisDeclarationADesignatedInitializer()) {
585       if (InitMethod)
586         *InitMethod = MD;
587       return true;
588     }
589   }
590   for (const auto *Ext : IFace->visible_extensions()) {
591     if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) {
592       if (MD->isThisDeclarationADesignatedInitializer()) {
593         if (InitMethod)
594           *InitMethod = MD;
595         return true;
596       }
597     }
598   }
599   return false;
600 }
601 
allocateDefinitionData()602 void ObjCInterfaceDecl::allocateDefinitionData() {
603   assert(!hasDefinition() && "ObjC class already has a definition");
604   Data.setPointer(new (getASTContext()) DefinitionData());
605   Data.getPointer()->Definition = this;
606 
607   // Make the type point at the definition, now that we have one.
608   if (TypeForDecl)
609     cast<ObjCInterfaceType>(TypeForDecl)->Decl = this;
610 }
611 
startDefinition()612 void ObjCInterfaceDecl::startDefinition() {
613   allocateDefinitionData();
614 
615   // Update all of the declarations with a pointer to the definition.
616   for (auto *RD : redecls()) {
617     if (RD != this)
618       RD->Data = Data;
619   }
620 }
621 
lookupInstanceVariable(IdentifierInfo * ID,ObjCInterfaceDecl * & clsDeclared)622 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
623                                               ObjCInterfaceDecl *&clsDeclared) {
624   // FIXME: Should make sure no callers ever do this.
625   if (!hasDefinition())
626     return nullptr;
627 
628   if (data().ExternallyCompleted)
629     LoadExternalDefinition();
630 
631   ObjCInterfaceDecl* ClassDecl = this;
632   while (ClassDecl != nullptr) {
633     if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
634       clsDeclared = ClassDecl;
635       return I;
636     }
637 
638     for (const auto *Ext : ClassDecl->visible_extensions()) {
639       if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) {
640         clsDeclared = ClassDecl;
641         return I;
642       }
643     }
644 
645     ClassDecl = ClassDecl->getSuperClass();
646   }
647   return nullptr;
648 }
649 
650 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
651 /// class whose name is passed as argument. If it is not one of the super classes
652 /// the it returns NULL.
lookupInheritedClass(const IdentifierInfo * ICName)653 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
654                                         const IdentifierInfo*ICName) {
655   // FIXME: Should make sure no callers ever do this.
656   if (!hasDefinition())
657     return nullptr;
658 
659   if (data().ExternallyCompleted)
660     LoadExternalDefinition();
661 
662   ObjCInterfaceDecl* ClassDecl = this;
663   while (ClassDecl != nullptr) {
664     if (ClassDecl->getIdentifier() == ICName)
665       return ClassDecl;
666     ClassDecl = ClassDecl->getSuperClass();
667   }
668   return nullptr;
669 }
670 
671 ObjCProtocolDecl *
lookupNestedProtocol(IdentifierInfo * Name)672 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) {
673   for (auto *P : all_referenced_protocols())
674     if (P->lookupProtocolNamed(Name))
675       return P;
676   ObjCInterfaceDecl *SuperClass = getSuperClass();
677   return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr;
678 }
679 
680 /// lookupMethod - This method returns an instance/class method by looking in
681 /// the class, its categories, and its super classes (using a linear search).
682 /// When argument category "C" is specified, any implicit method found
683 /// in this category is ignored.
lookupMethod(Selector Sel,bool isInstance,bool shallowCategoryLookup,bool followSuper,const ObjCCategoryDecl * C) const684 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
685                                                 bool isInstance,
686                                                 bool shallowCategoryLookup,
687                                                 bool followSuper,
688                                                 const ObjCCategoryDecl *C) const
689 {
690   // FIXME: Should make sure no callers ever do this.
691   if (!hasDefinition())
692     return nullptr;
693 
694   const ObjCInterfaceDecl* ClassDecl = this;
695   ObjCMethodDecl *MethodDecl = nullptr;
696 
697   if (data().ExternallyCompleted)
698     LoadExternalDefinition();
699 
700   while (ClassDecl) {
701     // 1. Look through primary class.
702     if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
703       return MethodDecl;
704 
705     // 2. Didn't find one yet - now look through categories.
706     for (const auto *Cat : ClassDecl->visible_categories())
707       if ((MethodDecl = Cat->getMethod(Sel, isInstance)))
708         if (C != Cat || !MethodDecl->isImplicit())
709           return MethodDecl;
710 
711     // 3. Didn't find one yet - look through primary class's protocols.
712     for (const auto *I : ClassDecl->protocols())
713       if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
714         return MethodDecl;
715 
716     // 4. Didn't find one yet - now look through categories' protocols
717     if (!shallowCategoryLookup)
718       for (const auto *Cat : ClassDecl->visible_categories()) {
719         // Didn't find one yet - look through protocols.
720         const ObjCList<ObjCProtocolDecl> &Protocols =
721           Cat->getReferencedProtocols();
722         for (auto *Protocol : Protocols)
723           if ((MethodDecl = Protocol->lookupMethod(Sel, isInstance)))
724             if (C != Cat || !MethodDecl->isImplicit())
725               return MethodDecl;
726       }
727 
728 
729     if (!followSuper)
730       return nullptr;
731 
732     // 5. Get to the super class (if any).
733     ClassDecl = ClassDecl->getSuperClass();
734   }
735   return nullptr;
736 }
737 
738 // Will search "local" class/category implementations for a method decl.
739 // If failed, then we search in class's root for an instance method.
740 // Returns 0 if no method is found.
lookupPrivateMethod(const Selector & Sel,bool Instance) const741 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
742                                    const Selector &Sel,
743                                    bool Instance) const {
744   // FIXME: Should make sure no callers ever do this.
745   if (!hasDefinition())
746     return nullptr;
747 
748   if (data().ExternallyCompleted)
749     LoadExternalDefinition();
750 
751   ObjCMethodDecl *Method = nullptr;
752   if (ObjCImplementationDecl *ImpDecl = getImplementation())
753     Method = Instance ? ImpDecl->getInstanceMethod(Sel)
754                       : ImpDecl->getClassMethod(Sel);
755 
756   // Look through local category implementations associated with the class.
757   if (!Method)
758     Method = getCategoryMethod(Sel, Instance);
759 
760   // Before we give up, check if the selector is an instance method.
761   // But only in the root. This matches gcc's behavior and what the
762   // runtime expects.
763   if (!Instance && !Method && !getSuperClass()) {
764     Method = lookupInstanceMethod(Sel);
765     // Look through local category implementations associated
766     // with the root class.
767     if (!Method)
768       Method = lookupPrivateMethod(Sel, true);
769   }
770 
771   if (!Method && getSuperClass())
772     return getSuperClass()->lookupPrivateMethod(Sel, Instance);
773   return Method;
774 }
775 
776 //===----------------------------------------------------------------------===//
777 // ObjCMethodDecl
778 //===----------------------------------------------------------------------===//
779 
ObjCMethodDecl(SourceLocation beginLoc,SourceLocation endLoc,Selector SelInfo,QualType T,TypeSourceInfo * ReturnTInfo,DeclContext * contextDecl,bool isInstance,bool isVariadic,bool isPropertyAccessor,bool isSynthesizedAccessorStub,bool isImplicitlyDeclared,bool isDefined,ImplementationControl impControl,bool HasRelatedResultType)780 ObjCMethodDecl::ObjCMethodDecl(
781     SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo,
782     QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl,
783     bool isInstance, bool isVariadic, bool isPropertyAccessor,
784     bool isSynthesizedAccessorStub, bool isImplicitlyDeclared, bool isDefined,
785     ImplementationControl impControl, bool HasRelatedResultType)
786     : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo),
787       DeclContext(ObjCMethod), MethodDeclType(T), ReturnTInfo(ReturnTInfo),
788       DeclEndLoc(endLoc) {
789 
790   // Initialized the bits stored in DeclContext.
791   ObjCMethodDeclBits.Family =
792       static_cast<ObjCMethodFamily>(InvalidObjCMethodFamily);
793   setInstanceMethod(isInstance);
794   setVariadic(isVariadic);
795   setPropertyAccessor(isPropertyAccessor);
796   setSynthesizedAccessorStub(isSynthesizedAccessorStub);
797   setDefined(isDefined);
798   setIsRedeclaration(false);
799   setHasRedeclaration(false);
800   setDeclImplementation(impControl);
801   setObjCDeclQualifier(OBJC_TQ_None);
802   setRelatedResultType(HasRelatedResultType);
803   setSelLocsKind(SelLoc_StandardNoSpace);
804   setOverriding(false);
805   setHasSkippedBody(false);
806 
807   setImplicit(isImplicitlyDeclared);
808 }
809 
Create(ASTContext & C,SourceLocation beginLoc,SourceLocation endLoc,Selector SelInfo,QualType T,TypeSourceInfo * ReturnTInfo,DeclContext * contextDecl,bool isInstance,bool isVariadic,bool isPropertyAccessor,bool isSynthesizedAccessorStub,bool isImplicitlyDeclared,bool isDefined,ImplementationControl impControl,bool HasRelatedResultType)810 ObjCMethodDecl *ObjCMethodDecl::Create(
811     ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
812     Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
813     DeclContext *contextDecl, bool isInstance, bool isVariadic,
814     bool isPropertyAccessor, bool isSynthesizedAccessorStub,
815     bool isImplicitlyDeclared, bool isDefined, ImplementationControl impControl,
816     bool HasRelatedResultType) {
817   return new (C, contextDecl) ObjCMethodDecl(
818       beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance,
819       isVariadic, isPropertyAccessor, isSynthesizedAccessorStub,
820       isImplicitlyDeclared, isDefined, impControl, HasRelatedResultType);
821 }
822 
CreateDeserialized(ASTContext & C,unsigned ID)823 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
824   return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(),
825                                     Selector(), QualType(), nullptr, nullptr);
826 }
827 
isDirectMethod() const828 bool ObjCMethodDecl::isDirectMethod() const {
829   return hasAttr<ObjCDirectAttr>() &&
830          !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting;
831 }
832 
isThisDeclarationADesignatedInitializer() const833 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const {
834   return getMethodFamily() == OMF_init &&
835       hasAttr<ObjCDesignatedInitializerAttr>();
836 }
837 
definedInNSObject(const ASTContext & Ctx) const838 bool ObjCMethodDecl::definedInNSObject(const ASTContext &Ctx) const {
839   if (const auto *PD = dyn_cast<const ObjCProtocolDecl>(getDeclContext()))
840     return PD->getIdentifier() == Ctx.getNSObjectName();
841   if (const auto *ID = dyn_cast<const ObjCInterfaceDecl>(getDeclContext()))
842     return ID->getIdentifier() == Ctx.getNSObjectName();
843   return false;
844 }
845 
isDesignatedInitializerForTheInterface(const ObjCMethodDecl ** InitMethod) const846 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface(
847     const ObjCMethodDecl **InitMethod) const {
848   if (getMethodFamily() != OMF_init)
849     return false;
850   const DeclContext *DC = getDeclContext();
851   if (isa<ObjCProtocolDecl>(DC))
852     return false;
853   if (const ObjCInterfaceDecl *ID = getClassInterface())
854     return ID->isDesignatedInitializer(getSelector(), InitMethod);
855   return false;
856 }
857 
hasParamDestroyedInCallee() const858 bool ObjCMethodDecl::hasParamDestroyedInCallee() const {
859   for (auto param : parameters()) {
860     if (param->isDestroyedInCallee())
861       return true;
862   }
863   return false;
864 }
865 
getBody() const866 Stmt *ObjCMethodDecl::getBody() const {
867   return Body.get(getASTContext().getExternalSource());
868 }
869 
setAsRedeclaration(const ObjCMethodDecl * PrevMethod)870 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
871   assert(PrevMethod);
872   getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
873   setIsRedeclaration(true);
874   PrevMethod->setHasRedeclaration(true);
875 }
876 
setParamsAndSelLocs(ASTContext & C,ArrayRef<ParmVarDecl * > Params,ArrayRef<SourceLocation> SelLocs)877 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
878                                          ArrayRef<ParmVarDecl*> Params,
879                                          ArrayRef<SourceLocation> SelLocs) {
880   ParamsAndSelLocs = nullptr;
881   NumParams = Params.size();
882   if (Params.empty() && SelLocs.empty())
883     return;
884 
885   static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
886                 "Alignment not sufficient for SourceLocation");
887 
888   unsigned Size = sizeof(ParmVarDecl *) * NumParams +
889                   sizeof(SourceLocation) * SelLocs.size();
890   ParamsAndSelLocs = C.Allocate(Size);
891   std::copy(Params.begin(), Params.end(), getParams());
892   std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
893 }
894 
getSelectorLocs(SmallVectorImpl<SourceLocation> & SelLocs) const895 void ObjCMethodDecl::getSelectorLocs(
896                                SmallVectorImpl<SourceLocation> &SelLocs) const {
897   for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
898     SelLocs.push_back(getSelectorLoc(i));
899 }
900 
setMethodParams(ASTContext & C,ArrayRef<ParmVarDecl * > Params,ArrayRef<SourceLocation> SelLocs)901 void ObjCMethodDecl::setMethodParams(ASTContext &C,
902                                      ArrayRef<ParmVarDecl*> Params,
903                                      ArrayRef<SourceLocation> SelLocs) {
904   assert((!SelLocs.empty() || isImplicit()) &&
905          "No selector locs for non-implicit method");
906   if (isImplicit())
907     return setParamsAndSelLocs(C, Params, llvm::None);
908 
909   setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params,
910                                         DeclEndLoc));
911   if (getSelLocsKind() != SelLoc_NonStandard)
912     return setParamsAndSelLocs(C, Params, llvm::None);
913 
914   setParamsAndSelLocs(C, Params, SelLocs);
915 }
916 
917 /// A definition will return its interface declaration.
918 /// An interface declaration will return its definition.
919 /// Otherwise it will return itself.
getNextRedeclarationImpl()920 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() {
921   ASTContext &Ctx = getASTContext();
922   ObjCMethodDecl *Redecl = nullptr;
923   if (hasRedeclaration())
924     Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
925   if (Redecl)
926     return Redecl;
927 
928   auto *CtxD = cast<Decl>(getDeclContext());
929 
930   if (!CtxD->isInvalidDecl()) {
931     if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
932       if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
933         if (!ImplD->isInvalidDecl())
934           Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
935 
936     } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
937       if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
938         if (!ImplD->isInvalidDecl())
939           Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
940 
941     } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
942       if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
943         if (!IFD->isInvalidDecl())
944           Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
945 
946     } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
947       if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
948         if (!CatD->isInvalidDecl())
949           Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
950     }
951   }
952 
953   // Ensure that the discovered method redeclaration has a valid declaration
954   // context. Used to prevent infinite loops when iterating redeclarations in
955   // a partially invalid AST.
956   if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl())
957     Redecl = nullptr;
958 
959   if (!Redecl && isRedeclaration()) {
960     // This is the last redeclaration, go back to the first method.
961     return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
962                                                     isInstanceMethod(),
963                                                     /*AllowHidden=*/true);
964   }
965 
966   return Redecl ? Redecl : this;
967 }
968 
getCanonicalDecl()969 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
970   auto *CtxD = cast<Decl>(getDeclContext());
971   const auto &Sel = getSelector();
972 
973   if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
974     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) {
975       // When the container is the ObjCImplementationDecl (the primary
976       // @implementation), then the canonical Decl is either in
977       // the class Interface, or in any of its extension.
978       //
979       // So when we don't find it in the ObjCInterfaceDecl,
980       // sift through extensions too.
981       if (ObjCMethodDecl *MD = IFD->getMethod(Sel, isInstanceMethod()))
982         return MD;
983       for (auto *Ext : IFD->known_extensions())
984         if (ObjCMethodDecl *MD = Ext->getMethod(Sel, isInstanceMethod()))
985           return MD;
986     }
987   } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
988     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
989       if (ObjCMethodDecl *MD = CatD->getMethod(Sel, isInstanceMethod()))
990         return MD;
991   }
992 
993   if (isRedeclaration()) {
994     // It is possible that we have not done deserializing the ObjCMethod yet.
995     ObjCMethodDecl *MD =
996         cast<ObjCContainerDecl>(CtxD)->getMethod(Sel, isInstanceMethod(),
997                                                  /*AllowHidden=*/true);
998     return MD ? MD : this;
999   }
1000 
1001   return this;
1002 }
1003 
getEndLoc() const1004 SourceLocation ObjCMethodDecl::getEndLoc() const {
1005   if (Stmt *Body = getBody())
1006     return Body->getEndLoc();
1007   return DeclEndLoc;
1008 }
1009 
getMethodFamily() const1010 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
1011   auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family);
1012   if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
1013     return family;
1014 
1015   // Check for an explicit attribute.
1016   if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
1017     // The unfortunate necessity of mapping between enums here is due
1018     // to the attributes framework.
1019     switch (attr->getFamily()) {
1020     case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
1021     case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
1022     case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
1023     case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
1024     case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
1025     case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
1026     }
1027     ObjCMethodDeclBits.Family = family;
1028     return family;
1029   }
1030 
1031   family = getSelector().getMethodFamily();
1032   switch (family) {
1033   case OMF_None: break;
1034 
1035   // init only has a conventional meaning for an instance method, and
1036   // it has to return an object.
1037   case OMF_init:
1038     if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
1039       family = OMF_None;
1040     break;
1041 
1042   // alloc/copy/new have a conventional meaning for both class and
1043   // instance methods, but they require an object return.
1044   case OMF_alloc:
1045   case OMF_copy:
1046   case OMF_mutableCopy:
1047   case OMF_new:
1048     if (!getReturnType()->isObjCObjectPointerType())
1049       family = OMF_None;
1050     break;
1051 
1052   // These selectors have a conventional meaning only for instance methods.
1053   case OMF_dealloc:
1054   case OMF_finalize:
1055   case OMF_retain:
1056   case OMF_release:
1057   case OMF_autorelease:
1058   case OMF_retainCount:
1059   case OMF_self:
1060     if (!isInstanceMethod())
1061       family = OMF_None;
1062     break;
1063 
1064   case OMF_initialize:
1065     if (isInstanceMethod() || !getReturnType()->isVoidType())
1066       family = OMF_None;
1067     break;
1068 
1069   case OMF_performSelector:
1070     if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
1071       family = OMF_None;
1072     else {
1073       unsigned noParams = param_size();
1074       if (noParams < 1 || noParams > 3)
1075         family = OMF_None;
1076       else {
1077         ObjCMethodDecl::param_type_iterator it = param_type_begin();
1078         QualType ArgT = (*it);
1079         if (!ArgT->isObjCSelType()) {
1080           family = OMF_None;
1081           break;
1082         }
1083         while (--noParams) {
1084           it++;
1085           ArgT = (*it);
1086           if (!ArgT->isObjCIdType()) {
1087             family = OMF_None;
1088             break;
1089           }
1090         }
1091       }
1092     }
1093     break;
1094 
1095   }
1096 
1097   // Cache the result.
1098   ObjCMethodDeclBits.Family = family;
1099   return family;
1100 }
1101 
getSelfType(ASTContext & Context,const ObjCInterfaceDecl * OID,bool & selfIsPseudoStrong,bool & selfIsConsumed) const1102 QualType ObjCMethodDecl::getSelfType(ASTContext &Context,
1103                                      const ObjCInterfaceDecl *OID,
1104                                      bool &selfIsPseudoStrong,
1105                                      bool &selfIsConsumed) const {
1106   QualType selfTy;
1107   selfIsPseudoStrong = false;
1108   selfIsConsumed = false;
1109   if (isInstanceMethod()) {
1110     // There may be no interface context due to error in declaration
1111     // of the interface (which has been reported). Recover gracefully.
1112     if (OID) {
1113       selfTy = Context.getObjCInterfaceType(OID);
1114       selfTy = Context.getObjCObjectPointerType(selfTy);
1115     } else {
1116       selfTy = Context.getObjCIdType();
1117     }
1118   } else // we have a factory method.
1119     selfTy = Context.getObjCClassType();
1120 
1121   if (Context.getLangOpts().ObjCAutoRefCount) {
1122     if (isInstanceMethod()) {
1123       selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
1124 
1125       // 'self' is always __strong.  It's actually pseudo-strong except
1126       // in init methods (or methods labeled ns_consumes_self), though.
1127       Qualifiers qs;
1128       qs.setObjCLifetime(Qualifiers::OCL_Strong);
1129       selfTy = Context.getQualifiedType(selfTy, qs);
1130 
1131       // In addition, 'self' is const unless this is an init method.
1132       if (getMethodFamily() != OMF_init && !selfIsConsumed) {
1133         selfTy = selfTy.withConst();
1134         selfIsPseudoStrong = true;
1135       }
1136     }
1137     else {
1138       assert(isClassMethod());
1139       // 'self' is always const in class methods.
1140       selfTy = selfTy.withConst();
1141       selfIsPseudoStrong = true;
1142     }
1143   }
1144   return selfTy;
1145 }
1146 
createImplicitParams(ASTContext & Context,const ObjCInterfaceDecl * OID)1147 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
1148                                           const ObjCInterfaceDecl *OID) {
1149   bool selfIsPseudoStrong, selfIsConsumed;
1150   QualType selfTy =
1151     getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed);
1152   auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(),
1153                                          &Context.Idents.get("self"), selfTy,
1154                                          ImplicitParamDecl::ObjCSelf);
1155   setSelfDecl(Self);
1156 
1157   if (selfIsConsumed)
1158     Self->addAttr(NSConsumedAttr::CreateImplicit(Context));
1159 
1160   if (selfIsPseudoStrong)
1161     Self->setARCPseudoStrong(true);
1162 
1163   setCmdDecl(ImplicitParamDecl::Create(
1164       Context, this, SourceLocation(), &Context.Idents.get("_cmd"),
1165       Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd));
1166 }
1167 
getClassInterface()1168 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
1169   if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
1170     return ID;
1171   if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1172     return CD->getClassInterface();
1173   if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
1174     return IMD->getClassInterface();
1175   if (isa<ObjCProtocolDecl>(getDeclContext()))
1176     return nullptr;
1177   llvm_unreachable("unknown method context");
1178 }
1179 
getCategory()1180 ObjCCategoryDecl *ObjCMethodDecl::getCategory() {
1181   if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1182     return CD;
1183   if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(getDeclContext()))
1184     return IMD->getCategoryDecl();
1185   return nullptr;
1186 }
1187 
getReturnTypeSourceRange() const1188 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const {
1189   const auto *TSI = getReturnTypeSourceInfo();
1190   if (TSI)
1191     return TSI->getTypeLoc().getSourceRange();
1192   return SourceRange();
1193 }
1194 
getSendResultType() const1195 QualType ObjCMethodDecl::getSendResultType() const {
1196   ASTContext &Ctx = getASTContext();
1197   return getReturnType().getNonLValueExprType(Ctx)
1198            .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result);
1199 }
1200 
getSendResultType(QualType receiverType) const1201 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const {
1202   // FIXME: Handle related result types here.
1203 
1204   return getReturnType().getNonLValueExprType(getASTContext())
1205            .substObjCMemberType(receiverType, getDeclContext(),
1206                                 ObjCSubstitutionContext::Result);
1207 }
1208 
CollectOverriddenMethodsRecurse(const ObjCContainerDecl * Container,const ObjCMethodDecl * Method,SmallVectorImpl<const ObjCMethodDecl * > & Methods,bool MovedToSuper)1209 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
1210                                             const ObjCMethodDecl *Method,
1211                                SmallVectorImpl<const ObjCMethodDecl *> &Methods,
1212                                             bool MovedToSuper) {
1213   if (!Container)
1214     return;
1215 
1216   // In categories look for overridden methods from protocols. A method from
1217   // category is not "overridden" since it is considered as the "same" method
1218   // (same USR) as the one from the interface.
1219   if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1220     // Check whether we have a matching method at this category but only if we
1221     // are at the super class level.
1222     if (MovedToSuper)
1223       if (ObjCMethodDecl *
1224             Overridden = Container->getMethod(Method->getSelector(),
1225                                               Method->isInstanceMethod(),
1226                                               /*AllowHidden=*/true))
1227         if (Method != Overridden) {
1228           // We found an override at this category; there is no need to look
1229           // into its protocols.
1230           Methods.push_back(Overridden);
1231           return;
1232         }
1233 
1234     for (const auto *P : Category->protocols())
1235       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1236     return;
1237   }
1238 
1239   // Check whether we have a matching method at this level.
1240   if (const ObjCMethodDecl *
1241         Overridden = Container->getMethod(Method->getSelector(),
1242                                           Method->isInstanceMethod(),
1243                                           /*AllowHidden=*/true))
1244     if (Method != Overridden) {
1245       // We found an override at this level; there is no need to look
1246       // into other protocols or categories.
1247       Methods.push_back(Overridden);
1248       return;
1249     }
1250 
1251   if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
1252     for (const auto *P : Protocol->protocols())
1253       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1254   }
1255 
1256   if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1257     for (const auto *P : Interface->protocols())
1258       CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1259 
1260     for (const auto *Cat : Interface->known_categories())
1261       CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper);
1262 
1263     if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1264       return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1265                                              /*MovedToSuper=*/true);
1266   }
1267 }
1268 
CollectOverriddenMethods(const ObjCContainerDecl * Container,const ObjCMethodDecl * Method,SmallVectorImpl<const ObjCMethodDecl * > & Methods)1269 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1270                                             const ObjCMethodDecl *Method,
1271                              SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1272   CollectOverriddenMethodsRecurse(Container, Method, Methods,
1273                                   /*MovedToSuper=*/false);
1274 }
1275 
collectOverriddenMethodsSlow(const ObjCMethodDecl * Method,SmallVectorImpl<const ObjCMethodDecl * > & overridden)1276 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1277                           SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1278   assert(Method->isOverriding());
1279 
1280   if (const auto *ProtD =
1281           dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1282     CollectOverriddenMethods(ProtD, Method, overridden);
1283 
1284   } else if (const auto *IMD =
1285                  dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1286     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1287     if (!ID)
1288       return;
1289     // Start searching for overridden methods using the method from the
1290     // interface as starting point.
1291     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1292                                                     Method->isInstanceMethod(),
1293                                                     /*AllowHidden=*/true))
1294       Method = IFaceMeth;
1295     CollectOverriddenMethods(ID, Method, overridden);
1296 
1297   } else if (const auto *CatD =
1298                  dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1299     const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1300     if (!ID)
1301       return;
1302     // Start searching for overridden methods using the method from the
1303     // interface as starting point.
1304     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1305                                                      Method->isInstanceMethod(),
1306                                                      /*AllowHidden=*/true))
1307       Method = IFaceMeth;
1308     CollectOverriddenMethods(ID, Method, overridden);
1309 
1310   } else {
1311     CollectOverriddenMethods(
1312                   dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1313                   Method, overridden);
1314   }
1315 }
1316 
getOverriddenMethods(SmallVectorImpl<const ObjCMethodDecl * > & Overridden) const1317 void ObjCMethodDecl::getOverriddenMethods(
1318                     SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1319   const ObjCMethodDecl *Method = this;
1320 
1321   if (Method->isRedeclaration()) {
1322     Method = cast<ObjCContainerDecl>(Method->getDeclContext())
1323                  ->getMethod(Method->getSelector(), Method->isInstanceMethod(),
1324                              /*AllowHidden=*/true);
1325   }
1326 
1327   if (Method->isOverriding()) {
1328     collectOverriddenMethodsSlow(Method, Overridden);
1329     assert(!Overridden.empty() &&
1330            "ObjCMethodDecl's overriding bit is not as expected");
1331   }
1332 }
1333 
1334 const ObjCPropertyDecl *
findPropertyDecl(bool CheckOverrides) const1335 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1336   Selector Sel = getSelector();
1337   unsigned NumArgs = Sel.getNumArgs();
1338   if (NumArgs > 1)
1339     return nullptr;
1340 
1341   if (isPropertyAccessor()) {
1342     const auto *Container = cast<ObjCContainerDecl>(getParent());
1343     // For accessor stubs, go back to the interface.
1344     if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container))
1345       if (isSynthesizedAccessorStub())
1346         Container = ImplDecl->getClassInterface();
1347 
1348     bool IsGetter = (NumArgs == 0);
1349     bool IsInstance = isInstanceMethod();
1350 
1351     /// Local function that attempts to find a matching property within the
1352     /// given Objective-C container.
1353     auto findMatchingProperty =
1354       [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * {
1355       if (IsInstance) {
1356         for (const auto *I : Container->instance_properties()) {
1357           Selector NextSel = IsGetter ? I->getGetterName()
1358                                       : I->getSetterName();
1359           if (NextSel == Sel)
1360             return I;
1361         }
1362       } else {
1363         for (const auto *I : Container->class_properties()) {
1364           Selector NextSel = IsGetter ? I->getGetterName()
1365                                       : I->getSetterName();
1366           if (NextSel == Sel)
1367             return I;
1368         }
1369       }
1370 
1371       return nullptr;
1372     };
1373 
1374     // Look in the container we were given.
1375     if (const auto *Found = findMatchingProperty(Container))
1376       return Found;
1377 
1378     // If we're in a category or extension, look in the main class.
1379     const ObjCInterfaceDecl *ClassDecl = nullptr;
1380     if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1381       ClassDecl = Category->getClassInterface();
1382       if (const auto *Found = findMatchingProperty(ClassDecl))
1383         return Found;
1384     } else {
1385       // Determine whether the container is a class.
1386       ClassDecl = cast<ObjCInterfaceDecl>(Container);
1387     }
1388     assert(ClassDecl && "Failed to find main class");
1389 
1390     // If we have a class, check its visible extensions.
1391     for (const auto *Ext : ClassDecl->visible_extensions()) {
1392       if (Ext == Container)
1393         continue;
1394       if (const auto *Found = findMatchingProperty(Ext))
1395         return Found;
1396     }
1397 
1398     assert(isSynthesizedAccessorStub() && "expected an accessor stub");
1399 
1400     for (const auto *Cat : ClassDecl->known_categories()) {
1401       if (Cat == Container)
1402         continue;
1403       if (const auto *Found = findMatchingProperty(Cat))
1404         return Found;
1405     }
1406 
1407     llvm_unreachable("Marked as a property accessor but no property found!");
1408   }
1409 
1410   if (!CheckOverrides)
1411     return nullptr;
1412 
1413   using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>;
1414 
1415   OverridesTy Overrides;
1416   getOverriddenMethods(Overrides);
1417   for (const auto *Override : Overrides)
1418     if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false))
1419       return Prop;
1420 
1421   return nullptr;
1422 }
1423 
1424 //===----------------------------------------------------------------------===//
1425 // ObjCTypeParamDecl
1426 //===----------------------------------------------------------------------===//
1427 
anchor()1428 void ObjCTypeParamDecl::anchor() {}
1429 
Create(ASTContext & ctx,DeclContext * dc,ObjCTypeParamVariance variance,SourceLocation varianceLoc,unsigned index,SourceLocation nameLoc,IdentifierInfo * name,SourceLocation colonLoc,TypeSourceInfo * boundInfo)1430 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc,
1431                                              ObjCTypeParamVariance variance,
1432                                              SourceLocation varianceLoc,
1433                                              unsigned index,
1434                                              SourceLocation nameLoc,
1435                                              IdentifierInfo *name,
1436                                              SourceLocation colonLoc,
1437                                              TypeSourceInfo *boundInfo) {
1438   auto *TPDecl =
1439     new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index,
1440                                     nameLoc, name, colonLoc, boundInfo);
1441   QualType TPType = ctx.getObjCTypeParamType(TPDecl, {});
1442   TPDecl->setTypeForDecl(TPType.getTypePtr());
1443   return TPDecl;
1444 }
1445 
CreateDeserialized(ASTContext & ctx,unsigned ID)1446 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx,
1447                                                          unsigned ID) {
1448   return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr,
1449                                          ObjCTypeParamVariance::Invariant,
1450                                          SourceLocation(), 0, SourceLocation(),
1451                                          nullptr, SourceLocation(), nullptr);
1452 }
1453 
getSourceRange() const1454 SourceRange ObjCTypeParamDecl::getSourceRange() const {
1455   SourceLocation startLoc = VarianceLoc;
1456   if (startLoc.isInvalid())
1457     startLoc = getLocation();
1458 
1459   if (hasExplicitBound()) {
1460     return SourceRange(startLoc,
1461                        getTypeSourceInfo()->getTypeLoc().getEndLoc());
1462   }
1463 
1464   return SourceRange(startLoc);
1465 }
1466 
1467 //===----------------------------------------------------------------------===//
1468 // ObjCTypeParamList
1469 //===----------------------------------------------------------------------===//
ObjCTypeParamList(SourceLocation lAngleLoc,ArrayRef<ObjCTypeParamDecl * > typeParams,SourceLocation rAngleLoc)1470 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc,
1471                                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1472                                      SourceLocation rAngleLoc)
1473     : Brackets(lAngleLoc, rAngleLoc), NumParams(typeParams.size()) {
1474   std::copy(typeParams.begin(), typeParams.end(), begin());
1475 }
1476 
create(ASTContext & ctx,SourceLocation lAngleLoc,ArrayRef<ObjCTypeParamDecl * > typeParams,SourceLocation rAngleLoc)1477 ObjCTypeParamList *ObjCTypeParamList::create(
1478                      ASTContext &ctx,
1479                      SourceLocation lAngleLoc,
1480                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1481                      SourceLocation rAngleLoc) {
1482   void *mem =
1483       ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()),
1484                    alignof(ObjCTypeParamList));
1485   return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc);
1486 }
1487 
gatherDefaultTypeArgs(SmallVectorImpl<QualType> & typeArgs) const1488 void ObjCTypeParamList::gatherDefaultTypeArgs(
1489        SmallVectorImpl<QualType> &typeArgs) const {
1490   typeArgs.reserve(size());
1491   for (auto typeParam : *this)
1492     typeArgs.push_back(typeParam->getUnderlyingType());
1493 }
1494 
1495 //===----------------------------------------------------------------------===//
1496 // ObjCInterfaceDecl
1497 //===----------------------------------------------------------------------===//
1498 
Create(const ASTContext & C,DeclContext * DC,SourceLocation atLoc,IdentifierInfo * Id,ObjCTypeParamList * typeParamList,ObjCInterfaceDecl * PrevDecl,SourceLocation ClassLoc,bool isInternal)1499 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1500                                              DeclContext *DC,
1501                                              SourceLocation atLoc,
1502                                              IdentifierInfo *Id,
1503                                              ObjCTypeParamList *typeParamList,
1504                                              ObjCInterfaceDecl *PrevDecl,
1505                                              SourceLocation ClassLoc,
1506                                              bool isInternal){
1507   auto *Result = new (C, DC)
1508       ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl,
1509                         isInternal);
1510   Result->Data.setInt(!C.getLangOpts().Modules);
1511   C.getObjCInterfaceType(Result, PrevDecl);
1512   return Result;
1513 }
1514 
CreateDeserialized(const ASTContext & C,unsigned ID)1515 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1516                                                          unsigned ID) {
1517   auto *Result = new (C, ID)
1518       ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr,
1519                         SourceLocation(), nullptr, false);
1520   Result->Data.setInt(!C.getLangOpts().Modules);
1521   return Result;
1522 }
1523 
ObjCInterfaceDecl(const ASTContext & C,DeclContext * DC,SourceLocation AtLoc,IdentifierInfo * Id,ObjCTypeParamList * typeParamList,SourceLocation CLoc,ObjCInterfaceDecl * PrevDecl,bool IsInternal)1524 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1525                                      SourceLocation AtLoc, IdentifierInfo *Id,
1526                                      ObjCTypeParamList *typeParamList,
1527                                      SourceLocation CLoc,
1528                                      ObjCInterfaceDecl *PrevDecl,
1529                                      bool IsInternal)
1530     : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1531       redeclarable_base(C) {
1532   setPreviousDecl(PrevDecl);
1533 
1534   // Copy the 'data' pointer over.
1535   if (PrevDecl)
1536     Data = PrevDecl->Data;
1537 
1538   setImplicit(IsInternal);
1539 
1540   setTypeParamList(typeParamList);
1541 }
1542 
LoadExternalDefinition() const1543 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1544   assert(data().ExternallyCompleted && "Class is not externally completed");
1545   data().ExternallyCompleted = false;
1546   getASTContext().getExternalSource()->CompleteType(
1547                                         const_cast<ObjCInterfaceDecl *>(this));
1548 }
1549 
setExternallyCompleted()1550 void ObjCInterfaceDecl::setExternallyCompleted() {
1551   assert(getASTContext().getExternalSource() &&
1552          "Class can't be externally completed without an external source");
1553   assert(hasDefinition() &&
1554          "Forward declarations can't be externally completed");
1555   data().ExternallyCompleted = true;
1556 }
1557 
setHasDesignatedInitializers()1558 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1559   // Check for a complete definition and recover if not so.
1560   if (!isThisDeclarationADefinition())
1561     return;
1562   data().HasDesignatedInitializers = true;
1563 }
1564 
hasDesignatedInitializers() const1565 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1566   // Check for a complete definition and recover if not so.
1567   if (!isThisDeclarationADefinition())
1568     return false;
1569   if (data().ExternallyCompleted)
1570     LoadExternalDefinition();
1571 
1572   return data().HasDesignatedInitializers;
1573 }
1574 
1575 StringRef
getObjCRuntimeNameAsString() const1576 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1577   if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1578     return ObjCRTName->getMetadataName();
1579 
1580   return getName();
1581 }
1582 
1583 StringRef
getObjCRuntimeNameAsString() const1584 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1585   if (ObjCInterfaceDecl *ID =
1586       const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1587     return ID->getObjCRuntimeNameAsString();
1588 
1589   return getName();
1590 }
1591 
getImplementation() const1592 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1593   if (const ObjCInterfaceDecl *Def = getDefinition()) {
1594     if (data().ExternallyCompleted)
1595       LoadExternalDefinition();
1596 
1597     return getASTContext().getObjCImplementation(
1598              const_cast<ObjCInterfaceDecl*>(Def));
1599   }
1600 
1601   // FIXME: Should make sure no callers ever do this.
1602   return nullptr;
1603 }
1604 
setImplementation(ObjCImplementationDecl * ImplD)1605 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1606   getASTContext().setObjCImplementation(getDefinition(), ImplD);
1607 }
1608 
1609 namespace {
1610 
1611 struct SynthesizeIvarChunk {
1612   uint64_t Size;
1613   ObjCIvarDecl *Ivar;
1614 
SynthesizeIvarChunk__anon54581e400211::SynthesizeIvarChunk1615   SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1616       : Size(size), Ivar(ivar) {}
1617 };
1618 
operator <(const SynthesizeIvarChunk & LHS,const SynthesizeIvarChunk & RHS)1619 bool operator<(const SynthesizeIvarChunk & LHS,
1620                const SynthesizeIvarChunk &RHS) {
1621     return LHS.Size < RHS.Size;
1622 }
1623 
1624 } // namespace
1625 
1626 /// all_declared_ivar_begin - return first ivar declared in this class,
1627 /// its extensions and its implementation. Lazily build the list on first
1628 /// access.
1629 ///
1630 /// Caveat: The list returned by this method reflects the current
1631 /// state of the parser. The cache will be updated for every ivar
1632 /// added by an extension or the implementation when they are
1633 /// encountered.
1634 /// See also ObjCIvarDecl::Create().
all_declared_ivar_begin()1635 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1636   // FIXME: Should make sure no callers ever do this.
1637   if (!hasDefinition())
1638     return nullptr;
1639 
1640   ObjCIvarDecl *curIvar = nullptr;
1641   if (!data().IvarList) {
1642     if (!ivar_empty()) {
1643       ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1644       data().IvarList = *I; ++I;
1645       for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1646         curIvar->setNextIvar(*I);
1647     }
1648 
1649     for (const auto *Ext : known_extensions()) {
1650       if (!Ext->ivar_empty()) {
1651         ObjCCategoryDecl::ivar_iterator
1652           I = Ext->ivar_begin(),
1653           E = Ext->ivar_end();
1654         if (!data().IvarList) {
1655           data().IvarList = *I; ++I;
1656           curIvar = data().IvarList;
1657         }
1658         for ( ;I != E; curIvar = *I, ++I)
1659           curIvar->setNextIvar(*I);
1660       }
1661     }
1662     data().IvarListMissingImplementation = true;
1663   }
1664 
1665   // cached and complete!
1666   if (!data().IvarListMissingImplementation)
1667       return data().IvarList;
1668 
1669   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1670     data().IvarListMissingImplementation = false;
1671     if (!ImplDecl->ivar_empty()) {
1672       SmallVector<SynthesizeIvarChunk, 16> layout;
1673       for (auto *IV : ImplDecl->ivars()) {
1674         if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1675           layout.push_back(SynthesizeIvarChunk(
1676                              IV->getASTContext().getTypeSize(IV->getType()), IV));
1677           continue;
1678         }
1679         if (!data().IvarList)
1680           data().IvarList = IV;
1681         else
1682           curIvar->setNextIvar(IV);
1683         curIvar = IV;
1684       }
1685 
1686       if (!layout.empty()) {
1687         // Order synthesized ivars by their size.
1688         llvm::stable_sort(layout);
1689         unsigned Ix = 0, EIx = layout.size();
1690         if (!data().IvarList) {
1691           data().IvarList = layout[0].Ivar; Ix++;
1692           curIvar = data().IvarList;
1693         }
1694         for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1695           curIvar->setNextIvar(layout[Ix].Ivar);
1696       }
1697     }
1698   }
1699   return data().IvarList;
1700 }
1701 
1702 /// FindCategoryDeclaration - Finds category declaration in the list of
1703 /// categories for this class and returns it. Name of the category is passed
1704 /// in 'CategoryId'. If category not found, return 0;
1705 ///
1706 ObjCCategoryDecl *
FindCategoryDeclaration(IdentifierInfo * CategoryId) const1707 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1708   // FIXME: Should make sure no callers ever do this.
1709   if (!hasDefinition())
1710     return nullptr;
1711 
1712   if (data().ExternallyCompleted)
1713     LoadExternalDefinition();
1714 
1715   for (auto *Cat : visible_categories())
1716     if (Cat->getIdentifier() == CategoryId)
1717       return Cat;
1718 
1719   return nullptr;
1720 }
1721 
1722 ObjCMethodDecl *
getCategoryInstanceMethod(Selector Sel) const1723 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1724   for (const auto *Cat : visible_categories()) {
1725     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1726       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1727         return MD;
1728   }
1729 
1730   return nullptr;
1731 }
1732 
getCategoryClassMethod(Selector Sel) const1733 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1734   for (const auto *Cat : visible_categories()) {
1735     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1736       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1737         return MD;
1738   }
1739 
1740   return nullptr;
1741 }
1742 
1743 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1744 /// has been implemented in IDecl class, its super class or categories (if
1745 /// lookupCategory is true).
ClassImplementsProtocol(ObjCProtocolDecl * lProto,bool lookupCategory,bool RHSIsQualifiedID)1746 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1747                                     bool lookupCategory,
1748                                     bool RHSIsQualifiedID) {
1749   if (!hasDefinition())
1750     return false;
1751 
1752   ObjCInterfaceDecl *IDecl = this;
1753   // 1st, look up the class.
1754   for (auto *PI : IDecl->protocols()){
1755     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1756       return true;
1757     // This is dubious and is added to be compatible with gcc.  In gcc, it is
1758     // also allowed assigning a protocol-qualified 'id' type to a LHS object
1759     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1760     // object. This IMO, should be a bug.
1761     // FIXME: Treat this as an extension, and flag this as an error when GCC
1762     // extensions are not enabled.
1763     if (RHSIsQualifiedID &&
1764         getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1765       return true;
1766   }
1767 
1768   // 2nd, look up the category.
1769   if (lookupCategory)
1770     for (const auto *Cat : visible_categories()) {
1771       for (auto *PI : Cat->protocols())
1772         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1773           return true;
1774     }
1775 
1776   // 3rd, look up the super class(s)
1777   if (IDecl->getSuperClass())
1778     return
1779   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1780                                                   RHSIsQualifiedID);
1781 
1782   return false;
1783 }
1784 
1785 //===----------------------------------------------------------------------===//
1786 // ObjCIvarDecl
1787 //===----------------------------------------------------------------------===//
1788 
anchor()1789 void ObjCIvarDecl::anchor() {}
1790 
Create(ASTContext & C,ObjCContainerDecl * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,AccessControl ac,Expr * BW,bool synthesized)1791 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1792                                    SourceLocation StartLoc,
1793                                    SourceLocation IdLoc, IdentifierInfo *Id,
1794                                    QualType T, TypeSourceInfo *TInfo,
1795                                    AccessControl ac, Expr *BW,
1796                                    bool synthesized) {
1797   if (DC) {
1798     // Ivar's can only appear in interfaces, implementations (via synthesized
1799     // properties), and class extensions (via direct declaration, or synthesized
1800     // properties).
1801     //
1802     // FIXME: This should really be asserting this:
1803     //   (isa<ObjCCategoryDecl>(DC) &&
1804     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1805     // but unfortunately we sometimes place ivars into non-class extension
1806     // categories on error. This breaks an AST invariant, and should not be
1807     // fixed.
1808     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
1809             isa<ObjCCategoryDecl>(DC)) &&
1810            "Invalid ivar decl context!");
1811     // Once a new ivar is created in any of class/class-extension/implementation
1812     // decl contexts, the previously built IvarList must be rebuilt.
1813     auto *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1814     if (!ID) {
1815       if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC))
1816         ID = IM->getClassInterface();
1817       else
1818         ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1819     }
1820     ID->setIvarList(nullptr);
1821   }
1822 
1823   return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1824                                   synthesized);
1825 }
1826 
CreateDeserialized(ASTContext & C,unsigned ID)1827 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1828   return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1829                                   nullptr, QualType(), nullptr,
1830                                   ObjCIvarDecl::None, nullptr, false);
1831 }
1832 
getContainingInterface() const1833 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1834   const auto *DC = cast<ObjCContainerDecl>(getDeclContext());
1835 
1836   switch (DC->getKind()) {
1837   default:
1838   case ObjCCategoryImpl:
1839   case ObjCProtocol:
1840     llvm_unreachable("invalid ivar container!");
1841 
1842     // Ivars can only appear in class extension categories.
1843   case ObjCCategory: {
1844     const auto *CD = cast<ObjCCategoryDecl>(DC);
1845     assert(CD->IsClassExtension() && "invalid container for ivar!");
1846     return CD->getClassInterface();
1847   }
1848 
1849   case ObjCImplementation:
1850     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1851 
1852   case ObjCInterface:
1853     return cast<ObjCInterfaceDecl>(DC);
1854   }
1855 }
1856 
getUsageType(QualType objectType) const1857 QualType ObjCIvarDecl::getUsageType(QualType objectType) const {
1858   return getType().substObjCMemberType(objectType, getDeclContext(),
1859                                        ObjCSubstitutionContext::Property);
1860 }
1861 
1862 //===----------------------------------------------------------------------===//
1863 // ObjCAtDefsFieldDecl
1864 //===----------------------------------------------------------------------===//
1865 
anchor()1866 void ObjCAtDefsFieldDecl::anchor() {}
1867 
1868 ObjCAtDefsFieldDecl
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,Expr * BW)1869 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1870                              SourceLocation StartLoc,  SourceLocation IdLoc,
1871                              IdentifierInfo *Id, QualType T, Expr *BW) {
1872   return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1873 }
1874 
CreateDeserialized(ASTContext & C,unsigned ID)1875 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1876                                                              unsigned ID) {
1877   return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1878                                          SourceLocation(), nullptr, QualType(),
1879                                          nullptr);
1880 }
1881 
1882 //===----------------------------------------------------------------------===//
1883 // ObjCProtocolDecl
1884 //===----------------------------------------------------------------------===//
1885 
anchor()1886 void ObjCProtocolDecl::anchor() {}
1887 
ObjCProtocolDecl(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc,ObjCProtocolDecl * PrevDecl)1888 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1889                                    IdentifierInfo *Id, SourceLocation nameLoc,
1890                                    SourceLocation atStartLoc,
1891                                    ObjCProtocolDecl *PrevDecl)
1892     : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1893       redeclarable_base(C) {
1894   setPreviousDecl(PrevDecl);
1895   if (PrevDecl)
1896     Data = PrevDecl->Data;
1897 }
1898 
Create(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc,ObjCProtocolDecl * PrevDecl)1899 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1900                                            IdentifierInfo *Id,
1901                                            SourceLocation nameLoc,
1902                                            SourceLocation atStartLoc,
1903                                            ObjCProtocolDecl *PrevDecl) {
1904   auto *Result =
1905       new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1906   Result->Data.setInt(!C.getLangOpts().Modules);
1907   return Result;
1908 }
1909 
CreateDeserialized(ASTContext & C,unsigned ID)1910 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1911                                                        unsigned ID) {
1912   ObjCProtocolDecl *Result =
1913       new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1914                                    SourceLocation(), nullptr);
1915   Result->Data.setInt(!C.getLangOpts().Modules);
1916   return Result;
1917 }
1918 
isNonRuntimeProtocol() const1919 bool ObjCProtocolDecl::isNonRuntimeProtocol() const {
1920   return hasAttr<ObjCNonRuntimeProtocolAttr>();
1921 }
1922 
getImpliedProtocols(llvm::DenseSet<const ObjCProtocolDecl * > & IPs) const1923 void ObjCProtocolDecl::getImpliedProtocols(
1924     llvm::DenseSet<const ObjCProtocolDecl *> &IPs) const {
1925   std::queue<const ObjCProtocolDecl *> WorkQueue;
1926   WorkQueue.push(this);
1927 
1928   while (!WorkQueue.empty()) {
1929     const auto *PD = WorkQueue.front();
1930     WorkQueue.pop();
1931     for (const auto *Parent : PD->protocols()) {
1932       const auto *Can = Parent->getCanonicalDecl();
1933       auto Result = IPs.insert(Can);
1934       if (Result.second)
1935         WorkQueue.push(Parent);
1936     }
1937   }
1938 }
1939 
lookupProtocolNamed(IdentifierInfo * Name)1940 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1941   ObjCProtocolDecl *PDecl = this;
1942 
1943   if (Name == getIdentifier())
1944     return PDecl;
1945 
1946   for (auto *I : protocols())
1947     if ((PDecl = I->lookupProtocolNamed(Name)))
1948       return PDecl;
1949 
1950   return nullptr;
1951 }
1952 
1953 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1954 // it inherited.
lookupMethod(Selector Sel,bool isInstance) const1955 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1956                                                bool isInstance) const {
1957   ObjCMethodDecl *MethodDecl = nullptr;
1958 
1959   // If there is no definition or the definition is hidden, we don't find
1960   // anything.
1961   const ObjCProtocolDecl *Def = getDefinition();
1962   if (!Def || !Def->isUnconditionallyVisible())
1963     return nullptr;
1964 
1965   if ((MethodDecl = getMethod(Sel, isInstance)))
1966     return MethodDecl;
1967 
1968   for (const auto *I : protocols())
1969     if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1970       return MethodDecl;
1971   return nullptr;
1972 }
1973 
allocateDefinitionData()1974 void ObjCProtocolDecl::allocateDefinitionData() {
1975   assert(!Data.getPointer() && "Protocol already has a definition!");
1976   Data.setPointer(new (getASTContext()) DefinitionData);
1977   Data.getPointer()->Definition = this;
1978 }
1979 
startDefinition()1980 void ObjCProtocolDecl::startDefinition() {
1981   allocateDefinitionData();
1982 
1983   // Update all of the declarations with a pointer to the definition.
1984   for (auto *RD : redecls())
1985     RD->Data = this->Data;
1986 }
1987 
collectPropertiesToImplement(PropertyMap & PM,PropertyDeclOrder & PO) const1988 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1989                                                     PropertyDeclOrder &PO) const {
1990   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1991     for (auto *Prop : PDecl->properties()) {
1992       // Insert into PM if not there already.
1993       PM.insert(std::make_pair(
1994           std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()),
1995           Prop));
1996       PO.push_back(Prop);
1997     }
1998     // Scan through protocol's protocols.
1999     for (const auto *PI : PDecl->protocols())
2000       PI->collectPropertiesToImplement(PM, PO);
2001   }
2002 }
2003 
collectInheritedProtocolProperties(const ObjCPropertyDecl * Property,ProtocolPropertySet & PS,PropertyDeclOrder & PO) const2004 void ObjCProtocolDecl::collectInheritedProtocolProperties(
2005     const ObjCPropertyDecl *Property, ProtocolPropertySet &PS,
2006     PropertyDeclOrder &PO) const {
2007   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
2008     if (!PS.insert(PDecl).second)
2009       return;
2010     for (auto *Prop : PDecl->properties()) {
2011       if (Prop == Property)
2012         continue;
2013       if (Prop->getIdentifier() == Property->getIdentifier()) {
2014         PO.push_back(Prop);
2015         return;
2016       }
2017     }
2018     // Scan through protocol's protocols which did not have a matching property.
2019     for (const auto *PI : PDecl->protocols())
2020       PI->collectInheritedProtocolProperties(Property, PS, PO);
2021   }
2022 }
2023 
2024 StringRef
getObjCRuntimeNameAsString() const2025 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
2026   if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
2027     return ObjCRTName->getMetadataName();
2028 
2029   return getName();
2030 }
2031 
2032 //===----------------------------------------------------------------------===//
2033 // ObjCCategoryDecl
2034 //===----------------------------------------------------------------------===//
2035 
anchor()2036 void ObjCCategoryDecl::anchor() {}
2037 
ObjCCategoryDecl(DeclContext * DC,SourceLocation AtLoc,SourceLocation ClassNameLoc,SourceLocation CategoryNameLoc,IdentifierInfo * Id,ObjCInterfaceDecl * IDecl,ObjCTypeParamList * typeParamList,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2038 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2039                                    SourceLocation ClassNameLoc,
2040                                    SourceLocation CategoryNameLoc,
2041                                    IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2042                                    ObjCTypeParamList *typeParamList,
2043                                    SourceLocation IvarLBraceLoc,
2044                                    SourceLocation IvarRBraceLoc)
2045     : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
2046       ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc),
2047       IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
2048   setTypeParamList(typeParamList);
2049 }
2050 
Create(ASTContext & C,DeclContext * DC,SourceLocation AtLoc,SourceLocation ClassNameLoc,SourceLocation CategoryNameLoc,IdentifierInfo * Id,ObjCInterfaceDecl * IDecl,ObjCTypeParamList * typeParamList,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2051 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
2052                                            SourceLocation AtLoc,
2053                                            SourceLocation ClassNameLoc,
2054                                            SourceLocation CategoryNameLoc,
2055                                            IdentifierInfo *Id,
2056                                            ObjCInterfaceDecl *IDecl,
2057                                            ObjCTypeParamList *typeParamList,
2058                                            SourceLocation IvarLBraceLoc,
2059                                            SourceLocation IvarRBraceLoc) {
2060   auto *CatDecl =
2061       new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
2062                                    IDecl, typeParamList, IvarLBraceLoc,
2063                                    IvarRBraceLoc);
2064   if (IDecl) {
2065     // Link this category into its class's category list.
2066     CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
2067     if (IDecl->hasDefinition()) {
2068       IDecl->setCategoryListRaw(CatDecl);
2069       if (ASTMutationListener *L = C.getASTMutationListener())
2070         L->AddedObjCCategoryToInterface(CatDecl, IDecl);
2071     }
2072   }
2073 
2074   return CatDecl;
2075 }
2076 
CreateDeserialized(ASTContext & C,unsigned ID)2077 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
2078                                                        unsigned ID) {
2079   return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
2080                                       SourceLocation(), SourceLocation(),
2081                                       nullptr, nullptr, nullptr);
2082 }
2083 
getImplementation() const2084 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
2085   return getASTContext().getObjCImplementation(
2086                                            const_cast<ObjCCategoryDecl*>(this));
2087 }
2088 
setImplementation(ObjCCategoryImplDecl * ImplD)2089 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
2090   getASTContext().setObjCImplementation(this, ImplD);
2091 }
2092 
setTypeParamList(ObjCTypeParamList * TPL)2093 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) {
2094   TypeParamList = TPL;
2095   if (!TPL)
2096     return;
2097   // Set the declaration context of each of the type parameters.
2098   for (auto *typeParam : *TypeParamList)
2099     typeParam->setDeclContext(this);
2100 }
2101 
2102 //===----------------------------------------------------------------------===//
2103 // ObjCCategoryImplDecl
2104 //===----------------------------------------------------------------------===//
2105 
anchor()2106 void ObjCCategoryImplDecl::anchor() {}
2107 
2108 ObjCCategoryImplDecl *
Create(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,ObjCInterfaceDecl * ClassInterface,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation CategoryNameLoc)2109 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
2110                              IdentifierInfo *Id,
2111                              ObjCInterfaceDecl *ClassInterface,
2112                              SourceLocation nameLoc,
2113                              SourceLocation atStartLoc,
2114                              SourceLocation CategoryNameLoc) {
2115   if (ClassInterface && ClassInterface->hasDefinition())
2116     ClassInterface = ClassInterface->getDefinition();
2117   return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
2118                                           atStartLoc, CategoryNameLoc);
2119 }
2120 
CreateDeserialized(ASTContext & C,unsigned ID)2121 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
2122                                                                unsigned ID) {
2123   return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2124                                           SourceLocation(), SourceLocation(),
2125                                           SourceLocation());
2126 }
2127 
getCategoryDecl() const2128 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
2129   // The class interface might be NULL if we are working with invalid code.
2130   if (const ObjCInterfaceDecl *ID = getClassInterface())
2131     return ID->FindCategoryDeclaration(getIdentifier());
2132   return nullptr;
2133 }
2134 
anchor()2135 void ObjCImplDecl::anchor() {}
2136 
addPropertyImplementation(ObjCPropertyImplDecl * property)2137 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
2138   // FIXME: The context should be correct before we get here.
2139   property->setLexicalDeclContext(this);
2140   addDecl(property);
2141 }
2142 
setClassInterface(ObjCInterfaceDecl * IFace)2143 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
2144   ASTContext &Ctx = getASTContext();
2145 
2146   if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
2147     if (IFace)
2148       Ctx.setObjCImplementation(IFace, ImplD);
2149 
2150   } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
2151     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
2152       Ctx.setObjCImplementation(CD, ImplD);
2153   }
2154 
2155   ClassInterface = IFace;
2156 }
2157 
2158 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2159 /// properties implemented in this \@implementation block and returns
2160 /// the implemented property that uses it.
2161 ObjCPropertyImplDecl *ObjCImplDecl::
FindPropertyImplIvarDecl(IdentifierInfo * ivarId) const2162 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
2163   for (auto *PID : property_impls())
2164     if (PID->getPropertyIvarDecl() &&
2165         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
2166       return PID;
2167   return nullptr;
2168 }
2169 
2170 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2171 /// added to the list of those properties \@synthesized/\@dynamic in this
2172 /// category \@implementation block.
2173 ObjCPropertyImplDecl *ObjCImplDecl::
FindPropertyImplDecl(IdentifierInfo * Id,ObjCPropertyQueryKind QueryKind) const2174 FindPropertyImplDecl(IdentifierInfo *Id,
2175                      ObjCPropertyQueryKind QueryKind) const {
2176   ObjCPropertyImplDecl *ClassPropImpl = nullptr;
2177   for (auto *PID : property_impls())
2178     // If queryKind is unknown, we return the instance property if one
2179     // exists; otherwise we return the class property.
2180     if (PID->getPropertyDecl()->getIdentifier() == Id) {
2181       if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
2182            !PID->getPropertyDecl()->isClassProperty()) ||
2183           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
2184            PID->getPropertyDecl()->isClassProperty()) ||
2185           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
2186            !PID->getPropertyDecl()->isClassProperty()))
2187         return PID;
2188 
2189       if (PID->getPropertyDecl()->isClassProperty())
2190         ClassPropImpl = PID;
2191     }
2192 
2193   if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
2194     // We can't find the instance property, return the class property.
2195     return ClassPropImpl;
2196 
2197   return nullptr;
2198 }
2199 
operator <<(raw_ostream & OS,const ObjCCategoryImplDecl & CID)2200 raw_ostream &clang::operator<<(raw_ostream &OS,
2201                                const ObjCCategoryImplDecl &CID) {
2202   OS << CID.getName();
2203   return OS;
2204 }
2205 
2206 //===----------------------------------------------------------------------===//
2207 // ObjCImplementationDecl
2208 //===----------------------------------------------------------------------===//
2209 
anchor()2210 void ObjCImplementationDecl::anchor() {}
2211 
2212 ObjCImplementationDecl *
Create(ASTContext & C,DeclContext * DC,ObjCInterfaceDecl * ClassInterface,ObjCInterfaceDecl * SuperDecl,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation superLoc,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2213 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
2214                                ObjCInterfaceDecl *ClassInterface,
2215                                ObjCInterfaceDecl *SuperDecl,
2216                                SourceLocation nameLoc,
2217                                SourceLocation atStartLoc,
2218                                SourceLocation superLoc,
2219                                SourceLocation IvarLBraceLoc,
2220                                SourceLocation IvarRBraceLoc) {
2221   if (ClassInterface && ClassInterface->hasDefinition())
2222     ClassInterface = ClassInterface->getDefinition();
2223   return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
2224                                             nameLoc, atStartLoc, superLoc,
2225                                             IvarLBraceLoc, IvarRBraceLoc);
2226 }
2227 
2228 ObjCImplementationDecl *
CreateDeserialized(ASTContext & C,unsigned ID)2229 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2230   return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2231                                             SourceLocation(), SourceLocation());
2232 }
2233 
setIvarInitializers(ASTContext & C,CXXCtorInitializer ** initializers,unsigned numInitializers)2234 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2235                                              CXXCtorInitializer ** initializers,
2236                                                  unsigned numInitializers) {
2237   if (numInitializers > 0) {
2238     NumIvarInitializers = numInitializers;
2239     auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers];
2240     memcpy(ivarInitializers, initializers,
2241            numInitializers * sizeof(CXXCtorInitializer*));
2242     IvarInitializers = ivarInitializers;
2243   }
2244 }
2245 
2246 ObjCImplementationDecl::init_const_iterator
init_begin() const2247 ObjCImplementationDecl::init_begin() const {
2248   return IvarInitializers.get(getASTContext().getExternalSource());
2249 }
2250 
operator <<(raw_ostream & OS,const ObjCImplementationDecl & ID)2251 raw_ostream &clang::operator<<(raw_ostream &OS,
2252                                const ObjCImplementationDecl &ID) {
2253   OS << ID.getName();
2254   return OS;
2255 }
2256 
2257 //===----------------------------------------------------------------------===//
2258 // ObjCCompatibleAliasDecl
2259 //===----------------------------------------------------------------------===//
2260 
anchor()2261 void ObjCCompatibleAliasDecl::anchor() {}
2262 
2263 ObjCCompatibleAliasDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,ObjCInterfaceDecl * AliasedClass)2264 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
2265                                 SourceLocation L,
2266                                 IdentifierInfo *Id,
2267                                 ObjCInterfaceDecl* AliasedClass) {
2268   return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
2269 }
2270 
2271 ObjCCompatibleAliasDecl *
CreateDeserialized(ASTContext & C,unsigned ID)2272 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2273   return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2274                                              nullptr, nullptr);
2275 }
2276 
2277 //===----------------------------------------------------------------------===//
2278 // ObjCPropertyDecl
2279 //===----------------------------------------------------------------------===//
2280 
anchor()2281 void ObjCPropertyDecl::anchor() {}
2282 
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,SourceLocation AtLoc,SourceLocation LParenLoc,QualType T,TypeSourceInfo * TSI,PropertyControl propControl)2283 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
2284                                            SourceLocation L,
2285                                            IdentifierInfo *Id,
2286                                            SourceLocation AtLoc,
2287                                            SourceLocation LParenLoc,
2288                                            QualType T,
2289                                            TypeSourceInfo *TSI,
2290                                            PropertyControl propControl) {
2291   return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
2292                                       propControl);
2293 }
2294 
CreateDeserialized(ASTContext & C,unsigned ID)2295 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
2296                                                        unsigned ID) {
2297   return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2298                                       SourceLocation(), SourceLocation(),
2299                                       QualType(), nullptr, None);
2300 }
2301 
getUsageType(QualType objectType) const2302 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const {
2303   return DeclType.substObjCMemberType(objectType, getDeclContext(),
2304                                       ObjCSubstitutionContext::Property);
2305 }
2306 
isDirectProperty() const2307 bool ObjCPropertyDecl::isDirectProperty() const {
2308   return (PropertyAttributes & ObjCPropertyAttribute::kind_direct) &&
2309          !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting;
2310 }
2311 
2312 //===----------------------------------------------------------------------===//
2313 // ObjCPropertyImplDecl
2314 //===----------------------------------------------------------------------===//
2315 
Create(ASTContext & C,DeclContext * DC,SourceLocation atLoc,SourceLocation L,ObjCPropertyDecl * property,Kind PK,ObjCIvarDecl * ivar,SourceLocation ivarLoc)2316 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
2317                                                    DeclContext *DC,
2318                                                    SourceLocation atLoc,
2319                                                    SourceLocation L,
2320                                                    ObjCPropertyDecl *property,
2321                                                    Kind PK,
2322                                                    ObjCIvarDecl *ivar,
2323                                                    SourceLocation ivarLoc) {
2324   return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
2325                                           ivarLoc);
2326 }
2327 
CreateDeserialized(ASTContext & C,unsigned ID)2328 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
2329                                                                unsigned ID) {
2330   return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2331                                           SourceLocation(), nullptr, Dynamic,
2332                                           nullptr, SourceLocation());
2333 }
2334 
getSourceRange() const2335 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
2336   SourceLocation EndLoc = getLocation();
2337   if (IvarLoc.isValid())
2338     EndLoc = IvarLoc;
2339 
2340   return SourceRange(AtLoc, EndLoc);
2341 }
2342