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
getBody() const858 Stmt *ObjCMethodDecl::getBody() const {
859 return Body.get(getASTContext().getExternalSource());
860 }
861
setAsRedeclaration(const ObjCMethodDecl * PrevMethod)862 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
863 assert(PrevMethod);
864 getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
865 setIsRedeclaration(true);
866 PrevMethod->setHasRedeclaration(true);
867 }
868
setParamsAndSelLocs(ASTContext & C,ArrayRef<ParmVarDecl * > Params,ArrayRef<SourceLocation> SelLocs)869 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
870 ArrayRef<ParmVarDecl*> Params,
871 ArrayRef<SourceLocation> SelLocs) {
872 ParamsAndSelLocs = nullptr;
873 NumParams = Params.size();
874 if (Params.empty() && SelLocs.empty())
875 return;
876
877 static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation),
878 "Alignment not sufficient for SourceLocation");
879
880 unsigned Size = sizeof(ParmVarDecl *) * NumParams +
881 sizeof(SourceLocation) * SelLocs.size();
882 ParamsAndSelLocs = C.Allocate(Size);
883 std::copy(Params.begin(), Params.end(), getParams());
884 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
885 }
886
getSelectorLocs(SmallVectorImpl<SourceLocation> & SelLocs) const887 void ObjCMethodDecl::getSelectorLocs(
888 SmallVectorImpl<SourceLocation> &SelLocs) const {
889 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
890 SelLocs.push_back(getSelectorLoc(i));
891 }
892
setMethodParams(ASTContext & C,ArrayRef<ParmVarDecl * > Params,ArrayRef<SourceLocation> SelLocs)893 void ObjCMethodDecl::setMethodParams(ASTContext &C,
894 ArrayRef<ParmVarDecl*> Params,
895 ArrayRef<SourceLocation> SelLocs) {
896 assert((!SelLocs.empty() || isImplicit()) &&
897 "No selector locs for non-implicit method");
898 if (isImplicit())
899 return setParamsAndSelLocs(C, Params, llvm::None);
900
901 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params,
902 DeclEndLoc));
903 if (getSelLocsKind() != SelLoc_NonStandard)
904 return setParamsAndSelLocs(C, Params, llvm::None);
905
906 setParamsAndSelLocs(C, Params, SelLocs);
907 }
908
909 /// A definition will return its interface declaration.
910 /// An interface declaration will return its definition.
911 /// Otherwise it will return itself.
getNextRedeclarationImpl()912 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() {
913 ASTContext &Ctx = getASTContext();
914 ObjCMethodDecl *Redecl = nullptr;
915 if (hasRedeclaration())
916 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
917 if (Redecl)
918 return Redecl;
919
920 auto *CtxD = cast<Decl>(getDeclContext());
921
922 if (!CtxD->isInvalidDecl()) {
923 if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
924 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
925 if (!ImplD->isInvalidDecl())
926 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
927
928 } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
929 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
930 if (!ImplD->isInvalidDecl())
931 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
932
933 } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
934 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
935 if (!IFD->isInvalidDecl())
936 Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
937
938 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
939 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
940 if (!CatD->isInvalidDecl())
941 Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
942 }
943 }
944
945 // Ensure that the discovered method redeclaration has a valid declaration
946 // context. Used to prevent infinite loops when iterating redeclarations in
947 // a partially invalid AST.
948 if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl())
949 Redecl = nullptr;
950
951 if (!Redecl && isRedeclaration()) {
952 // This is the last redeclaration, go back to the first method.
953 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
954 isInstanceMethod(),
955 /*AllowHidden=*/true);
956 }
957
958 return Redecl ? Redecl : this;
959 }
960
getCanonicalDecl()961 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
962 auto *CtxD = cast<Decl>(getDeclContext());
963 const auto &Sel = getSelector();
964
965 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
966 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) {
967 // When the container is the ObjCImplementationDecl (the primary
968 // @implementation), then the canonical Decl is either in
969 // the class Interface, or in any of its extension.
970 //
971 // So when we don't find it in the ObjCInterfaceDecl,
972 // sift through extensions too.
973 if (ObjCMethodDecl *MD = IFD->getMethod(Sel, isInstanceMethod()))
974 return MD;
975 for (auto *Ext : IFD->known_extensions())
976 if (ObjCMethodDecl *MD = Ext->getMethod(Sel, isInstanceMethod()))
977 return MD;
978 }
979 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
980 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
981 if (ObjCMethodDecl *MD = CatD->getMethod(Sel, isInstanceMethod()))
982 return MD;
983 }
984
985 if (isRedeclaration()) {
986 // It is possible that we have not done deserializing the ObjCMethod yet.
987 ObjCMethodDecl *MD =
988 cast<ObjCContainerDecl>(CtxD)->getMethod(Sel, isInstanceMethod(),
989 /*AllowHidden=*/true);
990 return MD ? MD : this;
991 }
992
993 return this;
994 }
995
getEndLoc() const996 SourceLocation ObjCMethodDecl::getEndLoc() const {
997 if (Stmt *Body = getBody())
998 return Body->getEndLoc();
999 return DeclEndLoc;
1000 }
1001
getMethodFamily() const1002 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
1003 auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family);
1004 if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
1005 return family;
1006
1007 // Check for an explicit attribute.
1008 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
1009 // The unfortunate necessity of mapping between enums here is due
1010 // to the attributes framework.
1011 switch (attr->getFamily()) {
1012 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
1013 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
1014 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
1015 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
1016 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
1017 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
1018 }
1019 ObjCMethodDeclBits.Family = family;
1020 return family;
1021 }
1022
1023 family = getSelector().getMethodFamily();
1024 switch (family) {
1025 case OMF_None: break;
1026
1027 // init only has a conventional meaning for an instance method, and
1028 // it has to return an object.
1029 case OMF_init:
1030 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
1031 family = OMF_None;
1032 break;
1033
1034 // alloc/copy/new have a conventional meaning for both class and
1035 // instance methods, but they require an object return.
1036 case OMF_alloc:
1037 case OMF_copy:
1038 case OMF_mutableCopy:
1039 case OMF_new:
1040 if (!getReturnType()->isObjCObjectPointerType())
1041 family = OMF_None;
1042 break;
1043
1044 // These selectors have a conventional meaning only for instance methods.
1045 case OMF_dealloc:
1046 case OMF_finalize:
1047 case OMF_retain:
1048 case OMF_release:
1049 case OMF_autorelease:
1050 case OMF_retainCount:
1051 case OMF_self:
1052 if (!isInstanceMethod())
1053 family = OMF_None;
1054 break;
1055
1056 case OMF_initialize:
1057 if (isInstanceMethod() || !getReturnType()->isVoidType())
1058 family = OMF_None;
1059 break;
1060
1061 case OMF_performSelector:
1062 if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
1063 family = OMF_None;
1064 else {
1065 unsigned noParams = param_size();
1066 if (noParams < 1 || noParams > 3)
1067 family = OMF_None;
1068 else {
1069 ObjCMethodDecl::param_type_iterator it = param_type_begin();
1070 QualType ArgT = (*it);
1071 if (!ArgT->isObjCSelType()) {
1072 family = OMF_None;
1073 break;
1074 }
1075 while (--noParams) {
1076 it++;
1077 ArgT = (*it);
1078 if (!ArgT->isObjCIdType()) {
1079 family = OMF_None;
1080 break;
1081 }
1082 }
1083 }
1084 }
1085 break;
1086
1087 }
1088
1089 // Cache the result.
1090 ObjCMethodDeclBits.Family = family;
1091 return family;
1092 }
1093
getSelfType(ASTContext & Context,const ObjCInterfaceDecl * OID,bool & selfIsPseudoStrong,bool & selfIsConsumed) const1094 QualType ObjCMethodDecl::getSelfType(ASTContext &Context,
1095 const ObjCInterfaceDecl *OID,
1096 bool &selfIsPseudoStrong,
1097 bool &selfIsConsumed) const {
1098 QualType selfTy;
1099 selfIsPseudoStrong = false;
1100 selfIsConsumed = false;
1101 if (isInstanceMethod()) {
1102 // There may be no interface context due to error in declaration
1103 // of the interface (which has been reported). Recover gracefully.
1104 if (OID) {
1105 selfTy = Context.getObjCInterfaceType(OID);
1106 selfTy = Context.getObjCObjectPointerType(selfTy);
1107 } else {
1108 selfTy = Context.getObjCIdType();
1109 }
1110 } else // we have a factory method.
1111 selfTy = Context.getObjCClassType();
1112
1113 if (Context.getLangOpts().ObjCAutoRefCount) {
1114 if (isInstanceMethod()) {
1115 selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
1116
1117 // 'self' is always __strong. It's actually pseudo-strong except
1118 // in init methods (or methods labeled ns_consumes_self), though.
1119 Qualifiers qs;
1120 qs.setObjCLifetime(Qualifiers::OCL_Strong);
1121 selfTy = Context.getQualifiedType(selfTy, qs);
1122
1123 // In addition, 'self' is const unless this is an init method.
1124 if (getMethodFamily() != OMF_init && !selfIsConsumed) {
1125 selfTy = selfTy.withConst();
1126 selfIsPseudoStrong = true;
1127 }
1128 }
1129 else {
1130 assert(isClassMethod());
1131 // 'self' is always const in class methods.
1132 selfTy = selfTy.withConst();
1133 selfIsPseudoStrong = true;
1134 }
1135 }
1136 return selfTy;
1137 }
1138
createImplicitParams(ASTContext & Context,const ObjCInterfaceDecl * OID)1139 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
1140 const ObjCInterfaceDecl *OID) {
1141 bool selfIsPseudoStrong, selfIsConsumed;
1142 QualType selfTy =
1143 getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed);
1144 auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(),
1145 &Context.Idents.get("self"), selfTy,
1146 ImplicitParamDecl::ObjCSelf);
1147 setSelfDecl(Self);
1148
1149 if (selfIsConsumed)
1150 Self->addAttr(NSConsumedAttr::CreateImplicit(Context));
1151
1152 if (selfIsPseudoStrong)
1153 Self->setARCPseudoStrong(true);
1154
1155 setCmdDecl(ImplicitParamDecl::Create(
1156 Context, this, SourceLocation(), &Context.Idents.get("_cmd"),
1157 Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd));
1158 }
1159
getClassInterface()1160 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
1161 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
1162 return ID;
1163 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1164 return CD->getClassInterface();
1165 if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
1166 return IMD->getClassInterface();
1167 if (isa<ObjCProtocolDecl>(getDeclContext()))
1168 return nullptr;
1169 llvm_unreachable("unknown method context");
1170 }
1171
getCategory()1172 ObjCCategoryDecl *ObjCMethodDecl::getCategory() {
1173 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
1174 return CD;
1175 if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(getDeclContext()))
1176 return IMD->getCategoryDecl();
1177 return nullptr;
1178 }
1179
getReturnTypeSourceRange() const1180 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const {
1181 const auto *TSI = getReturnTypeSourceInfo();
1182 if (TSI)
1183 return TSI->getTypeLoc().getSourceRange();
1184 return SourceRange();
1185 }
1186
getSendResultType() const1187 QualType ObjCMethodDecl::getSendResultType() const {
1188 ASTContext &Ctx = getASTContext();
1189 return getReturnType().getNonLValueExprType(Ctx)
1190 .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result);
1191 }
1192
getSendResultType(QualType receiverType) const1193 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const {
1194 // FIXME: Handle related result types here.
1195
1196 return getReturnType().getNonLValueExprType(getASTContext())
1197 .substObjCMemberType(receiverType, getDeclContext(),
1198 ObjCSubstitutionContext::Result);
1199 }
1200
CollectOverriddenMethodsRecurse(const ObjCContainerDecl * Container,const ObjCMethodDecl * Method,SmallVectorImpl<const ObjCMethodDecl * > & Methods,bool MovedToSuper)1201 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
1202 const ObjCMethodDecl *Method,
1203 SmallVectorImpl<const ObjCMethodDecl *> &Methods,
1204 bool MovedToSuper) {
1205 if (!Container)
1206 return;
1207
1208 // In categories look for overridden methods from protocols. A method from
1209 // category is not "overridden" since it is considered as the "same" method
1210 // (same USR) as the one from the interface.
1211 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1212 // Check whether we have a matching method at this category but only if we
1213 // are at the super class level.
1214 if (MovedToSuper)
1215 if (ObjCMethodDecl *
1216 Overridden = Container->getMethod(Method->getSelector(),
1217 Method->isInstanceMethod(),
1218 /*AllowHidden=*/true))
1219 if (Method != Overridden) {
1220 // We found an override at this category; there is no need to look
1221 // into its protocols.
1222 Methods.push_back(Overridden);
1223 return;
1224 }
1225
1226 for (const auto *P : Category->protocols())
1227 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1228 return;
1229 }
1230
1231 // Check whether we have a matching method at this level.
1232 if (const ObjCMethodDecl *
1233 Overridden = Container->getMethod(Method->getSelector(),
1234 Method->isInstanceMethod(),
1235 /*AllowHidden=*/true))
1236 if (Method != Overridden) {
1237 // We found an override at this level; there is no need to look
1238 // into other protocols or categories.
1239 Methods.push_back(Overridden);
1240 return;
1241 }
1242
1243 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
1244 for (const auto *P : Protocol->protocols())
1245 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1246 }
1247
1248 if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1249 for (const auto *P : Interface->protocols())
1250 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1251
1252 for (const auto *Cat : Interface->known_categories())
1253 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper);
1254
1255 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1256 return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1257 /*MovedToSuper=*/true);
1258 }
1259 }
1260
CollectOverriddenMethods(const ObjCContainerDecl * Container,const ObjCMethodDecl * Method,SmallVectorImpl<const ObjCMethodDecl * > & Methods)1261 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1262 const ObjCMethodDecl *Method,
1263 SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1264 CollectOverriddenMethodsRecurse(Container, Method, Methods,
1265 /*MovedToSuper=*/false);
1266 }
1267
collectOverriddenMethodsSlow(const ObjCMethodDecl * Method,SmallVectorImpl<const ObjCMethodDecl * > & overridden)1268 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1269 SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1270 assert(Method->isOverriding());
1271
1272 if (const auto *ProtD =
1273 dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1274 CollectOverriddenMethods(ProtD, Method, overridden);
1275
1276 } else if (const auto *IMD =
1277 dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1278 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1279 if (!ID)
1280 return;
1281 // Start searching for overridden methods using the method from the
1282 // interface as starting point.
1283 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1284 Method->isInstanceMethod(),
1285 /*AllowHidden=*/true))
1286 Method = IFaceMeth;
1287 CollectOverriddenMethods(ID, Method, overridden);
1288
1289 } else if (const auto *CatD =
1290 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1291 const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1292 if (!ID)
1293 return;
1294 // Start searching for overridden methods using the method from the
1295 // interface as starting point.
1296 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1297 Method->isInstanceMethod(),
1298 /*AllowHidden=*/true))
1299 Method = IFaceMeth;
1300 CollectOverriddenMethods(ID, Method, overridden);
1301
1302 } else {
1303 CollectOverriddenMethods(
1304 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1305 Method, overridden);
1306 }
1307 }
1308
getOverriddenMethods(SmallVectorImpl<const ObjCMethodDecl * > & Overridden) const1309 void ObjCMethodDecl::getOverriddenMethods(
1310 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1311 const ObjCMethodDecl *Method = this;
1312
1313 if (Method->isRedeclaration()) {
1314 Method = cast<ObjCContainerDecl>(Method->getDeclContext())
1315 ->getMethod(Method->getSelector(), Method->isInstanceMethod(),
1316 /*AllowHidden=*/true);
1317 }
1318
1319 if (Method->isOverriding()) {
1320 collectOverriddenMethodsSlow(Method, Overridden);
1321 assert(!Overridden.empty() &&
1322 "ObjCMethodDecl's overriding bit is not as expected");
1323 }
1324 }
1325
1326 const ObjCPropertyDecl *
findPropertyDecl(bool CheckOverrides) const1327 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1328 Selector Sel = getSelector();
1329 unsigned NumArgs = Sel.getNumArgs();
1330 if (NumArgs > 1)
1331 return nullptr;
1332
1333 if (isPropertyAccessor()) {
1334 const auto *Container = cast<ObjCContainerDecl>(getParent());
1335 // For accessor stubs, go back to the interface.
1336 if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container))
1337 if (isSynthesizedAccessorStub())
1338 Container = ImplDecl->getClassInterface();
1339
1340 bool IsGetter = (NumArgs == 0);
1341 bool IsInstance = isInstanceMethod();
1342
1343 /// Local function that attempts to find a matching property within the
1344 /// given Objective-C container.
1345 auto findMatchingProperty =
1346 [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * {
1347 if (IsInstance) {
1348 for (const auto *I : Container->instance_properties()) {
1349 Selector NextSel = IsGetter ? I->getGetterName()
1350 : I->getSetterName();
1351 if (NextSel == Sel)
1352 return I;
1353 }
1354 } else {
1355 for (const auto *I : Container->class_properties()) {
1356 Selector NextSel = IsGetter ? I->getGetterName()
1357 : I->getSetterName();
1358 if (NextSel == Sel)
1359 return I;
1360 }
1361 }
1362
1363 return nullptr;
1364 };
1365
1366 // Look in the container we were given.
1367 if (const auto *Found = findMatchingProperty(Container))
1368 return Found;
1369
1370 // If we're in a category or extension, look in the main class.
1371 const ObjCInterfaceDecl *ClassDecl = nullptr;
1372 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
1373 ClassDecl = Category->getClassInterface();
1374 if (const auto *Found = findMatchingProperty(ClassDecl))
1375 return Found;
1376 } else {
1377 // Determine whether the container is a class.
1378 ClassDecl = cast<ObjCInterfaceDecl>(Container);
1379 }
1380 assert(ClassDecl && "Failed to find main class");
1381
1382 // If we have a class, check its visible extensions.
1383 for (const auto *Ext : ClassDecl->visible_extensions()) {
1384 if (Ext == Container)
1385 continue;
1386 if (const auto *Found = findMatchingProperty(Ext))
1387 return Found;
1388 }
1389
1390 assert(isSynthesizedAccessorStub() && "expected an accessor stub");
1391
1392 for (const auto *Cat : ClassDecl->known_categories()) {
1393 if (Cat == Container)
1394 continue;
1395 if (const auto *Found = findMatchingProperty(Cat))
1396 return Found;
1397 }
1398
1399 llvm_unreachable("Marked as a property accessor but no property found!");
1400 }
1401
1402 if (!CheckOverrides)
1403 return nullptr;
1404
1405 using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>;
1406
1407 OverridesTy Overrides;
1408 getOverriddenMethods(Overrides);
1409 for (const auto *Override : Overrides)
1410 if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false))
1411 return Prop;
1412
1413 return nullptr;
1414 }
1415
1416 //===----------------------------------------------------------------------===//
1417 // ObjCTypeParamDecl
1418 //===----------------------------------------------------------------------===//
1419
anchor()1420 void ObjCTypeParamDecl::anchor() {}
1421
Create(ASTContext & ctx,DeclContext * dc,ObjCTypeParamVariance variance,SourceLocation varianceLoc,unsigned index,SourceLocation nameLoc,IdentifierInfo * name,SourceLocation colonLoc,TypeSourceInfo * boundInfo)1422 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc,
1423 ObjCTypeParamVariance variance,
1424 SourceLocation varianceLoc,
1425 unsigned index,
1426 SourceLocation nameLoc,
1427 IdentifierInfo *name,
1428 SourceLocation colonLoc,
1429 TypeSourceInfo *boundInfo) {
1430 auto *TPDecl =
1431 new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index,
1432 nameLoc, name, colonLoc, boundInfo);
1433 QualType TPType = ctx.getObjCTypeParamType(TPDecl, {});
1434 TPDecl->setTypeForDecl(TPType.getTypePtr());
1435 return TPDecl;
1436 }
1437
CreateDeserialized(ASTContext & ctx,unsigned ID)1438 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx,
1439 unsigned ID) {
1440 return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr,
1441 ObjCTypeParamVariance::Invariant,
1442 SourceLocation(), 0, SourceLocation(),
1443 nullptr, SourceLocation(), nullptr);
1444 }
1445
getSourceRange() const1446 SourceRange ObjCTypeParamDecl::getSourceRange() const {
1447 SourceLocation startLoc = VarianceLoc;
1448 if (startLoc.isInvalid())
1449 startLoc = getLocation();
1450
1451 if (hasExplicitBound()) {
1452 return SourceRange(startLoc,
1453 getTypeSourceInfo()->getTypeLoc().getEndLoc());
1454 }
1455
1456 return SourceRange(startLoc);
1457 }
1458
1459 //===----------------------------------------------------------------------===//
1460 // ObjCTypeParamList
1461 //===----------------------------------------------------------------------===//
ObjCTypeParamList(SourceLocation lAngleLoc,ArrayRef<ObjCTypeParamDecl * > typeParams,SourceLocation rAngleLoc)1462 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc,
1463 ArrayRef<ObjCTypeParamDecl *> typeParams,
1464 SourceLocation rAngleLoc)
1465 : Brackets(lAngleLoc, rAngleLoc), NumParams(typeParams.size()) {
1466 std::copy(typeParams.begin(), typeParams.end(), begin());
1467 }
1468
create(ASTContext & ctx,SourceLocation lAngleLoc,ArrayRef<ObjCTypeParamDecl * > typeParams,SourceLocation rAngleLoc)1469 ObjCTypeParamList *ObjCTypeParamList::create(
1470 ASTContext &ctx,
1471 SourceLocation lAngleLoc,
1472 ArrayRef<ObjCTypeParamDecl *> typeParams,
1473 SourceLocation rAngleLoc) {
1474 void *mem =
1475 ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()),
1476 alignof(ObjCTypeParamList));
1477 return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc);
1478 }
1479
gatherDefaultTypeArgs(SmallVectorImpl<QualType> & typeArgs) const1480 void ObjCTypeParamList::gatherDefaultTypeArgs(
1481 SmallVectorImpl<QualType> &typeArgs) const {
1482 typeArgs.reserve(size());
1483 for (auto typeParam : *this)
1484 typeArgs.push_back(typeParam->getUnderlyingType());
1485 }
1486
1487 //===----------------------------------------------------------------------===//
1488 // ObjCInterfaceDecl
1489 //===----------------------------------------------------------------------===//
1490
Create(const ASTContext & C,DeclContext * DC,SourceLocation atLoc,IdentifierInfo * Id,ObjCTypeParamList * typeParamList,ObjCInterfaceDecl * PrevDecl,SourceLocation ClassLoc,bool isInternal)1491 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1492 DeclContext *DC,
1493 SourceLocation atLoc,
1494 IdentifierInfo *Id,
1495 ObjCTypeParamList *typeParamList,
1496 ObjCInterfaceDecl *PrevDecl,
1497 SourceLocation ClassLoc,
1498 bool isInternal){
1499 auto *Result = new (C, DC)
1500 ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl,
1501 isInternal);
1502 Result->Data.setInt(!C.getLangOpts().Modules);
1503 C.getObjCInterfaceType(Result, PrevDecl);
1504 return Result;
1505 }
1506
CreateDeserialized(const ASTContext & C,unsigned ID)1507 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1508 unsigned ID) {
1509 auto *Result = new (C, ID)
1510 ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr,
1511 SourceLocation(), nullptr, false);
1512 Result->Data.setInt(!C.getLangOpts().Modules);
1513 return Result;
1514 }
1515
ObjCInterfaceDecl(const ASTContext & C,DeclContext * DC,SourceLocation AtLoc,IdentifierInfo * Id,ObjCTypeParamList * typeParamList,SourceLocation CLoc,ObjCInterfaceDecl * PrevDecl,bool IsInternal)1516 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1517 SourceLocation AtLoc, IdentifierInfo *Id,
1518 ObjCTypeParamList *typeParamList,
1519 SourceLocation CLoc,
1520 ObjCInterfaceDecl *PrevDecl,
1521 bool IsInternal)
1522 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1523 redeclarable_base(C) {
1524 setPreviousDecl(PrevDecl);
1525
1526 // Copy the 'data' pointer over.
1527 if (PrevDecl)
1528 Data = PrevDecl->Data;
1529
1530 setImplicit(IsInternal);
1531
1532 setTypeParamList(typeParamList);
1533 }
1534
LoadExternalDefinition() const1535 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1536 assert(data().ExternallyCompleted && "Class is not externally completed");
1537 data().ExternallyCompleted = false;
1538 getASTContext().getExternalSource()->CompleteType(
1539 const_cast<ObjCInterfaceDecl *>(this));
1540 }
1541
setExternallyCompleted()1542 void ObjCInterfaceDecl::setExternallyCompleted() {
1543 assert(getASTContext().getExternalSource() &&
1544 "Class can't be externally completed without an external source");
1545 assert(hasDefinition() &&
1546 "Forward declarations can't be externally completed");
1547 data().ExternallyCompleted = true;
1548 }
1549
setHasDesignatedInitializers()1550 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1551 // Check for a complete definition and recover if not so.
1552 if (!isThisDeclarationADefinition())
1553 return;
1554 data().HasDesignatedInitializers = true;
1555 }
1556
hasDesignatedInitializers() const1557 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1558 // Check for a complete definition and recover if not so.
1559 if (!isThisDeclarationADefinition())
1560 return false;
1561 if (data().ExternallyCompleted)
1562 LoadExternalDefinition();
1563
1564 return data().HasDesignatedInitializers;
1565 }
1566
1567 StringRef
getObjCRuntimeNameAsString() const1568 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1569 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1570 return ObjCRTName->getMetadataName();
1571
1572 return getName();
1573 }
1574
1575 StringRef
getObjCRuntimeNameAsString() const1576 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1577 if (ObjCInterfaceDecl *ID =
1578 const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1579 return ID->getObjCRuntimeNameAsString();
1580
1581 return getName();
1582 }
1583
getImplementation() const1584 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1585 if (const ObjCInterfaceDecl *Def = getDefinition()) {
1586 if (data().ExternallyCompleted)
1587 LoadExternalDefinition();
1588
1589 return getASTContext().getObjCImplementation(
1590 const_cast<ObjCInterfaceDecl*>(Def));
1591 }
1592
1593 // FIXME: Should make sure no callers ever do this.
1594 return nullptr;
1595 }
1596
setImplementation(ObjCImplementationDecl * ImplD)1597 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1598 getASTContext().setObjCImplementation(getDefinition(), ImplD);
1599 }
1600
1601 namespace {
1602
1603 struct SynthesizeIvarChunk {
1604 uint64_t Size;
1605 ObjCIvarDecl *Ivar;
1606
SynthesizeIvarChunk__anon823593a80211::SynthesizeIvarChunk1607 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1608 : Size(size), Ivar(ivar) {}
1609 };
1610
operator <(const SynthesizeIvarChunk & LHS,const SynthesizeIvarChunk & RHS)1611 bool operator<(const SynthesizeIvarChunk & LHS,
1612 const SynthesizeIvarChunk &RHS) {
1613 return LHS.Size < RHS.Size;
1614 }
1615
1616 } // namespace
1617
1618 /// all_declared_ivar_begin - return first ivar declared in this class,
1619 /// its extensions and its implementation. Lazily build the list on first
1620 /// access.
1621 ///
1622 /// Caveat: The list returned by this method reflects the current
1623 /// state of the parser. The cache will be updated for every ivar
1624 /// added by an extension or the implementation when they are
1625 /// encountered.
1626 /// See also ObjCIvarDecl::Create().
all_declared_ivar_begin()1627 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1628 // FIXME: Should make sure no callers ever do this.
1629 if (!hasDefinition())
1630 return nullptr;
1631
1632 ObjCIvarDecl *curIvar = nullptr;
1633 if (!data().IvarList) {
1634 if (!ivar_empty()) {
1635 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1636 data().IvarList = *I; ++I;
1637 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1638 curIvar->setNextIvar(*I);
1639 }
1640
1641 for (const auto *Ext : known_extensions()) {
1642 if (!Ext->ivar_empty()) {
1643 ObjCCategoryDecl::ivar_iterator
1644 I = Ext->ivar_begin(),
1645 E = Ext->ivar_end();
1646 if (!data().IvarList) {
1647 data().IvarList = *I; ++I;
1648 curIvar = data().IvarList;
1649 }
1650 for ( ;I != E; curIvar = *I, ++I)
1651 curIvar->setNextIvar(*I);
1652 }
1653 }
1654 data().IvarListMissingImplementation = true;
1655 }
1656
1657 // cached and complete!
1658 if (!data().IvarListMissingImplementation)
1659 return data().IvarList;
1660
1661 if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1662 data().IvarListMissingImplementation = false;
1663 if (!ImplDecl->ivar_empty()) {
1664 SmallVector<SynthesizeIvarChunk, 16> layout;
1665 for (auto *IV : ImplDecl->ivars()) {
1666 if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1667 layout.push_back(SynthesizeIvarChunk(
1668 IV->getASTContext().getTypeSize(IV->getType()), IV));
1669 continue;
1670 }
1671 if (!data().IvarList)
1672 data().IvarList = IV;
1673 else
1674 curIvar->setNextIvar(IV);
1675 curIvar = IV;
1676 }
1677
1678 if (!layout.empty()) {
1679 // Order synthesized ivars by their size.
1680 llvm::stable_sort(layout);
1681 unsigned Ix = 0, EIx = layout.size();
1682 if (!data().IvarList) {
1683 data().IvarList = layout[0].Ivar; Ix++;
1684 curIvar = data().IvarList;
1685 }
1686 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1687 curIvar->setNextIvar(layout[Ix].Ivar);
1688 }
1689 }
1690 }
1691 return data().IvarList;
1692 }
1693
1694 /// FindCategoryDeclaration - Finds category declaration in the list of
1695 /// categories for this class and returns it. Name of the category is passed
1696 /// in 'CategoryId'. If category not found, return 0;
1697 ///
1698 ObjCCategoryDecl *
FindCategoryDeclaration(IdentifierInfo * CategoryId) const1699 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1700 // FIXME: Should make sure no callers ever do this.
1701 if (!hasDefinition())
1702 return nullptr;
1703
1704 if (data().ExternallyCompleted)
1705 LoadExternalDefinition();
1706
1707 for (auto *Cat : visible_categories())
1708 if (Cat->getIdentifier() == CategoryId)
1709 return Cat;
1710
1711 return nullptr;
1712 }
1713
1714 ObjCMethodDecl *
getCategoryInstanceMethod(Selector Sel) const1715 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1716 for (const auto *Cat : visible_categories()) {
1717 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1718 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1719 return MD;
1720 }
1721
1722 return nullptr;
1723 }
1724
getCategoryClassMethod(Selector Sel) const1725 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1726 for (const auto *Cat : visible_categories()) {
1727 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1728 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1729 return MD;
1730 }
1731
1732 return nullptr;
1733 }
1734
1735 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1736 /// has been implemented in IDecl class, its super class or categories (if
1737 /// lookupCategory is true).
ClassImplementsProtocol(ObjCProtocolDecl * lProto,bool lookupCategory,bool RHSIsQualifiedID)1738 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1739 bool lookupCategory,
1740 bool RHSIsQualifiedID) {
1741 if (!hasDefinition())
1742 return false;
1743
1744 ObjCInterfaceDecl *IDecl = this;
1745 // 1st, look up the class.
1746 for (auto *PI : IDecl->protocols()){
1747 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1748 return true;
1749 // This is dubious and is added to be compatible with gcc. In gcc, it is
1750 // also allowed assigning a protocol-qualified 'id' type to a LHS object
1751 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1752 // object. This IMO, should be a bug.
1753 // FIXME: Treat this as an extension, and flag this as an error when GCC
1754 // extensions are not enabled.
1755 if (RHSIsQualifiedID &&
1756 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1757 return true;
1758 }
1759
1760 // 2nd, look up the category.
1761 if (lookupCategory)
1762 for (const auto *Cat : visible_categories()) {
1763 for (auto *PI : Cat->protocols())
1764 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1765 return true;
1766 }
1767
1768 // 3rd, look up the super class(s)
1769 if (IDecl->getSuperClass())
1770 return
1771 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1772 RHSIsQualifiedID);
1773
1774 return false;
1775 }
1776
1777 //===----------------------------------------------------------------------===//
1778 // ObjCIvarDecl
1779 //===----------------------------------------------------------------------===//
1780
anchor()1781 void ObjCIvarDecl::anchor() {}
1782
Create(ASTContext & C,ObjCContainerDecl * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,AccessControl ac,Expr * BW,bool synthesized)1783 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1784 SourceLocation StartLoc,
1785 SourceLocation IdLoc, IdentifierInfo *Id,
1786 QualType T, TypeSourceInfo *TInfo,
1787 AccessControl ac, Expr *BW,
1788 bool synthesized) {
1789 if (DC) {
1790 // Ivar's can only appear in interfaces, implementations (via synthesized
1791 // properties), and class extensions (via direct declaration, or synthesized
1792 // properties).
1793 //
1794 // FIXME: This should really be asserting this:
1795 // (isa<ObjCCategoryDecl>(DC) &&
1796 // cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1797 // but unfortunately we sometimes place ivars into non-class extension
1798 // categories on error. This breaks an AST invariant, and should not be
1799 // fixed.
1800 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
1801 isa<ObjCCategoryDecl>(DC)) &&
1802 "Invalid ivar decl context!");
1803 // Once a new ivar is created in any of class/class-extension/implementation
1804 // decl contexts, the previously built IvarList must be rebuilt.
1805 auto *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1806 if (!ID) {
1807 if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC))
1808 ID = IM->getClassInterface();
1809 else
1810 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1811 }
1812 ID->setIvarList(nullptr);
1813 }
1814
1815 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1816 synthesized);
1817 }
1818
CreateDeserialized(ASTContext & C,unsigned ID)1819 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1820 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1821 nullptr, QualType(), nullptr,
1822 ObjCIvarDecl::None, nullptr, false);
1823 }
1824
getContainingInterface() const1825 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1826 const auto *DC = cast<ObjCContainerDecl>(getDeclContext());
1827
1828 switch (DC->getKind()) {
1829 default:
1830 case ObjCCategoryImpl:
1831 case ObjCProtocol:
1832 llvm_unreachable("invalid ivar container!");
1833
1834 // Ivars can only appear in class extension categories.
1835 case ObjCCategory: {
1836 const auto *CD = cast<ObjCCategoryDecl>(DC);
1837 assert(CD->IsClassExtension() && "invalid container for ivar!");
1838 return CD->getClassInterface();
1839 }
1840
1841 case ObjCImplementation:
1842 return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1843
1844 case ObjCInterface:
1845 return cast<ObjCInterfaceDecl>(DC);
1846 }
1847 }
1848
getUsageType(QualType objectType) const1849 QualType ObjCIvarDecl::getUsageType(QualType objectType) const {
1850 return getType().substObjCMemberType(objectType, getDeclContext(),
1851 ObjCSubstitutionContext::Property);
1852 }
1853
1854 //===----------------------------------------------------------------------===//
1855 // ObjCAtDefsFieldDecl
1856 //===----------------------------------------------------------------------===//
1857
anchor()1858 void ObjCAtDefsFieldDecl::anchor() {}
1859
1860 ObjCAtDefsFieldDecl
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,Expr * BW)1861 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1862 SourceLocation StartLoc, SourceLocation IdLoc,
1863 IdentifierInfo *Id, QualType T, Expr *BW) {
1864 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1865 }
1866
CreateDeserialized(ASTContext & C,unsigned ID)1867 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1868 unsigned ID) {
1869 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1870 SourceLocation(), nullptr, QualType(),
1871 nullptr);
1872 }
1873
1874 //===----------------------------------------------------------------------===//
1875 // ObjCProtocolDecl
1876 //===----------------------------------------------------------------------===//
1877
anchor()1878 void ObjCProtocolDecl::anchor() {}
1879
ObjCProtocolDecl(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc,ObjCProtocolDecl * PrevDecl)1880 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1881 IdentifierInfo *Id, SourceLocation nameLoc,
1882 SourceLocation atStartLoc,
1883 ObjCProtocolDecl *PrevDecl)
1884 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1885 redeclarable_base(C) {
1886 setPreviousDecl(PrevDecl);
1887 if (PrevDecl)
1888 Data = PrevDecl->Data;
1889 }
1890
Create(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc,ObjCProtocolDecl * PrevDecl)1891 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1892 IdentifierInfo *Id,
1893 SourceLocation nameLoc,
1894 SourceLocation atStartLoc,
1895 ObjCProtocolDecl *PrevDecl) {
1896 auto *Result =
1897 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1898 Result->Data.setInt(!C.getLangOpts().Modules);
1899 return Result;
1900 }
1901
CreateDeserialized(ASTContext & C,unsigned ID)1902 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1903 unsigned ID) {
1904 ObjCProtocolDecl *Result =
1905 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1906 SourceLocation(), nullptr);
1907 Result->Data.setInt(!C.getLangOpts().Modules);
1908 return Result;
1909 }
1910
isNonRuntimeProtocol() const1911 bool ObjCProtocolDecl::isNonRuntimeProtocol() const {
1912 return hasAttr<ObjCNonRuntimeProtocolAttr>();
1913 }
1914
getImpliedProtocols(llvm::DenseSet<const ObjCProtocolDecl * > & IPs) const1915 void ObjCProtocolDecl::getImpliedProtocols(
1916 llvm::DenseSet<const ObjCProtocolDecl *> &IPs) const {
1917 std::queue<const ObjCProtocolDecl *> WorkQueue;
1918 WorkQueue.push(this);
1919
1920 while (!WorkQueue.empty()) {
1921 const auto *PD = WorkQueue.front();
1922 WorkQueue.pop();
1923 for (const auto *Parent : PD->protocols()) {
1924 const auto *Can = Parent->getCanonicalDecl();
1925 auto Result = IPs.insert(Can);
1926 if (Result.second)
1927 WorkQueue.push(Parent);
1928 }
1929 }
1930 }
1931
lookupProtocolNamed(IdentifierInfo * Name)1932 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1933 ObjCProtocolDecl *PDecl = this;
1934
1935 if (Name == getIdentifier())
1936 return PDecl;
1937
1938 for (auto *I : protocols())
1939 if ((PDecl = I->lookupProtocolNamed(Name)))
1940 return PDecl;
1941
1942 return nullptr;
1943 }
1944
1945 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1946 // it inherited.
lookupMethod(Selector Sel,bool isInstance) const1947 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1948 bool isInstance) const {
1949 ObjCMethodDecl *MethodDecl = nullptr;
1950
1951 // If there is no definition or the definition is hidden, we don't find
1952 // anything.
1953 const ObjCProtocolDecl *Def = getDefinition();
1954 if (!Def || !Def->isUnconditionallyVisible())
1955 return nullptr;
1956
1957 if ((MethodDecl = getMethod(Sel, isInstance)))
1958 return MethodDecl;
1959
1960 for (const auto *I : protocols())
1961 if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1962 return MethodDecl;
1963 return nullptr;
1964 }
1965
allocateDefinitionData()1966 void ObjCProtocolDecl::allocateDefinitionData() {
1967 assert(!Data.getPointer() && "Protocol already has a definition!");
1968 Data.setPointer(new (getASTContext()) DefinitionData);
1969 Data.getPointer()->Definition = this;
1970 }
1971
startDefinition()1972 void ObjCProtocolDecl::startDefinition() {
1973 allocateDefinitionData();
1974
1975 // Update all of the declarations with a pointer to the definition.
1976 for (auto *RD : redecls())
1977 RD->Data = this->Data;
1978 }
1979
collectPropertiesToImplement(PropertyMap & PM,PropertyDeclOrder & PO) const1980 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1981 PropertyDeclOrder &PO) const {
1982 if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1983 for (auto *Prop : PDecl->properties()) {
1984 // Insert into PM if not there already.
1985 PM.insert(std::make_pair(
1986 std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()),
1987 Prop));
1988 PO.push_back(Prop);
1989 }
1990 // Scan through protocol's protocols.
1991 for (const auto *PI : PDecl->protocols())
1992 PI->collectPropertiesToImplement(PM, PO);
1993 }
1994 }
1995
collectInheritedProtocolProperties(const ObjCPropertyDecl * Property,ProtocolPropertySet & PS,PropertyDeclOrder & PO) const1996 void ObjCProtocolDecl::collectInheritedProtocolProperties(
1997 const ObjCPropertyDecl *Property, ProtocolPropertySet &PS,
1998 PropertyDeclOrder &PO) const {
1999 if (const ObjCProtocolDecl *PDecl = getDefinition()) {
2000 if (!PS.insert(PDecl).second)
2001 return;
2002 for (auto *Prop : PDecl->properties()) {
2003 if (Prop == Property)
2004 continue;
2005 if (Prop->getIdentifier() == Property->getIdentifier()) {
2006 PO.push_back(Prop);
2007 return;
2008 }
2009 }
2010 // Scan through protocol's protocols which did not have a matching property.
2011 for (const auto *PI : PDecl->protocols())
2012 PI->collectInheritedProtocolProperties(Property, PS, PO);
2013 }
2014 }
2015
2016 StringRef
getObjCRuntimeNameAsString() const2017 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
2018 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
2019 return ObjCRTName->getMetadataName();
2020
2021 return getName();
2022 }
2023
2024 //===----------------------------------------------------------------------===//
2025 // ObjCCategoryDecl
2026 //===----------------------------------------------------------------------===//
2027
anchor()2028 void ObjCCategoryDecl::anchor() {}
2029
ObjCCategoryDecl(DeclContext * DC,SourceLocation AtLoc,SourceLocation ClassNameLoc,SourceLocation CategoryNameLoc,IdentifierInfo * Id,ObjCInterfaceDecl * IDecl,ObjCTypeParamList * typeParamList,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2030 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2031 SourceLocation ClassNameLoc,
2032 SourceLocation CategoryNameLoc,
2033 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2034 ObjCTypeParamList *typeParamList,
2035 SourceLocation IvarLBraceLoc,
2036 SourceLocation IvarRBraceLoc)
2037 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
2038 ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc),
2039 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
2040 setTypeParamList(typeParamList);
2041 }
2042
Create(ASTContext & C,DeclContext * DC,SourceLocation AtLoc,SourceLocation ClassNameLoc,SourceLocation CategoryNameLoc,IdentifierInfo * Id,ObjCInterfaceDecl * IDecl,ObjCTypeParamList * typeParamList,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2043 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
2044 SourceLocation AtLoc,
2045 SourceLocation ClassNameLoc,
2046 SourceLocation CategoryNameLoc,
2047 IdentifierInfo *Id,
2048 ObjCInterfaceDecl *IDecl,
2049 ObjCTypeParamList *typeParamList,
2050 SourceLocation IvarLBraceLoc,
2051 SourceLocation IvarRBraceLoc) {
2052 auto *CatDecl =
2053 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
2054 IDecl, typeParamList, IvarLBraceLoc,
2055 IvarRBraceLoc);
2056 if (IDecl) {
2057 // Link this category into its class's category list.
2058 CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
2059 if (IDecl->hasDefinition()) {
2060 IDecl->setCategoryListRaw(CatDecl);
2061 if (ASTMutationListener *L = C.getASTMutationListener())
2062 L->AddedObjCCategoryToInterface(CatDecl, IDecl);
2063 }
2064 }
2065
2066 return CatDecl;
2067 }
2068
CreateDeserialized(ASTContext & C,unsigned ID)2069 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
2070 unsigned ID) {
2071 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
2072 SourceLocation(), SourceLocation(),
2073 nullptr, nullptr, nullptr);
2074 }
2075
getImplementation() const2076 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
2077 return getASTContext().getObjCImplementation(
2078 const_cast<ObjCCategoryDecl*>(this));
2079 }
2080
setImplementation(ObjCCategoryImplDecl * ImplD)2081 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
2082 getASTContext().setObjCImplementation(this, ImplD);
2083 }
2084
setTypeParamList(ObjCTypeParamList * TPL)2085 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) {
2086 TypeParamList = TPL;
2087 if (!TPL)
2088 return;
2089 // Set the declaration context of each of the type parameters.
2090 for (auto *typeParam : *TypeParamList)
2091 typeParam->setDeclContext(this);
2092 }
2093
2094 //===----------------------------------------------------------------------===//
2095 // ObjCCategoryImplDecl
2096 //===----------------------------------------------------------------------===//
2097
anchor()2098 void ObjCCategoryImplDecl::anchor() {}
2099
2100 ObjCCategoryImplDecl *
Create(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,ObjCInterfaceDecl * ClassInterface,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation CategoryNameLoc)2101 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
2102 IdentifierInfo *Id,
2103 ObjCInterfaceDecl *ClassInterface,
2104 SourceLocation nameLoc,
2105 SourceLocation atStartLoc,
2106 SourceLocation CategoryNameLoc) {
2107 if (ClassInterface && ClassInterface->hasDefinition())
2108 ClassInterface = ClassInterface->getDefinition();
2109 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
2110 atStartLoc, CategoryNameLoc);
2111 }
2112
CreateDeserialized(ASTContext & C,unsigned ID)2113 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
2114 unsigned ID) {
2115 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2116 SourceLocation(), SourceLocation(),
2117 SourceLocation());
2118 }
2119
getCategoryDecl() const2120 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
2121 // The class interface might be NULL if we are working with invalid code.
2122 if (const ObjCInterfaceDecl *ID = getClassInterface())
2123 return ID->FindCategoryDeclaration(getIdentifier());
2124 return nullptr;
2125 }
2126
anchor()2127 void ObjCImplDecl::anchor() {}
2128
addPropertyImplementation(ObjCPropertyImplDecl * property)2129 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
2130 // FIXME: The context should be correct before we get here.
2131 property->setLexicalDeclContext(this);
2132 addDecl(property);
2133 }
2134
setClassInterface(ObjCInterfaceDecl * IFace)2135 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
2136 ASTContext &Ctx = getASTContext();
2137
2138 if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
2139 if (IFace)
2140 Ctx.setObjCImplementation(IFace, ImplD);
2141
2142 } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
2143 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
2144 Ctx.setObjCImplementation(CD, ImplD);
2145 }
2146
2147 ClassInterface = IFace;
2148 }
2149
2150 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2151 /// properties implemented in this \@implementation block and returns
2152 /// the implemented property that uses it.
2153 ObjCPropertyImplDecl *ObjCImplDecl::
FindPropertyImplIvarDecl(IdentifierInfo * ivarId) const2154 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
2155 for (auto *PID : property_impls())
2156 if (PID->getPropertyIvarDecl() &&
2157 PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
2158 return PID;
2159 return nullptr;
2160 }
2161
2162 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2163 /// added to the list of those properties \@synthesized/\@dynamic in this
2164 /// category \@implementation block.
2165 ObjCPropertyImplDecl *ObjCImplDecl::
FindPropertyImplDecl(IdentifierInfo * Id,ObjCPropertyQueryKind QueryKind) const2166 FindPropertyImplDecl(IdentifierInfo *Id,
2167 ObjCPropertyQueryKind QueryKind) const {
2168 ObjCPropertyImplDecl *ClassPropImpl = nullptr;
2169 for (auto *PID : property_impls())
2170 // If queryKind is unknown, we return the instance property if one
2171 // exists; otherwise we return the class property.
2172 if (PID->getPropertyDecl()->getIdentifier() == Id) {
2173 if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
2174 !PID->getPropertyDecl()->isClassProperty()) ||
2175 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
2176 PID->getPropertyDecl()->isClassProperty()) ||
2177 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
2178 !PID->getPropertyDecl()->isClassProperty()))
2179 return PID;
2180
2181 if (PID->getPropertyDecl()->isClassProperty())
2182 ClassPropImpl = PID;
2183 }
2184
2185 if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
2186 // We can't find the instance property, return the class property.
2187 return ClassPropImpl;
2188
2189 return nullptr;
2190 }
2191
operator <<(raw_ostream & OS,const ObjCCategoryImplDecl & CID)2192 raw_ostream &clang::operator<<(raw_ostream &OS,
2193 const ObjCCategoryImplDecl &CID) {
2194 OS << CID.getName();
2195 return OS;
2196 }
2197
2198 //===----------------------------------------------------------------------===//
2199 // ObjCImplementationDecl
2200 //===----------------------------------------------------------------------===//
2201
anchor()2202 void ObjCImplementationDecl::anchor() {}
2203
2204 ObjCImplementationDecl *
Create(ASTContext & C,DeclContext * DC,ObjCInterfaceDecl * ClassInterface,ObjCInterfaceDecl * SuperDecl,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation superLoc,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2205 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
2206 ObjCInterfaceDecl *ClassInterface,
2207 ObjCInterfaceDecl *SuperDecl,
2208 SourceLocation nameLoc,
2209 SourceLocation atStartLoc,
2210 SourceLocation superLoc,
2211 SourceLocation IvarLBraceLoc,
2212 SourceLocation IvarRBraceLoc) {
2213 if (ClassInterface && ClassInterface->hasDefinition())
2214 ClassInterface = ClassInterface->getDefinition();
2215 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
2216 nameLoc, atStartLoc, superLoc,
2217 IvarLBraceLoc, IvarRBraceLoc);
2218 }
2219
2220 ObjCImplementationDecl *
CreateDeserialized(ASTContext & C,unsigned ID)2221 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2222 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2223 SourceLocation(), SourceLocation());
2224 }
2225
setIvarInitializers(ASTContext & C,CXXCtorInitializer ** initializers,unsigned numInitializers)2226 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2227 CXXCtorInitializer ** initializers,
2228 unsigned numInitializers) {
2229 if (numInitializers > 0) {
2230 NumIvarInitializers = numInitializers;
2231 auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers];
2232 memcpy(ivarInitializers, initializers,
2233 numInitializers * sizeof(CXXCtorInitializer*));
2234 IvarInitializers = ivarInitializers;
2235 }
2236 }
2237
2238 ObjCImplementationDecl::init_const_iterator
init_begin() const2239 ObjCImplementationDecl::init_begin() const {
2240 return IvarInitializers.get(getASTContext().getExternalSource());
2241 }
2242
operator <<(raw_ostream & OS,const ObjCImplementationDecl & ID)2243 raw_ostream &clang::operator<<(raw_ostream &OS,
2244 const ObjCImplementationDecl &ID) {
2245 OS << ID.getName();
2246 return OS;
2247 }
2248
2249 //===----------------------------------------------------------------------===//
2250 // ObjCCompatibleAliasDecl
2251 //===----------------------------------------------------------------------===//
2252
anchor()2253 void ObjCCompatibleAliasDecl::anchor() {}
2254
2255 ObjCCompatibleAliasDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,ObjCInterfaceDecl * AliasedClass)2256 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
2257 SourceLocation L,
2258 IdentifierInfo *Id,
2259 ObjCInterfaceDecl* AliasedClass) {
2260 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
2261 }
2262
2263 ObjCCompatibleAliasDecl *
CreateDeserialized(ASTContext & C,unsigned ID)2264 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2265 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2266 nullptr, nullptr);
2267 }
2268
2269 //===----------------------------------------------------------------------===//
2270 // ObjCPropertyDecl
2271 //===----------------------------------------------------------------------===//
2272
anchor()2273 void ObjCPropertyDecl::anchor() {}
2274
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,SourceLocation AtLoc,SourceLocation LParenLoc,QualType T,TypeSourceInfo * TSI,PropertyControl propControl)2275 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
2276 SourceLocation L,
2277 IdentifierInfo *Id,
2278 SourceLocation AtLoc,
2279 SourceLocation LParenLoc,
2280 QualType T,
2281 TypeSourceInfo *TSI,
2282 PropertyControl propControl) {
2283 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
2284 propControl);
2285 }
2286
CreateDeserialized(ASTContext & C,unsigned ID)2287 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
2288 unsigned ID) {
2289 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2290 SourceLocation(), SourceLocation(),
2291 QualType(), nullptr, None);
2292 }
2293
getUsageType(QualType objectType) const2294 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const {
2295 return DeclType.substObjCMemberType(objectType, getDeclContext(),
2296 ObjCSubstitutionContext::Property);
2297 }
2298
isDirectProperty() const2299 bool ObjCPropertyDecl::isDirectProperty() const {
2300 return (PropertyAttributes & ObjCPropertyAttribute::kind_direct) &&
2301 !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting;
2302 }
2303
2304 //===----------------------------------------------------------------------===//
2305 // ObjCPropertyImplDecl
2306 //===----------------------------------------------------------------------===//
2307
Create(ASTContext & C,DeclContext * DC,SourceLocation atLoc,SourceLocation L,ObjCPropertyDecl * property,Kind PK,ObjCIvarDecl * ivar,SourceLocation ivarLoc)2308 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
2309 DeclContext *DC,
2310 SourceLocation atLoc,
2311 SourceLocation L,
2312 ObjCPropertyDecl *property,
2313 Kind PK,
2314 ObjCIvarDecl *ivar,
2315 SourceLocation ivarLoc) {
2316 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
2317 ivarLoc);
2318 }
2319
CreateDeserialized(ASTContext & C,unsigned ID)2320 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
2321 unsigned ID) {
2322 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2323 SourceLocation(), nullptr, Dynamic,
2324 nullptr, SourceLocation());
2325 }
2326
getSourceRange() const2327 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
2328 SourceLocation EndLoc = getLocation();
2329 if (IvarLoc.isValid())
2330 EndLoc = IvarLoc;
2331
2332 return SourceRange(AtLoc, EndLoc);
2333 }
2334