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