1 //===- DeclObjC.cpp - ObjC Declaration AST Node Implementation ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Objective-C related Decl classes.
11 //===----------------------------------------------------------------------===//
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/ODRHash.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/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"
39 using namespace clang
;
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 void ObjCListBase::set(void *const* InList
, unsigned Elts
, ASTContext
&Ctx
) {
47 if (Elts
== 0) return; // Setting to an empty list is a noop.
49 List
= new (Ctx
) void*[Elts
];
51 memcpy(List
, InList
, sizeof(void*)*Elts
);
54 void ObjCProtocolList::set(ObjCProtocolDecl
* const* InList
, unsigned Elts
,
55 const SourceLocation
*Locs
, ASTContext
&Ctx
) {
59 Locations
= new (Ctx
) SourceLocation
[Elts
];
60 memcpy(Locations
, Locs
, sizeof(SourceLocation
) * Elts
);
61 set(InList
, Elts
, Ctx
);
64 //===----------------------------------------------------------------------===//
66 //===----------------------------------------------------------------------===//
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
);
75 void ObjCContainerDecl::anchor() {}
77 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
80 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
))
90 // Get the local instance/class method declared in this interface.
92 ObjCContainerDecl::getMethod(Selector Sel
, bool isInstance
,
93 bool AllowHidden
) const {
94 // If this context is a hidden protocol definition, don't find any
96 if (const auto *Proto
= dyn_cast
<ObjCProtocolDecl
>(this)) {
97 if (const ObjCProtocolDecl
*Def
= Proto
->getDefinition())
98 if (!Def
->isUnconditionallyVisible() && !AllowHidden
)
102 // Since instance & class methods can have the same name, the loop below
103 // ensures we get the correct method.
105 // @interface Whatever
106 // - (int) class_method;
107 // + (float) class_method;
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
)
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.
124 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())
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())
142 if (Cat
->IsClassExtension())
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
)
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
))
162 // And in its super class.
163 ObjCInterfaceDecl
*OSC
= ID
->getSuperClass();
165 if (OSC
->HasUserDeclaredSetterMethod(Property
))
167 OSC
= OSC
->getSuperClass();
170 if (const auto *PD
= dyn_cast
<ObjCProtocolDecl
>(this))
171 for (const auto *PI
: PD
->protocols())
172 if (PI
->HasUserDeclaredSetterMethod(Property
))
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
183 if (const auto *Proto
= dyn_cast
<ObjCProtocolDecl
>(DC
)) {
184 if (const ObjCProtocolDecl
*Def
= Proto
->getDefinition())
185 if (!Def
->isUnconditionallyVisible())
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
,
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
;
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()))
214 if (PD
->isClassProperty())
218 if (queryKind
== ObjCPropertyQueryKind::OBJC_PR_query_unknown
)
219 // We can't find the instance property, return the class property.
226 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext
&Ctx
) const {
227 SmallString
<128> ivarName
;
229 llvm::raw_svector_ostream
os(ivarName
);
230 os
<< '_' << getIdentifier()->getName();
232 return &Ctx
.Idents
.get(ivarName
.str());
235 ObjCPropertyDecl
*ObjCContainerDecl::getProperty(const IdentifierInfo
*Id
,
236 bool IsInstance
) const {
237 for (auto *LookupResult
: lookup(Id
)) {
238 if (auto *Prop
= dyn_cast
<ObjCPropertyDecl
>(LookupResult
)) {
239 if (Prop
->isInstanceProperty() == IsInstance
) {
247 /// FindPropertyDeclaration - Finds declaration of the property given its name
248 /// in 'PropertyId' and returns it. It returns 0, if not found.
249 ObjCPropertyDecl
*ObjCContainerDecl::FindPropertyDeclaration(
250 const IdentifierInfo
*PropertyId
,
251 ObjCPropertyQueryKind QueryKind
) const {
252 // Don't find properties within hidden protocol definitions.
253 if (const auto *Proto
= dyn_cast
<ObjCProtocolDecl
>(this)) {
254 if (const ObjCProtocolDecl
*Def
= Proto
->getDefinition())
255 if (!Def
->isUnconditionallyVisible())
259 // Search the extensions of a class first; they override what's in
261 if (const auto *ClassDecl
= dyn_cast
<ObjCInterfaceDecl
>(this)) {
262 for (const auto *Ext
: ClassDecl
->visible_extensions()) {
263 if (auto *P
= Ext
->FindPropertyDeclaration(PropertyId
, QueryKind
))
268 if (ObjCPropertyDecl
*PD
=
269 ObjCPropertyDecl::findPropertyDecl(cast
<DeclContext
>(this), PropertyId
,
276 case Decl::ObjCProtocol
: {
277 const auto *PID
= cast
<ObjCProtocolDecl
>(this);
278 for (const auto *I
: PID
->protocols())
279 if (ObjCPropertyDecl
*P
= I
->FindPropertyDeclaration(PropertyId
,
284 case Decl::ObjCInterface
: {
285 const auto *OID
= cast
<ObjCInterfaceDecl
>(this);
286 // Look through categories (but not extensions; they were handled above).
287 for (const auto *Cat
: OID
->visible_categories()) {
288 if (!Cat
->IsClassExtension())
289 if (ObjCPropertyDecl
*P
= Cat
->FindPropertyDeclaration(
290 PropertyId
, QueryKind
))
294 // Look through protocols.
295 for (const auto *I
: OID
->all_referenced_protocols())
296 if (ObjCPropertyDecl
*P
= I
->FindPropertyDeclaration(PropertyId
,
300 // Finally, check the super class.
301 if (const ObjCInterfaceDecl
*superClass
= OID
->getSuperClass())
302 return superClass
->FindPropertyDeclaration(PropertyId
, QueryKind
);
305 case Decl::ObjCCategory
: {
306 const auto *OCD
= cast
<ObjCCategoryDecl
>(this);
307 // Look through protocols.
308 if (!OCD
->IsClassExtension())
309 for (const auto *I
: OCD
->protocols())
310 if (ObjCPropertyDecl
*P
= I
->FindPropertyDeclaration(PropertyId
,
319 void ObjCInterfaceDecl::anchor() {}
321 ObjCTypeParamList
*ObjCInterfaceDecl::getTypeParamList() const {
322 // If this particular declaration has a type parameter list, return it.
323 if (ObjCTypeParamList
*written
= getTypeParamListAsWritten())
326 // If there is a definition, return its type parameter list.
327 if (const ObjCInterfaceDecl
*def
= getDefinition())
328 return def
->getTypeParamListAsWritten();
330 // Otherwise, look at previous declarations to determine whether any
331 // of them has a type parameter list, skipping over those
332 // declarations that do not.
333 for (const ObjCInterfaceDecl
*decl
= getMostRecentDecl(); decl
;
334 decl
= decl
->getPreviousDecl()) {
335 if (ObjCTypeParamList
*written
= decl
->getTypeParamListAsWritten())
342 void ObjCInterfaceDecl::setTypeParamList(ObjCTypeParamList
*TPL
) {
346 // Set the declaration context of each of the type parameters.
347 for (auto *typeParam
: *TypeParamList
)
348 typeParam
->setDeclContext(this);
351 ObjCInterfaceDecl
*ObjCInterfaceDecl::getSuperClass() const {
352 // FIXME: Should make sure no callers ever do this.
353 if (!hasDefinition())
356 if (data().ExternallyCompleted
)
357 LoadExternalDefinition();
359 if (const ObjCObjectType
*superType
= getSuperClassType()) {
360 if (ObjCInterfaceDecl
*superDecl
= superType
->getInterface()) {
361 if (ObjCInterfaceDecl
*superDef
= superDecl
->getDefinition())
371 SourceLocation
ObjCInterfaceDecl::getSuperClassLoc() const {
372 if (TypeSourceInfo
*superTInfo
= getSuperClassTInfo())
373 return superTInfo
->getTypeLoc().getBeginLoc();
375 return SourceLocation();
378 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
379 /// with name 'PropertyId' in the primary class; including those in protocols
380 /// (direct or indirect) used by the primary class.
382 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
383 IdentifierInfo
*PropertyId
,
384 ObjCPropertyQueryKind QueryKind
) const {
385 // FIXME: Should make sure no callers ever do this.
386 if (!hasDefinition())
389 if (data().ExternallyCompleted
)
390 LoadExternalDefinition();
392 if (ObjCPropertyDecl
*PD
=
393 ObjCPropertyDecl::findPropertyDecl(cast
<DeclContext
>(this), PropertyId
,
397 // Look through protocols.
398 for (const auto *I
: all_referenced_protocols())
399 if (ObjCPropertyDecl
*P
= I
->FindPropertyDeclaration(PropertyId
,
406 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap
&PM
) const {
407 for (auto *Prop
: properties()) {
408 PM
[std::make_pair(Prop
->getIdentifier(), Prop
->isClassProperty())] = Prop
;
410 for (const auto *Ext
: known_extensions()) {
411 const ObjCCategoryDecl
*ClassExt
= Ext
;
412 for (auto *Prop
: ClassExt
->properties()) {
413 PM
[std::make_pair(Prop
->getIdentifier(), Prop
->isClassProperty())] = Prop
;
416 for (const auto *PI
: all_referenced_protocols())
417 PI
->collectPropertiesToImplement(PM
);
418 // Note, the properties declared only in class extensions are still copied
419 // into the main @interface's property list, and therefore we don't
420 // explicitly, have to search class extension properties.
423 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const {
424 const ObjCInterfaceDecl
*Class
= this;
426 if (Class
->hasAttr
<ArcWeakrefUnavailableAttr
>())
428 Class
= Class
->getSuperClass();
433 const ObjCInterfaceDecl
*ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const {
434 const ObjCInterfaceDecl
*Class
= this;
436 if (Class
->hasAttr
<ObjCRequiresPropertyDefsAttr
>())
438 Class
= Class
->getSuperClass();
443 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
444 ObjCProtocolDecl
*const* ExtList
, unsigned ExtNum
,
446 if (data().ExternallyCompleted
)
447 LoadExternalDefinition();
449 if (data().AllReferencedProtocols
.empty() &&
450 data().ReferencedProtocols
.empty()) {
451 data().AllReferencedProtocols
.set(ExtList
, ExtNum
, C
);
455 // Check for duplicate protocol in class's protocol list.
456 // This is O(n*m). But it is extremely rare and number of protocols in
457 // class or its extension are very few.
458 SmallVector
<ObjCProtocolDecl
*, 8> ProtocolRefs
;
459 for (unsigned i
= 0; i
< ExtNum
; i
++) {
460 bool protocolExists
= false;
461 ObjCProtocolDecl
*ProtoInExtension
= ExtList
[i
];
462 for (auto *Proto
: all_referenced_protocols()) {
463 if (C
.ProtocolCompatibleWithProtocol(ProtoInExtension
, Proto
)) {
464 protocolExists
= true;
468 // Do we want to warn on a protocol in extension class which
469 // already exist in the class? Probably not.
471 ProtocolRefs
.push_back(ProtoInExtension
);
474 if (ProtocolRefs
.empty())
477 // Merge ProtocolRefs into class's protocol list;
478 ProtocolRefs
.append(all_referenced_protocol_begin(),
479 all_referenced_protocol_end());
481 data().AllReferencedProtocols
.set(ProtocolRefs
.data(), ProtocolRefs
.size(),C
);
484 const ObjCInterfaceDecl
*
485 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const {
486 const ObjCInterfaceDecl
*IFace
= this;
488 if (IFace
->hasDesignatedInitializers())
490 if (!IFace
->inheritsDesignatedInitializers())
492 IFace
= IFace
->getSuperClass();
497 static bool isIntroducingInitializers(const ObjCInterfaceDecl
*D
) {
498 for (const auto *MD
: D
->instance_methods()) {
499 if (MD
->getMethodFamily() == OMF_init
&& !MD
->isOverriding())
502 for (const auto *Ext
: D
->visible_extensions()) {
503 for (const auto *MD
: Ext
->instance_methods()) {
504 if (MD
->getMethodFamily() == OMF_init
&& !MD
->isOverriding())
508 if (const auto *ImplD
= D
->getImplementation()) {
509 for (const auto *MD
: ImplD
->instance_methods()) {
510 if (MD
->getMethodFamily() == OMF_init
&& !MD
->isOverriding())
517 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const {
518 switch (data().InheritedDesignatedInitializers
) {
519 case DefinitionData::IDI_Inherited
:
521 case DefinitionData::IDI_NotInherited
:
523 case DefinitionData::IDI_Unknown
:
524 // If the class introduced initializers we conservatively assume that we
525 // don't know if any of them is a designated initializer to avoid possible
526 // misleading warnings.
527 if (isIntroducingInitializers(this)) {
528 data().InheritedDesignatedInitializers
= DefinitionData::IDI_NotInherited
;
530 if (auto SuperD
= getSuperClass()) {
531 data().InheritedDesignatedInitializers
=
532 SuperD
->declaresOrInheritsDesignatedInitializers() ?
533 DefinitionData::IDI_Inherited
:
534 DefinitionData::IDI_NotInherited
;
536 data().InheritedDesignatedInitializers
=
537 DefinitionData::IDI_NotInherited
;
540 assert(data().InheritedDesignatedInitializers
541 != DefinitionData::IDI_Unknown
);
542 return data().InheritedDesignatedInitializers
==
543 DefinitionData::IDI_Inherited
;
546 llvm_unreachable("unexpected InheritedDesignatedInitializers value");
549 void ObjCInterfaceDecl::getDesignatedInitializers(
550 llvm::SmallVectorImpl
<const ObjCMethodDecl
*> &Methods
) const {
551 // Check for a complete definition and recover if not so.
552 if (!isThisDeclarationADefinition())
554 if (data().ExternallyCompleted
)
555 LoadExternalDefinition();
557 const ObjCInterfaceDecl
*IFace
= findInterfaceWithDesignatedInitializers();
561 for (const auto *MD
: IFace
->instance_methods())
562 if (MD
->isThisDeclarationADesignatedInitializer())
563 Methods
.push_back(MD
);
564 for (const auto *Ext
: IFace
->visible_extensions()) {
565 for (const auto *MD
: Ext
->instance_methods())
566 if (MD
->isThisDeclarationADesignatedInitializer())
567 Methods
.push_back(MD
);
571 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel
,
572 const ObjCMethodDecl
**InitMethod
) const {
573 bool HasCompleteDef
= isThisDeclarationADefinition();
574 // During deserialization the data record for the ObjCInterfaceDecl could
575 // be made invariant by reusing the canonical decl. Take this into account
576 // when checking for the complete definition.
577 if (!HasCompleteDef
&& getCanonicalDecl()->hasDefinition() &&
578 getCanonicalDecl()->getDefinition() == getDefinition())
579 HasCompleteDef
= true;
581 // Check for a complete definition and recover if not so.
585 if (data().ExternallyCompleted
)
586 LoadExternalDefinition();
588 const ObjCInterfaceDecl
*IFace
= findInterfaceWithDesignatedInitializers();
592 if (const ObjCMethodDecl
*MD
= IFace
->getInstanceMethod(Sel
)) {
593 if (MD
->isThisDeclarationADesignatedInitializer()) {
599 for (const auto *Ext
: IFace
->visible_extensions()) {
600 if (const ObjCMethodDecl
*MD
= Ext
->getInstanceMethod(Sel
)) {
601 if (MD
->isThisDeclarationADesignatedInitializer()) {
611 void ObjCInterfaceDecl::allocateDefinitionData() {
612 assert(!hasDefinition() && "ObjC class already has a definition");
613 Data
.setPointer(new (getASTContext()) DefinitionData());
614 Data
.getPointer()->Definition
= this;
617 void ObjCInterfaceDecl::startDefinition() {
618 allocateDefinitionData();
620 // Update all of the declarations with a pointer to the definition.
621 for (auto *RD
: redecls()) {
627 void ObjCInterfaceDecl::startDuplicateDefinitionForComparison() {
628 Data
.setPointer(nullptr);
629 allocateDefinitionData();
630 // Don't propagate data to other redeclarations.
633 void ObjCInterfaceDecl::mergeDuplicateDefinitionWithCommon(
634 const ObjCInterfaceDecl
*Definition
) {
635 Data
= Definition
->Data
;
638 ObjCIvarDecl
*ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo
*ID
,
639 ObjCInterfaceDecl
*&clsDeclared
) {
640 // FIXME: Should make sure no callers ever do this.
641 if (!hasDefinition())
644 if (data().ExternallyCompleted
)
645 LoadExternalDefinition();
647 ObjCInterfaceDecl
* ClassDecl
= this;
648 while (ClassDecl
!= nullptr) {
649 if (ObjCIvarDecl
*I
= ClassDecl
->getIvarDecl(ID
)) {
650 clsDeclared
= ClassDecl
;
654 for (const auto *Ext
: ClassDecl
->visible_extensions()) {
655 if (ObjCIvarDecl
*I
= Ext
->getIvarDecl(ID
)) {
656 clsDeclared
= ClassDecl
;
661 ClassDecl
= ClassDecl
->getSuperClass();
666 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
667 /// class whose name is passed as argument. If it is not one of the super classes
668 /// the it returns NULL.
669 ObjCInterfaceDecl
*ObjCInterfaceDecl::lookupInheritedClass(
670 const IdentifierInfo
*ICName
) {
671 // FIXME: Should make sure no callers ever do this.
672 if (!hasDefinition())
675 if (data().ExternallyCompleted
)
676 LoadExternalDefinition();
678 ObjCInterfaceDecl
* ClassDecl
= this;
679 while (ClassDecl
!= nullptr) {
680 if (ClassDecl
->getIdentifier() == ICName
)
682 ClassDecl
= ClassDecl
->getSuperClass();
688 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo
*Name
) {
689 for (auto *P
: all_referenced_protocols())
690 if (P
->lookupProtocolNamed(Name
))
692 ObjCInterfaceDecl
*SuperClass
= getSuperClass();
693 return SuperClass
? SuperClass
->lookupNestedProtocol(Name
) : nullptr;
696 /// lookupMethod - This method returns an instance/class method by looking in
697 /// the class, its categories, and its super classes (using a linear search).
698 /// When argument category "C" is specified, any implicit method found
699 /// in this category is ignored.
700 ObjCMethodDecl
*ObjCInterfaceDecl::lookupMethod(Selector Sel
,
702 bool shallowCategoryLookup
,
704 const ObjCCategoryDecl
*C
) const
706 // FIXME: Should make sure no callers ever do this.
707 if (!hasDefinition())
710 const ObjCInterfaceDecl
* ClassDecl
= this;
711 ObjCMethodDecl
*MethodDecl
= nullptr;
713 if (data().ExternallyCompleted
)
714 LoadExternalDefinition();
717 // 1. Look through primary class.
718 if ((MethodDecl
= ClassDecl
->getMethod(Sel
, isInstance
)))
721 // 2. Didn't find one yet - now look through categories.
722 for (const auto *Cat
: ClassDecl
->visible_categories())
723 if ((MethodDecl
= Cat
->getMethod(Sel
, isInstance
)))
724 if (C
!= Cat
|| !MethodDecl
->isImplicit())
727 // 3. Didn't find one yet - look through primary class's protocols.
728 for (const auto *I
: ClassDecl
->protocols())
729 if ((MethodDecl
= I
->lookupMethod(Sel
, isInstance
)))
732 // 4. Didn't find one yet - now look through categories' protocols
733 if (!shallowCategoryLookup
)
734 for (const auto *Cat
: ClassDecl
->visible_categories()) {
735 // Didn't find one yet - look through protocols.
736 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
737 Cat
->getReferencedProtocols();
738 for (auto *Protocol
: Protocols
)
739 if ((MethodDecl
= Protocol
->lookupMethod(Sel
, isInstance
)))
740 if (C
!= Cat
|| !MethodDecl
->isImplicit())
748 // 5. Get to the super class (if any).
749 ClassDecl
= ClassDecl
->getSuperClass();
754 // Will search "local" class/category implementations for a method decl.
755 // If failed, then we search in class's root for an instance method.
756 // Returns 0 if no method is found.
757 ObjCMethodDecl
*ObjCInterfaceDecl::lookupPrivateMethod(
759 bool Instance
) const {
760 // FIXME: Should make sure no callers ever do this.
761 if (!hasDefinition())
764 if (data().ExternallyCompleted
)
765 LoadExternalDefinition();
767 ObjCMethodDecl
*Method
= nullptr;
768 if (ObjCImplementationDecl
*ImpDecl
= getImplementation())
769 Method
= Instance
? ImpDecl
->getInstanceMethod(Sel
)
770 : ImpDecl
->getClassMethod(Sel
);
772 // Look through local category implementations associated with the class.
774 Method
= getCategoryMethod(Sel
, Instance
);
776 // Before we give up, check if the selector is an instance method.
777 // But only in the root. This matches gcc's behavior and what the
779 if (!Instance
&& !Method
&& !getSuperClass()) {
780 Method
= lookupInstanceMethod(Sel
);
781 // Look through local category implementations associated
782 // with the root class.
784 Method
= lookupPrivateMethod(Sel
, true);
787 if (!Method
&& getSuperClass())
788 return getSuperClass()->lookupPrivateMethod(Sel
, Instance
);
792 unsigned ObjCInterfaceDecl::getODRHash() {
793 assert(hasDefinition() && "ODRHash only for records with definitions");
795 // Previously calculated hash is stored in DefinitionData.
797 return data().ODRHash
;
799 // Only calculate hash on first call of getODRHash per record.
801 Hasher
.AddObjCInterfaceDecl(getDefinition());
802 data().ODRHash
= Hasher
.CalculateHash();
805 return data().ODRHash
;
808 bool ObjCInterfaceDecl::hasODRHash() const {
809 if (!hasDefinition())
811 return data().HasODRHash
;
814 void ObjCInterfaceDecl::setHasODRHash(bool HasHash
) {
815 assert(hasDefinition() && "Cannot set ODRHash without definition");
816 data().HasODRHash
= HasHash
;
819 //===----------------------------------------------------------------------===//
821 //===----------------------------------------------------------------------===//
823 ObjCMethodDecl::ObjCMethodDecl(
824 SourceLocation beginLoc
, SourceLocation endLoc
, Selector SelInfo
,
825 QualType T
, TypeSourceInfo
*ReturnTInfo
, DeclContext
*contextDecl
,
826 bool isInstance
, bool isVariadic
, bool isPropertyAccessor
,
827 bool isSynthesizedAccessorStub
, bool isImplicitlyDeclared
, bool isDefined
,
828 ObjCImplementationControl impControl
, bool HasRelatedResultType
)
829 : NamedDecl(ObjCMethod
, contextDecl
, beginLoc
, SelInfo
),
830 DeclContext(ObjCMethod
), MethodDeclType(T
), ReturnTInfo(ReturnTInfo
),
833 // Initialized the bits stored in DeclContext.
834 ObjCMethodDeclBits
.Family
=
835 static_cast<ObjCMethodFamily
>(InvalidObjCMethodFamily
);
836 setInstanceMethod(isInstance
);
837 setVariadic(isVariadic
);
838 setPropertyAccessor(isPropertyAccessor
);
839 setSynthesizedAccessorStub(isSynthesizedAccessorStub
);
840 setDefined(isDefined
);
841 setIsRedeclaration(false);
842 setHasRedeclaration(false);
843 setDeclImplementation(impControl
);
844 setObjCDeclQualifier(OBJC_TQ_None
);
845 setRelatedResultType(HasRelatedResultType
);
846 setSelLocsKind(SelLoc_StandardNoSpace
);
847 setOverriding(false);
848 setHasSkippedBody(false);
850 setImplicit(isImplicitlyDeclared
);
853 ObjCMethodDecl
*ObjCMethodDecl::Create(
854 ASTContext
&C
, SourceLocation beginLoc
, SourceLocation endLoc
,
855 Selector SelInfo
, QualType T
, TypeSourceInfo
*ReturnTInfo
,
856 DeclContext
*contextDecl
, bool isInstance
, bool isVariadic
,
857 bool isPropertyAccessor
, bool isSynthesizedAccessorStub
,
858 bool isImplicitlyDeclared
, bool isDefined
,
859 ObjCImplementationControl impControl
, bool HasRelatedResultType
) {
860 return new (C
, contextDecl
) ObjCMethodDecl(
861 beginLoc
, endLoc
, SelInfo
, T
, ReturnTInfo
, contextDecl
, isInstance
,
862 isVariadic
, isPropertyAccessor
, isSynthesizedAccessorStub
,
863 isImplicitlyDeclared
, isDefined
, impControl
, HasRelatedResultType
);
866 ObjCMethodDecl
*ObjCMethodDecl::CreateDeserialized(ASTContext
&C
, unsigned ID
) {
867 return new (C
, ID
) ObjCMethodDecl(SourceLocation(), SourceLocation(),
868 Selector(), QualType(), nullptr, nullptr);
871 bool ObjCMethodDecl::isDirectMethod() const {
872 return hasAttr
<ObjCDirectAttr
>() &&
873 !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting
;
876 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const {
877 return getMethodFamily() == OMF_init
&&
878 hasAttr
<ObjCDesignatedInitializerAttr
>();
881 bool ObjCMethodDecl::definedInNSObject(const ASTContext
&Ctx
) const {
882 if (const auto *PD
= dyn_cast
<const ObjCProtocolDecl
>(getDeclContext()))
883 return PD
->getIdentifier() == Ctx
.getNSObjectName();
884 if (const auto *ID
= dyn_cast
<const ObjCInterfaceDecl
>(getDeclContext()))
885 return ID
->getIdentifier() == Ctx
.getNSObjectName();
889 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface(
890 const ObjCMethodDecl
**InitMethod
) const {
891 if (getMethodFamily() != OMF_init
)
893 const DeclContext
*DC
= getDeclContext();
894 if (isa
<ObjCProtocolDecl
>(DC
))
896 if (const ObjCInterfaceDecl
*ID
= getClassInterface())
897 return ID
->isDesignatedInitializer(getSelector(), InitMethod
);
901 bool ObjCMethodDecl::hasParamDestroyedInCallee() const {
902 for (auto *param
: parameters()) {
903 if (param
->isDestroyedInCallee())
909 Stmt
*ObjCMethodDecl::getBody() const {
910 return Body
.get(getASTContext().getExternalSource());
913 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl
*PrevMethod
) {
915 getASTContext().setObjCMethodRedeclaration(PrevMethod
, this);
916 setIsRedeclaration(true);
917 PrevMethod
->setHasRedeclaration(true);
920 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext
&C
,
921 ArrayRef
<ParmVarDecl
*> Params
,
922 ArrayRef
<SourceLocation
> SelLocs
) {
923 ParamsAndSelLocs
= nullptr;
924 NumParams
= Params
.size();
925 if (Params
.empty() && SelLocs
.empty())
928 static_assert(alignof(ParmVarDecl
*) >= alignof(SourceLocation
),
929 "Alignment not sufficient for SourceLocation");
931 unsigned Size
= sizeof(ParmVarDecl
*) * NumParams
+
932 sizeof(SourceLocation
) * SelLocs
.size();
933 ParamsAndSelLocs
= C
.Allocate(Size
);
934 std::uninitialized_copy(Params
.begin(), Params
.end(), getParams());
935 std::uninitialized_copy(SelLocs
.begin(), SelLocs
.end(), getStoredSelLocs());
938 void ObjCMethodDecl::getSelectorLocs(
939 SmallVectorImpl
<SourceLocation
> &SelLocs
) const {
940 for (unsigned i
= 0, e
= getNumSelectorLocs(); i
!= e
; ++i
)
941 SelLocs
.push_back(getSelectorLoc(i
));
944 void ObjCMethodDecl::setMethodParams(ASTContext
&C
,
945 ArrayRef
<ParmVarDecl
*> Params
,
946 ArrayRef
<SourceLocation
> SelLocs
) {
947 assert((!SelLocs
.empty() || isImplicit()) &&
948 "No selector locs for non-implicit method");
950 return setParamsAndSelLocs(C
, Params
, std::nullopt
);
952 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs
, Params
,
954 if (getSelLocsKind() != SelLoc_NonStandard
)
955 return setParamsAndSelLocs(C
, Params
, std::nullopt
);
957 setParamsAndSelLocs(C
, Params
, SelLocs
);
960 /// A definition will return its interface declaration.
961 /// An interface declaration will return its definition.
962 /// Otherwise it will return itself.
963 ObjCMethodDecl
*ObjCMethodDecl::getNextRedeclarationImpl() {
964 ASTContext
&Ctx
= getASTContext();
965 ObjCMethodDecl
*Redecl
= nullptr;
966 if (hasRedeclaration())
967 Redecl
= const_cast<ObjCMethodDecl
*>(Ctx
.getObjCMethodRedeclaration(this));
971 auto *CtxD
= cast
<Decl
>(getDeclContext());
973 if (!CtxD
->isInvalidDecl()) {
974 if (auto *IFD
= dyn_cast
<ObjCInterfaceDecl
>(CtxD
)) {
975 if (ObjCImplementationDecl
*ImplD
= Ctx
.getObjCImplementation(IFD
))
976 if (!ImplD
->isInvalidDecl())
977 Redecl
= ImplD
->getMethod(getSelector(), isInstanceMethod());
979 } else if (auto *CD
= dyn_cast
<ObjCCategoryDecl
>(CtxD
)) {
980 if (ObjCCategoryImplDecl
*ImplD
= Ctx
.getObjCImplementation(CD
))
981 if (!ImplD
->isInvalidDecl())
982 Redecl
= ImplD
->getMethod(getSelector(), isInstanceMethod());
984 } else if (auto *ImplD
= dyn_cast
<ObjCImplementationDecl
>(CtxD
)) {
985 if (ObjCInterfaceDecl
*IFD
= ImplD
->getClassInterface())
986 if (!IFD
->isInvalidDecl())
987 Redecl
= IFD
->getMethod(getSelector(), isInstanceMethod());
989 } else if (auto *CImplD
= dyn_cast
<ObjCCategoryImplDecl
>(CtxD
)) {
990 if (ObjCCategoryDecl
*CatD
= CImplD
->getCategoryDecl())
991 if (!CatD
->isInvalidDecl())
992 Redecl
= CatD
->getMethod(getSelector(), isInstanceMethod());
996 // Ensure that the discovered method redeclaration has a valid declaration
997 // context. Used to prevent infinite loops when iterating redeclarations in
998 // a partially invalid AST.
999 if (Redecl
&& cast
<Decl
>(Redecl
->getDeclContext())->isInvalidDecl())
1002 if (!Redecl
&& isRedeclaration()) {
1003 // This is the last redeclaration, go back to the first method.
1004 return cast
<ObjCContainerDecl
>(CtxD
)->getMethod(getSelector(),
1006 /*AllowHidden=*/true);
1009 return Redecl
? Redecl
: this;
1012 ObjCMethodDecl
*ObjCMethodDecl::getCanonicalDecl() {
1013 auto *CtxD
= cast
<Decl
>(getDeclContext());
1014 const auto &Sel
= getSelector();
1016 if (auto *ImplD
= dyn_cast
<ObjCImplementationDecl
>(CtxD
)) {
1017 if (ObjCInterfaceDecl
*IFD
= ImplD
->getClassInterface()) {
1018 // When the container is the ObjCImplementationDecl (the primary
1019 // @implementation), then the canonical Decl is either in
1020 // the class Interface, or in any of its extension.
1022 // So when we don't find it in the ObjCInterfaceDecl,
1023 // sift through extensions too.
1024 if (ObjCMethodDecl
*MD
= IFD
->getMethod(Sel
, isInstanceMethod()))
1026 for (auto *Ext
: IFD
->known_extensions())
1027 if (ObjCMethodDecl
*MD
= Ext
->getMethod(Sel
, isInstanceMethod()))
1030 } else if (auto *CImplD
= dyn_cast
<ObjCCategoryImplDecl
>(CtxD
)) {
1031 if (ObjCCategoryDecl
*CatD
= CImplD
->getCategoryDecl())
1032 if (ObjCMethodDecl
*MD
= CatD
->getMethod(Sel
, isInstanceMethod()))
1036 if (isRedeclaration()) {
1037 // It is possible that we have not done deserializing the ObjCMethod yet.
1038 ObjCMethodDecl
*MD
=
1039 cast
<ObjCContainerDecl
>(CtxD
)->getMethod(Sel
, isInstanceMethod(),
1040 /*AllowHidden=*/true);
1041 return MD
? MD
: this;
1047 SourceLocation
ObjCMethodDecl::getEndLoc() const {
1048 if (Stmt
*Body
= getBody())
1049 return Body
->getEndLoc();
1053 ObjCMethodFamily
ObjCMethodDecl::getMethodFamily() const {
1054 auto family
= static_cast<ObjCMethodFamily
>(ObjCMethodDeclBits
.Family
);
1055 if (family
!= static_cast<unsigned>(InvalidObjCMethodFamily
))
1058 // Check for an explicit attribute.
1059 if (const ObjCMethodFamilyAttr
*attr
= getAttr
<ObjCMethodFamilyAttr
>()) {
1060 // The unfortunate necessity of mapping between enums here is due
1061 // to the attributes framework.
1062 switch (attr
->getFamily()) {
1063 case ObjCMethodFamilyAttr::OMF_None
: family
= OMF_None
; break;
1064 case ObjCMethodFamilyAttr::OMF_alloc
: family
= OMF_alloc
; break;
1065 case ObjCMethodFamilyAttr::OMF_copy
: family
= OMF_copy
; break;
1066 case ObjCMethodFamilyAttr::OMF_init
: family
= OMF_init
; break;
1067 case ObjCMethodFamilyAttr::OMF_mutableCopy
: family
= OMF_mutableCopy
; break;
1068 case ObjCMethodFamilyAttr::OMF_new
: family
= OMF_new
; break;
1070 ObjCMethodDeclBits
.Family
= family
;
1074 family
= getSelector().getMethodFamily();
1076 case OMF_None
: break;
1078 // init only has a conventional meaning for an instance method, and
1079 // it has to return an object.
1081 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
1085 // alloc/copy/new have a conventional meaning for both class and
1086 // instance methods, but they require an object return.
1089 case OMF_mutableCopy
:
1091 if (!getReturnType()->isObjCObjectPointerType())
1095 // These selectors have a conventional meaning only for instance methods.
1100 case OMF_autorelease
:
1101 case OMF_retainCount
:
1103 if (!isInstanceMethod())
1107 case OMF_initialize
:
1108 if (isInstanceMethod() || !getReturnType()->isVoidType())
1112 case OMF_performSelector
:
1113 if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
1116 unsigned noParams
= param_size();
1117 if (noParams
< 1 || noParams
> 3)
1120 ObjCMethodDecl::param_type_iterator it
= param_type_begin();
1121 QualType ArgT
= (*it
);
1122 if (!ArgT
->isObjCSelType()) {
1126 while (--noParams
) {
1129 if (!ArgT
->isObjCIdType()) {
1140 // Cache the result.
1141 ObjCMethodDeclBits
.Family
= family
;
1145 QualType
ObjCMethodDecl::getSelfType(ASTContext
&Context
,
1146 const ObjCInterfaceDecl
*OID
,
1147 bool &selfIsPseudoStrong
,
1148 bool &selfIsConsumed
) const {
1150 selfIsPseudoStrong
= false;
1151 selfIsConsumed
= false;
1152 if (isInstanceMethod()) {
1153 // There may be no interface context due to error in declaration
1154 // of the interface (which has been reported). Recover gracefully.
1156 selfTy
= Context
.getObjCInterfaceType(OID
);
1157 selfTy
= Context
.getObjCObjectPointerType(selfTy
);
1159 selfTy
= Context
.getObjCIdType();
1161 } else // we have a factory method.
1162 selfTy
= Context
.getObjCClassType();
1164 if (Context
.getLangOpts().ObjCAutoRefCount
) {
1165 if (isInstanceMethod()) {
1166 selfIsConsumed
= hasAttr
<NSConsumesSelfAttr
>();
1168 // 'self' is always __strong. It's actually pseudo-strong except
1169 // in init methods (or methods labeled ns_consumes_self), though.
1171 qs
.setObjCLifetime(Qualifiers::OCL_Strong
);
1172 selfTy
= Context
.getQualifiedType(selfTy
, qs
);
1174 // In addition, 'self' is const unless this is an init method.
1175 if (getMethodFamily() != OMF_init
&& !selfIsConsumed
) {
1176 selfTy
= selfTy
.withConst();
1177 selfIsPseudoStrong
= true;
1181 assert(isClassMethod());
1182 // 'self' is always const in class methods.
1183 selfTy
= selfTy
.withConst();
1184 selfIsPseudoStrong
= true;
1190 void ObjCMethodDecl::createImplicitParams(ASTContext
&Context
,
1191 const ObjCInterfaceDecl
*OID
) {
1192 bool selfIsPseudoStrong
, selfIsConsumed
;
1194 getSelfType(Context
, OID
, selfIsPseudoStrong
, selfIsConsumed
);
1195 auto *Self
= ImplicitParamDecl::Create(Context
, this, SourceLocation(),
1196 &Context
.Idents
.get("self"), selfTy
,
1197 ImplicitParamDecl::ObjCSelf
);
1201 Self
->addAttr(NSConsumedAttr::CreateImplicit(Context
));
1203 if (selfIsPseudoStrong
)
1204 Self
->setARCPseudoStrong(true);
1206 setCmdDecl(ImplicitParamDecl::Create(
1207 Context
, this, SourceLocation(), &Context
.Idents
.get("_cmd"),
1208 Context
.getObjCSelType(), ImplicitParamDecl::ObjCCmd
));
1211 ObjCInterfaceDecl
*ObjCMethodDecl::getClassInterface() {
1212 if (auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(getDeclContext()))
1214 if (auto *CD
= dyn_cast
<ObjCCategoryDecl
>(getDeclContext()))
1215 return CD
->getClassInterface();
1216 if (auto *IMD
= dyn_cast
<ObjCImplDecl
>(getDeclContext()))
1217 return IMD
->getClassInterface();
1218 if (isa
<ObjCProtocolDecl
>(getDeclContext()))
1220 llvm_unreachable("unknown method context");
1223 ObjCCategoryDecl
*ObjCMethodDecl::getCategory() {
1224 if (auto *CD
= dyn_cast
<ObjCCategoryDecl
>(getDeclContext()))
1226 if (auto *IMD
= dyn_cast
<ObjCCategoryImplDecl
>(getDeclContext()))
1227 return IMD
->getCategoryDecl();
1231 SourceRange
ObjCMethodDecl::getReturnTypeSourceRange() const {
1232 const auto *TSI
= getReturnTypeSourceInfo();
1234 return TSI
->getTypeLoc().getSourceRange();
1235 return SourceRange();
1238 QualType
ObjCMethodDecl::getSendResultType() const {
1239 ASTContext
&Ctx
= getASTContext();
1240 return getReturnType().getNonLValueExprType(Ctx
)
1241 .substObjCTypeArgs(Ctx
, {}, ObjCSubstitutionContext::Result
);
1244 QualType
ObjCMethodDecl::getSendResultType(QualType receiverType
) const {
1245 // FIXME: Handle related result types here.
1247 return getReturnType().getNonLValueExprType(getASTContext())
1248 .substObjCMemberType(receiverType
, getDeclContext(),
1249 ObjCSubstitutionContext::Result
);
1252 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl
*Container
,
1253 const ObjCMethodDecl
*Method
,
1254 SmallVectorImpl
<const ObjCMethodDecl
*> &Methods
,
1255 bool MovedToSuper
) {
1259 // In categories look for overridden methods from protocols. A method from
1260 // category is not "overridden" since it is considered as the "same" method
1261 // (same USR) as the one from the interface.
1262 if (const auto *Category
= dyn_cast
<ObjCCategoryDecl
>(Container
)) {
1263 // Check whether we have a matching method at this category but only if we
1264 // are at the super class level.
1266 if (ObjCMethodDecl
*
1267 Overridden
= Container
->getMethod(Method
->getSelector(),
1268 Method
->isInstanceMethod(),
1269 /*AllowHidden=*/true))
1270 if (Method
!= Overridden
) {
1271 // We found an override at this category; there is no need to look
1272 // into its protocols.
1273 Methods
.push_back(Overridden
);
1277 for (const auto *P
: Category
->protocols())
1278 CollectOverriddenMethodsRecurse(P
, Method
, Methods
, MovedToSuper
);
1282 // Check whether we have a matching method at this level.
1283 if (const ObjCMethodDecl
*
1284 Overridden
= Container
->getMethod(Method
->getSelector(),
1285 Method
->isInstanceMethod(),
1286 /*AllowHidden=*/true))
1287 if (Method
!= Overridden
) {
1288 // We found an override at this level; there is no need to look
1289 // into other protocols or categories.
1290 Methods
.push_back(Overridden
);
1294 if (const auto *Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)){
1295 for (const auto *P
: Protocol
->protocols())
1296 CollectOverriddenMethodsRecurse(P
, Method
, Methods
, MovedToSuper
);
1299 if (const auto *Interface
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
1300 for (const auto *P
: Interface
->protocols())
1301 CollectOverriddenMethodsRecurse(P
, Method
, Methods
, MovedToSuper
);
1303 for (const auto *Cat
: Interface
->known_categories())
1304 CollectOverriddenMethodsRecurse(Cat
, Method
, Methods
, MovedToSuper
);
1306 if (const ObjCInterfaceDecl
*Super
= Interface
->getSuperClass())
1307 return CollectOverriddenMethodsRecurse(Super
, Method
, Methods
,
1308 /*MovedToSuper=*/true);
1312 static inline void CollectOverriddenMethods(const ObjCContainerDecl
*Container
,
1313 const ObjCMethodDecl
*Method
,
1314 SmallVectorImpl
<const ObjCMethodDecl
*> &Methods
) {
1315 CollectOverriddenMethodsRecurse(Container
, Method
, Methods
,
1316 /*MovedToSuper=*/false);
1319 static void collectOverriddenMethodsSlow(const ObjCMethodDecl
*Method
,
1320 SmallVectorImpl
<const ObjCMethodDecl
*> &overridden
) {
1321 assert(Method
->isOverriding());
1323 if (const auto *ProtD
=
1324 dyn_cast
<ObjCProtocolDecl
>(Method
->getDeclContext())) {
1325 CollectOverriddenMethods(ProtD
, Method
, overridden
);
1327 } else if (const auto *IMD
=
1328 dyn_cast
<ObjCImplDecl
>(Method
->getDeclContext())) {
1329 const ObjCInterfaceDecl
*ID
= IMD
->getClassInterface();
1332 // Start searching for overridden methods using the method from the
1333 // interface as starting point.
1334 if (const ObjCMethodDecl
*IFaceMeth
= ID
->getMethod(Method
->getSelector(),
1335 Method
->isInstanceMethod(),
1336 /*AllowHidden=*/true))
1338 CollectOverriddenMethods(ID
, Method
, overridden
);
1340 } else if (const auto *CatD
=
1341 dyn_cast
<ObjCCategoryDecl
>(Method
->getDeclContext())) {
1342 const ObjCInterfaceDecl
*ID
= CatD
->getClassInterface();
1345 // Start searching for overridden methods using the method from the
1346 // interface as starting point.
1347 if (const ObjCMethodDecl
*IFaceMeth
= ID
->getMethod(Method
->getSelector(),
1348 Method
->isInstanceMethod(),
1349 /*AllowHidden=*/true))
1351 CollectOverriddenMethods(ID
, Method
, overridden
);
1354 CollectOverriddenMethods(
1355 dyn_cast_or_null
<ObjCContainerDecl
>(Method
->getDeclContext()),
1356 Method
, overridden
);
1360 void ObjCMethodDecl::getOverriddenMethods(
1361 SmallVectorImpl
<const ObjCMethodDecl
*> &Overridden
) const {
1362 const ObjCMethodDecl
*Method
= this;
1364 if (Method
->isRedeclaration()) {
1365 Method
= cast
<ObjCContainerDecl
>(Method
->getDeclContext())
1366 ->getMethod(Method
->getSelector(), Method
->isInstanceMethod(),
1367 /*AllowHidden=*/true);
1370 if (Method
->isOverriding()) {
1371 collectOverriddenMethodsSlow(Method
, Overridden
);
1372 assert(!Overridden
.empty() &&
1373 "ObjCMethodDecl's overriding bit is not as expected");
1377 const ObjCPropertyDecl
*
1378 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides
) const {
1379 Selector Sel
= getSelector();
1380 unsigned NumArgs
= Sel
.getNumArgs();
1384 if (isPropertyAccessor()) {
1385 const auto *Container
= cast
<ObjCContainerDecl
>(getParent());
1386 // For accessor stubs, go back to the interface.
1387 if (auto *ImplDecl
= dyn_cast
<ObjCImplDecl
>(Container
))
1388 if (isSynthesizedAccessorStub())
1389 Container
= ImplDecl
->getClassInterface();
1391 bool IsGetter
= (NumArgs
== 0);
1392 bool IsInstance
= isInstanceMethod();
1394 /// Local function that attempts to find a matching property within the
1395 /// given Objective-C container.
1396 auto findMatchingProperty
=
1397 [&](const ObjCContainerDecl
*Container
) -> const ObjCPropertyDecl
* {
1399 for (const auto *I
: Container
->instance_properties()) {
1400 Selector NextSel
= IsGetter
? I
->getGetterName()
1401 : I
->getSetterName();
1406 for (const auto *I
: Container
->class_properties()) {
1407 Selector NextSel
= IsGetter
? I
->getGetterName()
1408 : I
->getSetterName();
1417 // Look in the container we were given.
1418 if (const auto *Found
= findMatchingProperty(Container
))
1421 // If we're in a category or extension, look in the main class.
1422 const ObjCInterfaceDecl
*ClassDecl
= nullptr;
1423 if (const auto *Category
= dyn_cast
<ObjCCategoryDecl
>(Container
)) {
1424 ClassDecl
= Category
->getClassInterface();
1425 if (const auto *Found
= findMatchingProperty(ClassDecl
))
1428 // Determine whether the container is a class.
1429 ClassDecl
= cast
<ObjCInterfaceDecl
>(Container
);
1431 assert(ClassDecl
&& "Failed to find main class");
1433 // If we have a class, check its visible extensions.
1434 for (const auto *Ext
: ClassDecl
->visible_extensions()) {
1435 if (Ext
== Container
)
1437 if (const auto *Found
= findMatchingProperty(Ext
))
1441 assert(isSynthesizedAccessorStub() && "expected an accessor stub");
1443 for (const auto *Cat
: ClassDecl
->known_categories()) {
1444 if (Cat
== Container
)
1446 if (const auto *Found
= findMatchingProperty(Cat
))
1450 llvm_unreachable("Marked as a property accessor but no property found!");
1453 if (!CheckOverrides
)
1456 using OverridesTy
= SmallVector
<const ObjCMethodDecl
*, 8>;
1458 OverridesTy Overrides
;
1459 getOverriddenMethods(Overrides
);
1460 for (const auto *Override
: Overrides
)
1461 if (const ObjCPropertyDecl
*Prop
= Override
->findPropertyDecl(false))
1467 //===----------------------------------------------------------------------===//
1468 // ObjCTypeParamDecl
1469 //===----------------------------------------------------------------------===//
1471 void ObjCTypeParamDecl::anchor() {}
1473 ObjCTypeParamDecl
*ObjCTypeParamDecl::Create(ASTContext
&ctx
, DeclContext
*dc
,
1474 ObjCTypeParamVariance variance
,
1475 SourceLocation varianceLoc
,
1477 SourceLocation nameLoc
,
1478 IdentifierInfo
*name
,
1479 SourceLocation colonLoc
,
1480 TypeSourceInfo
*boundInfo
) {
1482 new (ctx
, dc
) ObjCTypeParamDecl(ctx
, dc
, variance
, varianceLoc
, index
,
1483 nameLoc
, name
, colonLoc
, boundInfo
);
1484 QualType TPType
= ctx
.getObjCTypeParamType(TPDecl
, {});
1485 TPDecl
->setTypeForDecl(TPType
.getTypePtr());
1489 ObjCTypeParamDecl
*ObjCTypeParamDecl::CreateDeserialized(ASTContext
&ctx
,
1491 return new (ctx
, ID
) ObjCTypeParamDecl(ctx
, nullptr,
1492 ObjCTypeParamVariance::Invariant
,
1493 SourceLocation(), 0, SourceLocation(),
1494 nullptr, SourceLocation(), nullptr);
1497 SourceRange
ObjCTypeParamDecl::getSourceRange() const {
1498 SourceLocation startLoc
= VarianceLoc
;
1499 if (startLoc
.isInvalid())
1500 startLoc
= getLocation();
1502 if (hasExplicitBound()) {
1503 return SourceRange(startLoc
,
1504 getTypeSourceInfo()->getTypeLoc().getEndLoc());
1507 return SourceRange(startLoc
);
1510 //===----------------------------------------------------------------------===//
1511 // ObjCTypeParamList
1512 //===----------------------------------------------------------------------===//
1513 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc
,
1514 ArrayRef
<ObjCTypeParamDecl
*> typeParams
,
1515 SourceLocation rAngleLoc
)
1516 : Brackets(lAngleLoc
, rAngleLoc
), NumParams(typeParams
.size()) {
1517 std::copy(typeParams
.begin(), typeParams
.end(), begin());
1520 ObjCTypeParamList
*ObjCTypeParamList::create(
1522 SourceLocation lAngleLoc
,
1523 ArrayRef
<ObjCTypeParamDecl
*> typeParams
,
1524 SourceLocation rAngleLoc
) {
1526 ctx
.Allocate(totalSizeToAlloc
<ObjCTypeParamDecl
*>(typeParams
.size()),
1527 alignof(ObjCTypeParamList
));
1528 return new (mem
) ObjCTypeParamList(lAngleLoc
, typeParams
, rAngleLoc
);
1531 void ObjCTypeParamList::gatherDefaultTypeArgs(
1532 SmallVectorImpl
<QualType
> &typeArgs
) const {
1533 typeArgs
.reserve(size());
1534 for (auto *typeParam
: *this)
1535 typeArgs
.push_back(typeParam
->getUnderlyingType());
1538 //===----------------------------------------------------------------------===//
1539 // ObjCInterfaceDecl
1540 //===----------------------------------------------------------------------===//
1542 ObjCInterfaceDecl
*ObjCInterfaceDecl::Create(const ASTContext
&C
,
1544 SourceLocation atLoc
,
1546 ObjCTypeParamList
*typeParamList
,
1547 ObjCInterfaceDecl
*PrevDecl
,
1548 SourceLocation ClassLoc
,
1550 auto *Result
= new (C
, DC
)
1551 ObjCInterfaceDecl(C
, DC
, atLoc
, Id
, typeParamList
, ClassLoc
, PrevDecl
,
1553 Result
->Data
.setInt(!C
.getLangOpts().Modules
);
1554 C
.getObjCInterfaceType(Result
, PrevDecl
);
1558 ObjCInterfaceDecl
*ObjCInterfaceDecl::CreateDeserialized(const ASTContext
&C
,
1560 auto *Result
= new (C
, ID
)
1561 ObjCInterfaceDecl(C
, nullptr, SourceLocation(), nullptr, nullptr,
1562 SourceLocation(), nullptr, false);
1563 Result
->Data
.setInt(!C
.getLangOpts().Modules
);
1567 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext
&C
, DeclContext
*DC
,
1568 SourceLocation AtLoc
, IdentifierInfo
*Id
,
1569 ObjCTypeParamList
*typeParamList
,
1570 SourceLocation CLoc
,
1571 ObjCInterfaceDecl
*PrevDecl
,
1573 : ObjCContainerDecl(ObjCInterface
, DC
, Id
, CLoc
, AtLoc
),
1574 redeclarable_base(C
) {
1575 setPreviousDecl(PrevDecl
);
1577 // Copy the 'data' pointer over.
1579 Data
= PrevDecl
->Data
;
1581 setImplicit(IsInternal
);
1583 setTypeParamList(typeParamList
);
1586 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1587 assert(data().ExternallyCompleted
&& "Class is not externally completed");
1588 data().ExternallyCompleted
= false;
1589 getASTContext().getExternalSource()->CompleteType(
1590 const_cast<ObjCInterfaceDecl
*>(this));
1593 void ObjCInterfaceDecl::setExternallyCompleted() {
1594 assert(getASTContext().getExternalSource() &&
1595 "Class can't be externally completed without an external source");
1596 assert(hasDefinition() &&
1597 "Forward declarations can't be externally completed");
1598 data().ExternallyCompleted
= true;
1601 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1602 // Check for a complete definition and recover if not so.
1603 if (!isThisDeclarationADefinition())
1605 data().HasDesignatedInitializers
= true;
1608 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1609 // Check for a complete definition and recover if not so.
1610 if (!isThisDeclarationADefinition())
1612 if (data().ExternallyCompleted
)
1613 LoadExternalDefinition();
1615 return data().HasDesignatedInitializers
;
1619 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1620 if (const auto *ObjCRTName
= getAttr
<ObjCRuntimeNameAttr
>())
1621 return ObjCRTName
->getMetadataName();
1627 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1628 if (ObjCInterfaceDecl
*ID
=
1629 const_cast<ObjCImplementationDecl
*>(this)->getClassInterface())
1630 return ID
->getObjCRuntimeNameAsString();
1635 ObjCImplementationDecl
*ObjCInterfaceDecl::getImplementation() const {
1636 if (const ObjCInterfaceDecl
*Def
= getDefinition()) {
1637 if (data().ExternallyCompleted
)
1638 LoadExternalDefinition();
1640 return getASTContext().getObjCImplementation(
1641 const_cast<ObjCInterfaceDecl
*>(Def
));
1644 // FIXME: Should make sure no callers ever do this.
1648 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl
*ImplD
) {
1649 getASTContext().setObjCImplementation(getDefinition(), ImplD
);
1654 struct SynthesizeIvarChunk
{
1658 SynthesizeIvarChunk(uint64_t size
, ObjCIvarDecl
*ivar
)
1659 : Size(size
), Ivar(ivar
) {}
1662 bool operator<(const SynthesizeIvarChunk
& LHS
,
1663 const SynthesizeIvarChunk
&RHS
) {
1664 return LHS
.Size
< RHS
.Size
;
1669 /// all_declared_ivar_begin - return first ivar declared in this class,
1670 /// its extensions and its implementation. Lazily build the list on first
1673 /// Caveat: The list returned by this method reflects the current
1674 /// state of the parser. The cache will be updated for every ivar
1675 /// added by an extension or the implementation when they are
1677 /// See also ObjCIvarDecl::Create().
1678 ObjCIvarDecl
*ObjCInterfaceDecl::all_declared_ivar_begin() {
1679 // FIXME: Should make sure no callers ever do this.
1680 if (!hasDefinition())
1683 ObjCIvarDecl
*curIvar
= nullptr;
1684 if (!data().IvarList
) {
1685 // Force ivar deserialization upfront, before building IvarList.
1687 for (const auto *Ext
: known_extensions()) {
1688 (void)Ext
->ivar_empty();
1690 if (!ivar_empty()) {
1691 ObjCInterfaceDecl::ivar_iterator I
= ivar_begin(), E
= ivar_end();
1692 data().IvarList
= *I
; ++I
;
1693 for (curIvar
= data().IvarList
; I
!= E
; curIvar
= *I
, ++I
)
1694 curIvar
->setNextIvar(*I
);
1697 for (const auto *Ext
: known_extensions()) {
1698 if (!Ext
->ivar_empty()) {
1699 ObjCCategoryDecl::ivar_iterator
1700 I
= Ext
->ivar_begin(),
1701 E
= Ext
->ivar_end();
1702 if (!data().IvarList
) {
1703 data().IvarList
= *I
; ++I
;
1704 curIvar
= data().IvarList
;
1706 for ( ;I
!= E
; curIvar
= *I
, ++I
)
1707 curIvar
->setNextIvar(*I
);
1710 data().IvarListMissingImplementation
= true;
1713 // cached and complete!
1714 if (!data().IvarListMissingImplementation
)
1715 return data().IvarList
;
1717 if (ObjCImplementationDecl
*ImplDecl
= getImplementation()) {
1718 data().IvarListMissingImplementation
= false;
1719 if (!ImplDecl
->ivar_empty()) {
1720 SmallVector
<SynthesizeIvarChunk
, 16> layout
;
1721 for (auto *IV
: ImplDecl
->ivars()) {
1722 if (IV
->getSynthesize() && !IV
->isInvalidDecl()) {
1723 layout
.push_back(SynthesizeIvarChunk(
1724 IV
->getASTContext().getTypeSize(IV
->getType()), IV
));
1727 if (!data().IvarList
)
1728 data().IvarList
= IV
;
1730 curIvar
->setNextIvar(IV
);
1734 if (!layout
.empty()) {
1735 // Order synthesized ivars by their size.
1736 llvm::stable_sort(layout
);
1737 unsigned Ix
= 0, EIx
= layout
.size();
1738 if (!data().IvarList
) {
1739 data().IvarList
= layout
[0].Ivar
; Ix
++;
1740 curIvar
= data().IvarList
;
1742 for ( ; Ix
!= EIx
; curIvar
= layout
[Ix
].Ivar
, Ix
++)
1743 curIvar
->setNextIvar(layout
[Ix
].Ivar
);
1747 return data().IvarList
;
1750 /// FindCategoryDeclaration - Finds category declaration in the list of
1751 /// categories for this class and returns it. Name of the category is passed
1752 /// in 'CategoryId'. If category not found, return 0;
1755 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo
*CategoryId
) const {
1756 // FIXME: Should make sure no callers ever do this.
1757 if (!hasDefinition())
1760 if (data().ExternallyCompleted
)
1761 LoadExternalDefinition();
1763 for (auto *Cat
: visible_categories())
1764 if (Cat
->getIdentifier() == CategoryId
)
1771 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel
) const {
1772 for (const auto *Cat
: visible_categories()) {
1773 if (ObjCCategoryImplDecl
*Impl
= Cat
->getImplementation())
1774 if (ObjCMethodDecl
*MD
= Impl
->getInstanceMethod(Sel
))
1781 ObjCMethodDecl
*ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel
) const {
1782 for (const auto *Cat
: visible_categories()) {
1783 if (ObjCCategoryImplDecl
*Impl
= Cat
->getImplementation())
1784 if (ObjCMethodDecl
*MD
= Impl
->getClassMethod(Sel
))
1791 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1792 /// has been implemented in IDecl class, its super class or categories (if
1793 /// lookupCategory is true).
1794 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl
*lProto
,
1795 bool lookupCategory
,
1796 bool RHSIsQualifiedID
) {
1797 if (!hasDefinition())
1800 ObjCInterfaceDecl
*IDecl
= this;
1801 // 1st, look up the class.
1802 for (auto *PI
: IDecl
->protocols()){
1803 if (getASTContext().ProtocolCompatibleWithProtocol(lProto
, PI
))
1805 // This is dubious and is added to be compatible with gcc. In gcc, it is
1806 // also allowed assigning a protocol-qualified 'id' type to a LHS object
1807 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1808 // object. This IMO, should be a bug.
1809 // FIXME: Treat this as an extension, and flag this as an error when GCC
1810 // extensions are not enabled.
1811 if (RHSIsQualifiedID
&&
1812 getASTContext().ProtocolCompatibleWithProtocol(PI
, lProto
))
1816 // 2nd, look up the category.
1818 for (const auto *Cat
: visible_categories()) {
1819 for (auto *PI
: Cat
->protocols())
1820 if (getASTContext().ProtocolCompatibleWithProtocol(lProto
, PI
))
1824 // 3rd, look up the super class(s)
1825 if (IDecl
->getSuperClass())
1827 IDecl
->getSuperClass()->ClassImplementsProtocol(lProto
, lookupCategory
,
1833 //===----------------------------------------------------------------------===//
1835 //===----------------------------------------------------------------------===//
1837 void ObjCIvarDecl::anchor() {}
1839 ObjCIvarDecl
*ObjCIvarDecl::Create(ASTContext
&C
, ObjCContainerDecl
*DC
,
1840 SourceLocation StartLoc
,
1841 SourceLocation IdLoc
, IdentifierInfo
*Id
,
1842 QualType T
, TypeSourceInfo
*TInfo
,
1843 AccessControl ac
, Expr
*BW
,
1846 // Ivar's can only appear in interfaces, implementations (via synthesized
1847 // properties), and class extensions (via direct declaration, or synthesized
1850 // FIXME: This should really be asserting this:
1851 // (isa<ObjCCategoryDecl>(DC) &&
1852 // cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1853 // but unfortunately we sometimes place ivars into non-class extension
1854 // categories on error. This breaks an AST invariant, and should not be
1856 assert((isa
<ObjCInterfaceDecl
>(DC
) || isa
<ObjCImplementationDecl
>(DC
) ||
1857 isa
<ObjCCategoryDecl
>(DC
)) &&
1858 "Invalid ivar decl context!");
1859 // Once a new ivar is created in any of class/class-extension/implementation
1860 // decl contexts, the previously built IvarList must be rebuilt.
1861 auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(DC
);
1863 if (auto *IM
= dyn_cast
<ObjCImplementationDecl
>(DC
))
1864 ID
= IM
->getClassInterface();
1866 ID
= cast
<ObjCCategoryDecl
>(DC
)->getClassInterface();
1868 ID
->setIvarList(nullptr);
1871 return new (C
, DC
) ObjCIvarDecl(DC
, StartLoc
, IdLoc
, Id
, T
, TInfo
, ac
, BW
,
1875 ObjCIvarDecl
*ObjCIvarDecl::CreateDeserialized(ASTContext
&C
, unsigned ID
) {
1876 return new (C
, ID
) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1877 nullptr, QualType(), nullptr,
1878 ObjCIvarDecl::None
, nullptr, false);
1881 ObjCInterfaceDecl
*ObjCIvarDecl::getContainingInterface() {
1882 auto *DC
= cast
<ObjCContainerDecl
>(getDeclContext());
1884 switch (DC
->getKind()) {
1886 case ObjCCategoryImpl
:
1888 llvm_unreachable("invalid ivar container!");
1890 // Ivars can only appear in class extension categories.
1891 case ObjCCategory
: {
1892 auto *CD
= cast
<ObjCCategoryDecl
>(DC
);
1893 assert(CD
->IsClassExtension() && "invalid container for ivar!");
1894 return CD
->getClassInterface();
1897 case ObjCImplementation
:
1898 return cast
<ObjCImplementationDecl
>(DC
)->getClassInterface();
1901 return cast
<ObjCInterfaceDecl
>(DC
);
1905 QualType
ObjCIvarDecl::getUsageType(QualType objectType
) const {
1906 return getType().substObjCMemberType(objectType
, getDeclContext(),
1907 ObjCSubstitutionContext::Property
);
1910 //===----------------------------------------------------------------------===//
1911 // ObjCAtDefsFieldDecl
1912 //===----------------------------------------------------------------------===//
1914 void ObjCAtDefsFieldDecl::anchor() {}
1917 *ObjCAtDefsFieldDecl::Create(ASTContext
&C
, DeclContext
*DC
,
1918 SourceLocation StartLoc
, SourceLocation IdLoc
,
1919 IdentifierInfo
*Id
, QualType T
, Expr
*BW
) {
1920 return new (C
, DC
) ObjCAtDefsFieldDecl(DC
, StartLoc
, IdLoc
, Id
, T
, BW
);
1923 ObjCAtDefsFieldDecl
*ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext
&C
,
1925 return new (C
, ID
) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1926 SourceLocation(), nullptr, QualType(),
1930 //===----------------------------------------------------------------------===//
1932 //===----------------------------------------------------------------------===//
1934 void ObjCProtocolDecl::anchor() {}
1936 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext
&C
, DeclContext
*DC
,
1937 IdentifierInfo
*Id
, SourceLocation nameLoc
,
1938 SourceLocation atStartLoc
,
1939 ObjCProtocolDecl
*PrevDecl
)
1940 : ObjCContainerDecl(ObjCProtocol
, DC
, Id
, nameLoc
, atStartLoc
),
1941 redeclarable_base(C
) {
1942 setPreviousDecl(PrevDecl
);
1944 Data
= PrevDecl
->Data
;
1947 ObjCProtocolDecl
*ObjCProtocolDecl::Create(ASTContext
&C
, DeclContext
*DC
,
1949 SourceLocation nameLoc
,
1950 SourceLocation atStartLoc
,
1951 ObjCProtocolDecl
*PrevDecl
) {
1953 new (C
, DC
) ObjCProtocolDecl(C
, DC
, Id
, nameLoc
, atStartLoc
, PrevDecl
);
1954 Result
->Data
.setInt(!C
.getLangOpts().Modules
);
1958 ObjCProtocolDecl
*ObjCProtocolDecl::CreateDeserialized(ASTContext
&C
,
1960 ObjCProtocolDecl
*Result
=
1961 new (C
, ID
) ObjCProtocolDecl(C
, nullptr, nullptr, SourceLocation(),
1962 SourceLocation(), nullptr);
1963 Result
->Data
.setInt(!C
.getLangOpts().Modules
);
1967 bool ObjCProtocolDecl::isNonRuntimeProtocol() const {
1968 return hasAttr
<ObjCNonRuntimeProtocolAttr
>();
1971 void ObjCProtocolDecl::getImpliedProtocols(
1972 llvm::DenseSet
<const ObjCProtocolDecl
*> &IPs
) const {
1973 std::queue
<const ObjCProtocolDecl
*> WorkQueue
;
1974 WorkQueue
.push(this);
1976 while (!WorkQueue
.empty()) {
1977 const auto *PD
= WorkQueue
.front();
1979 for (const auto *Parent
: PD
->protocols()) {
1980 const auto *Can
= Parent
->getCanonicalDecl();
1981 auto Result
= IPs
.insert(Can
);
1983 WorkQueue
.push(Parent
);
1988 ObjCProtocolDecl
*ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo
*Name
) {
1989 ObjCProtocolDecl
*PDecl
= this;
1991 if (Name
== getIdentifier())
1994 for (auto *I
: protocols())
1995 if ((PDecl
= I
->lookupProtocolNamed(Name
)))
2001 // lookupMethod - Lookup a instance/class method in the protocol and protocols
2003 ObjCMethodDecl
*ObjCProtocolDecl::lookupMethod(Selector Sel
,
2004 bool isInstance
) const {
2005 ObjCMethodDecl
*MethodDecl
= nullptr;
2007 // If there is no definition or the definition is hidden, we don't find
2009 const ObjCProtocolDecl
*Def
= getDefinition();
2010 if (!Def
|| !Def
->isUnconditionallyVisible())
2013 if ((MethodDecl
= getMethod(Sel
, isInstance
)))
2016 for (const auto *I
: protocols())
2017 if ((MethodDecl
= I
->lookupMethod(Sel
, isInstance
)))
2022 void ObjCProtocolDecl::allocateDefinitionData() {
2023 assert(!Data
.getPointer() && "Protocol already has a definition!");
2024 Data
.setPointer(new (getASTContext()) DefinitionData
);
2025 Data
.getPointer()->Definition
= this;
2026 Data
.getPointer()->HasODRHash
= false;
2029 void ObjCProtocolDecl::startDefinition() {
2030 allocateDefinitionData();
2032 // Update all of the declarations with a pointer to the definition.
2033 for (auto *RD
: redecls())
2034 RD
->Data
= this->Data
;
2037 void ObjCProtocolDecl::startDuplicateDefinitionForComparison() {
2038 Data
.setPointer(nullptr);
2039 allocateDefinitionData();
2040 // Don't propagate data to other redeclarations.
2043 void ObjCProtocolDecl::mergeDuplicateDefinitionWithCommon(
2044 const ObjCProtocolDecl
*Definition
) {
2045 Data
= Definition
->Data
;
2048 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap
&PM
) const {
2049 if (const ObjCProtocolDecl
*PDecl
= getDefinition()) {
2050 for (auto *Prop
: PDecl
->properties()) {
2051 // Insert into PM if not there already.
2052 PM
.insert(std::make_pair(
2053 std::make_pair(Prop
->getIdentifier(), Prop
->isClassProperty()),
2056 // Scan through protocol's protocols.
2057 for (const auto *PI
: PDecl
->protocols())
2058 PI
->collectPropertiesToImplement(PM
);
2062 void ObjCProtocolDecl::collectInheritedProtocolProperties(
2063 const ObjCPropertyDecl
*Property
, ProtocolPropertySet
&PS
,
2064 PropertyDeclOrder
&PO
) const {
2065 if (const ObjCProtocolDecl
*PDecl
= getDefinition()) {
2066 if (!PS
.insert(PDecl
).second
)
2068 for (auto *Prop
: PDecl
->properties()) {
2069 if (Prop
== Property
)
2071 if (Prop
->getIdentifier() == Property
->getIdentifier()) {
2076 // Scan through protocol's protocols which did not have a matching property.
2077 for (const auto *PI
: PDecl
->protocols())
2078 PI
->collectInheritedProtocolProperties(Property
, PS
, PO
);
2083 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
2084 if (const auto *ObjCRTName
= getAttr
<ObjCRuntimeNameAttr
>())
2085 return ObjCRTName
->getMetadataName();
2090 unsigned ObjCProtocolDecl::getODRHash() {
2091 assert(hasDefinition() && "ODRHash only for records with definitions");
2093 // Previously calculated hash is stored in DefinitionData.
2095 return data().ODRHash
;
2097 // Only calculate hash on first call of getODRHash per record.
2099 Hasher
.AddObjCProtocolDecl(getDefinition());
2100 data().ODRHash
= Hasher
.CalculateHash();
2101 setHasODRHash(true);
2103 return data().ODRHash
;
2106 bool ObjCProtocolDecl::hasODRHash() const {
2107 if (!hasDefinition())
2109 return data().HasODRHash
;
2112 void ObjCProtocolDecl::setHasODRHash(bool HasHash
) {
2113 assert(hasDefinition() && "Cannot set ODRHash without definition");
2114 data().HasODRHash
= HasHash
;
2117 //===----------------------------------------------------------------------===//
2119 //===----------------------------------------------------------------------===//
2121 void ObjCCategoryDecl::anchor() {}
2123 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext
*DC
, SourceLocation AtLoc
,
2124 SourceLocation ClassNameLoc
,
2125 SourceLocation CategoryNameLoc
,
2126 IdentifierInfo
*Id
, ObjCInterfaceDecl
*IDecl
,
2127 ObjCTypeParamList
*typeParamList
,
2128 SourceLocation IvarLBraceLoc
,
2129 SourceLocation IvarRBraceLoc
)
2130 : ObjCContainerDecl(ObjCCategory
, DC
, Id
, ClassNameLoc
, AtLoc
),
2131 ClassInterface(IDecl
), CategoryNameLoc(CategoryNameLoc
),
2132 IvarLBraceLoc(IvarLBraceLoc
), IvarRBraceLoc(IvarRBraceLoc
) {
2133 setTypeParamList(typeParamList
);
2136 ObjCCategoryDecl
*ObjCCategoryDecl::Create(ASTContext
&C
, DeclContext
*DC
,
2137 SourceLocation AtLoc
,
2138 SourceLocation ClassNameLoc
,
2139 SourceLocation CategoryNameLoc
,
2141 ObjCInterfaceDecl
*IDecl
,
2142 ObjCTypeParamList
*typeParamList
,
2143 SourceLocation IvarLBraceLoc
,
2144 SourceLocation IvarRBraceLoc
) {
2146 new (C
, DC
) ObjCCategoryDecl(DC
, AtLoc
, ClassNameLoc
, CategoryNameLoc
, Id
,
2147 IDecl
, typeParamList
, IvarLBraceLoc
,
2150 // Link this category into its class's category list.
2151 CatDecl
->NextClassCategory
= IDecl
->getCategoryListRaw();
2152 if (IDecl
->hasDefinition()) {
2153 IDecl
->setCategoryListRaw(CatDecl
);
2154 if (ASTMutationListener
*L
= C
.getASTMutationListener())
2155 L
->AddedObjCCategoryToInterface(CatDecl
, IDecl
);
2162 ObjCCategoryDecl
*ObjCCategoryDecl::CreateDeserialized(ASTContext
&C
,
2164 return new (C
, ID
) ObjCCategoryDecl(nullptr, SourceLocation(),
2165 SourceLocation(), SourceLocation(),
2166 nullptr, nullptr, nullptr);
2169 ObjCCategoryImplDecl
*ObjCCategoryDecl::getImplementation() const {
2170 return getASTContext().getObjCImplementation(
2171 const_cast<ObjCCategoryDecl
*>(this));
2174 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl
*ImplD
) {
2175 getASTContext().setObjCImplementation(this, ImplD
);
2178 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList
*TPL
) {
2179 TypeParamList
= TPL
;
2182 // Set the declaration context of each of the type parameters.
2183 for (auto *typeParam
: *TypeParamList
)
2184 typeParam
->setDeclContext(this);
2187 //===----------------------------------------------------------------------===//
2188 // ObjCCategoryImplDecl
2189 //===----------------------------------------------------------------------===//
2191 void ObjCCategoryImplDecl::anchor() {}
2193 ObjCCategoryImplDecl
*
2194 ObjCCategoryImplDecl::Create(ASTContext
&C
, DeclContext
*DC
,
2196 ObjCInterfaceDecl
*ClassInterface
,
2197 SourceLocation nameLoc
,
2198 SourceLocation atStartLoc
,
2199 SourceLocation CategoryNameLoc
) {
2200 if (ClassInterface
&& ClassInterface
->hasDefinition())
2201 ClassInterface
= ClassInterface
->getDefinition();
2202 return new (C
, DC
) ObjCCategoryImplDecl(DC
, Id
, ClassInterface
, nameLoc
,
2203 atStartLoc
, CategoryNameLoc
);
2206 ObjCCategoryImplDecl
*ObjCCategoryImplDecl::CreateDeserialized(ASTContext
&C
,
2208 return new (C
, ID
) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2209 SourceLocation(), SourceLocation(),
2213 ObjCCategoryDecl
*ObjCCategoryImplDecl::getCategoryDecl() const {
2214 // The class interface might be NULL if we are working with invalid code.
2215 if (const ObjCInterfaceDecl
*ID
= getClassInterface())
2216 return ID
->FindCategoryDeclaration(getIdentifier());
2220 void ObjCImplDecl::anchor() {}
2222 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl
*property
) {
2223 // FIXME: The context should be correct before we get here.
2224 property
->setLexicalDeclContext(this);
2228 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl
*IFace
) {
2229 ASTContext
&Ctx
= getASTContext();
2231 if (auto *ImplD
= dyn_cast_or_null
<ObjCImplementationDecl
>(this)) {
2233 Ctx
.setObjCImplementation(IFace
, ImplD
);
2235 } else if (auto *ImplD
= dyn_cast_or_null
<ObjCCategoryImplDecl
>(this)) {
2236 if (ObjCCategoryDecl
*CD
= IFace
->FindCategoryDeclaration(getIdentifier()))
2237 Ctx
.setObjCImplementation(CD
, ImplD
);
2240 ClassInterface
= IFace
;
2243 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2244 /// properties implemented in this \@implementation block and returns
2245 /// the implemented property that uses it.
2246 ObjCPropertyImplDecl
*ObjCImplDecl::
2247 FindPropertyImplIvarDecl(IdentifierInfo
*ivarId
) const {
2248 for (auto *PID
: property_impls())
2249 if (PID
->getPropertyIvarDecl() &&
2250 PID
->getPropertyIvarDecl()->getIdentifier() == ivarId
)
2255 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2256 /// added to the list of those properties \@synthesized/\@dynamic in this
2257 /// category \@implementation block.
2258 ObjCPropertyImplDecl
*ObjCImplDecl::
2259 FindPropertyImplDecl(IdentifierInfo
*Id
,
2260 ObjCPropertyQueryKind QueryKind
) const {
2261 ObjCPropertyImplDecl
*ClassPropImpl
= nullptr;
2262 for (auto *PID
: property_impls())
2263 // If queryKind is unknown, we return the instance property if one
2264 // exists; otherwise we return the class property.
2265 if (PID
->getPropertyDecl()->getIdentifier() == Id
) {
2266 if ((QueryKind
== ObjCPropertyQueryKind::OBJC_PR_query_unknown
&&
2267 !PID
->getPropertyDecl()->isClassProperty()) ||
2268 (QueryKind
== ObjCPropertyQueryKind::OBJC_PR_query_class
&&
2269 PID
->getPropertyDecl()->isClassProperty()) ||
2270 (QueryKind
== ObjCPropertyQueryKind::OBJC_PR_query_instance
&&
2271 !PID
->getPropertyDecl()->isClassProperty()))
2274 if (PID
->getPropertyDecl()->isClassProperty())
2275 ClassPropImpl
= PID
;
2278 if (QueryKind
== ObjCPropertyQueryKind::OBJC_PR_query_unknown
)
2279 // We can't find the instance property, return the class property.
2280 return ClassPropImpl
;
2285 raw_ostream
&clang::operator<<(raw_ostream
&OS
,
2286 const ObjCCategoryImplDecl
&CID
) {
2287 OS
<< CID
.getName();
2291 //===----------------------------------------------------------------------===//
2292 // ObjCImplementationDecl
2293 //===----------------------------------------------------------------------===//
2295 void ObjCImplementationDecl::anchor() {}
2297 ObjCImplementationDecl
*
2298 ObjCImplementationDecl::Create(ASTContext
&C
, DeclContext
*DC
,
2299 ObjCInterfaceDecl
*ClassInterface
,
2300 ObjCInterfaceDecl
*SuperDecl
,
2301 SourceLocation nameLoc
,
2302 SourceLocation atStartLoc
,
2303 SourceLocation superLoc
,
2304 SourceLocation IvarLBraceLoc
,
2305 SourceLocation IvarRBraceLoc
) {
2306 if (ClassInterface
&& ClassInterface
->hasDefinition())
2307 ClassInterface
= ClassInterface
->getDefinition();
2308 return new (C
, DC
) ObjCImplementationDecl(DC
, ClassInterface
, SuperDecl
,
2309 nameLoc
, atStartLoc
, superLoc
,
2310 IvarLBraceLoc
, IvarRBraceLoc
);
2313 ObjCImplementationDecl
*
2314 ObjCImplementationDecl::CreateDeserialized(ASTContext
&C
, unsigned ID
) {
2315 return new (C
, ID
) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2316 SourceLocation(), SourceLocation());
2319 void ObjCImplementationDecl::setIvarInitializers(ASTContext
&C
,
2320 CXXCtorInitializer
** initializers
,
2321 unsigned numInitializers
) {
2322 if (numInitializers
> 0) {
2323 NumIvarInitializers
= numInitializers
;
2324 auto **ivarInitializers
= new (C
) CXXCtorInitializer
*[NumIvarInitializers
];
2325 memcpy(ivarInitializers
, initializers
,
2326 numInitializers
* sizeof(CXXCtorInitializer
*));
2327 IvarInitializers
= ivarInitializers
;
2331 ObjCImplementationDecl::init_const_iterator
2332 ObjCImplementationDecl::init_begin() const {
2333 return IvarInitializers
.get(getASTContext().getExternalSource());
2336 raw_ostream
&clang::operator<<(raw_ostream
&OS
,
2337 const ObjCImplementationDecl
&ID
) {
2342 //===----------------------------------------------------------------------===//
2343 // ObjCCompatibleAliasDecl
2344 //===----------------------------------------------------------------------===//
2346 void ObjCCompatibleAliasDecl::anchor() {}
2348 ObjCCompatibleAliasDecl
*
2349 ObjCCompatibleAliasDecl::Create(ASTContext
&C
, DeclContext
*DC
,
2352 ObjCInterfaceDecl
* AliasedClass
) {
2353 return new (C
, DC
) ObjCCompatibleAliasDecl(DC
, L
, Id
, AliasedClass
);
2356 ObjCCompatibleAliasDecl
*
2357 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext
&C
, unsigned ID
) {
2358 return new (C
, ID
) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2362 //===----------------------------------------------------------------------===//
2364 //===----------------------------------------------------------------------===//
2366 void ObjCPropertyDecl::anchor() {}
2368 ObjCPropertyDecl
*ObjCPropertyDecl::Create(ASTContext
&C
, DeclContext
*DC
,
2371 SourceLocation AtLoc
,
2372 SourceLocation LParenLoc
,
2374 TypeSourceInfo
*TSI
,
2375 PropertyControl propControl
) {
2376 return new (C
, DC
) ObjCPropertyDecl(DC
, L
, Id
, AtLoc
, LParenLoc
, T
, TSI
,
2380 ObjCPropertyDecl
*ObjCPropertyDecl::CreateDeserialized(ASTContext
&C
,
2382 return new (C
, ID
) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2383 SourceLocation(), SourceLocation(),
2384 QualType(), nullptr, None
);
2387 QualType
ObjCPropertyDecl::getUsageType(QualType objectType
) const {
2388 return DeclType
.substObjCMemberType(objectType
, getDeclContext(),
2389 ObjCSubstitutionContext::Property
);
2392 bool ObjCPropertyDecl::isDirectProperty() const {
2393 return (PropertyAttributes
& ObjCPropertyAttribute::kind_direct
) &&
2394 !getASTContext().getLangOpts().ObjCDisableDirectMethodsForTesting
;
2397 //===----------------------------------------------------------------------===//
2398 // ObjCPropertyImplDecl
2399 //===----------------------------------------------------------------------===//
2401 ObjCPropertyImplDecl
*ObjCPropertyImplDecl::Create(ASTContext
&C
,
2403 SourceLocation atLoc
,
2405 ObjCPropertyDecl
*property
,
2408 SourceLocation ivarLoc
) {
2409 return new (C
, DC
) ObjCPropertyImplDecl(DC
, atLoc
, L
, property
, PK
, ivar
,
2413 ObjCPropertyImplDecl
*ObjCPropertyImplDecl::CreateDeserialized(ASTContext
&C
,
2415 return new (C
, ID
) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2416 SourceLocation(), nullptr, Dynamic
,
2417 nullptr, SourceLocation());
2420 SourceRange
ObjCPropertyImplDecl::getSourceRange() const {
2421 SourceLocation EndLoc
= getLocation();
2422 if (IvarLoc
.isValid())
2425 return SourceRange(AtLoc
, EndLoc
);