DeclObjC.cpp 75 KB

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