SemaDeclObjC.cpp 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606
  1. //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
  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 semantic analysis for Objective C declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/DataRecursiveASTVisitor.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Sema/DeclSpec.h"
  24. #include "clang/Sema/ExternalSemaSource.h"
  25. #include "clang/Sema/Lookup.h"
  26. #include "clang/Sema/Scope.h"
  27. #include "clang/Sema/ScopeInfo.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/DenseSet.h"
  30. #include "TypeLocBuilder.h"
  31. using namespace clang;
  32. /// Check whether the given method, which must be in the 'init'
  33. /// family, is a valid member of that family.
  34. ///
  35. /// \param receiverTypeIfCall - if null, check this as if declaring it;
  36. /// if non-null, check this as if making a call to it with the given
  37. /// receiver type
  38. ///
  39. /// \return true to indicate that there was an error and appropriate
  40. /// actions were taken
  41. bool Sema::checkInitMethod(ObjCMethodDecl *method,
  42. QualType receiverTypeIfCall) {
  43. if (method->isInvalidDecl()) return true;
  44. // This castAs is safe: methods that don't return an object
  45. // pointer won't be inferred as inits and will reject an explicit
  46. // objc_method_family(init).
  47. // We ignore protocols here. Should we? What about Class?
  48. const ObjCObjectType *result =
  49. method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
  50. if (result->isObjCId()) {
  51. return false;
  52. } else if (result->isObjCClass()) {
  53. // fall through: always an error
  54. } else {
  55. ObjCInterfaceDecl *resultClass = result->getInterface();
  56. assert(resultClass && "unexpected object type!");
  57. // It's okay for the result type to still be a forward declaration
  58. // if we're checking an interface declaration.
  59. if (!resultClass->hasDefinition()) {
  60. if (receiverTypeIfCall.isNull() &&
  61. !isa<ObjCImplementationDecl>(method->getDeclContext()))
  62. return false;
  63. // Otherwise, we try to compare class types.
  64. } else {
  65. // If this method was declared in a protocol, we can't check
  66. // anything unless we have a receiver type that's an interface.
  67. const ObjCInterfaceDecl *receiverClass = nullptr;
  68. if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
  69. if (receiverTypeIfCall.isNull())
  70. return false;
  71. receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
  72. ->getInterfaceDecl();
  73. // This can be null for calls to e.g. id<Foo>.
  74. if (!receiverClass) return false;
  75. } else {
  76. receiverClass = method->getClassInterface();
  77. assert(receiverClass && "method not associated with a class!");
  78. }
  79. // If either class is a subclass of the other, it's fine.
  80. if (receiverClass->isSuperClassOf(resultClass) ||
  81. resultClass->isSuperClassOf(receiverClass))
  82. return false;
  83. }
  84. }
  85. SourceLocation loc = method->getLocation();
  86. // If we're in a system header, and this is not a call, just make
  87. // the method unusable.
  88. if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
  89. method->addAttr(UnavailableAttr::CreateImplicit(Context,
  90. "init method returns a type unrelated to its receiver type",
  91. loc));
  92. return true;
  93. }
  94. // Otherwise, it's an error.
  95. Diag(loc, diag::err_arc_init_method_unrelated_result_type);
  96. method->setInvalidDecl();
  97. return true;
  98. }
  99. void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
  100. const ObjCMethodDecl *Overridden) {
  101. if (Overridden->hasRelatedResultType() &&
  102. !NewMethod->hasRelatedResultType()) {
  103. // This can only happen when the method follows a naming convention that
  104. // implies a related result type, and the original (overridden) method has
  105. // a suitable return type, but the new (overriding) method does not have
  106. // a suitable return type.
  107. QualType ResultType = NewMethod->getReturnType();
  108. SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
  109. // Figure out which class this method is part of, if any.
  110. ObjCInterfaceDecl *CurrentClass
  111. = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
  112. if (!CurrentClass) {
  113. DeclContext *DC = NewMethod->getDeclContext();
  114. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
  115. CurrentClass = Cat->getClassInterface();
  116. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
  117. CurrentClass = Impl->getClassInterface();
  118. else if (ObjCCategoryImplDecl *CatImpl
  119. = dyn_cast<ObjCCategoryImplDecl>(DC))
  120. CurrentClass = CatImpl->getClassInterface();
  121. }
  122. if (CurrentClass) {
  123. Diag(NewMethod->getLocation(),
  124. diag::warn_related_result_type_compatibility_class)
  125. << Context.getObjCInterfaceType(CurrentClass)
  126. << ResultType
  127. << ResultTypeRange;
  128. } else {
  129. Diag(NewMethod->getLocation(),
  130. diag::warn_related_result_type_compatibility_protocol)
  131. << ResultType
  132. << ResultTypeRange;
  133. }
  134. if (ObjCMethodFamily Family = Overridden->getMethodFamily())
  135. Diag(Overridden->getLocation(),
  136. diag::note_related_result_type_family)
  137. << /*overridden method*/ 0
  138. << Family;
  139. else
  140. Diag(Overridden->getLocation(),
  141. diag::note_related_result_type_overridden);
  142. }
  143. if (getLangOpts().ObjCAutoRefCount) {
  144. if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
  145. Overridden->hasAttr<NSReturnsRetainedAttr>())) {
  146. Diag(NewMethod->getLocation(),
  147. diag::err_nsreturns_retained_attribute_mismatch) << 1;
  148. Diag(Overridden->getLocation(), diag::note_previous_decl)
  149. << "method";
  150. }
  151. if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
  152. Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
  153. Diag(NewMethod->getLocation(),
  154. diag::err_nsreturns_retained_attribute_mismatch) << 0;
  155. Diag(Overridden->getLocation(), diag::note_previous_decl)
  156. << "method";
  157. }
  158. ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
  159. oe = Overridden->param_end();
  160. for (ObjCMethodDecl::param_iterator
  161. ni = NewMethod->param_begin(), ne = NewMethod->param_end();
  162. ni != ne && oi != oe; ++ni, ++oi) {
  163. const ParmVarDecl *oldDecl = (*oi);
  164. ParmVarDecl *newDecl = (*ni);
  165. if (newDecl->hasAttr<NSConsumedAttr>() !=
  166. oldDecl->hasAttr<NSConsumedAttr>()) {
  167. Diag(newDecl->getLocation(),
  168. diag::err_nsconsumed_attribute_mismatch);
  169. Diag(oldDecl->getLocation(), diag::note_previous_decl)
  170. << "parameter";
  171. }
  172. }
  173. }
  174. }
  175. /// \brief Check a method declaration for compatibility with the Objective-C
  176. /// ARC conventions.
  177. bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
  178. ObjCMethodFamily family = method->getMethodFamily();
  179. switch (family) {
  180. case OMF_None:
  181. case OMF_finalize:
  182. case OMF_retain:
  183. case OMF_release:
  184. case OMF_autorelease:
  185. case OMF_retainCount:
  186. case OMF_self:
  187. case OMF_initialize:
  188. case OMF_performSelector:
  189. return false;
  190. case OMF_dealloc:
  191. if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
  192. SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
  193. if (ResultTypeRange.isInvalid())
  194. Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
  195. << method->getReturnType()
  196. << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
  197. else
  198. Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
  199. << method->getReturnType()
  200. << FixItHint::CreateReplacement(ResultTypeRange, "void");
  201. return true;
  202. }
  203. return false;
  204. case OMF_init:
  205. // If the method doesn't obey the init rules, don't bother annotating it.
  206. if (checkInitMethod(method, QualType()))
  207. return true;
  208. method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
  209. // Don't add a second copy of this attribute, but otherwise don't
  210. // let it be suppressed.
  211. if (method->hasAttr<NSReturnsRetainedAttr>())
  212. return false;
  213. break;
  214. case OMF_alloc:
  215. case OMF_copy:
  216. case OMF_mutableCopy:
  217. case OMF_new:
  218. if (method->hasAttr<NSReturnsRetainedAttr>() ||
  219. method->hasAttr<NSReturnsNotRetainedAttr>() ||
  220. method->hasAttr<NSReturnsAutoreleasedAttr>())
  221. return false;
  222. break;
  223. }
  224. method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
  225. return false;
  226. }
  227. static void DiagnoseObjCImplementedDeprecations(Sema &S,
  228. NamedDecl *ND,
  229. SourceLocation ImplLoc,
  230. int select) {
  231. if (ND && ND->isDeprecated()) {
  232. S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
  233. if (select == 0)
  234. S.Diag(ND->getLocation(), diag::note_method_declared_at)
  235. << ND->getDeclName();
  236. else
  237. S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
  238. }
  239. }
  240. /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
  241. /// pool.
  242. void Sema::AddAnyMethodToGlobalPool(Decl *D) {
  243. ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
  244. // If we don't have a valid method decl, simply return.
  245. if (!MDecl)
  246. return;
  247. if (MDecl->isInstanceMethod())
  248. AddInstanceMethodToGlobalPool(MDecl, true);
  249. else
  250. AddFactoryMethodToGlobalPool(MDecl, true);
  251. }
  252. /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
  253. /// has explicit ownership attribute; false otherwise.
  254. static bool
  255. HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
  256. QualType T = Param->getType();
  257. if (const PointerType *PT = T->getAs<PointerType>()) {
  258. T = PT->getPointeeType();
  259. } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
  260. T = RT->getPointeeType();
  261. } else {
  262. return true;
  263. }
  264. // If we have a lifetime qualifier, but it's local, we must have
  265. // inferred it. So, it is implicit.
  266. return !T.getLocalQualifiers().hasObjCLifetime();
  267. }
  268. /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
  269. /// and user declared, in the method definition's AST.
  270. void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
  271. assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
  272. ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
  273. // If we don't have a valid method decl, simply return.
  274. if (!MDecl)
  275. return;
  276. // Allow all of Sema to see that we are entering a method definition.
  277. PushDeclContext(FnBodyScope, MDecl);
  278. PushFunctionScope();
  279. // Create Decl objects for each parameter, entrring them in the scope for
  280. // binding to their use.
  281. // Insert the invisible arguments, self and _cmd!
  282. MDecl->createImplicitParams(Context, MDecl->getClassInterface());
  283. PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
  284. PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
  285. // The ObjC parser requires parameter names so there's no need to check.
  286. CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
  287. /*CheckParameterNames=*/false);
  288. // Introduce all of the other parameters into this scope.
  289. for (auto *Param : MDecl->params()) {
  290. if (!Param->isInvalidDecl() &&
  291. getLangOpts().ObjCAutoRefCount &&
  292. !HasExplicitOwnershipAttr(*this, Param))
  293. Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
  294. Param->getType();
  295. if (Param->getIdentifier())
  296. PushOnScopeChains(Param, FnBodyScope);
  297. }
  298. // In ARC, disallow definition of retain/release/autorelease/retainCount
  299. if (getLangOpts().ObjCAutoRefCount) {
  300. switch (MDecl->getMethodFamily()) {
  301. case OMF_retain:
  302. case OMF_retainCount:
  303. case OMF_release:
  304. case OMF_autorelease:
  305. Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
  306. << 0 << MDecl->getSelector();
  307. break;
  308. case OMF_None:
  309. case OMF_dealloc:
  310. case OMF_finalize:
  311. case OMF_alloc:
  312. case OMF_init:
  313. case OMF_mutableCopy:
  314. case OMF_copy:
  315. case OMF_new:
  316. case OMF_self:
  317. case OMF_initialize:
  318. case OMF_performSelector:
  319. break;
  320. }
  321. }
  322. // Warn on deprecated methods under -Wdeprecated-implementations,
  323. // and prepare for warning on missing super calls.
  324. if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
  325. ObjCMethodDecl *IMD =
  326. IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
  327. if (IMD) {
  328. ObjCImplDecl *ImplDeclOfMethodDef =
  329. dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
  330. ObjCContainerDecl *ContDeclOfMethodDecl =
  331. dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
  332. ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
  333. if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
  334. ImplDeclOfMethodDecl = OID->getImplementation();
  335. else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
  336. if (CD->IsClassExtension()) {
  337. if (ObjCInterfaceDecl *OID = CD->getClassInterface())
  338. ImplDeclOfMethodDecl = OID->getImplementation();
  339. } else
  340. ImplDeclOfMethodDecl = CD->getImplementation();
  341. }
  342. // No need to issue deprecated warning if deprecated mehod in class/category
  343. // is being implemented in its own implementation (no overriding is involved).
  344. if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
  345. DiagnoseObjCImplementedDeprecations(*this,
  346. dyn_cast<NamedDecl>(IMD),
  347. MDecl->getLocation(), 0);
  348. }
  349. if (MDecl->getMethodFamily() == OMF_init) {
  350. if (MDecl->isDesignatedInitializerForTheInterface()) {
  351. getCurFunction()->ObjCIsDesignatedInit = true;
  352. getCurFunction()->ObjCWarnForNoDesignatedInitChain =
  353. IC->getSuperClass() != nullptr;
  354. } else if (IC->hasDesignatedInitializers()) {
  355. getCurFunction()->ObjCIsSecondaryInit = true;
  356. getCurFunction()->ObjCWarnForNoInitDelegation = true;
  357. }
  358. }
  359. // If this is "dealloc" or "finalize", set some bit here.
  360. // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
  361. // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
  362. // Only do this if the current class actually has a superclass.
  363. if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
  364. ObjCMethodFamily Family = MDecl->getMethodFamily();
  365. if (Family == OMF_dealloc) {
  366. if (!(getLangOpts().ObjCAutoRefCount ||
  367. getLangOpts().getGC() == LangOptions::GCOnly))
  368. getCurFunction()->ObjCShouldCallSuper = true;
  369. } else if (Family == OMF_finalize) {
  370. if (Context.getLangOpts().getGC() != LangOptions::NonGC)
  371. getCurFunction()->ObjCShouldCallSuper = true;
  372. } else {
  373. const ObjCMethodDecl *SuperMethod =
  374. SuperClass->lookupMethod(MDecl->getSelector(),
  375. MDecl->isInstanceMethod());
  376. getCurFunction()->ObjCShouldCallSuper =
  377. (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
  378. }
  379. }
  380. }
  381. }
  382. namespace {
  383. // Callback to only accept typo corrections that are Objective-C classes.
  384. // If an ObjCInterfaceDecl* is given to the constructor, then the validation
  385. // function will reject corrections to that class.
  386. class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
  387. public:
  388. ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
  389. explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
  390. : CurrentIDecl(IDecl) {}
  391. bool ValidateCandidate(const TypoCorrection &candidate) override {
  392. ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
  393. return ID && !declaresSameEntity(ID, CurrentIDecl);
  394. }
  395. private:
  396. ObjCInterfaceDecl *CurrentIDecl;
  397. };
  398. }
  399. static void diagnoseUseOfProtocols(Sema &TheSema,
  400. ObjCContainerDecl *CD,
  401. ObjCProtocolDecl *const *ProtoRefs,
  402. unsigned NumProtoRefs,
  403. const SourceLocation *ProtoLocs) {
  404. assert(ProtoRefs);
  405. // Diagnose availability in the context of the ObjC container.
  406. Sema::ContextRAII SavedContext(TheSema, CD);
  407. for (unsigned i = 0; i < NumProtoRefs; ++i) {
  408. (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
  409. }
  410. }
  411. void Sema::
  412. ActOnSuperClassOfClassInterface(Scope *S,
  413. SourceLocation AtInterfaceLoc,
  414. ObjCInterfaceDecl *IDecl,
  415. IdentifierInfo *ClassName,
  416. SourceLocation ClassLoc,
  417. IdentifierInfo *SuperName,
  418. SourceLocation SuperLoc,
  419. ArrayRef<ParsedType> SuperTypeArgs,
  420. SourceRange SuperTypeArgsRange) {
  421. // Check if a different kind of symbol declared in this scope.
  422. NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
  423. LookupOrdinaryName);
  424. if (!PrevDecl) {
  425. // Try to correct for a typo in the superclass name without correcting
  426. // to the class we're defining.
  427. if (TypoCorrection Corrected = CorrectTypo(
  428. DeclarationNameInfo(SuperName, SuperLoc),
  429. LookupOrdinaryName, TUScope,
  430. NULL, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
  431. CTK_ErrorRecovery)) {
  432. diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
  433. << SuperName << ClassName);
  434. PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
  435. }
  436. }
  437. if (declaresSameEntity(PrevDecl, IDecl)) {
  438. Diag(SuperLoc, diag::err_recursive_superclass)
  439. << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
  440. IDecl->setEndOfDefinitionLoc(ClassLoc);
  441. } else {
  442. ObjCInterfaceDecl *SuperClassDecl =
  443. dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  444. QualType SuperClassType;
  445. // Diagnose classes that inherit from deprecated classes.
  446. if (SuperClassDecl) {
  447. (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
  448. SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
  449. }
  450. if (PrevDecl && SuperClassDecl == 0) {
  451. // The previous declaration was not a class decl. Check if we have a
  452. // typedef. If we do, get the underlying class type.
  453. if (const TypedefNameDecl *TDecl =
  454. dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
  455. QualType T = TDecl->getUnderlyingType();
  456. if (T->isObjCObjectType()) {
  457. if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
  458. SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
  459. SuperClassType = Context.getTypeDeclType(TDecl);
  460. // This handles the following case:
  461. // @interface NewI @end
  462. // typedef NewI DeprI __attribute__((deprecated("blah")))
  463. // @interface SI : DeprI /* warn here */ @end
  464. (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
  465. }
  466. }
  467. }
  468. // This handles the following case:
  469. //
  470. // typedef int SuperClass;
  471. // @interface MyClass : SuperClass {} @end
  472. //
  473. if (!SuperClassDecl) {
  474. Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
  475. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  476. }
  477. }
  478. if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
  479. if (!SuperClassDecl)
  480. Diag(SuperLoc, diag::err_undef_superclass)
  481. << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
  482. else if (RequireCompleteType(SuperLoc,
  483. SuperClassType,
  484. diag::err_forward_superclass,
  485. SuperClassDecl->getDeclName(),
  486. ClassName,
  487. SourceRange(AtInterfaceLoc, ClassLoc))) {
  488. SuperClassDecl = 0;
  489. SuperClassType = QualType();
  490. }
  491. }
  492. if (SuperClassType.isNull()) {
  493. assert(!SuperClassDecl && "Failed to set SuperClassType?");
  494. return;
  495. }
  496. // Handle type arguments on the superclass.
  497. TypeSourceInfo *SuperClassTInfo = nullptr;
  498. if (!SuperTypeArgs.empty()) {
  499. TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
  500. S,
  501. SuperLoc,
  502. CreateParsedType(SuperClassType,
  503. nullptr),
  504. SuperTypeArgsRange.getBegin(),
  505. SuperTypeArgs,
  506. SuperTypeArgsRange.getEnd(),
  507. SourceLocation(),
  508. { },
  509. { },
  510. SourceLocation());
  511. if (!fullSuperClassType.isUsable())
  512. return;
  513. SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
  514. &SuperClassTInfo);
  515. }
  516. if (!SuperClassTInfo) {
  517. SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
  518. SuperLoc);
  519. }
  520. IDecl->setSuperClass(SuperClassTInfo);
  521. IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
  522. }
  523. }
  524. DeclResult Sema::actOnObjCTypeParam(Scope *S,
  525. ObjCTypeParamVariance variance,
  526. SourceLocation varianceLoc,
  527. unsigned index,
  528. IdentifierInfo *paramName,
  529. SourceLocation paramLoc,
  530. SourceLocation colonLoc,
  531. ParsedType parsedTypeBound) {
  532. // If there was an explicitly-provided type bound, check it.
  533. TypeSourceInfo *typeBoundInfo = nullptr;
  534. if (parsedTypeBound) {
  535. // The type bound can be any Objective-C pointer type.
  536. QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
  537. if (typeBound->isObjCObjectPointerType()) {
  538. // okay
  539. } else if (typeBound->isObjCObjectType()) {
  540. // The user forgot the * on an Objective-C pointer type, e.g.,
  541. // "T : NSView".
  542. SourceLocation starLoc = PP.getLocForEndOfToken(
  543. typeBoundInfo->getTypeLoc().getEndLoc());
  544. Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
  545. diag::err_objc_type_param_bound_missing_pointer)
  546. << typeBound << paramName
  547. << FixItHint::CreateInsertion(starLoc, " *");
  548. // Create a new type location builder so we can update the type
  549. // location information we have.
  550. TypeLocBuilder builder;
  551. builder.pushFullCopy(typeBoundInfo->getTypeLoc());
  552. // Create the Objective-C pointer type.
  553. typeBound = Context.getObjCObjectPointerType(typeBound);
  554. ObjCObjectPointerTypeLoc newT
  555. = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
  556. newT.setStarLoc(starLoc);
  557. // Form the new type source information.
  558. typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
  559. } else {
  560. // Not a valid type bound.
  561. Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
  562. diag::err_objc_type_param_bound_nonobject)
  563. << typeBound << paramName;
  564. // Forget the bound; we'll default to id later.
  565. typeBoundInfo = nullptr;
  566. }
  567. // Type bounds cannot have explicit nullability.
  568. if (typeBoundInfo) {
  569. // Type arguments cannot explicitly specify nullability.
  570. if (auto nullability = AttributedType::stripOuterNullability(typeBound)) {
  571. // Look at the type location information to find the nullability
  572. // specifier so we can zap it.
  573. SourceLocation nullabilityLoc
  574. = typeBoundInfo->getTypeLoc().findNullabilityLoc();
  575. SourceLocation diagLoc
  576. = nullabilityLoc.isValid()? nullabilityLoc
  577. : typeBoundInfo->getTypeLoc().getLocStart();
  578. Diag(diagLoc, diag::err_type_param_bound_explicit_nullability)
  579. << paramName << typeBoundInfo->getType()
  580. << FixItHint::CreateRemoval(nullabilityLoc);
  581. }
  582. }
  583. }
  584. // If there was no explicit type bound (or we removed it due to an error),
  585. // use 'id' instead.
  586. if (!typeBoundInfo) {
  587. colonLoc = SourceLocation();
  588. typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
  589. }
  590. // Create the type parameter.
  591. return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
  592. index, paramLoc, paramName, colonLoc,
  593. typeBoundInfo);
  594. }
  595. ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
  596. SourceLocation lAngleLoc,
  597. ArrayRef<Decl *> typeParamsIn,
  598. SourceLocation rAngleLoc) {
  599. // We know that the array only contains Objective-C type parameters.
  600. ArrayRef<ObjCTypeParamDecl *>
  601. typeParams(
  602. reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
  603. typeParamsIn.size());
  604. // Diagnose redeclarations of type parameters.
  605. // We do this now because Objective-C type parameters aren't pushed into
  606. // scope until later (after the instance variable block), but we want the
  607. // diagnostics to occur right after we parse the type parameter list.
  608. llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
  609. for (auto typeParam : typeParams) {
  610. auto known = knownParams.find(typeParam->getIdentifier());
  611. if (known != knownParams.end()) {
  612. Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
  613. << typeParam->getIdentifier()
  614. << SourceRange(known->second->getLocation());
  615. typeParam->setInvalidDecl();
  616. } else {
  617. knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
  618. // Push the type parameter into scope.
  619. PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
  620. }
  621. }
  622. // Create the parameter list.
  623. return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
  624. }
  625. void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
  626. for (auto typeParam : *typeParamList) {
  627. if (!typeParam->isInvalidDecl()) {
  628. S->RemoveDecl(typeParam);
  629. IdResolver.RemoveDecl(typeParam);
  630. }
  631. }
  632. }
  633. namespace {
  634. /// The context in which an Objective-C type parameter list occurs, for use
  635. /// in diagnostics.
  636. enum class TypeParamListContext {
  637. ForwardDeclaration,
  638. Definition,
  639. Category,
  640. Extension
  641. };
  642. }
  643. /// Check consistency between two Objective-C type parameter lists, e.g.,
  644. /// between a category/extension and an \@interface or between an \@class and an
  645. /// \@interface.
  646. static bool checkTypeParamListConsistency(Sema &S,
  647. ObjCTypeParamList *prevTypeParams,
  648. ObjCTypeParamList *newTypeParams,
  649. TypeParamListContext newContext) {
  650. // If the sizes don't match, complain about that.
  651. if (prevTypeParams->size() != newTypeParams->size()) {
  652. SourceLocation diagLoc;
  653. if (newTypeParams->size() > prevTypeParams->size()) {
  654. diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
  655. } else {
  656. diagLoc = S.PP.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
  657. }
  658. S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
  659. << static_cast<unsigned>(newContext)
  660. << (newTypeParams->size() > prevTypeParams->size())
  661. << prevTypeParams->size()
  662. << newTypeParams->size();
  663. return true;
  664. }
  665. // Match up the type parameters.
  666. for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
  667. ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
  668. ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
  669. // Check for consistency of the variance.
  670. if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
  671. if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
  672. newContext != TypeParamListContext::Definition) {
  673. // When the new type parameter is invariant and is not part
  674. // of the definition, just propagate the variance.
  675. newTypeParam->setVariance(prevTypeParam->getVariance());
  676. } else if (prevTypeParam->getVariance()
  677. == ObjCTypeParamVariance::Invariant &&
  678. !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
  679. cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
  680. ->getDefinition() == prevTypeParam->getDeclContext())) {
  681. // When the old parameter is invariant and was not part of the
  682. // definition, just ignore the difference because it doesn't
  683. // matter.
  684. } else {
  685. {
  686. // Diagnose the conflict and update the second declaration.
  687. SourceLocation diagLoc = newTypeParam->getVarianceLoc();
  688. if (diagLoc.isInvalid())
  689. diagLoc = newTypeParam->getLocStart();
  690. auto diag = S.Diag(diagLoc,
  691. diag::err_objc_type_param_variance_conflict)
  692. << static_cast<unsigned>(newTypeParam->getVariance())
  693. << newTypeParam->getDeclName()
  694. << static_cast<unsigned>(prevTypeParam->getVariance())
  695. << prevTypeParam->getDeclName();
  696. switch (prevTypeParam->getVariance()) {
  697. case ObjCTypeParamVariance::Invariant:
  698. diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
  699. break;
  700. case ObjCTypeParamVariance::Covariant:
  701. case ObjCTypeParamVariance::Contravariant: {
  702. StringRef newVarianceStr
  703. = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
  704. ? "__covariant"
  705. : "__contravariant";
  706. if (newTypeParam->getVariance()
  707. == ObjCTypeParamVariance::Invariant) {
  708. diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
  709. (newVarianceStr + " ").str());
  710. } else {
  711. diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
  712. newVarianceStr);
  713. }
  714. }
  715. }
  716. }
  717. S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
  718. << prevTypeParam->getDeclName();
  719. // Override the variance.
  720. newTypeParam->setVariance(prevTypeParam->getVariance());
  721. }
  722. }
  723. // If the bound types match, there's nothing to do.
  724. if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
  725. newTypeParam->getUnderlyingType()))
  726. continue;
  727. // If the new type parameter's bound was explicit, complain about it being
  728. // different from the original.
  729. if (newTypeParam->hasExplicitBound()) {
  730. SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
  731. ->getTypeLoc().getSourceRange();
  732. S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
  733. << newTypeParam->getUnderlyingType()
  734. << newTypeParam->getDeclName()
  735. << prevTypeParam->hasExplicitBound()
  736. << prevTypeParam->getUnderlyingType()
  737. << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
  738. << prevTypeParam->getDeclName()
  739. << FixItHint::CreateReplacement(
  740. newBoundRange,
  741. prevTypeParam->getUnderlyingType().getAsString(
  742. S.Context.getPrintingPolicy()));
  743. S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
  744. << prevTypeParam->getDeclName();
  745. // Override the new type parameter's bound type with the previous type,
  746. // so that it's consistent.
  747. newTypeParam->setTypeSourceInfo(
  748. S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
  749. continue;
  750. }
  751. // The new type parameter got the implicit bound of 'id'. That's okay for
  752. // categories and extensions (overwrite it later), but not for forward
  753. // declarations and @interfaces, because those must be standalone.
  754. if (newContext == TypeParamListContext::ForwardDeclaration ||
  755. newContext == TypeParamListContext::Definition) {
  756. // Diagnose this problem for forward declarations and definitions.
  757. SourceLocation insertionLoc
  758. = S.PP.getLocForEndOfToken(newTypeParam->getLocation());
  759. std::string newCode
  760. = " : " + prevTypeParam->getUnderlyingType().getAsString(
  761. S.Context.getPrintingPolicy());
  762. S.Diag(newTypeParam->getLocation(),
  763. diag::err_objc_type_param_bound_missing)
  764. << prevTypeParam->getUnderlyingType()
  765. << newTypeParam->getDeclName()
  766. << (newContext == TypeParamListContext::ForwardDeclaration)
  767. << FixItHint::CreateInsertion(insertionLoc, newCode);
  768. S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
  769. << prevTypeParam->getDeclName();
  770. }
  771. // Update the new type parameter's bound to match the previous one.
  772. newTypeParam->setTypeSourceInfo(
  773. S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
  774. }
  775. return false;
  776. }
  777. Decl *Sema::
  778. ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
  779. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  780. ObjCTypeParamList *typeParamList,
  781. IdentifierInfo *SuperName, SourceLocation SuperLoc,
  782. ArrayRef<ParsedType> SuperTypeArgs,
  783. SourceRange SuperTypeArgsRange,
  784. Decl * const *ProtoRefs, unsigned NumProtoRefs,
  785. const SourceLocation *ProtoLocs,
  786. SourceLocation EndProtoLoc, AttributeList *AttrList) {
  787. assert(ClassName && "Missing class identifier");
  788. // Check for another declaration kind with the same name.
  789. NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
  790. LookupOrdinaryName, ForRedeclaration);
  791. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  792. Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
  793. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  794. }
  795. // Create a declaration to describe this @interface.
  796. ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  797. if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
  798. // A previous decl with a different name is because of
  799. // @compatibility_alias, for example:
  800. // \code
  801. // @class NewImage;
  802. // @compatibility_alias OldImage NewImage;
  803. // \endcode
  804. // A lookup for 'OldImage' will return the 'NewImage' decl.
  805. //
  806. // In such a case use the real declaration name, instead of the alias one,
  807. // otherwise we will break IdentifierResolver and redecls-chain invariants.
  808. // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
  809. // has been aliased.
  810. ClassName = PrevIDecl->getIdentifier();
  811. }
  812. // If there was a forward declaration with type parameters, check
  813. // for consistency.
  814. if (PrevIDecl) {
  815. if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
  816. if (typeParamList) {
  817. // Both have type parameter lists; check for consistency.
  818. if (checkTypeParamListConsistency(*this, prevTypeParamList,
  819. typeParamList,
  820. TypeParamListContext::Definition)) {
  821. typeParamList = nullptr;
  822. }
  823. } else {
  824. Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
  825. << ClassName;
  826. Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
  827. << ClassName;
  828. // Clone the type parameter list.
  829. SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
  830. for (auto typeParam : *prevTypeParamList) {
  831. clonedTypeParams.push_back(
  832. ObjCTypeParamDecl::Create(
  833. Context,
  834. CurContext,
  835. typeParam->getVariance(),
  836. SourceLocation(),
  837. typeParam->getIndex(),
  838. SourceLocation(),
  839. typeParam->getIdentifier(),
  840. SourceLocation(),
  841. Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
  842. }
  843. typeParamList = ObjCTypeParamList::create(Context,
  844. SourceLocation(),
  845. clonedTypeParams,
  846. SourceLocation());
  847. }
  848. }
  849. }
  850. ObjCInterfaceDecl *IDecl
  851. = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
  852. typeParamList, PrevIDecl, ClassLoc);
  853. if (PrevIDecl) {
  854. // Class already seen. Was it a definition?
  855. if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
  856. Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
  857. << PrevIDecl->getDeclName();
  858. Diag(Def->getLocation(), diag::note_previous_definition);
  859. IDecl->setInvalidDecl();
  860. }
  861. }
  862. if (AttrList)
  863. ProcessDeclAttributeList(TUScope, IDecl, AttrList);
  864. PushOnScopeChains(IDecl, TUScope);
  865. // Start the definition of this class. If we're in a redefinition case, there
  866. // may already be a definition, so we'll end up adding to it.
  867. if (!IDecl->hasDefinition())
  868. IDecl->startDefinition();
  869. if (SuperName) {
  870. // Diagnose availability in the context of the @interface.
  871. ContextRAII SavedContext(*this, IDecl);
  872. ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
  873. ClassName, ClassLoc,
  874. SuperName, SuperLoc, SuperTypeArgs,
  875. SuperTypeArgsRange);
  876. } else { // we have a root class.
  877. IDecl->setEndOfDefinitionLoc(ClassLoc);
  878. }
  879. // Check then save referenced protocols.
  880. if (NumProtoRefs) {
  881. diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
  882. NumProtoRefs, ProtoLocs);
  883. IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
  884. ProtoLocs, Context);
  885. IDecl->setEndOfDefinitionLoc(EndProtoLoc);
  886. }
  887. CheckObjCDeclScope(IDecl);
  888. return ActOnObjCContainerStartDefinition(IDecl);
  889. }
  890. /// ActOnTypedefedProtocols - this action finds protocol list as part of the
  891. /// typedef'ed use for a qualified super class and adds them to the list
  892. /// of the protocols.
  893. void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
  894. IdentifierInfo *SuperName,
  895. SourceLocation SuperLoc) {
  896. if (!SuperName)
  897. return;
  898. NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
  899. LookupOrdinaryName);
  900. if (!IDecl)
  901. return;
  902. if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
  903. QualType T = TDecl->getUnderlyingType();
  904. if (T->isObjCObjectType())
  905. if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
  906. ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
  907. }
  908. }
  909. /// ActOnCompatibilityAlias - this action is called after complete parsing of
  910. /// a \@compatibility_alias declaration. It sets up the alias relationships.
  911. Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
  912. IdentifierInfo *AliasName,
  913. SourceLocation AliasLocation,
  914. IdentifierInfo *ClassName,
  915. SourceLocation ClassLocation) {
  916. // Look for previous declaration of alias name
  917. NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
  918. LookupOrdinaryName, ForRedeclaration);
  919. if (ADecl) {
  920. Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
  921. Diag(ADecl->getLocation(), diag::note_previous_declaration);
  922. return nullptr;
  923. }
  924. // Check for class declaration
  925. NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
  926. LookupOrdinaryName, ForRedeclaration);
  927. if (const TypedefNameDecl *TDecl =
  928. dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
  929. QualType T = TDecl->getUnderlyingType();
  930. if (T->isObjCObjectType()) {
  931. if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
  932. ClassName = IDecl->getIdentifier();
  933. CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
  934. LookupOrdinaryName, ForRedeclaration);
  935. }
  936. }
  937. }
  938. ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
  939. if (!CDecl) {
  940. Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
  941. if (CDeclU)
  942. Diag(CDeclU->getLocation(), diag::note_previous_declaration);
  943. return nullptr;
  944. }
  945. // Everything checked out, instantiate a new alias declaration AST.
  946. ObjCCompatibleAliasDecl *AliasDecl =
  947. ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
  948. if (!CheckObjCDeclScope(AliasDecl))
  949. PushOnScopeChains(AliasDecl, TUScope);
  950. return AliasDecl;
  951. }
  952. bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
  953. IdentifierInfo *PName,
  954. SourceLocation &Ploc, SourceLocation PrevLoc,
  955. const ObjCList<ObjCProtocolDecl> &PList) {
  956. bool res = false;
  957. for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
  958. E = PList.end(); I != E; ++I) {
  959. if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
  960. Ploc)) {
  961. if (PDecl->getIdentifier() == PName) {
  962. Diag(Ploc, diag::err_protocol_has_circular_dependency);
  963. Diag(PrevLoc, diag::note_previous_definition);
  964. res = true;
  965. }
  966. if (!PDecl->hasDefinition())
  967. continue;
  968. if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
  969. PDecl->getLocation(), PDecl->getReferencedProtocols()))
  970. res = true;
  971. }
  972. }
  973. return res;
  974. }
  975. Decl *
  976. Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
  977. IdentifierInfo *ProtocolName,
  978. SourceLocation ProtocolLoc,
  979. Decl * const *ProtoRefs,
  980. unsigned NumProtoRefs,
  981. const SourceLocation *ProtoLocs,
  982. SourceLocation EndProtoLoc,
  983. AttributeList *AttrList) {
  984. bool err = false;
  985. // FIXME: Deal with AttrList.
  986. assert(ProtocolName && "Missing protocol identifier");
  987. ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
  988. ForRedeclaration);
  989. ObjCProtocolDecl *PDecl = nullptr;
  990. if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
  991. // If we already have a definition, complain.
  992. Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
  993. Diag(Def->getLocation(), diag::note_previous_definition);
  994. // Create a new protocol that is completely distinct from previous
  995. // declarations, and do not make this protocol available for name lookup.
  996. // That way, we'll end up completely ignoring the duplicate.
  997. // FIXME: Can we turn this into an error?
  998. PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
  999. ProtocolLoc, AtProtoInterfaceLoc,
  1000. /*PrevDecl=*/nullptr);
  1001. PDecl->startDefinition();
  1002. } else {
  1003. if (PrevDecl) {
  1004. // Check for circular dependencies among protocol declarations. This can
  1005. // only happen if this protocol was forward-declared.
  1006. ObjCList<ObjCProtocolDecl> PList;
  1007. PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
  1008. err = CheckForwardProtocolDeclarationForCircularDependency(
  1009. ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
  1010. }
  1011. // Create the new declaration.
  1012. PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
  1013. ProtocolLoc, AtProtoInterfaceLoc,
  1014. /*PrevDecl=*/PrevDecl);
  1015. PushOnScopeChains(PDecl, TUScope);
  1016. PDecl->startDefinition();
  1017. }
  1018. if (AttrList)
  1019. ProcessDeclAttributeList(TUScope, PDecl, AttrList);
  1020. // Merge attributes from previous declarations.
  1021. if (PrevDecl)
  1022. mergeDeclAttributes(PDecl, PrevDecl);
  1023. if (!err && NumProtoRefs ) {
  1024. /// Check then save referenced protocols.
  1025. diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
  1026. NumProtoRefs, ProtoLocs);
  1027. PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
  1028. ProtoLocs, Context);
  1029. }
  1030. CheckObjCDeclScope(PDecl);
  1031. return ActOnObjCContainerStartDefinition(PDecl);
  1032. }
  1033. static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
  1034. ObjCProtocolDecl *&UndefinedProtocol) {
  1035. if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
  1036. UndefinedProtocol = PDecl;
  1037. return true;
  1038. }
  1039. for (auto *PI : PDecl->protocols())
  1040. if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
  1041. UndefinedProtocol = PI;
  1042. return true;
  1043. }
  1044. return false;
  1045. }
  1046. /// FindProtocolDeclaration - This routine looks up protocols and
  1047. /// issues an error if they are not declared. It returns list of
  1048. /// protocol declarations in its 'Protocols' argument.
  1049. void
  1050. Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
  1051. const IdentifierLocPair *ProtocolId,
  1052. unsigned NumProtocols,
  1053. SmallVectorImpl<Decl *> &Protocols) {
  1054. for (unsigned i = 0; i != NumProtocols; ++i) {
  1055. ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
  1056. ProtocolId[i].second);
  1057. if (!PDecl) {
  1058. TypoCorrection Corrected = CorrectTypo(
  1059. DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
  1060. LookupObjCProtocolName, TUScope, nullptr,
  1061. llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
  1062. CTK_ErrorRecovery);
  1063. if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
  1064. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
  1065. << ProtocolId[i].first);
  1066. }
  1067. if (!PDecl) {
  1068. Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
  1069. << ProtocolId[i].first;
  1070. continue;
  1071. }
  1072. // If this is a forward protocol declaration, get its definition.
  1073. if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
  1074. PDecl = PDecl->getDefinition();
  1075. // For an objc container, delay protocol reference checking until after we
  1076. // can set the objc decl as the availability context, otherwise check now.
  1077. if (!ForObjCContainer) {
  1078. (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
  1079. }
  1080. // If this is a forward declaration and we are supposed to warn in this
  1081. // case, do it.
  1082. // FIXME: Recover nicely in the hidden case.
  1083. ObjCProtocolDecl *UndefinedProtocol;
  1084. if (WarnOnDeclarations &&
  1085. NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
  1086. Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
  1087. << ProtocolId[i].first;
  1088. Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
  1089. << UndefinedProtocol;
  1090. }
  1091. Protocols.push_back(PDecl);
  1092. }
  1093. }
  1094. namespace {
  1095. // Callback to only accept typo corrections that are either
  1096. // Objective-C protocols or valid Objective-C type arguments.
  1097. class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
  1098. ASTContext &Context;
  1099. Sema::LookupNameKind LookupKind;
  1100. public:
  1101. ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
  1102. Sema::LookupNameKind lookupKind)
  1103. : Context(context), LookupKind(lookupKind) { }
  1104. bool ValidateCandidate(const TypoCorrection &candidate) override {
  1105. // If we're allowed to find protocols and we have a protocol, accept it.
  1106. if (LookupKind != Sema::LookupOrdinaryName) {
  1107. if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
  1108. return true;
  1109. }
  1110. // If we're allowed to find type names and we have one, accept it.
  1111. if (LookupKind != Sema::LookupObjCProtocolName) {
  1112. // If we have a type declaration, we might accept this result.
  1113. if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
  1114. // If we found a tag declaration outside of C++, skip it. This
  1115. // can happy because we look for any name when there is no
  1116. // bias to protocol or type names.
  1117. if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
  1118. return false;
  1119. // Make sure the type is something we would accept as a type
  1120. // argument.
  1121. auto type = Context.getTypeDeclType(typeDecl);
  1122. if (type->isObjCObjectPointerType() ||
  1123. type->isBlockPointerType() ||
  1124. type->isDependentType() ||
  1125. type->isObjCObjectType())
  1126. return true;
  1127. return false;
  1128. }
  1129. // If we have an Objective-C class type, accept it; there will
  1130. // be another fix to add the '*'.
  1131. if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
  1132. return true;
  1133. return false;
  1134. }
  1135. return false;
  1136. }
  1137. };
  1138. } // end anonymous namespace
  1139. void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
  1140. Scope *S,
  1141. ParsedType baseType,
  1142. SourceLocation lAngleLoc,
  1143. ArrayRef<IdentifierInfo *> identifiers,
  1144. ArrayRef<SourceLocation> identifierLocs,
  1145. SourceLocation rAngleLoc,
  1146. SourceLocation &typeArgsLAngleLoc,
  1147. SmallVectorImpl<ParsedType> &typeArgs,
  1148. SourceLocation &typeArgsRAngleLoc,
  1149. SourceLocation &protocolLAngleLoc,
  1150. SmallVectorImpl<Decl *> &protocols,
  1151. SourceLocation &protocolRAngleLoc,
  1152. bool warnOnIncompleteProtocols) {
  1153. // Local function that updates the declaration specifiers with
  1154. // protocol information.
  1155. unsigned numProtocolsResolved = 0;
  1156. auto resolvedAsProtocols = [&] {
  1157. assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
  1158. // Determine whether the base type is a parameterized class, in
  1159. // which case we want to warn about typos such as
  1160. // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
  1161. ObjCInterfaceDecl *baseClass = nullptr;
  1162. QualType base = GetTypeFromParser(baseType, nullptr);
  1163. bool allAreTypeNames = false;
  1164. SourceLocation firstClassNameLoc;
  1165. if (!base.isNull()) {
  1166. if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
  1167. baseClass = objcObjectType->getInterface();
  1168. if (baseClass) {
  1169. if (auto typeParams = baseClass->getTypeParamList()) {
  1170. if (typeParams->size() == numProtocolsResolved) {
  1171. // Note that we should be looking for type names, too.
  1172. allAreTypeNames = true;
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
  1179. ObjCProtocolDecl *&proto
  1180. = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
  1181. // For an objc container, delay protocol reference checking until after we
  1182. // can set the objc decl as the availability context, otherwise check now.
  1183. if (!warnOnIncompleteProtocols) {
  1184. (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
  1185. }
  1186. // If this is a forward protocol declaration, get its definition.
  1187. if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
  1188. proto = proto->getDefinition();
  1189. // If this is a forward declaration and we are supposed to warn in this
  1190. // case, do it.
  1191. // FIXME: Recover nicely in the hidden case.
  1192. ObjCProtocolDecl *forwardDecl = nullptr;
  1193. if (warnOnIncompleteProtocols &&
  1194. NestedProtocolHasNoDefinition(proto, forwardDecl)) {
  1195. Diag(identifierLocs[i], diag::warn_undef_protocolref)
  1196. << proto->getDeclName();
  1197. Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
  1198. << forwardDecl;
  1199. }
  1200. // If everything this far has been a type name (and we care
  1201. // about such things), check whether this name refers to a type
  1202. // as well.
  1203. if (allAreTypeNames) {
  1204. if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
  1205. LookupOrdinaryName)) {
  1206. if (isa<ObjCInterfaceDecl>(decl)) {
  1207. if (firstClassNameLoc.isInvalid())
  1208. firstClassNameLoc = identifierLocs[i];
  1209. } else if (!isa<TypeDecl>(decl)) {
  1210. // Not a type.
  1211. allAreTypeNames = false;
  1212. }
  1213. } else {
  1214. allAreTypeNames = false;
  1215. }
  1216. }
  1217. }
  1218. // All of the protocols listed also have type names, and at least
  1219. // one is an Objective-C class name. Check whether all of the
  1220. // protocol conformances are declared by the base class itself, in
  1221. // which case we warn.
  1222. if (allAreTypeNames && firstClassNameLoc.isValid()) {
  1223. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
  1224. Context.CollectInheritedProtocols(baseClass, knownProtocols);
  1225. bool allProtocolsDeclared = true;
  1226. for (auto proto : protocols) {
  1227. if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
  1228. allProtocolsDeclared = false;
  1229. break;
  1230. }
  1231. }
  1232. if (allProtocolsDeclared) {
  1233. Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
  1234. << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
  1235. << FixItHint::CreateInsertion(
  1236. PP.getLocForEndOfToken(firstClassNameLoc), " *");
  1237. }
  1238. }
  1239. protocolLAngleLoc = lAngleLoc;
  1240. protocolRAngleLoc = rAngleLoc;
  1241. assert(protocols.size() == identifierLocs.size());
  1242. };
  1243. // Attempt to resolve all of the identifiers as protocols.
  1244. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1245. ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
  1246. protocols.push_back(proto);
  1247. if (proto)
  1248. ++numProtocolsResolved;
  1249. }
  1250. // If all of the names were protocols, these were protocol qualifiers.
  1251. if (numProtocolsResolved == identifiers.size())
  1252. return resolvedAsProtocols();
  1253. // Attempt to resolve all of the identifiers as type names or
  1254. // Objective-C class names. The latter is technically ill-formed,
  1255. // but is probably something like \c NSArray<NSView *> missing the
  1256. // \c*.
  1257. typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
  1258. SmallVector<TypeOrClassDecl, 4> typeDecls;
  1259. unsigned numTypeDeclsResolved = 0;
  1260. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1261. NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
  1262. LookupOrdinaryName);
  1263. if (!decl) {
  1264. typeDecls.push_back(TypeOrClassDecl());
  1265. continue;
  1266. }
  1267. if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
  1268. typeDecls.push_back(typeDecl);
  1269. ++numTypeDeclsResolved;
  1270. continue;
  1271. }
  1272. if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
  1273. typeDecls.push_back(objcClass);
  1274. ++numTypeDeclsResolved;
  1275. continue;
  1276. }
  1277. typeDecls.push_back(TypeOrClassDecl());
  1278. }
  1279. AttributeFactory attrFactory;
  1280. // Local function that forms a reference to the given type or
  1281. // Objective-C class declaration.
  1282. auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
  1283. -> TypeResult {
  1284. // Form declaration specifiers. They simply refer to the type.
  1285. DeclSpec DS(attrFactory);
  1286. const char* prevSpec; // unused
  1287. unsigned diagID; // unused
  1288. QualType type;
  1289. if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
  1290. type = Context.getTypeDeclType(actualTypeDecl);
  1291. else
  1292. type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
  1293. TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
  1294. ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
  1295. DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
  1296. parsedType, Context.getPrintingPolicy());
  1297. // Use the identifier location for the type source range.
  1298. DS.SetRangeStart(loc);
  1299. DS.SetRangeEnd(loc);
  1300. // Form the declarator.
  1301. Declarator D(DS, Declarator::TypeNameContext);
  1302. // If we have a typedef of an Objective-C class type that is missing a '*',
  1303. // add the '*'.
  1304. if (type->getAs<ObjCInterfaceType>()) {
  1305. SourceLocation starLoc = PP.getLocForEndOfToken(loc);
  1306. ParsedAttributes parsedAttrs(attrFactory);
  1307. D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
  1308. SourceLocation(),
  1309. SourceLocation(),
  1310. SourceLocation(),
  1311. SourceLocation()),
  1312. parsedAttrs,
  1313. starLoc);
  1314. // Diagnose the missing '*'.
  1315. Diag(loc, diag::err_objc_type_arg_missing_star)
  1316. << type
  1317. << FixItHint::CreateInsertion(starLoc, " *");
  1318. }
  1319. // Convert this to a type.
  1320. return ActOnTypeName(S, D);
  1321. };
  1322. // Local function that updates the declaration specifiers with
  1323. // type argument information.
  1324. auto resolvedAsTypeDecls = [&] {
  1325. // We did not resolve these as protocols.
  1326. protocols.clear();
  1327. assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
  1328. // Map type declarations to type arguments.
  1329. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1330. // Map type reference to a type.
  1331. TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
  1332. if (!type.isUsable()) {
  1333. typeArgs.clear();
  1334. return;
  1335. }
  1336. typeArgs.push_back(type.get());
  1337. }
  1338. typeArgsLAngleLoc = lAngleLoc;
  1339. typeArgsRAngleLoc = rAngleLoc;
  1340. };
  1341. // If all of the identifiers can be resolved as type names or
  1342. // Objective-C class names, we have type arguments.
  1343. if (numTypeDeclsResolved == identifiers.size())
  1344. return resolvedAsTypeDecls();
  1345. // Error recovery: some names weren't found, or we have a mix of
  1346. // type and protocol names. Go resolve all of the unresolved names
  1347. // and complain if we can't find a consistent answer.
  1348. LookupNameKind lookupKind = LookupAnyName;
  1349. for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
  1350. // If we already have a protocol or type. Check whether it is the
  1351. // right thing.
  1352. if (protocols[i] || typeDecls[i]) {
  1353. // If we haven't figured out whether we want types or protocols
  1354. // yet, try to figure it out from this name.
  1355. if (lookupKind == LookupAnyName) {
  1356. // If this name refers to both a protocol and a type (e.g., \c
  1357. // NSObject), don't conclude anything yet.
  1358. if (protocols[i] && typeDecls[i])
  1359. continue;
  1360. // Otherwise, let this name decide whether we'll be correcting
  1361. // toward types or protocols.
  1362. lookupKind = protocols[i] ? LookupObjCProtocolName
  1363. : LookupOrdinaryName;
  1364. continue;
  1365. }
  1366. // If we want protocols and we have a protocol, there's nothing
  1367. // more to do.
  1368. if (lookupKind == LookupObjCProtocolName && protocols[i])
  1369. continue;
  1370. // If we want types and we have a type declaration, there's
  1371. // nothing more to do.
  1372. if (lookupKind == LookupOrdinaryName && typeDecls[i])
  1373. continue;
  1374. // We have a conflict: some names refer to protocols and others
  1375. // refer to types.
  1376. Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols)
  1377. << (protocols[i] != nullptr)
  1378. << identifiers[i]
  1379. << identifiers[0]
  1380. << SourceRange(identifierLocs[0]);
  1381. protocols.clear();
  1382. typeArgs.clear();
  1383. return;
  1384. }
  1385. // Perform typo correction on the name.
  1386. TypoCorrection corrected = CorrectTypo(
  1387. DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
  1388. nullptr,
  1389. llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
  1390. lookupKind),
  1391. CTK_ErrorRecovery);
  1392. if (corrected) {
  1393. // Did we find a protocol?
  1394. if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
  1395. diagnoseTypo(corrected,
  1396. PDiag(diag::err_undeclared_protocol_suggest)
  1397. << identifiers[i]);
  1398. lookupKind = LookupObjCProtocolName;
  1399. protocols[i] = proto;
  1400. ++numProtocolsResolved;
  1401. continue;
  1402. }
  1403. // Did we find a type?
  1404. if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
  1405. diagnoseTypo(corrected,
  1406. PDiag(diag::err_unknown_typename_suggest)
  1407. << identifiers[i]);
  1408. lookupKind = LookupOrdinaryName;
  1409. typeDecls[i] = typeDecl;
  1410. ++numTypeDeclsResolved;
  1411. continue;
  1412. }
  1413. // Did we find an Objective-C class?
  1414. if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
  1415. diagnoseTypo(corrected,
  1416. PDiag(diag::err_unknown_type_or_class_name_suggest)
  1417. << identifiers[i] << true);
  1418. lookupKind = LookupOrdinaryName;
  1419. typeDecls[i] = objcClass;
  1420. ++numTypeDeclsResolved;
  1421. continue;
  1422. }
  1423. }
  1424. // We couldn't find anything.
  1425. Diag(identifierLocs[i],
  1426. (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
  1427. : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
  1428. : diag::err_unknown_typename))
  1429. << identifiers[i];
  1430. protocols.clear();
  1431. typeArgs.clear();
  1432. return;
  1433. }
  1434. // If all of the names were (corrected to) protocols, these were
  1435. // protocol qualifiers.
  1436. if (numProtocolsResolved == identifiers.size())
  1437. return resolvedAsProtocols();
  1438. // Otherwise, all of the names were (corrected to) types.
  1439. assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
  1440. return resolvedAsTypeDecls();
  1441. }
  1442. /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
  1443. /// a class method in its extension.
  1444. ///
  1445. void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
  1446. ObjCInterfaceDecl *ID) {
  1447. if (!ID)
  1448. return; // Possibly due to previous error
  1449. llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
  1450. for (auto *MD : ID->methods())
  1451. MethodMap[MD->getSelector()] = MD;
  1452. if (MethodMap.empty())
  1453. return;
  1454. for (const auto *Method : CAT->methods()) {
  1455. const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
  1456. if (PrevMethod &&
  1457. (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
  1458. !MatchTwoMethodDeclarations(Method, PrevMethod)) {
  1459. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  1460. << Method->getDeclName();
  1461. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  1462. }
  1463. }
  1464. }
  1465. /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
  1466. Sema::DeclGroupPtrTy
  1467. Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
  1468. const IdentifierLocPair *IdentList,
  1469. unsigned NumElts,
  1470. AttributeList *attrList) {
  1471. SmallVector<Decl *, 8> DeclsInGroup;
  1472. for (unsigned i = 0; i != NumElts; ++i) {
  1473. IdentifierInfo *Ident = IdentList[i].first;
  1474. ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
  1475. ForRedeclaration);
  1476. ObjCProtocolDecl *PDecl
  1477. = ObjCProtocolDecl::Create(Context, CurContext, Ident,
  1478. IdentList[i].second, AtProtocolLoc,
  1479. PrevDecl);
  1480. PushOnScopeChains(PDecl, TUScope);
  1481. CheckObjCDeclScope(PDecl);
  1482. if (attrList)
  1483. ProcessDeclAttributeList(TUScope, PDecl, attrList);
  1484. if (PrevDecl)
  1485. mergeDeclAttributes(PDecl, PrevDecl);
  1486. DeclsInGroup.push_back(PDecl);
  1487. }
  1488. return BuildDeclaratorGroup(DeclsInGroup, false);
  1489. }
  1490. Decl *Sema::
  1491. ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
  1492. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  1493. ObjCTypeParamList *typeParamList,
  1494. IdentifierInfo *CategoryName,
  1495. SourceLocation CategoryLoc,
  1496. Decl * const *ProtoRefs,
  1497. unsigned NumProtoRefs,
  1498. const SourceLocation *ProtoLocs,
  1499. SourceLocation EndProtoLoc) {
  1500. ObjCCategoryDecl *CDecl;
  1501. ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
  1502. /// Check that class of this category is already completely declared.
  1503. if (!IDecl
  1504. || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
  1505. diag::err_category_forward_interface,
  1506. CategoryName == nullptr)) {
  1507. // Create an invalid ObjCCategoryDecl to serve as context for
  1508. // the enclosing method declarations. We mark the decl invalid
  1509. // to make it clear that this isn't a valid AST.
  1510. CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
  1511. ClassLoc, CategoryLoc, CategoryName,
  1512. IDecl, typeParamList);
  1513. CDecl->setInvalidDecl();
  1514. CurContext->addDecl(CDecl);
  1515. if (!IDecl)
  1516. Diag(ClassLoc, diag::err_undef_interface) << ClassName;
  1517. return ActOnObjCContainerStartDefinition(CDecl);
  1518. }
  1519. if (!CategoryName && IDecl->getImplementation()) {
  1520. Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
  1521. Diag(IDecl->getImplementation()->getLocation(),
  1522. diag::note_implementation_declared);
  1523. }
  1524. if (CategoryName) {
  1525. /// Check for duplicate interface declaration for this category
  1526. if (ObjCCategoryDecl *Previous
  1527. = IDecl->FindCategoryDeclaration(CategoryName)) {
  1528. // Class extensions can be declared multiple times, categories cannot.
  1529. Diag(CategoryLoc, diag::warn_dup_category_def)
  1530. << ClassName << CategoryName;
  1531. Diag(Previous->getLocation(), diag::note_previous_definition);
  1532. }
  1533. }
  1534. // If we have a type parameter list, check it.
  1535. if (typeParamList) {
  1536. if (auto prevTypeParamList = IDecl->getTypeParamList()) {
  1537. if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
  1538. CategoryName
  1539. ? TypeParamListContext::Category
  1540. : TypeParamListContext::Extension))
  1541. typeParamList = nullptr;
  1542. } else {
  1543. Diag(typeParamList->getLAngleLoc(),
  1544. diag::err_objc_parameterized_category_nonclass)
  1545. << (CategoryName != nullptr)
  1546. << ClassName
  1547. << typeParamList->getSourceRange();
  1548. typeParamList = nullptr;
  1549. }
  1550. }
  1551. CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
  1552. ClassLoc, CategoryLoc, CategoryName, IDecl,
  1553. typeParamList);
  1554. // FIXME: PushOnScopeChains?
  1555. CurContext->addDecl(CDecl);
  1556. if (NumProtoRefs) {
  1557. diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
  1558. NumProtoRefs, ProtoLocs);
  1559. CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
  1560. ProtoLocs, Context);
  1561. // Protocols in the class extension belong to the class.
  1562. if (CDecl->IsClassExtension())
  1563. IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
  1564. NumProtoRefs, Context);
  1565. }
  1566. CheckObjCDeclScope(CDecl);
  1567. return ActOnObjCContainerStartDefinition(CDecl);
  1568. }
  1569. /// ActOnStartCategoryImplementation - Perform semantic checks on the
  1570. /// category implementation declaration and build an ObjCCategoryImplDecl
  1571. /// object.
  1572. Decl *Sema::ActOnStartCategoryImplementation(
  1573. SourceLocation AtCatImplLoc,
  1574. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  1575. IdentifierInfo *CatName, SourceLocation CatLoc) {
  1576. ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
  1577. ObjCCategoryDecl *CatIDecl = nullptr;
  1578. if (IDecl && IDecl->hasDefinition()) {
  1579. CatIDecl = IDecl->FindCategoryDeclaration(CatName);
  1580. if (!CatIDecl) {
  1581. // Category @implementation with no corresponding @interface.
  1582. // Create and install one.
  1583. CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
  1584. ClassLoc, CatLoc,
  1585. CatName, IDecl,
  1586. /*typeParamList=*/nullptr);
  1587. CatIDecl->setImplicit();
  1588. }
  1589. }
  1590. ObjCCategoryImplDecl *CDecl =
  1591. ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
  1592. ClassLoc, AtCatImplLoc, CatLoc);
  1593. /// Check that class of this category is already completely declared.
  1594. if (!IDecl) {
  1595. Diag(ClassLoc, diag::err_undef_interface) << ClassName;
  1596. CDecl->setInvalidDecl();
  1597. } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
  1598. diag::err_undef_interface)) {
  1599. CDecl->setInvalidDecl();
  1600. }
  1601. // FIXME: PushOnScopeChains?
  1602. CurContext->addDecl(CDecl);
  1603. // If the interface is deprecated/unavailable, warn/error about it.
  1604. if (IDecl)
  1605. DiagnoseUseOfDecl(IDecl, ClassLoc);
  1606. /// Check that CatName, category name, is not used in another implementation.
  1607. if (CatIDecl) {
  1608. if (CatIDecl->getImplementation()) {
  1609. Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
  1610. << CatName;
  1611. Diag(CatIDecl->getImplementation()->getLocation(),
  1612. diag::note_previous_definition);
  1613. CDecl->setInvalidDecl();
  1614. } else {
  1615. CatIDecl->setImplementation(CDecl);
  1616. // Warn on implementating category of deprecated class under
  1617. // -Wdeprecated-implementations flag.
  1618. DiagnoseObjCImplementedDeprecations(*this,
  1619. dyn_cast<NamedDecl>(IDecl),
  1620. CDecl->getLocation(), 2);
  1621. }
  1622. }
  1623. CheckObjCDeclScope(CDecl);
  1624. return ActOnObjCContainerStartDefinition(CDecl);
  1625. }
  1626. Decl *Sema::ActOnStartClassImplementation(
  1627. SourceLocation AtClassImplLoc,
  1628. IdentifierInfo *ClassName, SourceLocation ClassLoc,
  1629. IdentifierInfo *SuperClassname,
  1630. SourceLocation SuperClassLoc) {
  1631. ObjCInterfaceDecl *IDecl = nullptr;
  1632. // Check for another declaration kind with the same name.
  1633. NamedDecl *PrevDecl
  1634. = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
  1635. ForRedeclaration);
  1636. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  1637. Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
  1638. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1639. } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
  1640. RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
  1641. diag::warn_undef_interface);
  1642. } else {
  1643. // We did not find anything with the name ClassName; try to correct for
  1644. // typos in the class name.
  1645. TypoCorrection Corrected = CorrectTypo(
  1646. DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
  1647. nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
  1648. if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
  1649. // Suggest the (potentially) correct interface name. Don't provide a
  1650. // code-modification hint or use the typo name for recovery, because
  1651. // this is just a warning. The program may actually be correct.
  1652. diagnoseTypo(Corrected,
  1653. PDiag(diag::warn_undef_interface_suggest) << ClassName,
  1654. /*ErrorRecovery*/false);
  1655. } else {
  1656. Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
  1657. }
  1658. }
  1659. // Check that super class name is valid class name
  1660. ObjCInterfaceDecl *SDecl = nullptr;
  1661. if (SuperClassname) {
  1662. // Check if a different kind of symbol declared in this scope.
  1663. PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
  1664. LookupOrdinaryName);
  1665. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  1666. Diag(SuperClassLoc, diag::err_redefinition_different_kind)
  1667. << SuperClassname;
  1668. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  1669. } else {
  1670. SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  1671. if (SDecl && !SDecl->hasDefinition())
  1672. SDecl = nullptr;
  1673. if (!SDecl)
  1674. Diag(SuperClassLoc, diag::err_undef_superclass)
  1675. << SuperClassname << ClassName;
  1676. else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
  1677. // This implementation and its interface do not have the same
  1678. // super class.
  1679. Diag(SuperClassLoc, diag::err_conflicting_super_class)
  1680. << SDecl->getDeclName();
  1681. Diag(SDecl->getLocation(), diag::note_previous_definition);
  1682. }
  1683. }
  1684. }
  1685. if (!IDecl) {
  1686. // Legacy case of @implementation with no corresponding @interface.
  1687. // Build, chain & install the interface decl into the identifier.
  1688. // FIXME: Do we support attributes on the @implementation? If so we should
  1689. // copy them over.
  1690. IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
  1691. ClassName, /*typeParamList=*/nullptr,
  1692. /*PrevDecl=*/nullptr, ClassLoc,
  1693. true);
  1694. IDecl->startDefinition();
  1695. if (SDecl) {
  1696. IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
  1697. Context.getObjCInterfaceType(SDecl),
  1698. SuperClassLoc));
  1699. IDecl->setEndOfDefinitionLoc(SuperClassLoc);
  1700. } else {
  1701. IDecl->setEndOfDefinitionLoc(ClassLoc);
  1702. }
  1703. PushOnScopeChains(IDecl, TUScope);
  1704. } else {
  1705. // Mark the interface as being completed, even if it was just as
  1706. // @class ....;
  1707. // declaration; the user cannot reopen it.
  1708. if (!IDecl->hasDefinition())
  1709. IDecl->startDefinition();
  1710. }
  1711. ObjCImplementationDecl* IMPDecl =
  1712. ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
  1713. ClassLoc, AtClassImplLoc, SuperClassLoc);
  1714. if (CheckObjCDeclScope(IMPDecl))
  1715. return ActOnObjCContainerStartDefinition(IMPDecl);
  1716. // Check that there is no duplicate implementation of this class.
  1717. if (IDecl->getImplementation()) {
  1718. // FIXME: Don't leak everything!
  1719. Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
  1720. Diag(IDecl->getImplementation()->getLocation(),
  1721. diag::note_previous_definition);
  1722. IMPDecl->setInvalidDecl();
  1723. } else { // add it to the list.
  1724. IDecl->setImplementation(IMPDecl);
  1725. PushOnScopeChains(IMPDecl, TUScope);
  1726. // Warn on implementating deprecated class under
  1727. // -Wdeprecated-implementations flag.
  1728. DiagnoseObjCImplementedDeprecations(*this,
  1729. dyn_cast<NamedDecl>(IDecl),
  1730. IMPDecl->getLocation(), 1);
  1731. }
  1732. return ActOnObjCContainerStartDefinition(IMPDecl);
  1733. }
  1734. Sema::DeclGroupPtrTy
  1735. Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
  1736. SmallVector<Decl *, 64> DeclsInGroup;
  1737. DeclsInGroup.reserve(Decls.size() + 1);
  1738. for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
  1739. Decl *Dcl = Decls[i];
  1740. if (!Dcl)
  1741. continue;
  1742. if (Dcl->getDeclContext()->isFileContext())
  1743. Dcl->setTopLevelDeclInObjCContainer();
  1744. DeclsInGroup.push_back(Dcl);
  1745. }
  1746. DeclsInGroup.push_back(ObjCImpDecl);
  1747. return BuildDeclaratorGroup(DeclsInGroup, false);
  1748. }
  1749. void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
  1750. ObjCIvarDecl **ivars, unsigned numIvars,
  1751. SourceLocation RBrace) {
  1752. assert(ImpDecl && "missing implementation decl");
  1753. ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
  1754. if (!IDecl)
  1755. return;
  1756. /// Check case of non-existing \@interface decl.
  1757. /// (legacy objective-c \@implementation decl without an \@interface decl).
  1758. /// Add implementations's ivar to the synthesize class's ivar list.
  1759. if (IDecl->isImplicitInterfaceDecl()) {
  1760. IDecl->setEndOfDefinitionLoc(RBrace);
  1761. // Add ivar's to class's DeclContext.
  1762. for (unsigned i = 0, e = numIvars; i != e; ++i) {
  1763. ivars[i]->setLexicalDeclContext(ImpDecl);
  1764. IDecl->makeDeclVisibleInContext(ivars[i]);
  1765. ImpDecl->addDecl(ivars[i]);
  1766. }
  1767. return;
  1768. }
  1769. // If implementation has empty ivar list, just return.
  1770. if (numIvars == 0)
  1771. return;
  1772. assert(ivars && "missing @implementation ivars");
  1773. if (LangOpts.ObjCRuntime.isNonFragile()) {
  1774. if (ImpDecl->getSuperClass())
  1775. Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
  1776. for (unsigned i = 0; i < numIvars; i++) {
  1777. ObjCIvarDecl* ImplIvar = ivars[i];
  1778. if (const ObjCIvarDecl *ClsIvar =
  1779. IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
  1780. Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
  1781. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  1782. continue;
  1783. }
  1784. // Check class extensions (unnamed categories) for duplicate ivars.
  1785. for (const auto *CDecl : IDecl->visible_extensions()) {
  1786. if (const ObjCIvarDecl *ClsExtIvar =
  1787. CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
  1788. Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
  1789. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  1790. continue;
  1791. }
  1792. }
  1793. // Instance ivar to Implementation's DeclContext.
  1794. ImplIvar->setLexicalDeclContext(ImpDecl);
  1795. IDecl->makeDeclVisibleInContext(ImplIvar);
  1796. ImpDecl->addDecl(ImplIvar);
  1797. }
  1798. return;
  1799. }
  1800. // Check interface's Ivar list against those in the implementation.
  1801. // names and types must match.
  1802. //
  1803. unsigned j = 0;
  1804. ObjCInterfaceDecl::ivar_iterator
  1805. IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
  1806. for (; numIvars > 0 && IVI != IVE; ++IVI) {
  1807. ObjCIvarDecl* ImplIvar = ivars[j++];
  1808. ObjCIvarDecl* ClsIvar = *IVI;
  1809. assert (ImplIvar && "missing implementation ivar");
  1810. assert (ClsIvar && "missing class ivar");
  1811. // First, make sure the types match.
  1812. if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
  1813. Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
  1814. << ImplIvar->getIdentifier()
  1815. << ImplIvar->getType() << ClsIvar->getType();
  1816. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  1817. } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
  1818. ImplIvar->getBitWidthValue(Context) !=
  1819. ClsIvar->getBitWidthValue(Context)) {
  1820. Diag(ImplIvar->getBitWidth()->getLocStart(),
  1821. diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
  1822. Diag(ClsIvar->getBitWidth()->getLocStart(),
  1823. diag::note_previous_definition);
  1824. }
  1825. // Make sure the names are identical.
  1826. if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
  1827. Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
  1828. << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
  1829. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  1830. }
  1831. --numIvars;
  1832. }
  1833. if (numIvars > 0)
  1834. Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
  1835. else if (IVI != IVE)
  1836. Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
  1837. }
  1838. static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
  1839. ObjCMethodDecl *method,
  1840. bool &IncompleteImpl,
  1841. unsigned DiagID,
  1842. NamedDecl *NeededFor = nullptr) {
  1843. // No point warning no definition of method which is 'unavailable'.
  1844. switch (method->getAvailability()) {
  1845. case AR_Available:
  1846. case AR_Deprecated:
  1847. break;
  1848. // Don't warn about unavailable or not-yet-introduced methods.
  1849. case AR_NotYetIntroduced:
  1850. case AR_Unavailable:
  1851. return;
  1852. }
  1853. // FIXME: For now ignore 'IncompleteImpl'.
  1854. // Previously we grouped all unimplemented methods under a single
  1855. // warning, but some users strongly voiced that they would prefer
  1856. // separate warnings. We will give that approach a try, as that
  1857. // matches what we do with protocols.
  1858. {
  1859. const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
  1860. B << method;
  1861. if (NeededFor)
  1862. B << NeededFor;
  1863. }
  1864. // Issue a note to the original declaration.
  1865. SourceLocation MethodLoc = method->getLocStart();
  1866. if (MethodLoc.isValid())
  1867. S.Diag(MethodLoc, diag::note_method_declared_at) << method;
  1868. }
  1869. /// Determines if type B can be substituted for type A. Returns true if we can
  1870. /// guarantee that anything that the user will do to an object of type A can
  1871. /// also be done to an object of type B. This is trivially true if the two
  1872. /// types are the same, or if B is a subclass of A. It becomes more complex
  1873. /// in cases where protocols are involved.
  1874. ///
  1875. /// Object types in Objective-C describe the minimum requirements for an
  1876. /// object, rather than providing a complete description of a type. For
  1877. /// example, if A is a subclass of B, then B* may refer to an instance of A.
  1878. /// The principle of substitutability means that we may use an instance of A
  1879. /// anywhere that we may use an instance of B - it will implement all of the
  1880. /// ivars of B and all of the methods of B.
  1881. ///
  1882. /// This substitutability is important when type checking methods, because
  1883. /// the implementation may have stricter type definitions than the interface.
  1884. /// The interface specifies minimum requirements, but the implementation may
  1885. /// have more accurate ones. For example, a method may privately accept
  1886. /// instances of B, but only publish that it accepts instances of A. Any
  1887. /// object passed to it will be type checked against B, and so will implicitly
  1888. /// by a valid A*. Similarly, a method may return a subclass of the class that
  1889. /// it is declared as returning.
  1890. ///
  1891. /// This is most important when considering subclassing. A method in a
  1892. /// subclass must accept any object as an argument that its superclass's
  1893. /// implementation accepts. It may, however, accept a more general type
  1894. /// without breaking substitutability (i.e. you can still use the subclass
  1895. /// anywhere that you can use the superclass, but not vice versa). The
  1896. /// converse requirement applies to return types: the return type for a
  1897. /// subclass method must be a valid object of the kind that the superclass
  1898. /// advertises, but it may be specified more accurately. This avoids the need
  1899. /// for explicit down-casting by callers.
  1900. ///
  1901. /// Note: This is a stricter requirement than for assignment.
  1902. static bool isObjCTypeSubstitutable(ASTContext &Context,
  1903. const ObjCObjectPointerType *A,
  1904. const ObjCObjectPointerType *B,
  1905. bool rejectId) {
  1906. // Reject a protocol-unqualified id.
  1907. if (rejectId && B->isObjCIdType()) return false;
  1908. // If B is a qualified id, then A must also be a qualified id and it must
  1909. // implement all of the protocols in B. It may not be a qualified class.
  1910. // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
  1911. // stricter definition so it is not substitutable for id<A>.
  1912. if (B->isObjCQualifiedIdType()) {
  1913. return A->isObjCQualifiedIdType() &&
  1914. Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
  1915. QualType(B,0),
  1916. false);
  1917. }
  1918. /*
  1919. // id is a special type that bypasses type checking completely. We want a
  1920. // warning when it is used in one place but not another.
  1921. if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
  1922. // If B is a qualified id, then A must also be a qualified id (which it isn't
  1923. // if we've got this far)
  1924. if (B->isObjCQualifiedIdType()) return false;
  1925. */
  1926. // Now we know that A and B are (potentially-qualified) class types. The
  1927. // normal rules for assignment apply.
  1928. return Context.canAssignObjCInterfaces(A, B);
  1929. }
  1930. static SourceRange getTypeRange(TypeSourceInfo *TSI) {
  1931. return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
  1932. }
  1933. /// Determine whether two set of Objective-C declaration qualifiers conflict.
  1934. static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
  1935. Decl::ObjCDeclQualifier y) {
  1936. return (x & ~Decl::OBJC_TQ_CSNullability) !=
  1937. (y & ~Decl::OBJC_TQ_CSNullability);
  1938. }
  1939. static bool CheckMethodOverrideReturn(Sema &S,
  1940. ObjCMethodDecl *MethodImpl,
  1941. ObjCMethodDecl *MethodDecl,
  1942. bool IsProtocolMethodDecl,
  1943. bool IsOverridingMode,
  1944. bool Warn) {
  1945. if (IsProtocolMethodDecl &&
  1946. objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
  1947. MethodImpl->getObjCDeclQualifier())) {
  1948. if (Warn) {
  1949. S.Diag(MethodImpl->getLocation(),
  1950. (IsOverridingMode
  1951. ? diag::warn_conflicting_overriding_ret_type_modifiers
  1952. : diag::warn_conflicting_ret_type_modifiers))
  1953. << MethodImpl->getDeclName()
  1954. << MethodImpl->getReturnTypeSourceRange();
  1955. S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
  1956. << MethodDecl->getReturnTypeSourceRange();
  1957. }
  1958. else
  1959. return false;
  1960. }
  1961. if (Warn && IsOverridingMode &&
  1962. !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
  1963. !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
  1964. MethodDecl->getReturnType(),
  1965. false)) {
  1966. auto nullabilityMethodImpl =
  1967. *MethodImpl->getReturnType()->getNullability(S.Context);
  1968. auto nullabilityMethodDecl =
  1969. *MethodDecl->getReturnType()->getNullability(S.Context);
  1970. S.Diag(MethodImpl->getLocation(),
  1971. diag::warn_conflicting_nullability_attr_overriding_ret_types)
  1972. << DiagNullabilityKind(
  1973. nullabilityMethodImpl,
  1974. ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  1975. != 0))
  1976. << DiagNullabilityKind(
  1977. nullabilityMethodDecl,
  1978. ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  1979. != 0));
  1980. S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
  1981. }
  1982. if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
  1983. MethodDecl->getReturnType()))
  1984. return true;
  1985. if (!Warn)
  1986. return false;
  1987. unsigned DiagID =
  1988. IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
  1989. : diag::warn_conflicting_ret_types;
  1990. // Mismatches between ObjC pointers go into a different warning
  1991. // category, and sometimes they're even completely whitelisted.
  1992. if (const ObjCObjectPointerType *ImplPtrTy =
  1993. MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
  1994. if (const ObjCObjectPointerType *IfacePtrTy =
  1995. MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
  1996. // Allow non-matching return types as long as they don't violate
  1997. // the principle of substitutability. Specifically, we permit
  1998. // return types that are subclasses of the declared return type,
  1999. // or that are more-qualified versions of the declared type.
  2000. if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
  2001. return false;
  2002. DiagID =
  2003. IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
  2004. : diag::warn_non_covariant_ret_types;
  2005. }
  2006. }
  2007. S.Diag(MethodImpl->getLocation(), DiagID)
  2008. << MethodImpl->getDeclName() << MethodDecl->getReturnType()
  2009. << MethodImpl->getReturnType()
  2010. << MethodImpl->getReturnTypeSourceRange();
  2011. S.Diag(MethodDecl->getLocation(), IsOverridingMode
  2012. ? diag::note_previous_declaration
  2013. : diag::note_previous_definition)
  2014. << MethodDecl->getReturnTypeSourceRange();
  2015. return false;
  2016. }
  2017. static bool CheckMethodOverrideParam(Sema &S,
  2018. ObjCMethodDecl *MethodImpl,
  2019. ObjCMethodDecl *MethodDecl,
  2020. ParmVarDecl *ImplVar,
  2021. ParmVarDecl *IfaceVar,
  2022. bool IsProtocolMethodDecl,
  2023. bool IsOverridingMode,
  2024. bool Warn) {
  2025. if (IsProtocolMethodDecl &&
  2026. objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
  2027. IfaceVar->getObjCDeclQualifier())) {
  2028. if (Warn) {
  2029. if (IsOverridingMode)
  2030. S.Diag(ImplVar->getLocation(),
  2031. diag::warn_conflicting_overriding_param_modifiers)
  2032. << getTypeRange(ImplVar->getTypeSourceInfo())
  2033. << MethodImpl->getDeclName();
  2034. else S.Diag(ImplVar->getLocation(),
  2035. diag::warn_conflicting_param_modifiers)
  2036. << getTypeRange(ImplVar->getTypeSourceInfo())
  2037. << MethodImpl->getDeclName();
  2038. S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
  2039. << getTypeRange(IfaceVar->getTypeSourceInfo());
  2040. }
  2041. else
  2042. return false;
  2043. }
  2044. QualType ImplTy = ImplVar->getType();
  2045. QualType IfaceTy = IfaceVar->getType();
  2046. if (Warn && IsOverridingMode &&
  2047. !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
  2048. !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
  2049. S.Diag(ImplVar->getLocation(),
  2050. diag::warn_conflicting_nullability_attr_overriding_param_types)
  2051. << DiagNullabilityKind(
  2052. *ImplTy->getNullability(S.Context),
  2053. ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2054. != 0))
  2055. << DiagNullabilityKind(
  2056. *IfaceTy->getNullability(S.Context),
  2057. ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2058. != 0));
  2059. S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
  2060. }
  2061. if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
  2062. return true;
  2063. if (!Warn)
  2064. return false;
  2065. unsigned DiagID =
  2066. IsOverridingMode ? diag::warn_conflicting_overriding_param_types
  2067. : diag::warn_conflicting_param_types;
  2068. // Mismatches between ObjC pointers go into a different warning
  2069. // category, and sometimes they're even completely whitelisted.
  2070. if (const ObjCObjectPointerType *ImplPtrTy =
  2071. ImplTy->getAs<ObjCObjectPointerType>()) {
  2072. if (const ObjCObjectPointerType *IfacePtrTy =
  2073. IfaceTy->getAs<ObjCObjectPointerType>()) {
  2074. // Allow non-matching argument types as long as they don't
  2075. // violate the principle of substitutability. Specifically, the
  2076. // implementation must accept any objects that the superclass
  2077. // accepts, however it may also accept others.
  2078. if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
  2079. return false;
  2080. DiagID =
  2081. IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
  2082. : diag::warn_non_contravariant_param_types;
  2083. }
  2084. }
  2085. S.Diag(ImplVar->getLocation(), DiagID)
  2086. << getTypeRange(ImplVar->getTypeSourceInfo())
  2087. << MethodImpl->getDeclName() << IfaceTy << ImplTy;
  2088. S.Diag(IfaceVar->getLocation(),
  2089. (IsOverridingMode ? diag::note_previous_declaration
  2090. : diag::note_previous_definition))
  2091. << getTypeRange(IfaceVar->getTypeSourceInfo());
  2092. return false;
  2093. }
  2094. /// In ARC, check whether the conventional meanings of the two methods
  2095. /// match. If they don't, it's a hard error.
  2096. static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
  2097. ObjCMethodDecl *decl) {
  2098. ObjCMethodFamily implFamily = impl->getMethodFamily();
  2099. ObjCMethodFamily declFamily = decl->getMethodFamily();
  2100. if (implFamily == declFamily) return false;
  2101. // Since conventions are sorted by selector, the only possibility is
  2102. // that the types differ enough to cause one selector or the other
  2103. // to fall out of the family.
  2104. assert(implFamily == OMF_None || declFamily == OMF_None);
  2105. // No further diagnostics required on invalid declarations.
  2106. if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
  2107. const ObjCMethodDecl *unmatched = impl;
  2108. ObjCMethodFamily family = declFamily;
  2109. unsigned errorID = diag::err_arc_lost_method_convention;
  2110. unsigned noteID = diag::note_arc_lost_method_convention;
  2111. if (declFamily == OMF_None) {
  2112. unmatched = decl;
  2113. family = implFamily;
  2114. errorID = diag::err_arc_gained_method_convention;
  2115. noteID = diag::note_arc_gained_method_convention;
  2116. }
  2117. // Indexes into a %select clause in the diagnostic.
  2118. enum FamilySelector {
  2119. F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
  2120. };
  2121. FamilySelector familySelector = FamilySelector();
  2122. switch (family) {
  2123. case OMF_None: llvm_unreachable("logic error, no method convention");
  2124. case OMF_retain:
  2125. case OMF_release:
  2126. case OMF_autorelease:
  2127. case OMF_dealloc:
  2128. case OMF_finalize:
  2129. case OMF_retainCount:
  2130. case OMF_self:
  2131. case OMF_initialize:
  2132. case OMF_performSelector:
  2133. // Mismatches for these methods don't change ownership
  2134. // conventions, so we don't care.
  2135. return false;
  2136. case OMF_init: familySelector = F_init; break;
  2137. case OMF_alloc: familySelector = F_alloc; break;
  2138. case OMF_copy: familySelector = F_copy; break;
  2139. case OMF_mutableCopy: familySelector = F_mutableCopy; break;
  2140. case OMF_new: familySelector = F_new; break;
  2141. }
  2142. enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
  2143. ReasonSelector reasonSelector;
  2144. // The only reason these methods don't fall within their families is
  2145. // due to unusual result types.
  2146. if (unmatched->getReturnType()->isObjCObjectPointerType()) {
  2147. reasonSelector = R_UnrelatedReturn;
  2148. } else {
  2149. reasonSelector = R_NonObjectReturn;
  2150. }
  2151. S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
  2152. S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
  2153. return true;
  2154. }
  2155. void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
  2156. ObjCMethodDecl *MethodDecl,
  2157. bool IsProtocolMethodDecl) {
  2158. if (getLangOpts().ObjCAutoRefCount &&
  2159. checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
  2160. return;
  2161. CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
  2162. IsProtocolMethodDecl, false,
  2163. true);
  2164. for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
  2165. IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
  2166. EF = MethodDecl->param_end();
  2167. IM != EM && IF != EF; ++IM, ++IF) {
  2168. CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
  2169. IsProtocolMethodDecl, false, true);
  2170. }
  2171. if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
  2172. Diag(ImpMethodDecl->getLocation(),
  2173. diag::warn_conflicting_variadic);
  2174. Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
  2175. }
  2176. }
  2177. void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
  2178. ObjCMethodDecl *Overridden,
  2179. bool IsProtocolMethodDecl) {
  2180. CheckMethodOverrideReturn(*this, Method, Overridden,
  2181. IsProtocolMethodDecl, true,
  2182. true);
  2183. for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
  2184. IF = Overridden->param_begin(), EM = Method->param_end(),
  2185. EF = Overridden->param_end();
  2186. IM != EM && IF != EF; ++IM, ++IF) {
  2187. CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
  2188. IsProtocolMethodDecl, true, true);
  2189. }
  2190. if (Method->isVariadic() != Overridden->isVariadic()) {
  2191. Diag(Method->getLocation(),
  2192. diag::warn_conflicting_overriding_variadic);
  2193. Diag(Overridden->getLocation(), diag::note_previous_declaration);
  2194. }
  2195. }
  2196. /// WarnExactTypedMethods - This routine issues a warning if method
  2197. /// implementation declaration matches exactly that of its declaration.
  2198. void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
  2199. ObjCMethodDecl *MethodDecl,
  2200. bool IsProtocolMethodDecl) {
  2201. // don't issue warning when protocol method is optional because primary
  2202. // class is not required to implement it and it is safe for protocol
  2203. // to implement it.
  2204. if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
  2205. return;
  2206. // don't issue warning when primary class's method is
  2207. // depecated/unavailable.
  2208. if (MethodDecl->hasAttr<UnavailableAttr>() ||
  2209. MethodDecl->hasAttr<DeprecatedAttr>())
  2210. return;
  2211. bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
  2212. IsProtocolMethodDecl, false, false);
  2213. if (match)
  2214. for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
  2215. IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
  2216. EF = MethodDecl->param_end();
  2217. IM != EM && IF != EF; ++IM, ++IF) {
  2218. match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
  2219. *IM, *IF,
  2220. IsProtocolMethodDecl, false, false);
  2221. if (!match)
  2222. break;
  2223. }
  2224. if (match)
  2225. match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
  2226. if (match)
  2227. match = !(MethodDecl->isClassMethod() &&
  2228. MethodDecl->getSelector() == GetNullarySelector("load", Context));
  2229. if (match) {
  2230. Diag(ImpMethodDecl->getLocation(),
  2231. diag::warn_category_method_impl_match);
  2232. Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
  2233. << MethodDecl->getDeclName();
  2234. }
  2235. }
  2236. /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
  2237. /// improve the efficiency of selector lookups and type checking by associating
  2238. /// with each protocol / interface / category the flattened instance tables. If
  2239. /// we used an immutable set to keep the table then it wouldn't add significant
  2240. /// memory cost and it would be handy for lookups.
  2241. typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
  2242. typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
  2243. static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
  2244. ProtocolNameSet &PNS) {
  2245. if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
  2246. PNS.insert(PDecl->getIdentifier());
  2247. for (const auto *PI : PDecl->protocols())
  2248. findProtocolsWithExplicitImpls(PI, PNS);
  2249. }
  2250. /// Recursively populates a set with all conformed protocols in a class
  2251. /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
  2252. /// attribute.
  2253. static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
  2254. ProtocolNameSet &PNS) {
  2255. if (!Super)
  2256. return;
  2257. for (const auto *I : Super->all_referenced_protocols())
  2258. findProtocolsWithExplicitImpls(I, PNS);
  2259. findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
  2260. }
  2261. /// CheckProtocolMethodDefs - This routine checks unimplemented methods
  2262. /// Declared in protocol, and those referenced by it.
  2263. static void CheckProtocolMethodDefs(Sema &S,
  2264. SourceLocation ImpLoc,
  2265. ObjCProtocolDecl *PDecl,
  2266. bool& IncompleteImpl,
  2267. const Sema::SelectorSet &InsMap,
  2268. const Sema::SelectorSet &ClsMap,
  2269. ObjCContainerDecl *CDecl,
  2270. LazyProtocolNameSet &ProtocolsExplictImpl) {
  2271. ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
  2272. ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
  2273. : dyn_cast<ObjCInterfaceDecl>(CDecl);
  2274. assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
  2275. ObjCInterfaceDecl *Super = IDecl->getSuperClass();
  2276. ObjCInterfaceDecl *NSIDecl = nullptr;
  2277. // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
  2278. // then we should check if any class in the super class hierarchy also
  2279. // conforms to this protocol, either directly or via protocol inheritance.
  2280. // If so, we can skip checking this protocol completely because we
  2281. // know that a parent class already satisfies this protocol.
  2282. //
  2283. // Note: we could generalize this logic for all protocols, and merely
  2284. // add the limit on looking at the super class chain for just
  2285. // specially marked protocols. This may be a good optimization. This
  2286. // change is restricted to 'objc_protocol_requires_explicit_implementation'
  2287. // protocols for now for controlled evaluation.
  2288. if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
  2289. if (!ProtocolsExplictImpl) {
  2290. ProtocolsExplictImpl.reset(new ProtocolNameSet);
  2291. findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
  2292. }
  2293. if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
  2294. ProtocolsExplictImpl->end())
  2295. return;
  2296. // If no super class conforms to the protocol, we should not search
  2297. // for methods in the super class to implicitly satisfy the protocol.
  2298. Super = nullptr;
  2299. }
  2300. if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
  2301. // check to see if class implements forwardInvocation method and objects
  2302. // of this class are derived from 'NSProxy' so that to forward requests
  2303. // from one object to another.
  2304. // Under such conditions, which means that every method possible is
  2305. // implemented in the class, we should not issue "Method definition not
  2306. // found" warnings.
  2307. // FIXME: Use a general GetUnarySelector method for this.
  2308. IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
  2309. Selector fISelector = S.Context.Selectors.getSelector(1, &II);
  2310. if (InsMap.count(fISelector))
  2311. // Is IDecl derived from 'NSProxy'? If so, no instance methods
  2312. // need be implemented in the implementation.
  2313. NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
  2314. }
  2315. // If this is a forward protocol declaration, get its definition.
  2316. if (!PDecl->isThisDeclarationADefinition() &&
  2317. PDecl->getDefinition())
  2318. PDecl = PDecl->getDefinition();
  2319. // If a method lookup fails locally we still need to look and see if
  2320. // the method was implemented by a base class or an inherited
  2321. // protocol. This lookup is slow, but occurs rarely in correct code
  2322. // and otherwise would terminate in a warning.
  2323. // check unimplemented instance methods.
  2324. if (!NSIDecl)
  2325. for (auto *method : PDecl->instance_methods()) {
  2326. if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
  2327. !method->isPropertyAccessor() &&
  2328. !InsMap.count(method->getSelector()) &&
  2329. (!Super || !Super->lookupMethod(method->getSelector(),
  2330. true /* instance */,
  2331. false /* shallowCategory */,
  2332. true /* followsSuper */,
  2333. nullptr /* category */))) {
  2334. // If a method is not implemented in the category implementation but
  2335. // has been declared in its primary class, superclass,
  2336. // or in one of their protocols, no need to issue the warning.
  2337. // This is because method will be implemented in the primary class
  2338. // or one of its super class implementation.
  2339. // Ugly, but necessary. Method declared in protcol might have
  2340. // have been synthesized due to a property declared in the class which
  2341. // uses the protocol.
  2342. if (ObjCMethodDecl *MethodInClass =
  2343. IDecl->lookupMethod(method->getSelector(),
  2344. true /* instance */,
  2345. true /* shallowCategoryLookup */,
  2346. false /* followSuper */))
  2347. if (C || MethodInClass->isPropertyAccessor())
  2348. continue;
  2349. unsigned DIAG = diag::warn_unimplemented_protocol_method;
  2350. if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
  2351. WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
  2352. PDecl);
  2353. }
  2354. }
  2355. }
  2356. // check unimplemented class methods
  2357. for (auto *method : PDecl->class_methods()) {
  2358. if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
  2359. !ClsMap.count(method->getSelector()) &&
  2360. (!Super || !Super->lookupMethod(method->getSelector(),
  2361. false /* class method */,
  2362. false /* shallowCategoryLookup */,
  2363. true /* followSuper */,
  2364. nullptr /* category */))) {
  2365. // See above comment for instance method lookups.
  2366. if (C && IDecl->lookupMethod(method->getSelector(),
  2367. false /* class */,
  2368. true /* shallowCategoryLookup */,
  2369. false /* followSuper */))
  2370. continue;
  2371. unsigned DIAG = diag::warn_unimplemented_protocol_method;
  2372. if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
  2373. WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
  2374. }
  2375. }
  2376. }
  2377. // Check on this protocols's referenced protocols, recursively.
  2378. for (auto *PI : PDecl->protocols())
  2379. CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
  2380. CDecl, ProtocolsExplictImpl);
  2381. }
  2382. /// MatchAllMethodDeclarations - Check methods declared in interface
  2383. /// or protocol against those declared in their implementations.
  2384. ///
  2385. void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
  2386. const SelectorSet &ClsMap,
  2387. SelectorSet &InsMapSeen,
  2388. SelectorSet &ClsMapSeen,
  2389. ObjCImplDecl* IMPDecl,
  2390. ObjCContainerDecl* CDecl,
  2391. bool &IncompleteImpl,
  2392. bool ImmediateClass,
  2393. bool WarnCategoryMethodImpl) {
  2394. // Check and see if instance methods in class interface have been
  2395. // implemented in the implementation class. If so, their types match.
  2396. for (auto *I : CDecl->instance_methods()) {
  2397. if (!InsMapSeen.insert(I->getSelector()).second)
  2398. continue;
  2399. if (!I->isPropertyAccessor() &&
  2400. !InsMap.count(I->getSelector())) {
  2401. if (ImmediateClass)
  2402. WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
  2403. diag::warn_undef_method_impl);
  2404. continue;
  2405. } else {
  2406. ObjCMethodDecl *ImpMethodDecl =
  2407. IMPDecl->getInstanceMethod(I->getSelector());
  2408. assert(CDecl->getInstanceMethod(I->getSelector()) &&
  2409. "Expected to find the method through lookup as well");
  2410. // ImpMethodDecl may be null as in a @dynamic property.
  2411. if (ImpMethodDecl) {
  2412. if (!WarnCategoryMethodImpl)
  2413. WarnConflictingTypedMethods(ImpMethodDecl, I,
  2414. isa<ObjCProtocolDecl>(CDecl));
  2415. else if (!I->isPropertyAccessor())
  2416. WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
  2417. }
  2418. }
  2419. }
  2420. // Check and see if class methods in class interface have been
  2421. // implemented in the implementation class. If so, their types match.
  2422. for (auto *I : CDecl->class_methods()) {
  2423. if (!ClsMapSeen.insert(I->getSelector()).second)
  2424. continue;
  2425. if (!ClsMap.count(I->getSelector())) {
  2426. if (ImmediateClass)
  2427. WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
  2428. diag::warn_undef_method_impl);
  2429. } else {
  2430. ObjCMethodDecl *ImpMethodDecl =
  2431. IMPDecl->getClassMethod(I->getSelector());
  2432. assert(CDecl->getClassMethod(I->getSelector()) &&
  2433. "Expected to find the method through lookup as well");
  2434. if (!WarnCategoryMethodImpl)
  2435. WarnConflictingTypedMethods(ImpMethodDecl, I,
  2436. isa<ObjCProtocolDecl>(CDecl));
  2437. else
  2438. WarnExactTypedMethods(ImpMethodDecl, I,
  2439. isa<ObjCProtocolDecl>(CDecl));
  2440. }
  2441. }
  2442. if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
  2443. // Also, check for methods declared in protocols inherited by
  2444. // this protocol.
  2445. for (auto *PI : PD->protocols())
  2446. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2447. IMPDecl, PI, IncompleteImpl, false,
  2448. WarnCategoryMethodImpl);
  2449. }
  2450. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
  2451. // when checking that methods in implementation match their declaration,
  2452. // i.e. when WarnCategoryMethodImpl is false, check declarations in class
  2453. // extension; as well as those in categories.
  2454. if (!WarnCategoryMethodImpl) {
  2455. for (auto *Cat : I->visible_categories())
  2456. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2457. IMPDecl, Cat, IncompleteImpl, false,
  2458. WarnCategoryMethodImpl);
  2459. } else {
  2460. // Also methods in class extensions need be looked at next.
  2461. for (auto *Ext : I->visible_extensions())
  2462. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2463. IMPDecl, Ext, IncompleteImpl, false,
  2464. WarnCategoryMethodImpl);
  2465. }
  2466. // Check for any implementation of a methods declared in protocol.
  2467. for (auto *PI : I->all_referenced_protocols())
  2468. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2469. IMPDecl, PI, IncompleteImpl, false,
  2470. WarnCategoryMethodImpl);
  2471. // FIXME. For now, we are not checking for extact match of methods
  2472. // in category implementation and its primary class's super class.
  2473. if (!WarnCategoryMethodImpl && I->getSuperClass())
  2474. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2475. IMPDecl,
  2476. I->getSuperClass(), IncompleteImpl, false);
  2477. }
  2478. }
  2479. /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
  2480. /// category matches with those implemented in its primary class and
  2481. /// warns each time an exact match is found.
  2482. void Sema::CheckCategoryVsClassMethodMatches(
  2483. ObjCCategoryImplDecl *CatIMPDecl) {
  2484. // Get category's primary class.
  2485. ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
  2486. if (!CatDecl)
  2487. return;
  2488. ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
  2489. if (!IDecl)
  2490. return;
  2491. ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
  2492. SelectorSet InsMap, ClsMap;
  2493. for (const auto *I : CatIMPDecl->instance_methods()) {
  2494. Selector Sel = I->getSelector();
  2495. // When checking for methods implemented in the category, skip over
  2496. // those declared in category class's super class. This is because
  2497. // the super class must implement the method.
  2498. if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
  2499. continue;
  2500. InsMap.insert(Sel);
  2501. }
  2502. for (const auto *I : CatIMPDecl->class_methods()) {
  2503. Selector Sel = I->getSelector();
  2504. if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
  2505. continue;
  2506. ClsMap.insert(Sel);
  2507. }
  2508. if (InsMap.empty() && ClsMap.empty())
  2509. return;
  2510. SelectorSet InsMapSeen, ClsMapSeen;
  2511. bool IncompleteImpl = false;
  2512. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2513. CatIMPDecl, IDecl,
  2514. IncompleteImpl, false,
  2515. true /*WarnCategoryMethodImpl*/);
  2516. }
  2517. void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
  2518. ObjCContainerDecl* CDecl,
  2519. bool IncompleteImpl) {
  2520. SelectorSet InsMap;
  2521. // Check and see if instance methods in class interface have been
  2522. // implemented in the implementation class.
  2523. for (const auto *I : IMPDecl->instance_methods())
  2524. InsMap.insert(I->getSelector());
  2525. // Check and see if properties declared in the interface have either 1)
  2526. // an implementation or 2) there is a @synthesize/@dynamic implementation
  2527. // of the property in the @implementation.
  2528. if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  2529. bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
  2530. LangOpts.ObjCRuntime.isNonFragile() &&
  2531. !IDecl->isObjCRequiresPropertyDefs();
  2532. DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
  2533. }
  2534. // Diagnose null-resettable synthesized setters.
  2535. diagnoseNullResettableSynthesizedSetters(IMPDecl);
  2536. SelectorSet ClsMap;
  2537. for (const auto *I : IMPDecl->class_methods())
  2538. ClsMap.insert(I->getSelector());
  2539. // Check for type conflict of methods declared in a class/protocol and
  2540. // its implementation; if any.
  2541. SelectorSet InsMapSeen, ClsMapSeen;
  2542. MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
  2543. IMPDecl, CDecl,
  2544. IncompleteImpl, true);
  2545. // check all methods implemented in category against those declared
  2546. // in its primary class.
  2547. if (ObjCCategoryImplDecl *CatDecl =
  2548. dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
  2549. CheckCategoryVsClassMethodMatches(CatDecl);
  2550. // Check the protocol list for unimplemented methods in the @implementation
  2551. // class.
  2552. // Check and see if class methods in class interface have been
  2553. // implemented in the implementation class.
  2554. LazyProtocolNameSet ExplicitImplProtocols;
  2555. if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
  2556. for (auto *PI : I->all_referenced_protocols())
  2557. CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
  2558. InsMap, ClsMap, I, ExplicitImplProtocols);
  2559. // Check class extensions (unnamed categories)
  2560. for (auto *Ext : I->visible_extensions())
  2561. ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
  2562. } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  2563. // For extended class, unimplemented methods in its protocols will
  2564. // be reported in the primary class.
  2565. if (!C->IsClassExtension()) {
  2566. for (auto *P : C->protocols())
  2567. CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
  2568. IncompleteImpl, InsMap, ClsMap, CDecl,
  2569. ExplicitImplProtocols);
  2570. DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
  2571. /*SynthesizeProperties=*/false);
  2572. }
  2573. } else
  2574. llvm_unreachable("invalid ObjCContainerDecl type.");
  2575. }
  2576. Sema::DeclGroupPtrTy
  2577. Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
  2578. IdentifierInfo **IdentList,
  2579. SourceLocation *IdentLocs,
  2580. ArrayRef<ObjCTypeParamList *> TypeParamLists,
  2581. unsigned NumElts) {
  2582. SmallVector<Decl *, 8> DeclsInGroup;
  2583. for (unsigned i = 0; i != NumElts; ++i) {
  2584. // Check for another declaration kind with the same name.
  2585. NamedDecl *PrevDecl
  2586. = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
  2587. LookupOrdinaryName, ForRedeclaration);
  2588. if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
  2589. // GCC apparently allows the following idiom:
  2590. //
  2591. // typedef NSObject < XCElementTogglerP > XCElementToggler;
  2592. // @class XCElementToggler;
  2593. //
  2594. // Here we have chosen to ignore the forward class declaration
  2595. // with a warning. Since this is the implied behavior.
  2596. TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
  2597. if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
  2598. Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
  2599. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  2600. } else {
  2601. // a forward class declaration matching a typedef name of a class refers
  2602. // to the underlying class. Just ignore the forward class with a warning
  2603. // as this will force the intended behavior which is to lookup the
  2604. // typedef name.
  2605. if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
  2606. Diag(AtClassLoc, diag::warn_forward_class_redefinition)
  2607. << IdentList[i];
  2608. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  2609. continue;
  2610. }
  2611. }
  2612. }
  2613. // Create a declaration to describe this forward declaration.
  2614. ObjCInterfaceDecl *PrevIDecl
  2615. = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
  2616. IdentifierInfo *ClassName = IdentList[i];
  2617. if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
  2618. // A previous decl with a different name is because of
  2619. // @compatibility_alias, for example:
  2620. // \code
  2621. // @class NewImage;
  2622. // @compatibility_alias OldImage NewImage;
  2623. // \endcode
  2624. // A lookup for 'OldImage' will return the 'NewImage' decl.
  2625. //
  2626. // In such a case use the real declaration name, instead of the alias one,
  2627. // otherwise we will break IdentifierResolver and redecls-chain invariants.
  2628. // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
  2629. // has been aliased.
  2630. ClassName = PrevIDecl->getIdentifier();
  2631. }
  2632. // If this forward declaration has type parameters, compare them with the
  2633. // type parameters of the previous declaration.
  2634. ObjCTypeParamList *TypeParams = TypeParamLists[i];
  2635. if (PrevIDecl && TypeParams) {
  2636. if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
  2637. // Check for consistency with the previous declaration.
  2638. if (checkTypeParamListConsistency(
  2639. *this, PrevTypeParams, TypeParams,
  2640. TypeParamListContext::ForwardDeclaration)) {
  2641. TypeParams = nullptr;
  2642. }
  2643. } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
  2644. // The @interface does not have type parameters. Complain.
  2645. Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
  2646. << ClassName
  2647. << TypeParams->getSourceRange();
  2648. Diag(Def->getLocation(), diag::note_defined_here)
  2649. << ClassName;
  2650. TypeParams = nullptr;
  2651. }
  2652. }
  2653. ObjCInterfaceDecl *IDecl
  2654. = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
  2655. ClassName, TypeParams, PrevIDecl,
  2656. IdentLocs[i]);
  2657. IDecl->setAtEndRange(IdentLocs[i]);
  2658. PushOnScopeChains(IDecl, TUScope);
  2659. CheckObjCDeclScope(IDecl);
  2660. DeclsInGroup.push_back(IDecl);
  2661. }
  2662. return BuildDeclaratorGroup(DeclsInGroup, false);
  2663. }
  2664. static bool tryMatchRecordTypes(ASTContext &Context,
  2665. Sema::MethodMatchStrategy strategy,
  2666. const Type *left, const Type *right);
  2667. static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
  2668. QualType leftQT, QualType rightQT) {
  2669. const Type *left =
  2670. Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
  2671. const Type *right =
  2672. Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
  2673. if (left == right) return true;
  2674. // If we're doing a strict match, the types have to match exactly.
  2675. if (strategy == Sema::MMS_strict) return false;
  2676. if (left->isIncompleteType() || right->isIncompleteType()) return false;
  2677. // Otherwise, use this absurdly complicated algorithm to try to
  2678. // validate the basic, low-level compatibility of the two types.
  2679. // As a minimum, require the sizes and alignments to match.
  2680. TypeInfo LeftTI = Context.getTypeInfo(left);
  2681. TypeInfo RightTI = Context.getTypeInfo(right);
  2682. if (LeftTI.Width != RightTI.Width)
  2683. return false;
  2684. if (LeftTI.Align != RightTI.Align)
  2685. return false;
  2686. // Consider all the kinds of non-dependent canonical types:
  2687. // - functions and arrays aren't possible as return and parameter types
  2688. // - vector types of equal size can be arbitrarily mixed
  2689. if (isa<VectorType>(left)) return isa<VectorType>(right);
  2690. if (isa<VectorType>(right)) return false;
  2691. // - references should only match references of identical type
  2692. // - structs, unions, and Objective-C objects must match more-or-less
  2693. // exactly
  2694. // - everything else should be a scalar
  2695. if (!left->isScalarType() || !right->isScalarType())
  2696. return tryMatchRecordTypes(Context, strategy, left, right);
  2697. // Make scalars agree in kind, except count bools as chars, and group
  2698. // all non-member pointers together.
  2699. Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
  2700. Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
  2701. if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
  2702. if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
  2703. if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
  2704. leftSK = Type::STK_ObjCObjectPointer;
  2705. if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
  2706. rightSK = Type::STK_ObjCObjectPointer;
  2707. // Note that data member pointers and function member pointers don't
  2708. // intermix because of the size differences.
  2709. return (leftSK == rightSK);
  2710. }
  2711. static bool tryMatchRecordTypes(ASTContext &Context,
  2712. Sema::MethodMatchStrategy strategy,
  2713. const Type *lt, const Type *rt) {
  2714. assert(lt && rt && lt != rt);
  2715. if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
  2716. RecordDecl *left = cast<RecordType>(lt)->getDecl();
  2717. RecordDecl *right = cast<RecordType>(rt)->getDecl();
  2718. // Require union-hood to match.
  2719. if (left->isUnion() != right->isUnion()) return false;
  2720. // Require an exact match if either is non-POD.
  2721. if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
  2722. (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
  2723. return false;
  2724. // Require size and alignment to match.
  2725. TypeInfo LeftTI = Context.getTypeInfo(lt);
  2726. TypeInfo RightTI = Context.getTypeInfo(rt);
  2727. if (LeftTI.Width != RightTI.Width)
  2728. return false;
  2729. if (LeftTI.Align != RightTI.Align)
  2730. return false;
  2731. // Require fields to match.
  2732. RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
  2733. RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
  2734. for (; li != le && ri != re; ++li, ++ri) {
  2735. if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
  2736. return false;
  2737. }
  2738. return (li == le && ri == re);
  2739. }
  2740. /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
  2741. /// returns true, or false, accordingly.
  2742. /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
  2743. bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
  2744. const ObjCMethodDecl *right,
  2745. MethodMatchStrategy strategy) {
  2746. if (!matchTypes(Context, strategy, left->getReturnType(),
  2747. right->getReturnType()))
  2748. return false;
  2749. // If either is hidden, it is not considered to match.
  2750. if (left->isHidden() || right->isHidden())
  2751. return false;
  2752. if (getLangOpts().ObjCAutoRefCount &&
  2753. (left->hasAttr<NSReturnsRetainedAttr>()
  2754. != right->hasAttr<NSReturnsRetainedAttr>() ||
  2755. left->hasAttr<NSConsumesSelfAttr>()
  2756. != right->hasAttr<NSConsumesSelfAttr>()))
  2757. return false;
  2758. ObjCMethodDecl::param_const_iterator
  2759. li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
  2760. re = right->param_end();
  2761. for (; li != le && ri != re; ++li, ++ri) {
  2762. assert(ri != right->param_end() && "Param mismatch");
  2763. const ParmVarDecl *lparm = *li, *rparm = *ri;
  2764. if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
  2765. return false;
  2766. if (getLangOpts().ObjCAutoRefCount &&
  2767. lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
  2768. return false;
  2769. }
  2770. return true;
  2771. }
  2772. void Sema::addMethodToGlobalList(ObjCMethodList *List,
  2773. ObjCMethodDecl *Method) {
  2774. // Record at the head of the list whether there were 0, 1, or >= 2 methods
  2775. // inside categories.
  2776. if (ObjCCategoryDecl *CD =
  2777. dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
  2778. if (!CD->IsClassExtension() && List->getBits() < 2)
  2779. List->setBits(List->getBits() + 1);
  2780. // If the list is empty, make it a singleton list.
  2781. if (List->getMethod() == nullptr) {
  2782. List->setMethod(Method);
  2783. List->setNext(nullptr);
  2784. return;
  2785. }
  2786. // We've seen a method with this name, see if we have already seen this type
  2787. // signature.
  2788. ObjCMethodList *Previous = List;
  2789. for (; List; Previous = List, List = List->getNext()) {
  2790. // If we are building a module, keep all of the methods.
  2791. if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
  2792. continue;
  2793. if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
  2794. // Even if two method types do not match, we would like to say
  2795. // there is more than one declaration so unavailability/deprecated
  2796. // warning is not too noisy.
  2797. if (!Method->isDefined())
  2798. List->setHasMoreThanOneDecl(true);
  2799. continue;
  2800. }
  2801. ObjCMethodDecl *PrevObjCMethod = List->getMethod();
  2802. // Propagate the 'defined' bit.
  2803. if (Method->isDefined())
  2804. PrevObjCMethod->setDefined(true);
  2805. else {
  2806. // Objective-C doesn't allow an @interface for a class after its
  2807. // @implementation. So if Method is not defined and there already is
  2808. // an entry for this type signature, Method has to be for a different
  2809. // class than PrevObjCMethod.
  2810. List->setHasMoreThanOneDecl(true);
  2811. }
  2812. // If a method is deprecated, push it in the global pool.
  2813. // This is used for better diagnostics.
  2814. if (Method->isDeprecated()) {
  2815. if (!PrevObjCMethod->isDeprecated())
  2816. List->setMethod(Method);
  2817. }
  2818. // If the new method is unavailable, push it into global pool
  2819. // unless previous one is deprecated.
  2820. if (Method->isUnavailable()) {
  2821. if (PrevObjCMethod->getAvailability() < AR_Deprecated)
  2822. List->setMethod(Method);
  2823. }
  2824. return;
  2825. }
  2826. // We have a new signature for an existing method - add it.
  2827. // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
  2828. ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
  2829. Previous->setNext(new (Mem) ObjCMethodList(Method));
  2830. }
  2831. /// \brief Read the contents of the method pool for a given selector from
  2832. /// external storage.
  2833. void Sema::ReadMethodPool(Selector Sel) {
  2834. assert(ExternalSource && "We need an external AST source");
  2835. ExternalSource->ReadMethodPool(Sel);
  2836. }
  2837. void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
  2838. bool instance) {
  2839. // Ignore methods of invalid containers.
  2840. if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
  2841. return;
  2842. if (ExternalSource)
  2843. ReadMethodPool(Method->getSelector());
  2844. GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
  2845. if (Pos == MethodPool.end())
  2846. Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
  2847. GlobalMethods())).first;
  2848. Method->setDefined(impl);
  2849. ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
  2850. addMethodToGlobalList(&Entry, Method);
  2851. }
  2852. /// Determines if this is an "acceptable" loose mismatch in the global
  2853. /// method pool. This exists mostly as a hack to get around certain
  2854. /// global mismatches which we can't afford to make warnings / errors.
  2855. /// Really, what we want is a way to take a method out of the global
  2856. /// method pool.
  2857. static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
  2858. ObjCMethodDecl *other) {
  2859. if (!chosen->isInstanceMethod())
  2860. return false;
  2861. Selector sel = chosen->getSelector();
  2862. if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
  2863. return false;
  2864. // Don't complain about mismatches for -length if the method we
  2865. // chose has an integral result type.
  2866. return (chosen->getReturnType()->isIntegerType());
  2867. }
  2868. bool Sema::CollectMultipleMethodsInGlobalPool(
  2869. Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
  2870. if (ExternalSource)
  2871. ReadMethodPool(Sel);
  2872. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  2873. if (Pos == MethodPool.end())
  2874. return false;
  2875. // Gather the non-hidden methods.
  2876. ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
  2877. for (ObjCMethodList *M = &MethList; M; M = M->getNext())
  2878. if (M->getMethod() && !M->getMethod()->isHidden())
  2879. Methods.push_back(M->getMethod());
  2880. return Methods.size() > 1;
  2881. }
  2882. bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
  2883. SourceRange R,
  2884. bool receiverIdOrClass) {
  2885. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  2886. // Test for no method in the pool which should not trigger any warning by
  2887. // caller.
  2888. if (Pos == MethodPool.end())
  2889. return true;
  2890. ObjCMethodList &MethList =
  2891. BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
  2892. // Diagnose finding more than one method in global pool
  2893. SmallVector<ObjCMethodDecl *, 4> Methods;
  2894. Methods.push_back(BestMethod);
  2895. for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext())
  2896. if (ObjCMethodDecl *M = ML->getMethod())
  2897. if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>())
  2898. Methods.push_back(M);
  2899. if (Methods.size() > 1)
  2900. DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
  2901. return MethList.hasMoreThanOneDecl();
  2902. }
  2903. ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
  2904. bool receiverIdOrClass,
  2905. bool instance) {
  2906. if (ExternalSource)
  2907. ReadMethodPool(Sel);
  2908. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  2909. if (Pos == MethodPool.end())
  2910. return nullptr;
  2911. // Gather the non-hidden methods.
  2912. ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
  2913. SmallVector<ObjCMethodDecl *, 4> Methods;
  2914. for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
  2915. if (M->getMethod() && !M->getMethod()->isHidden())
  2916. return M->getMethod();
  2917. }
  2918. return nullptr;
  2919. }
  2920. void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
  2921. Selector Sel, SourceRange R,
  2922. bool receiverIdOrClass) {
  2923. // We found multiple methods, so we may have to complain.
  2924. bool issueDiagnostic = false, issueError = false;
  2925. // We support a warning which complains about *any* difference in
  2926. // method signature.
  2927. bool strictSelectorMatch =
  2928. receiverIdOrClass &&
  2929. !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
  2930. if (strictSelectorMatch) {
  2931. for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
  2932. if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
  2933. issueDiagnostic = true;
  2934. break;
  2935. }
  2936. }
  2937. }
  2938. // If we didn't see any strict differences, we won't see any loose
  2939. // differences. In ARC, however, we also need to check for loose
  2940. // mismatches, because most of them are errors.
  2941. if (!strictSelectorMatch ||
  2942. (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
  2943. for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
  2944. // This checks if the methods differ in type mismatch.
  2945. if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
  2946. !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
  2947. issueDiagnostic = true;
  2948. if (getLangOpts().ObjCAutoRefCount)
  2949. issueError = true;
  2950. break;
  2951. }
  2952. }
  2953. if (issueDiagnostic) {
  2954. if (issueError)
  2955. Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
  2956. else if (strictSelectorMatch)
  2957. Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
  2958. else
  2959. Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
  2960. Diag(Methods[0]->getLocStart(),
  2961. issueError ? diag::note_possibility : diag::note_using)
  2962. << Methods[0]->getSourceRange();
  2963. for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
  2964. Diag(Methods[I]->getLocStart(), diag::note_also_found)
  2965. << Methods[I]->getSourceRange();
  2966. }
  2967. }
  2968. }
  2969. ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
  2970. GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
  2971. if (Pos == MethodPool.end())
  2972. return nullptr;
  2973. GlobalMethods &Methods = Pos->second;
  2974. for (const ObjCMethodList *Method = &Methods.first; Method;
  2975. Method = Method->getNext())
  2976. if (Method->getMethod() &&
  2977. (Method->getMethod()->isDefined() ||
  2978. Method->getMethod()->isPropertyAccessor()))
  2979. return Method->getMethod();
  2980. for (const ObjCMethodList *Method = &Methods.second; Method;
  2981. Method = Method->getNext())
  2982. if (Method->getMethod() &&
  2983. (Method->getMethod()->isDefined() ||
  2984. Method->getMethod()->isPropertyAccessor()))
  2985. return Method->getMethod();
  2986. return nullptr;
  2987. }
  2988. static void
  2989. HelperSelectorsForTypoCorrection(
  2990. SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
  2991. StringRef Typo, const ObjCMethodDecl * Method) {
  2992. const unsigned MaxEditDistance = 1;
  2993. unsigned BestEditDistance = MaxEditDistance + 1;
  2994. std::string MethodName = Method->getSelector().getAsString();
  2995. unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
  2996. if (MinPossibleEditDistance > 0 &&
  2997. Typo.size() / MinPossibleEditDistance < 1)
  2998. return;
  2999. unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
  3000. if (EditDistance > MaxEditDistance)
  3001. return;
  3002. if (EditDistance == BestEditDistance)
  3003. BestMethod.push_back(Method);
  3004. else if (EditDistance < BestEditDistance) {
  3005. BestMethod.clear();
  3006. BestMethod.push_back(Method);
  3007. }
  3008. }
  3009. static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
  3010. QualType ObjectType) {
  3011. if (ObjectType.isNull())
  3012. return true;
  3013. if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
  3014. return true;
  3015. return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
  3016. nullptr;
  3017. }
  3018. const ObjCMethodDecl *
  3019. Sema::SelectorsForTypoCorrection(Selector Sel,
  3020. QualType ObjectType) {
  3021. unsigned NumArgs = Sel.getNumArgs();
  3022. SmallVector<const ObjCMethodDecl *, 8> Methods;
  3023. bool ObjectIsId = true, ObjectIsClass = true;
  3024. if (ObjectType.isNull())
  3025. ObjectIsId = ObjectIsClass = false;
  3026. else if (!ObjectType->isObjCObjectPointerType())
  3027. return nullptr;
  3028. else if (const ObjCObjectPointerType *ObjCPtr =
  3029. ObjectType->getAsObjCInterfacePointerType()) {
  3030. ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
  3031. ObjectIsId = ObjectIsClass = false;
  3032. }
  3033. else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
  3034. ObjectIsClass = false;
  3035. else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
  3036. ObjectIsId = false;
  3037. else
  3038. return nullptr;
  3039. for (GlobalMethodPool::iterator b = MethodPool.begin(),
  3040. e = MethodPool.end(); b != e; b++) {
  3041. // instance methods
  3042. for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
  3043. if (M->getMethod() &&
  3044. (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
  3045. (M->getMethod()->getSelector() != Sel)) {
  3046. if (ObjectIsId)
  3047. Methods.push_back(M->getMethod());
  3048. else if (!ObjectIsClass &&
  3049. HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
  3050. ObjectType))
  3051. Methods.push_back(M->getMethod());
  3052. }
  3053. // class methods
  3054. for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
  3055. if (M->getMethod() &&
  3056. (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
  3057. (M->getMethod()->getSelector() != Sel)) {
  3058. if (ObjectIsClass)
  3059. Methods.push_back(M->getMethod());
  3060. else if (!ObjectIsId &&
  3061. HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
  3062. ObjectType))
  3063. Methods.push_back(M->getMethod());
  3064. }
  3065. }
  3066. SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
  3067. for (unsigned i = 0, e = Methods.size(); i < e; i++) {
  3068. HelperSelectorsForTypoCorrection(SelectedMethods,
  3069. Sel.getAsString(), Methods[i]);
  3070. }
  3071. return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
  3072. }
  3073. /// DiagnoseDuplicateIvars -
  3074. /// Check for duplicate ivars in the entire class at the start of
  3075. /// \@implementation. This becomes necesssary because class extension can
  3076. /// add ivars to a class in random order which will not be known until
  3077. /// class's \@implementation is seen.
  3078. void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
  3079. ObjCInterfaceDecl *SID) {
  3080. for (auto *Ivar : ID->ivars()) {
  3081. if (Ivar->isInvalidDecl())
  3082. continue;
  3083. if (IdentifierInfo *II = Ivar->getIdentifier()) {
  3084. ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
  3085. if (prevIvar) {
  3086. Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
  3087. Diag(prevIvar->getLocation(), diag::note_previous_declaration);
  3088. Ivar->setInvalidDecl();
  3089. }
  3090. }
  3091. }
  3092. }
  3093. Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
  3094. switch (CurContext->getDeclKind()) {
  3095. case Decl::ObjCInterface:
  3096. return Sema::OCK_Interface;
  3097. case Decl::ObjCProtocol:
  3098. return Sema::OCK_Protocol;
  3099. case Decl::ObjCCategory:
  3100. if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
  3101. return Sema::OCK_ClassExtension;
  3102. return Sema::OCK_Category;
  3103. case Decl::ObjCImplementation:
  3104. return Sema::OCK_Implementation;
  3105. case Decl::ObjCCategoryImpl:
  3106. return Sema::OCK_CategoryImplementation;
  3107. default:
  3108. return Sema::OCK_None;
  3109. }
  3110. }
  3111. // Note: For class/category implementations, allMethods is always null.
  3112. Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
  3113. ArrayRef<DeclGroupPtrTy> allTUVars) {
  3114. #if 1 // HLSL Change Starts
  3115. (void)(S);
  3116. (void)(AtEnd);
  3117. (void)(allMethods);
  3118. (void)(allTUVars);
  3119. return nullptr;
  3120. #else
  3121. if (getObjCContainerKind() == Sema::OCK_None)
  3122. return nullptr;
  3123. assert(AtEnd.isValid() && "Invalid location for '@end'");
  3124. ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
  3125. Decl *ClassDecl = cast<Decl>(OCD);
  3126. bool isInterfaceDeclKind =
  3127. isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
  3128. || isa<ObjCProtocolDecl>(ClassDecl);
  3129. bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
  3130. // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
  3131. llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
  3132. llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
  3133. for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
  3134. ObjCMethodDecl *Method =
  3135. cast_or_null<ObjCMethodDecl>(allMethods[i]);
  3136. if (!Method) continue; // Already issued a diagnostic.
  3137. if (Method->isInstanceMethod()) {
  3138. /// Check for instance method of the same name with incompatible types
  3139. const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
  3140. bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
  3141. : false;
  3142. if ((isInterfaceDeclKind && PrevMethod && !match)
  3143. || (checkIdenticalMethods && match)) {
  3144. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  3145. << Method->getDeclName();
  3146. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3147. Method->setInvalidDecl();
  3148. } else {
  3149. if (PrevMethod) {
  3150. Method->setAsRedeclaration(PrevMethod);
  3151. if (!Context.getSourceManager().isInSystemHeader(
  3152. Method->getLocation()))
  3153. Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
  3154. << Method->getDeclName();
  3155. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3156. }
  3157. InsMap[Method->getSelector()] = Method;
  3158. /// The following allows us to typecheck messages to "id".
  3159. AddInstanceMethodToGlobalPool(Method);
  3160. }
  3161. } else {
  3162. /// Check for class method of the same name with incompatible types
  3163. const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
  3164. bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
  3165. : false;
  3166. if ((isInterfaceDeclKind && PrevMethod && !match)
  3167. || (checkIdenticalMethods && match)) {
  3168. Diag(Method->getLocation(), diag::err_duplicate_method_decl)
  3169. << Method->getDeclName();
  3170. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3171. Method->setInvalidDecl();
  3172. } else {
  3173. if (PrevMethod) {
  3174. Method->setAsRedeclaration(PrevMethod);
  3175. if (!Context.getSourceManager().isInSystemHeader(
  3176. Method->getLocation()))
  3177. Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
  3178. << Method->getDeclName();
  3179. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3180. }
  3181. ClsMap[Method->getSelector()] = Method;
  3182. AddFactoryMethodToGlobalPool(Method);
  3183. }
  3184. }
  3185. }
  3186. if (isa<ObjCInterfaceDecl>(ClassDecl)) {
  3187. // Nothing to do here.
  3188. } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
  3189. // Categories are used to extend the class by declaring new methods.
  3190. // By the same token, they are also used to add new properties. No
  3191. // need to compare the added property to those in the class.
  3192. if (C->IsClassExtension()) {
  3193. ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
  3194. DiagnoseClassExtensionDupMethods(C, CCPrimary);
  3195. }
  3196. }
  3197. if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
  3198. if (CDecl->getIdentifier())
  3199. // ProcessPropertyDecl is responsible for diagnosing conflicts with any
  3200. // user-defined setter/getter. It also synthesizes setter/getter methods
  3201. // and adds them to the DeclContext and global method pools.
  3202. for (auto *I : CDecl->properties())
  3203. ProcessPropertyDecl(I, CDecl);
  3204. CDecl->setAtEndRange(AtEnd);
  3205. }
  3206. if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
  3207. IC->setAtEndRange(AtEnd);
  3208. if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
  3209. // Any property declared in a class extension might have user
  3210. // declared setter or getter in current class extension or one
  3211. // of the other class extensions. Mark them as synthesized as
  3212. // property will be synthesized when property with same name is
  3213. // seen in the @implementation.
  3214. for (const auto *Ext : IDecl->visible_extensions()) {
  3215. for (const auto *Property : Ext->properties()) {
  3216. // Skip over properties declared @dynamic
  3217. if (const ObjCPropertyImplDecl *PIDecl
  3218. = IC->FindPropertyImplDecl(Property->getIdentifier()))
  3219. if (PIDecl->getPropertyImplementation()
  3220. == ObjCPropertyImplDecl::Dynamic)
  3221. continue;
  3222. for (const auto *Ext : IDecl->visible_extensions()) {
  3223. if (ObjCMethodDecl *GetterMethod
  3224. = Ext->getInstanceMethod(Property->getGetterName()))
  3225. GetterMethod->setPropertyAccessor(true);
  3226. if (!Property->isReadOnly())
  3227. if (ObjCMethodDecl *SetterMethod
  3228. = Ext->getInstanceMethod(Property->getSetterName()))
  3229. SetterMethod->setPropertyAccessor(true);
  3230. }
  3231. }
  3232. }
  3233. ImplMethodsVsClassMethods(S, IC, IDecl);
  3234. AtomicPropertySetterGetterRules(IC, IDecl);
  3235. DiagnoseOwningPropertyGetterSynthesis(IC);
  3236. DiagnoseUnusedBackingIvarInAccessor(S, IC);
  3237. if (IDecl->hasDesignatedInitializers())
  3238. DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
  3239. bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
  3240. if (IDecl->getSuperClass() == nullptr) {
  3241. // This class has no superclass, so check that it has been marked with
  3242. // __attribute((objc_root_class)).
  3243. if (!HasRootClassAttr) {
  3244. SourceLocation DeclLoc(IDecl->getLocation());
  3245. SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
  3246. Diag(DeclLoc, diag::warn_objc_root_class_missing)
  3247. << IDecl->getIdentifier();
  3248. // See if NSObject is in the current scope, and if it is, suggest
  3249. // adding " : NSObject " to the class declaration.
  3250. NamedDecl *IF = LookupSingleName(TUScope,
  3251. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
  3252. DeclLoc, LookupOrdinaryName);
  3253. ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  3254. if (NSObjectDecl && NSObjectDecl->getDefinition()) {
  3255. Diag(SuperClassLoc, diag::note_objc_needs_superclass)
  3256. << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
  3257. } else {
  3258. Diag(SuperClassLoc, diag::note_objc_needs_superclass);
  3259. }
  3260. }
  3261. } else if (HasRootClassAttr) {
  3262. // Complain that only root classes may have this attribute.
  3263. Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
  3264. }
  3265. if (LangOpts.ObjCRuntime.isNonFragile()) {
  3266. while (IDecl->getSuperClass()) {
  3267. DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
  3268. IDecl = IDecl->getSuperClass();
  3269. }
  3270. }
  3271. }
  3272. SetIvarInitializers(IC);
  3273. } else if (ObjCCategoryImplDecl* CatImplClass =
  3274. dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
  3275. CatImplClass->setAtEndRange(AtEnd);
  3276. // Find category interface decl and then check that all methods declared
  3277. // in this interface are implemented in the category @implementation.
  3278. if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
  3279. if (ObjCCategoryDecl *Cat
  3280. = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
  3281. ImplMethodsVsClassMethods(S, CatImplClass, Cat);
  3282. }
  3283. }
  3284. }
  3285. if (isInterfaceDeclKind) {
  3286. // Reject invalid vardecls.
  3287. for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
  3288. DeclGroupRef DG = allTUVars[i].get();
  3289. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  3290. if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
  3291. if (!VDecl->hasExternalStorage())
  3292. Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
  3293. }
  3294. }
  3295. }
  3296. ActOnObjCContainerFinishDefinition();
  3297. for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
  3298. DeclGroupRef DG = allTUVars[i].get();
  3299. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
  3300. (*I)->setTopLevelDeclInObjCContainer();
  3301. Consumer.HandleTopLevelDeclInObjCContainer(DG);
  3302. }
  3303. ActOnDocumentableDecl(ClassDecl);
  3304. return ClassDecl;
  3305. #endif // HLSL Change Ends
  3306. }
  3307. #if 0 // HLSL Change Starts
  3308. /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
  3309. /// objective-c's type qualifier from the parser version of the same info.
  3310. static Decl::ObjCDeclQualifier
  3311. CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
  3312. return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
  3313. }
  3314. /// \brief Check whether the declared result type of the given Objective-C
  3315. /// method declaration is compatible with the method's class.
  3316. ///
  3317. static Sema::ResultTypeCompatibilityKind
  3318. CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
  3319. ObjCInterfaceDecl *CurrentClass) {
  3320. QualType ResultType = Method->getReturnType();
  3321. // If an Objective-C method inherits its related result type, then its
  3322. // declared result type must be compatible with its own class type. The
  3323. // declared result type is compatible if:
  3324. if (const ObjCObjectPointerType *ResultObjectType
  3325. = ResultType->getAs<ObjCObjectPointerType>()) {
  3326. // - it is id or qualified id, or
  3327. if (ResultObjectType->isObjCIdType() ||
  3328. ResultObjectType->isObjCQualifiedIdType())
  3329. return Sema::RTC_Compatible;
  3330. if (CurrentClass) {
  3331. if (ObjCInterfaceDecl *ResultClass
  3332. = ResultObjectType->getInterfaceDecl()) {
  3333. // - it is the same as the method's class type, or
  3334. if (declaresSameEntity(CurrentClass, ResultClass))
  3335. return Sema::RTC_Compatible;
  3336. // - it is a superclass of the method's class type
  3337. if (ResultClass->isSuperClassOf(CurrentClass))
  3338. return Sema::RTC_Compatible;
  3339. }
  3340. } else {
  3341. // Any Objective-C pointer type might be acceptable for a protocol
  3342. // method; we just don't know.
  3343. return Sema::RTC_Unknown;
  3344. }
  3345. }
  3346. return Sema::RTC_Incompatible;
  3347. }
  3348. #endif // HLSL Change Ends
  3349. namespace {
  3350. /// A helper class for searching for methods which a particular method
  3351. /// overrides.
  3352. class OverrideSearch {
  3353. public:
  3354. Sema &S;
  3355. ObjCMethodDecl *Method;
  3356. llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
  3357. bool Recursive;
  3358. public:
  3359. OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
  3360. Selector selector = method->getSelector();
  3361. // Bypass this search if we've never seen an instance/class method
  3362. // with this selector before.
  3363. Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
  3364. if (it == S.MethodPool.end()) {
  3365. if (!S.getExternalSource()) return;
  3366. S.ReadMethodPool(selector);
  3367. it = S.MethodPool.find(selector);
  3368. if (it == S.MethodPool.end())
  3369. return;
  3370. }
  3371. ObjCMethodList &list =
  3372. method->isInstanceMethod() ? it->second.first : it->second.second;
  3373. if (!list.getMethod()) return;
  3374. ObjCContainerDecl *container
  3375. = cast<ObjCContainerDecl>(method->getDeclContext());
  3376. // Prevent the search from reaching this container again. This is
  3377. // important with categories, which override methods from the
  3378. // interface and each other.
  3379. if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
  3380. searchFromContainer(container);
  3381. if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
  3382. searchFromContainer(Interface);
  3383. } else {
  3384. searchFromContainer(container);
  3385. }
  3386. }
  3387. typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
  3388. iterator begin() const { return Overridden.begin(); }
  3389. iterator end() const { return Overridden.end(); }
  3390. private:
  3391. void searchFromContainer(ObjCContainerDecl *container) {
  3392. if (container->isInvalidDecl()) return;
  3393. switch (container->getDeclKind()) {
  3394. #define OBJCCONTAINER(type, base) \
  3395. case Decl::type: \
  3396. searchFrom(cast<type##Decl>(container)); \
  3397. break;
  3398. #define ABSTRACT_DECL(expansion)
  3399. #define DECL(type, base) \
  3400. case Decl::type:
  3401. #include "clang/AST/DeclNodes.inc"
  3402. llvm_unreachable("not an ObjC container!");
  3403. }
  3404. }
  3405. void searchFrom(ObjCProtocolDecl *protocol) {
  3406. if (!protocol->hasDefinition())
  3407. return;
  3408. // A method in a protocol declaration overrides declarations from
  3409. // referenced ("parent") protocols.
  3410. search(protocol->getReferencedProtocols());
  3411. }
  3412. void searchFrom(ObjCCategoryDecl *category) {
  3413. // A method in a category declaration overrides declarations from
  3414. // the main class and from protocols the category references.
  3415. // The main class is handled in the constructor.
  3416. search(category->getReferencedProtocols());
  3417. }
  3418. void searchFrom(ObjCCategoryImplDecl *impl) {
  3419. // A method in a category definition that has a category
  3420. // declaration overrides declarations from the category
  3421. // declaration.
  3422. if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
  3423. search(category);
  3424. if (ObjCInterfaceDecl *Interface = category->getClassInterface())
  3425. search(Interface);
  3426. // Otherwise it overrides declarations from the class.
  3427. } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
  3428. search(Interface);
  3429. }
  3430. }
  3431. void searchFrom(ObjCInterfaceDecl *iface) {
  3432. // A method in a class declaration overrides declarations from
  3433. if (!iface->hasDefinition())
  3434. return;
  3435. // - categories,
  3436. for (auto *Cat : iface->known_categories())
  3437. search(Cat);
  3438. // - the super class, and
  3439. if (ObjCInterfaceDecl *super = iface->getSuperClass())
  3440. search(super);
  3441. // - any referenced protocols.
  3442. search(iface->getReferencedProtocols());
  3443. }
  3444. void searchFrom(ObjCImplementationDecl *impl) {
  3445. // A method in a class implementation overrides declarations from
  3446. // the class interface.
  3447. if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
  3448. search(Interface);
  3449. }
  3450. void search(const ObjCProtocolList &protocols) {
  3451. for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
  3452. i != e; ++i)
  3453. search(*i);
  3454. }
  3455. void search(ObjCContainerDecl *container) {
  3456. // Check for a method in this container which matches this selector.
  3457. ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
  3458. Method->isInstanceMethod(),
  3459. /*AllowHidden=*/true);
  3460. // If we find one, record it and bail out.
  3461. if (meth) {
  3462. Overridden.insert(meth);
  3463. return;
  3464. }
  3465. // Otherwise, search for methods that a hypothetical method here
  3466. // would have overridden.
  3467. // Note that we're now in a recursive case.
  3468. Recursive = true;
  3469. searchFromContainer(container);
  3470. }
  3471. };
  3472. }
  3473. void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
  3474. ObjCInterfaceDecl *CurrentClass,
  3475. ResultTypeCompatibilityKind RTC) {
  3476. // Search for overridden methods and merge information down from them.
  3477. OverrideSearch overrides(*this, ObjCMethod);
  3478. // Keep track if the method overrides any method in the class's base classes,
  3479. // its protocols, or its categories' protocols; we will keep that info
  3480. // in the ObjCMethodDecl.
  3481. // For this info, a method in an implementation is not considered as
  3482. // overriding the same method in the interface or its categories.
  3483. bool hasOverriddenMethodsInBaseOrProtocol = false;
  3484. for (OverrideSearch::iterator
  3485. i = overrides.begin(), e = overrides.end(); i != e; ++i) {
  3486. ObjCMethodDecl *overridden = *i;
  3487. if (!hasOverriddenMethodsInBaseOrProtocol) {
  3488. if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
  3489. CurrentClass != overridden->getClassInterface() ||
  3490. overridden->isOverriding()) {
  3491. hasOverriddenMethodsInBaseOrProtocol = true;
  3492. } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
  3493. // OverrideSearch will return as "overridden" the same method in the
  3494. // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
  3495. // check whether a category of a base class introduced a method with the
  3496. // same selector, after the interface method declaration.
  3497. // To avoid unnecessary lookups in the majority of cases, we use the
  3498. // extra info bits in GlobalMethodPool to check whether there were any
  3499. // category methods with this selector.
  3500. GlobalMethodPool::iterator It =
  3501. MethodPool.find(ObjCMethod->getSelector());
  3502. if (It != MethodPool.end()) {
  3503. ObjCMethodList &List =
  3504. ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
  3505. unsigned CategCount = List.getBits();
  3506. if (CategCount > 0) {
  3507. // If the method is in a category we'll do lookup if there were at
  3508. // least 2 category methods recorded, otherwise only one will do.
  3509. if (CategCount > 1 ||
  3510. !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
  3511. OverrideSearch overrides(*this, overridden);
  3512. for (OverrideSearch::iterator
  3513. OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
  3514. ObjCMethodDecl *SuperOverridden = *OI;
  3515. if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
  3516. CurrentClass != SuperOverridden->getClassInterface()) {
  3517. hasOverriddenMethodsInBaseOrProtocol = true;
  3518. overridden->setOverriding(true);
  3519. break;
  3520. }
  3521. }
  3522. }
  3523. }
  3524. }
  3525. }
  3526. }
  3527. // Propagate down the 'related result type' bit from overridden methods.
  3528. if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
  3529. ObjCMethod->SetRelatedResultType();
  3530. // Then merge the declarations.
  3531. mergeObjCMethodDecls(ObjCMethod, overridden);
  3532. if (ObjCMethod->isImplicit() && overridden->isImplicit())
  3533. continue; // Conflicting properties are detected elsewhere.
  3534. // Check for overriding methods
  3535. if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
  3536. isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
  3537. CheckConflictingOverridingMethod(ObjCMethod, overridden,
  3538. isa<ObjCProtocolDecl>(overridden->getDeclContext()));
  3539. if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
  3540. isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
  3541. !overridden->isImplicit() /* not meant for properties */) {
  3542. ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
  3543. E = ObjCMethod->param_end();
  3544. ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
  3545. PrevE = overridden->param_end();
  3546. for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
  3547. assert(PrevI != overridden->param_end() && "Param mismatch");
  3548. QualType T1 = Context.getCanonicalType((*ParamI)->getType());
  3549. QualType T2 = Context.getCanonicalType((*PrevI)->getType());
  3550. // If type of argument of method in this class does not match its
  3551. // respective argument type in the super class method, issue warning;
  3552. if (!Context.typesAreCompatible(T1, T2)) {
  3553. Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
  3554. << T1 << T2;
  3555. Diag(overridden->getLocation(), diag::note_previous_declaration);
  3556. break;
  3557. }
  3558. }
  3559. }
  3560. }
  3561. ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
  3562. }
  3563. #if 0 // HLSL Change Starts - HLSL does not support ObjC constructs
  3564. /// Merge type nullability from for a redeclaration of the same entity,
  3565. /// producing the updated type of the redeclared entity.
  3566. static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
  3567. QualType type,
  3568. bool usesCSKeyword,
  3569. SourceLocation prevLoc,
  3570. QualType prevType,
  3571. bool prevUsesCSKeyword) {
  3572. // Determine the nullability of both types.
  3573. auto nullability = type->getNullability(S.Context);
  3574. auto prevNullability = prevType->getNullability(S.Context);
  3575. // Easy case: both have nullability.
  3576. if (nullability.hasValue() == prevNullability.hasValue()) {
  3577. // Neither has nullability; continue.
  3578. if (!nullability)
  3579. return type;
  3580. // The nullabilities are equivalent; do nothing.
  3581. if (*nullability == *prevNullability)
  3582. return type;
  3583. // Complain about mismatched nullability.
  3584. S.Diag(loc, diag::err_nullability_conflicting)
  3585. << DiagNullabilityKind(*nullability, usesCSKeyword)
  3586. << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
  3587. return type;
  3588. }
  3589. // If it's the redeclaration that has nullability, don't change anything.
  3590. if (nullability)
  3591. return type;
  3592. // Otherwise, provide the result with the same nullability.
  3593. return S.Context.getAttributedType(
  3594. AttributedType::getNullabilityAttrKind(*prevNullability),
  3595. type, type);
  3596. }
  3597. /// Merge information from the declaration of a method in the \@interface
  3598. /// (or a category/extension) into the corresponding method in the
  3599. /// @implementation (for a class or category).
  3600. static void mergeInterfaceMethodToImpl(Sema &S,
  3601. ObjCMethodDecl *method,
  3602. ObjCMethodDecl *prevMethod) {
  3603. // Merge the objc_requires_super attribute.
  3604. if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
  3605. !method->hasAttr<ObjCRequiresSuperAttr>()) {
  3606. // merge the attribute into implementation.
  3607. method->addAttr(
  3608. ObjCRequiresSuperAttr::CreateImplicit(S.Context,
  3609. method->getLocation()));
  3610. }
  3611. // Merge nullability of the result type.
  3612. QualType newReturnType
  3613. = mergeTypeNullabilityForRedecl(
  3614. S, method->getReturnTypeSourceRange().getBegin(),
  3615. method->getReturnType(),
  3616. method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
  3617. prevMethod->getReturnTypeSourceRange().getBegin(),
  3618. prevMethod->getReturnType(),
  3619. prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
  3620. method->setReturnType(newReturnType);
  3621. // Handle each of the parameters.
  3622. unsigned numParams = method->param_size();
  3623. unsigned numPrevParams = prevMethod->param_size();
  3624. for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
  3625. ParmVarDecl *param = method->param_begin()[i];
  3626. ParmVarDecl *prevParam = prevMethod->param_begin()[i];
  3627. // Merge nullability.
  3628. QualType newParamType
  3629. = mergeTypeNullabilityForRedecl(
  3630. S, param->getLocation(), param->getType(),
  3631. param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
  3632. prevParam->getLocation(), prevParam->getType(),
  3633. prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
  3634. param->setType(newParamType);
  3635. }
  3636. }
  3637. #endif // HLSL Change Ends - HLSL does not support ObjC constructs
  3638. Decl *Sema::ActOnMethodDeclaration(
  3639. Scope *S,
  3640. SourceLocation MethodLoc, SourceLocation EndLoc,
  3641. tok::TokenKind MethodType,
  3642. ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
  3643. ArrayRef<SourceLocation> SelectorLocs,
  3644. Selector Sel,
  3645. // optional arguments. The number of types/arguments is obtained
  3646. // from the Sel.getNumArgs().
  3647. ObjCArgInfo *ArgInfo,
  3648. DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
  3649. AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
  3650. bool isVariadic, bool MethodDefinition) {
  3651. // HLSL Change Starts
  3652. llvm_unreachable("HLSL does not support ObjC constructs");
  3653. #if 0
  3654. // Make sure we can establish a context for the method.
  3655. if (!CurContext->isObjCContainer()) {
  3656. Diag(MethodLoc, diag::error_missing_method_context);
  3657. return nullptr;
  3658. }
  3659. ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
  3660. Decl *ClassDecl = cast<Decl>(OCD);
  3661. QualType resultDeclType;
  3662. bool HasRelatedResultType = false;
  3663. TypeSourceInfo *ReturnTInfo = nullptr;
  3664. if (ReturnType) {
  3665. resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
  3666. if (CheckFunctionReturnType(resultDeclType, MethodLoc))
  3667. return nullptr;
  3668. QualType bareResultType = resultDeclType;
  3669. (void)AttributedType::stripOuterNullability(bareResultType);
  3670. HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
  3671. } else { // get the type for "id".
  3672. resultDeclType = Context.getObjCIdType();
  3673. Diag(MethodLoc, diag::warn_missing_method_return_type)
  3674. << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
  3675. }
  3676. ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
  3677. Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
  3678. MethodType == tok::minus, isVariadic,
  3679. /*isPropertyAccessor=*/false,
  3680. /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
  3681. MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
  3682. : ObjCMethodDecl::Required,
  3683. HasRelatedResultType);
  3684. SmallVector<ParmVarDecl*, 16> Params;
  3685. for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
  3686. QualType ArgType;
  3687. TypeSourceInfo *DI;
  3688. if (!ArgInfo[i].Type) {
  3689. ArgType = Context.getObjCIdType();
  3690. DI = nullptr;
  3691. } else {
  3692. ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
  3693. }
  3694. LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
  3695. LookupOrdinaryName, ForRedeclaration);
  3696. LookupName(R, S);
  3697. if (R.isSingleResult()) {
  3698. NamedDecl *PrevDecl = R.getFoundDecl();
  3699. if (S->isDeclScope(PrevDecl)) {
  3700. Diag(ArgInfo[i].NameLoc,
  3701. (MethodDefinition ? diag::warn_method_param_redefinition
  3702. : diag::warn_method_param_declaration))
  3703. << ArgInfo[i].Name;
  3704. Diag(PrevDecl->getLocation(),
  3705. diag::note_previous_declaration);
  3706. }
  3707. }
  3708. SourceLocation StartLoc = DI
  3709. ? DI->getTypeLoc().getBeginLoc()
  3710. : ArgInfo[i].NameLoc;
  3711. ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
  3712. ArgInfo[i].NameLoc, ArgInfo[i].Name,
  3713. ArgType, DI, SC_None);
  3714. Param->setObjCMethodScopeInfo(i);
  3715. Param->setObjCDeclQualifier(
  3716. CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
  3717. // Apply the attributes to the parameter.
  3718. ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
  3719. if (Param->hasAttr<BlocksAttr>()) {
  3720. Diag(Param->getLocation(), diag::err_block_on_nonlocal);
  3721. Param->setInvalidDecl();
  3722. }
  3723. S->AddDecl(Param);
  3724. IdResolver.AddDecl(Param);
  3725. Params.push_back(Param);
  3726. }
  3727. for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
  3728. ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
  3729. QualType ArgType = Param->getType();
  3730. if (ArgType.isNull())
  3731. ArgType = Context.getObjCIdType();
  3732. else
  3733. // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
  3734. ArgType = Context.getAdjustedParameterType(ArgType);
  3735. Param->setDeclContext(ObjCMethod);
  3736. Params.push_back(Param);
  3737. }
  3738. ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
  3739. ObjCMethod->setObjCDeclQualifier(
  3740. CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
  3741. if (AttrList)
  3742. ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
  3743. // Add the method now.
  3744. const ObjCMethodDecl *PrevMethod = nullptr;
  3745. if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
  3746. if (MethodType == tok::minus) {
  3747. PrevMethod = ImpDecl->getInstanceMethod(Sel);
  3748. ImpDecl->addInstanceMethod(ObjCMethod);
  3749. } else {
  3750. PrevMethod = ImpDecl->getClassMethod(Sel);
  3751. ImpDecl->addClassMethod(ObjCMethod);
  3752. }
  3753. // Merge information from the @interface declaration into the
  3754. // @implementation.
  3755. if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
  3756. if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
  3757. ObjCMethod->isInstanceMethod())) {
  3758. mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
  3759. // Warn about defining -dealloc in a category.
  3760. if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
  3761. ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
  3762. Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
  3763. << ObjCMethod->getDeclName();
  3764. }
  3765. }
  3766. }
  3767. } else {
  3768. cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
  3769. }
  3770. if (PrevMethod) {
  3771. // You can never have two method definitions with the same name.
  3772. Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
  3773. << ObjCMethod->getDeclName();
  3774. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3775. ObjCMethod->setInvalidDecl();
  3776. return ObjCMethod;
  3777. }
  3778. // If this Objective-C method does not have a related result type, but we
  3779. // are allowed to infer related result types, try to do so based on the
  3780. // method family.
  3781. ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
  3782. if (!CurrentClass) {
  3783. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
  3784. CurrentClass = Cat->getClassInterface();
  3785. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
  3786. CurrentClass = Impl->getClassInterface();
  3787. else if (ObjCCategoryImplDecl *CatImpl
  3788. = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
  3789. CurrentClass = CatImpl->getClassInterface();
  3790. }
  3791. ResultTypeCompatibilityKind RTC
  3792. = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
  3793. CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
  3794. bool ARCError = false;
  3795. if (getLangOpts().ObjCAutoRefCount)
  3796. ARCError = CheckARCMethodDecl(ObjCMethod);
  3797. // Infer the related result type when possible.
  3798. if (!ARCError && RTC == Sema::RTC_Compatible &&
  3799. !ObjCMethod->hasRelatedResultType() &&
  3800. LangOpts.ObjCInferRelatedResultType) {
  3801. bool InferRelatedResultType = false;
  3802. switch (ObjCMethod->getMethodFamily()) {
  3803. case OMF_None:
  3804. case OMF_copy:
  3805. case OMF_dealloc:
  3806. case OMF_finalize:
  3807. case OMF_mutableCopy:
  3808. case OMF_release:
  3809. case OMF_retainCount:
  3810. case OMF_initialize:
  3811. case OMF_performSelector:
  3812. break;
  3813. case OMF_alloc:
  3814. case OMF_new:
  3815. InferRelatedResultType = ObjCMethod->isClassMethod();
  3816. break;
  3817. case OMF_init:
  3818. case OMF_autorelease:
  3819. case OMF_retain:
  3820. case OMF_self:
  3821. InferRelatedResultType = ObjCMethod->isInstanceMethod();
  3822. break;
  3823. }
  3824. if (InferRelatedResultType &&
  3825. !ObjCMethod->getReturnType()->isObjCIndependentClassType())
  3826. ObjCMethod->SetRelatedResultType();
  3827. }
  3828. ActOnDocumentableDecl(ObjCMethod);
  3829. return ObjCMethod;
  3830. #endif // HLSL Change Ends
  3831. }
  3832. bool Sema::CheckObjCDeclScope(Decl *D) {
  3833. // Following is also an error. But it is caused by a missing @end
  3834. // and diagnostic is issued elsewhere.
  3835. if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
  3836. return false;
  3837. // If we switched context to translation unit while we are still lexically in
  3838. // an objc container, it means the parser missed emitting an error.
  3839. if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
  3840. return false;
  3841. Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
  3842. D->setInvalidDecl();
  3843. return true;
  3844. }
  3845. /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
  3846. /// instance variables of ClassName into Decls.
  3847. void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
  3848. IdentifierInfo *ClassName,
  3849. SmallVectorImpl<Decl*> &Decls) {
  3850. // Check that ClassName is a valid class
  3851. ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
  3852. if (!Class) {
  3853. Diag(DeclStart, diag::err_undef_interface) << ClassName;
  3854. return;
  3855. }
  3856. if (LangOpts.ObjCRuntime.isNonFragile()) {
  3857. Diag(DeclStart, diag::err_atdef_nonfragile_interface);
  3858. return;
  3859. }
  3860. // Collect the instance variables
  3861. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  3862. Context.DeepCollectObjCIvars(Class, true, Ivars);
  3863. // For each ivar, create a fresh ObjCAtDefsFieldDecl.
  3864. for (unsigned i = 0; i < Ivars.size(); i++) {
  3865. const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
  3866. RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
  3867. Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
  3868. /*FIXME: StartL=*/ID->getLocation(),
  3869. ID->getLocation(),
  3870. ID->getIdentifier(), ID->getType(),
  3871. ID->getBitWidth());
  3872. Decls.push_back(FD);
  3873. }
  3874. // Introduce all of these fields into the appropriate scope.
  3875. for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
  3876. D != Decls.end(); ++D) {
  3877. FieldDecl *FD = cast<FieldDecl>(*D);
  3878. if (getLangOpts().CPlusPlus)
  3879. PushOnScopeChains(cast<FieldDecl>(FD), S);
  3880. else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
  3881. Record->addDecl(FD);
  3882. }
  3883. }
  3884. /// \brief Build a type-check a new Objective-C exception variable declaration.
  3885. VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
  3886. SourceLocation StartLoc,
  3887. SourceLocation IdLoc,
  3888. IdentifierInfo *Id,
  3889. bool Invalid) {
  3890. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  3891. // duration shall not be qualified by an address-space qualifier."
  3892. // Since all parameters have automatic store duration, they can not have
  3893. // an address space.
  3894. if (T.getAddressSpace() != 0) {
  3895. Diag(IdLoc, diag::err_arg_with_address_space);
  3896. Invalid = true;
  3897. }
  3898. // An @catch parameter must be an unqualified object pointer type;
  3899. // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
  3900. if (Invalid) {
  3901. // Don't do any further checking.
  3902. } else if (T->isDependentType()) {
  3903. // Okay: we don't know what this type will instantiate to.
  3904. } else if (!T->isObjCObjectPointerType()) {
  3905. Invalid = true;
  3906. Diag(IdLoc ,diag::err_catch_param_not_objc_type);
  3907. } else if (T->isObjCQualifiedIdType()) {
  3908. Invalid = true;
  3909. Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
  3910. }
  3911. VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
  3912. T, TInfo, SC_None);
  3913. New->setExceptionVariable(true);
  3914. // In ARC, infer 'retaining' for variables of retainable type.
  3915. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
  3916. Invalid = true;
  3917. if (Invalid)
  3918. New->setInvalidDecl();
  3919. return New;
  3920. }
  3921. Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
  3922. const DeclSpec &DS = D.getDeclSpec();
  3923. // We allow the "register" storage class on exception variables because
  3924. // GCC did, but we drop it completely. Any other storage class is an error.
  3925. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  3926. Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
  3927. << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
  3928. } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3929. Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
  3930. << DeclSpec::getSpecifierName(SCS);
  3931. }
  3932. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  3933. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  3934. diag::err_invalid_thread)
  3935. << DeclSpec::getSpecifierName(TSCS);
  3936. D.getMutableDeclSpec().ClearStorageClassSpecs();
  3937. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  3938. // Check that there are no default arguments inside the type of this
  3939. // exception object (C++ only).
  3940. if (getLangOpts().CPlusPlus)
  3941. CheckExtraCXXDefaultArguments(D);
  3942. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  3943. QualType ExceptionType = TInfo->getType();
  3944. VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
  3945. D.getSourceRange().getBegin(),
  3946. D.getIdentifierLoc(),
  3947. D.getIdentifier(),
  3948. D.isInvalidType());
  3949. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  3950. if (D.getCXXScopeSpec().isSet()) {
  3951. Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
  3952. << D.getCXXScopeSpec().getRange();
  3953. New->setInvalidDecl();
  3954. }
  3955. // Add the parameter declaration into this scope.
  3956. S->AddDecl(New);
  3957. if (D.getIdentifier())
  3958. IdResolver.AddDecl(New);
  3959. ProcessDeclAttributes(S, New, D);
  3960. if (New->hasAttr<BlocksAttr>())
  3961. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  3962. return New;
  3963. }
  3964. /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
  3965. /// initialization.
  3966. void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
  3967. SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
  3968. for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
  3969. Iv= Iv->getNextIvar()) {
  3970. QualType QT = Context.getBaseElementType(Iv->getType());
  3971. if (QT->isRecordType())
  3972. Ivars.push_back(Iv);
  3973. }
  3974. }
  3975. void Sema::DiagnoseUseOfUnimplementedSelectors() {
  3976. // Load referenced selectors from the external source.
  3977. if (ExternalSource) {
  3978. SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
  3979. ExternalSource->ReadReferencedSelectors(Sels);
  3980. for (unsigned I = 0, N = Sels.size(); I != N; ++I)
  3981. ReferencedSelectors[Sels[I].first] = Sels[I].second;
  3982. }
  3983. // Warning will be issued only when selector table is
  3984. // generated (which means there is at lease one implementation
  3985. // in the TU). This is to match gcc's behavior.
  3986. if (ReferencedSelectors.empty() ||
  3987. !Context.AnyObjCImplementation())
  3988. return;
  3989. for (auto &SelectorAndLocation : ReferencedSelectors) {
  3990. Selector Sel = SelectorAndLocation.first;
  3991. SourceLocation Loc = SelectorAndLocation.second;
  3992. if (!LookupImplementedMethodInGlobalPool(Sel))
  3993. Diag(Loc, diag::warn_unimplemented_selector) << Sel;
  3994. }
  3995. return;
  3996. }
  3997. ObjCIvarDecl *
  3998. Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
  3999. const ObjCPropertyDecl *&PDecl) const {
  4000. if (Method->isClassMethod())
  4001. return nullptr;
  4002. const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
  4003. if (!IDecl)
  4004. return nullptr;
  4005. Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
  4006. /*shallowCategoryLookup=*/false,
  4007. /*followSuper=*/false);
  4008. if (!Method || !Method->isPropertyAccessor())
  4009. return nullptr;
  4010. if ((PDecl = Method->findPropertyDecl()))
  4011. if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
  4012. // property backing ivar must belong to property's class
  4013. // or be a private ivar in class's implementation.
  4014. // FIXME. fix the const-ness issue.
  4015. IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
  4016. IV->getIdentifier());
  4017. return IV;
  4018. }
  4019. return nullptr;
  4020. }
  4021. namespace {
  4022. /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
  4023. /// accessor references the backing ivar.
  4024. class UnusedBackingIvarChecker :
  4025. public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
  4026. public:
  4027. Sema &S;
  4028. const ObjCMethodDecl *Method;
  4029. const ObjCIvarDecl *IvarD;
  4030. bool AccessedIvar;
  4031. bool InvokedSelfMethod;
  4032. UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
  4033. const ObjCIvarDecl *IvarD)
  4034. : S(S), Method(Method), IvarD(IvarD),
  4035. AccessedIvar(false), InvokedSelfMethod(false) {
  4036. assert(IvarD);
  4037. }
  4038. bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  4039. if (E->getDecl() == IvarD) {
  4040. AccessedIvar = true;
  4041. return false;
  4042. }
  4043. return true;
  4044. }
  4045. bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
  4046. if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
  4047. S.isSelfExpr(E->getInstanceReceiver(), Method)) {
  4048. InvokedSelfMethod = true;
  4049. }
  4050. return true;
  4051. }
  4052. };
  4053. }
  4054. void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
  4055. const ObjCImplementationDecl *ImplD) {
  4056. #if 0 // HLSL Change
  4057. if (S->hasUnrecoverableErrorOccurred())
  4058. return;
  4059. for (const auto *CurMethod : ImplD->instance_methods()) {
  4060. unsigned DIAG = diag::warn_unused_property_backing_ivar;
  4061. SourceLocation Loc = CurMethod->getLocation();
  4062. if (Diags.isIgnored(DIAG, Loc))
  4063. continue;
  4064. const ObjCPropertyDecl *PDecl;
  4065. const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
  4066. if (!IV)
  4067. continue;
  4068. UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
  4069. Checker.TraverseStmt(CurMethod->getBody());
  4070. if (Checker.AccessedIvar)
  4071. continue;
  4072. // Do not issue this warning if backing ivar is used somewhere and accessor
  4073. // implementation makes a self call. This is to prevent false positive in
  4074. // cases where the ivar is accessed by another method that the accessor
  4075. // delegates to.
  4076. if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
  4077. Diag(Loc, DIAG) << IV;
  4078. Diag(PDecl->getLocation(), diag::note_property_declare);
  4079. }
  4080. }
  4081. #endif // HLSL Change
  4082. }