SemaDeclObjC.cpp 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602
  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. (S);
  3116. (AtEnd);
  3117. (allMethods);
  3118. (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. /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
  3308. /// objective-c's type qualifier from the parser version of the same info.
  3309. static Decl::ObjCDeclQualifier
  3310. CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
  3311. return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
  3312. }
  3313. /// \brief Check whether the declared result type of the given Objective-C
  3314. /// method declaration is compatible with the method's class.
  3315. ///
  3316. static Sema::ResultTypeCompatibilityKind
  3317. CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
  3318. ObjCInterfaceDecl *CurrentClass) {
  3319. QualType ResultType = Method->getReturnType();
  3320. // If an Objective-C method inherits its related result type, then its
  3321. // declared result type must be compatible with its own class type. The
  3322. // declared result type is compatible if:
  3323. if (const ObjCObjectPointerType *ResultObjectType
  3324. = ResultType->getAs<ObjCObjectPointerType>()) {
  3325. // - it is id or qualified id, or
  3326. if (ResultObjectType->isObjCIdType() ||
  3327. ResultObjectType->isObjCQualifiedIdType())
  3328. return Sema::RTC_Compatible;
  3329. if (CurrentClass) {
  3330. if (ObjCInterfaceDecl *ResultClass
  3331. = ResultObjectType->getInterfaceDecl()) {
  3332. // - it is the same as the method's class type, or
  3333. if (declaresSameEntity(CurrentClass, ResultClass))
  3334. return Sema::RTC_Compatible;
  3335. // - it is a superclass of the method's class type
  3336. if (ResultClass->isSuperClassOf(CurrentClass))
  3337. return Sema::RTC_Compatible;
  3338. }
  3339. } else {
  3340. // Any Objective-C pointer type might be acceptable for a protocol
  3341. // method; we just don't know.
  3342. return Sema::RTC_Unknown;
  3343. }
  3344. }
  3345. return Sema::RTC_Incompatible;
  3346. }
  3347. namespace {
  3348. /// A helper class for searching for methods which a particular method
  3349. /// overrides.
  3350. class OverrideSearch {
  3351. public:
  3352. Sema &S;
  3353. ObjCMethodDecl *Method;
  3354. llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
  3355. bool Recursive;
  3356. public:
  3357. OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
  3358. Selector selector = method->getSelector();
  3359. // Bypass this search if we've never seen an instance/class method
  3360. // with this selector before.
  3361. Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
  3362. if (it == S.MethodPool.end()) {
  3363. if (!S.getExternalSource()) return;
  3364. S.ReadMethodPool(selector);
  3365. it = S.MethodPool.find(selector);
  3366. if (it == S.MethodPool.end())
  3367. return;
  3368. }
  3369. ObjCMethodList &list =
  3370. method->isInstanceMethod() ? it->second.first : it->second.second;
  3371. if (!list.getMethod()) return;
  3372. ObjCContainerDecl *container
  3373. = cast<ObjCContainerDecl>(method->getDeclContext());
  3374. // Prevent the search from reaching this container again. This is
  3375. // important with categories, which override methods from the
  3376. // interface and each other.
  3377. if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
  3378. searchFromContainer(container);
  3379. if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
  3380. searchFromContainer(Interface);
  3381. } else {
  3382. searchFromContainer(container);
  3383. }
  3384. }
  3385. typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
  3386. iterator begin() const { return Overridden.begin(); }
  3387. iterator end() const { return Overridden.end(); }
  3388. private:
  3389. void searchFromContainer(ObjCContainerDecl *container) {
  3390. if (container->isInvalidDecl()) return;
  3391. switch (container->getDeclKind()) {
  3392. #define OBJCCONTAINER(type, base) \
  3393. case Decl::type: \
  3394. searchFrom(cast<type##Decl>(container)); \
  3395. break;
  3396. #define ABSTRACT_DECL(expansion)
  3397. #define DECL(type, base) \
  3398. case Decl::type:
  3399. #include "clang/AST/DeclNodes.inc"
  3400. llvm_unreachable("not an ObjC container!");
  3401. }
  3402. }
  3403. void searchFrom(ObjCProtocolDecl *protocol) {
  3404. if (!protocol->hasDefinition())
  3405. return;
  3406. // A method in a protocol declaration overrides declarations from
  3407. // referenced ("parent") protocols.
  3408. search(protocol->getReferencedProtocols());
  3409. }
  3410. void searchFrom(ObjCCategoryDecl *category) {
  3411. // A method in a category declaration overrides declarations from
  3412. // the main class and from protocols the category references.
  3413. // The main class is handled in the constructor.
  3414. search(category->getReferencedProtocols());
  3415. }
  3416. void searchFrom(ObjCCategoryImplDecl *impl) {
  3417. // A method in a category definition that has a category
  3418. // declaration overrides declarations from the category
  3419. // declaration.
  3420. if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
  3421. search(category);
  3422. if (ObjCInterfaceDecl *Interface = category->getClassInterface())
  3423. search(Interface);
  3424. // Otherwise it overrides declarations from the class.
  3425. } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
  3426. search(Interface);
  3427. }
  3428. }
  3429. void searchFrom(ObjCInterfaceDecl *iface) {
  3430. // A method in a class declaration overrides declarations from
  3431. if (!iface->hasDefinition())
  3432. return;
  3433. // - categories,
  3434. for (auto *Cat : iface->known_categories())
  3435. search(Cat);
  3436. // - the super class, and
  3437. if (ObjCInterfaceDecl *super = iface->getSuperClass())
  3438. search(super);
  3439. // - any referenced protocols.
  3440. search(iface->getReferencedProtocols());
  3441. }
  3442. void searchFrom(ObjCImplementationDecl *impl) {
  3443. // A method in a class implementation overrides declarations from
  3444. // the class interface.
  3445. if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
  3446. search(Interface);
  3447. }
  3448. void search(const ObjCProtocolList &protocols) {
  3449. for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
  3450. i != e; ++i)
  3451. search(*i);
  3452. }
  3453. void search(ObjCContainerDecl *container) {
  3454. // Check for a method in this container which matches this selector.
  3455. ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
  3456. Method->isInstanceMethod(),
  3457. /*AllowHidden=*/true);
  3458. // If we find one, record it and bail out.
  3459. if (meth) {
  3460. Overridden.insert(meth);
  3461. return;
  3462. }
  3463. // Otherwise, search for methods that a hypothetical method here
  3464. // would have overridden.
  3465. // Note that we're now in a recursive case.
  3466. Recursive = true;
  3467. searchFromContainer(container);
  3468. }
  3469. };
  3470. }
  3471. void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
  3472. ObjCInterfaceDecl *CurrentClass,
  3473. ResultTypeCompatibilityKind RTC) {
  3474. // Search for overridden methods and merge information down from them.
  3475. OverrideSearch overrides(*this, ObjCMethod);
  3476. // Keep track if the method overrides any method in the class's base classes,
  3477. // its protocols, or its categories' protocols; we will keep that info
  3478. // in the ObjCMethodDecl.
  3479. // For this info, a method in an implementation is not considered as
  3480. // overriding the same method in the interface or its categories.
  3481. bool hasOverriddenMethodsInBaseOrProtocol = false;
  3482. for (OverrideSearch::iterator
  3483. i = overrides.begin(), e = overrides.end(); i != e; ++i) {
  3484. ObjCMethodDecl *overridden = *i;
  3485. if (!hasOverriddenMethodsInBaseOrProtocol) {
  3486. if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
  3487. CurrentClass != overridden->getClassInterface() ||
  3488. overridden->isOverriding()) {
  3489. hasOverriddenMethodsInBaseOrProtocol = true;
  3490. } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
  3491. // OverrideSearch will return as "overridden" the same method in the
  3492. // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
  3493. // check whether a category of a base class introduced a method with the
  3494. // same selector, after the interface method declaration.
  3495. // To avoid unnecessary lookups in the majority of cases, we use the
  3496. // extra info bits in GlobalMethodPool to check whether there were any
  3497. // category methods with this selector.
  3498. GlobalMethodPool::iterator It =
  3499. MethodPool.find(ObjCMethod->getSelector());
  3500. if (It != MethodPool.end()) {
  3501. ObjCMethodList &List =
  3502. ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
  3503. unsigned CategCount = List.getBits();
  3504. if (CategCount > 0) {
  3505. // If the method is in a category we'll do lookup if there were at
  3506. // least 2 category methods recorded, otherwise only one will do.
  3507. if (CategCount > 1 ||
  3508. !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
  3509. OverrideSearch overrides(*this, overridden);
  3510. for (OverrideSearch::iterator
  3511. OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
  3512. ObjCMethodDecl *SuperOverridden = *OI;
  3513. if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
  3514. CurrentClass != SuperOverridden->getClassInterface()) {
  3515. hasOverriddenMethodsInBaseOrProtocol = true;
  3516. overridden->setOverriding(true);
  3517. break;
  3518. }
  3519. }
  3520. }
  3521. }
  3522. }
  3523. }
  3524. }
  3525. // Propagate down the 'related result type' bit from overridden methods.
  3526. if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
  3527. ObjCMethod->SetRelatedResultType();
  3528. // Then merge the declarations.
  3529. mergeObjCMethodDecls(ObjCMethod, overridden);
  3530. if (ObjCMethod->isImplicit() && overridden->isImplicit())
  3531. continue; // Conflicting properties are detected elsewhere.
  3532. // Check for overriding methods
  3533. if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
  3534. isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
  3535. CheckConflictingOverridingMethod(ObjCMethod, overridden,
  3536. isa<ObjCProtocolDecl>(overridden->getDeclContext()));
  3537. if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
  3538. isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
  3539. !overridden->isImplicit() /* not meant for properties */) {
  3540. ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
  3541. E = ObjCMethod->param_end();
  3542. ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
  3543. PrevE = overridden->param_end();
  3544. for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
  3545. assert(PrevI != overridden->param_end() && "Param mismatch");
  3546. QualType T1 = Context.getCanonicalType((*ParamI)->getType());
  3547. QualType T2 = Context.getCanonicalType((*PrevI)->getType());
  3548. // If type of argument of method in this class does not match its
  3549. // respective argument type in the super class method, issue warning;
  3550. if (!Context.typesAreCompatible(T1, T2)) {
  3551. Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
  3552. << T1 << T2;
  3553. Diag(overridden->getLocation(), diag::note_previous_declaration);
  3554. break;
  3555. }
  3556. }
  3557. }
  3558. }
  3559. ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
  3560. }
  3561. /// Merge type nullability from for a redeclaration of the same entity,
  3562. /// producing the updated type of the redeclared entity.
  3563. static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
  3564. QualType type,
  3565. bool usesCSKeyword,
  3566. SourceLocation prevLoc,
  3567. QualType prevType,
  3568. bool prevUsesCSKeyword) {
  3569. // Determine the nullability of both types.
  3570. auto nullability = type->getNullability(S.Context);
  3571. auto prevNullability = prevType->getNullability(S.Context);
  3572. // Easy case: both have nullability.
  3573. if (nullability.hasValue() == prevNullability.hasValue()) {
  3574. // Neither has nullability; continue.
  3575. if (!nullability)
  3576. return type;
  3577. // The nullabilities are equivalent; do nothing.
  3578. if (*nullability == *prevNullability)
  3579. return type;
  3580. // Complain about mismatched nullability.
  3581. S.Diag(loc, diag::err_nullability_conflicting)
  3582. << DiagNullabilityKind(*nullability, usesCSKeyword)
  3583. << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
  3584. return type;
  3585. }
  3586. // If it's the redeclaration that has nullability, don't change anything.
  3587. if (nullability)
  3588. return type;
  3589. // Otherwise, provide the result with the same nullability.
  3590. return S.Context.getAttributedType(
  3591. AttributedType::getNullabilityAttrKind(*prevNullability),
  3592. type, type);
  3593. }
  3594. /// Merge information from the declaration of a method in the \@interface
  3595. /// (or a category/extension) into the corresponding method in the
  3596. /// @implementation (for a class or category).
  3597. static void mergeInterfaceMethodToImpl(Sema &S,
  3598. ObjCMethodDecl *method,
  3599. ObjCMethodDecl *prevMethod) {
  3600. // Merge the objc_requires_super attribute.
  3601. if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
  3602. !method->hasAttr<ObjCRequiresSuperAttr>()) {
  3603. // merge the attribute into implementation.
  3604. method->addAttr(
  3605. ObjCRequiresSuperAttr::CreateImplicit(S.Context,
  3606. method->getLocation()));
  3607. }
  3608. // Merge nullability of the result type.
  3609. QualType newReturnType
  3610. = mergeTypeNullabilityForRedecl(
  3611. S, method->getReturnTypeSourceRange().getBegin(),
  3612. method->getReturnType(),
  3613. method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
  3614. prevMethod->getReturnTypeSourceRange().getBegin(),
  3615. prevMethod->getReturnType(),
  3616. prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
  3617. method->setReturnType(newReturnType);
  3618. // Handle each of the parameters.
  3619. unsigned numParams = method->param_size();
  3620. unsigned numPrevParams = prevMethod->param_size();
  3621. for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
  3622. ParmVarDecl *param = method->param_begin()[i];
  3623. ParmVarDecl *prevParam = prevMethod->param_begin()[i];
  3624. // Merge nullability.
  3625. QualType newParamType
  3626. = mergeTypeNullabilityForRedecl(
  3627. S, param->getLocation(), param->getType(),
  3628. param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
  3629. prevParam->getLocation(), prevParam->getType(),
  3630. prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
  3631. param->setType(newParamType);
  3632. }
  3633. }
  3634. Decl *Sema::ActOnMethodDeclaration(
  3635. Scope *S,
  3636. SourceLocation MethodLoc, SourceLocation EndLoc,
  3637. tok::TokenKind MethodType,
  3638. ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
  3639. ArrayRef<SourceLocation> SelectorLocs,
  3640. Selector Sel,
  3641. // optional arguments. The number of types/arguments is obtained
  3642. // from the Sel.getNumArgs().
  3643. ObjCArgInfo *ArgInfo,
  3644. DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
  3645. AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
  3646. bool isVariadic, bool MethodDefinition) {
  3647. // HLSL Change Starts
  3648. llvm_unreachable("HLSL does not support ObjC constructs");
  3649. #if 0
  3650. // Make sure we can establish a context for the method.
  3651. if (!CurContext->isObjCContainer()) {
  3652. Diag(MethodLoc, diag::error_missing_method_context);
  3653. return nullptr;
  3654. }
  3655. ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
  3656. Decl *ClassDecl = cast<Decl>(OCD);
  3657. QualType resultDeclType;
  3658. bool HasRelatedResultType = false;
  3659. TypeSourceInfo *ReturnTInfo = nullptr;
  3660. if (ReturnType) {
  3661. resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
  3662. if (CheckFunctionReturnType(resultDeclType, MethodLoc))
  3663. return nullptr;
  3664. QualType bareResultType = resultDeclType;
  3665. (void)AttributedType::stripOuterNullability(bareResultType);
  3666. HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
  3667. } else { // get the type for "id".
  3668. resultDeclType = Context.getObjCIdType();
  3669. Diag(MethodLoc, diag::warn_missing_method_return_type)
  3670. << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
  3671. }
  3672. ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
  3673. Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
  3674. MethodType == tok::minus, isVariadic,
  3675. /*isPropertyAccessor=*/false,
  3676. /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
  3677. MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
  3678. : ObjCMethodDecl::Required,
  3679. HasRelatedResultType);
  3680. SmallVector<ParmVarDecl*, 16> Params;
  3681. for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
  3682. QualType ArgType;
  3683. TypeSourceInfo *DI;
  3684. if (!ArgInfo[i].Type) {
  3685. ArgType = Context.getObjCIdType();
  3686. DI = nullptr;
  3687. } else {
  3688. ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
  3689. }
  3690. LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
  3691. LookupOrdinaryName, ForRedeclaration);
  3692. LookupName(R, S);
  3693. if (R.isSingleResult()) {
  3694. NamedDecl *PrevDecl = R.getFoundDecl();
  3695. if (S->isDeclScope(PrevDecl)) {
  3696. Diag(ArgInfo[i].NameLoc,
  3697. (MethodDefinition ? diag::warn_method_param_redefinition
  3698. : diag::warn_method_param_declaration))
  3699. << ArgInfo[i].Name;
  3700. Diag(PrevDecl->getLocation(),
  3701. diag::note_previous_declaration);
  3702. }
  3703. }
  3704. SourceLocation StartLoc = DI
  3705. ? DI->getTypeLoc().getBeginLoc()
  3706. : ArgInfo[i].NameLoc;
  3707. ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
  3708. ArgInfo[i].NameLoc, ArgInfo[i].Name,
  3709. ArgType, DI, SC_None);
  3710. Param->setObjCMethodScopeInfo(i);
  3711. Param->setObjCDeclQualifier(
  3712. CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
  3713. // Apply the attributes to the parameter.
  3714. ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
  3715. if (Param->hasAttr<BlocksAttr>()) {
  3716. Diag(Param->getLocation(), diag::err_block_on_nonlocal);
  3717. Param->setInvalidDecl();
  3718. }
  3719. S->AddDecl(Param);
  3720. IdResolver.AddDecl(Param);
  3721. Params.push_back(Param);
  3722. }
  3723. for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
  3724. ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
  3725. QualType ArgType = Param->getType();
  3726. if (ArgType.isNull())
  3727. ArgType = Context.getObjCIdType();
  3728. else
  3729. // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
  3730. ArgType = Context.getAdjustedParameterType(ArgType);
  3731. Param->setDeclContext(ObjCMethod);
  3732. Params.push_back(Param);
  3733. }
  3734. ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
  3735. ObjCMethod->setObjCDeclQualifier(
  3736. CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
  3737. if (AttrList)
  3738. ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
  3739. // Add the method now.
  3740. const ObjCMethodDecl *PrevMethod = nullptr;
  3741. if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
  3742. if (MethodType == tok::minus) {
  3743. PrevMethod = ImpDecl->getInstanceMethod(Sel);
  3744. ImpDecl->addInstanceMethod(ObjCMethod);
  3745. } else {
  3746. PrevMethod = ImpDecl->getClassMethod(Sel);
  3747. ImpDecl->addClassMethod(ObjCMethod);
  3748. }
  3749. // Merge information from the @interface declaration into the
  3750. // @implementation.
  3751. if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
  3752. if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
  3753. ObjCMethod->isInstanceMethod())) {
  3754. mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
  3755. // Warn about defining -dealloc in a category.
  3756. if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
  3757. ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
  3758. Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
  3759. << ObjCMethod->getDeclName();
  3760. }
  3761. }
  3762. }
  3763. } else {
  3764. cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
  3765. }
  3766. if (PrevMethod) {
  3767. // You can never have two method definitions with the same name.
  3768. Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
  3769. << ObjCMethod->getDeclName();
  3770. Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
  3771. ObjCMethod->setInvalidDecl();
  3772. return ObjCMethod;
  3773. }
  3774. // If this Objective-C method does not have a related result type, but we
  3775. // are allowed to infer related result types, try to do so based on the
  3776. // method family.
  3777. ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
  3778. if (!CurrentClass) {
  3779. if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
  3780. CurrentClass = Cat->getClassInterface();
  3781. else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
  3782. CurrentClass = Impl->getClassInterface();
  3783. else if (ObjCCategoryImplDecl *CatImpl
  3784. = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
  3785. CurrentClass = CatImpl->getClassInterface();
  3786. }
  3787. ResultTypeCompatibilityKind RTC
  3788. = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
  3789. CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
  3790. bool ARCError = false;
  3791. if (getLangOpts().ObjCAutoRefCount)
  3792. ARCError = CheckARCMethodDecl(ObjCMethod);
  3793. // Infer the related result type when possible.
  3794. if (!ARCError && RTC == Sema::RTC_Compatible &&
  3795. !ObjCMethod->hasRelatedResultType() &&
  3796. LangOpts.ObjCInferRelatedResultType) {
  3797. bool InferRelatedResultType = false;
  3798. switch (ObjCMethod->getMethodFamily()) {
  3799. case OMF_None:
  3800. case OMF_copy:
  3801. case OMF_dealloc:
  3802. case OMF_finalize:
  3803. case OMF_mutableCopy:
  3804. case OMF_release:
  3805. case OMF_retainCount:
  3806. case OMF_initialize:
  3807. case OMF_performSelector:
  3808. break;
  3809. case OMF_alloc:
  3810. case OMF_new:
  3811. InferRelatedResultType = ObjCMethod->isClassMethod();
  3812. break;
  3813. case OMF_init:
  3814. case OMF_autorelease:
  3815. case OMF_retain:
  3816. case OMF_self:
  3817. InferRelatedResultType = ObjCMethod->isInstanceMethod();
  3818. break;
  3819. }
  3820. if (InferRelatedResultType &&
  3821. !ObjCMethod->getReturnType()->isObjCIndependentClassType())
  3822. ObjCMethod->SetRelatedResultType();
  3823. }
  3824. ActOnDocumentableDecl(ObjCMethod);
  3825. return ObjCMethod;
  3826. #endif // HLSL Change Ends
  3827. }
  3828. bool Sema::CheckObjCDeclScope(Decl *D) {
  3829. // Following is also an error. But it is caused by a missing @end
  3830. // and diagnostic is issued elsewhere.
  3831. if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
  3832. return false;
  3833. // If we switched context to translation unit while we are still lexically in
  3834. // an objc container, it means the parser missed emitting an error.
  3835. if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
  3836. return false;
  3837. Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
  3838. D->setInvalidDecl();
  3839. return true;
  3840. }
  3841. /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
  3842. /// instance variables of ClassName into Decls.
  3843. void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
  3844. IdentifierInfo *ClassName,
  3845. SmallVectorImpl<Decl*> &Decls) {
  3846. // Check that ClassName is a valid class
  3847. ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
  3848. if (!Class) {
  3849. Diag(DeclStart, diag::err_undef_interface) << ClassName;
  3850. return;
  3851. }
  3852. if (LangOpts.ObjCRuntime.isNonFragile()) {
  3853. Diag(DeclStart, diag::err_atdef_nonfragile_interface);
  3854. return;
  3855. }
  3856. // Collect the instance variables
  3857. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  3858. Context.DeepCollectObjCIvars(Class, true, Ivars);
  3859. // For each ivar, create a fresh ObjCAtDefsFieldDecl.
  3860. for (unsigned i = 0; i < Ivars.size(); i++) {
  3861. const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
  3862. RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
  3863. Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
  3864. /*FIXME: StartL=*/ID->getLocation(),
  3865. ID->getLocation(),
  3866. ID->getIdentifier(), ID->getType(),
  3867. ID->getBitWidth());
  3868. Decls.push_back(FD);
  3869. }
  3870. // Introduce all of these fields into the appropriate scope.
  3871. for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
  3872. D != Decls.end(); ++D) {
  3873. FieldDecl *FD = cast<FieldDecl>(*D);
  3874. if (getLangOpts().CPlusPlus)
  3875. PushOnScopeChains(cast<FieldDecl>(FD), S);
  3876. else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
  3877. Record->addDecl(FD);
  3878. }
  3879. }
  3880. /// \brief Build a type-check a new Objective-C exception variable declaration.
  3881. VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
  3882. SourceLocation StartLoc,
  3883. SourceLocation IdLoc,
  3884. IdentifierInfo *Id,
  3885. bool Invalid) {
  3886. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  3887. // duration shall not be qualified by an address-space qualifier."
  3888. // Since all parameters have automatic store duration, they can not have
  3889. // an address space.
  3890. if (T.getAddressSpace() != 0) {
  3891. Diag(IdLoc, diag::err_arg_with_address_space);
  3892. Invalid = true;
  3893. }
  3894. // An @catch parameter must be an unqualified object pointer type;
  3895. // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
  3896. if (Invalid) {
  3897. // Don't do any further checking.
  3898. } else if (T->isDependentType()) {
  3899. // Okay: we don't know what this type will instantiate to.
  3900. } else if (!T->isObjCObjectPointerType()) {
  3901. Invalid = true;
  3902. Diag(IdLoc ,diag::err_catch_param_not_objc_type);
  3903. } else if (T->isObjCQualifiedIdType()) {
  3904. Invalid = true;
  3905. Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
  3906. }
  3907. VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
  3908. T, TInfo, SC_None);
  3909. New->setExceptionVariable(true);
  3910. // In ARC, infer 'retaining' for variables of retainable type.
  3911. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
  3912. Invalid = true;
  3913. if (Invalid)
  3914. New->setInvalidDecl();
  3915. return New;
  3916. }
  3917. Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
  3918. const DeclSpec &DS = D.getDeclSpec();
  3919. // We allow the "register" storage class on exception variables because
  3920. // GCC did, but we drop it completely. Any other storage class is an error.
  3921. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  3922. Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
  3923. << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
  3924. } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3925. Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
  3926. << DeclSpec::getSpecifierName(SCS);
  3927. }
  3928. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  3929. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  3930. diag::err_invalid_thread)
  3931. << DeclSpec::getSpecifierName(TSCS);
  3932. D.getMutableDeclSpec().ClearStorageClassSpecs();
  3933. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  3934. // Check that there are no default arguments inside the type of this
  3935. // exception object (C++ only).
  3936. if (getLangOpts().CPlusPlus)
  3937. CheckExtraCXXDefaultArguments(D);
  3938. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  3939. QualType ExceptionType = TInfo->getType();
  3940. VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
  3941. D.getSourceRange().getBegin(),
  3942. D.getIdentifierLoc(),
  3943. D.getIdentifier(),
  3944. D.isInvalidType());
  3945. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  3946. if (D.getCXXScopeSpec().isSet()) {
  3947. Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
  3948. << D.getCXXScopeSpec().getRange();
  3949. New->setInvalidDecl();
  3950. }
  3951. // Add the parameter declaration into this scope.
  3952. S->AddDecl(New);
  3953. if (D.getIdentifier())
  3954. IdResolver.AddDecl(New);
  3955. ProcessDeclAttributes(S, New, D);
  3956. if (New->hasAttr<BlocksAttr>())
  3957. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  3958. return New;
  3959. }
  3960. /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
  3961. /// initialization.
  3962. void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
  3963. SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
  3964. for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
  3965. Iv= Iv->getNextIvar()) {
  3966. QualType QT = Context.getBaseElementType(Iv->getType());
  3967. if (QT->isRecordType())
  3968. Ivars.push_back(Iv);
  3969. }
  3970. }
  3971. void Sema::DiagnoseUseOfUnimplementedSelectors() {
  3972. // Load referenced selectors from the external source.
  3973. if (ExternalSource) {
  3974. SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
  3975. ExternalSource->ReadReferencedSelectors(Sels);
  3976. for (unsigned I = 0, N = Sels.size(); I != N; ++I)
  3977. ReferencedSelectors[Sels[I].first] = Sels[I].second;
  3978. }
  3979. // Warning will be issued only when selector table is
  3980. // generated (which means there is at lease one implementation
  3981. // in the TU). This is to match gcc's behavior.
  3982. if (ReferencedSelectors.empty() ||
  3983. !Context.AnyObjCImplementation())
  3984. return;
  3985. for (auto &SelectorAndLocation : ReferencedSelectors) {
  3986. Selector Sel = SelectorAndLocation.first;
  3987. SourceLocation Loc = SelectorAndLocation.second;
  3988. if (!LookupImplementedMethodInGlobalPool(Sel))
  3989. Diag(Loc, diag::warn_unimplemented_selector) << Sel;
  3990. }
  3991. return;
  3992. }
  3993. ObjCIvarDecl *
  3994. Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
  3995. const ObjCPropertyDecl *&PDecl) const {
  3996. if (Method->isClassMethod())
  3997. return nullptr;
  3998. const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
  3999. if (!IDecl)
  4000. return nullptr;
  4001. Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
  4002. /*shallowCategoryLookup=*/false,
  4003. /*followSuper=*/false);
  4004. if (!Method || !Method->isPropertyAccessor())
  4005. return nullptr;
  4006. if ((PDecl = Method->findPropertyDecl()))
  4007. if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
  4008. // property backing ivar must belong to property's class
  4009. // or be a private ivar in class's implementation.
  4010. // FIXME. fix the const-ness issue.
  4011. IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
  4012. IV->getIdentifier());
  4013. return IV;
  4014. }
  4015. return nullptr;
  4016. }
  4017. namespace {
  4018. /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
  4019. /// accessor references the backing ivar.
  4020. class UnusedBackingIvarChecker :
  4021. public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
  4022. public:
  4023. Sema &S;
  4024. const ObjCMethodDecl *Method;
  4025. const ObjCIvarDecl *IvarD;
  4026. bool AccessedIvar;
  4027. bool InvokedSelfMethod;
  4028. UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
  4029. const ObjCIvarDecl *IvarD)
  4030. : S(S), Method(Method), IvarD(IvarD),
  4031. AccessedIvar(false), InvokedSelfMethod(false) {
  4032. assert(IvarD);
  4033. }
  4034. bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
  4035. if (E->getDecl() == IvarD) {
  4036. AccessedIvar = true;
  4037. return false;
  4038. }
  4039. return true;
  4040. }
  4041. bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
  4042. if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
  4043. S.isSelfExpr(E->getInstanceReceiver(), Method)) {
  4044. InvokedSelfMethod = true;
  4045. }
  4046. return true;
  4047. }
  4048. };
  4049. }
  4050. void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
  4051. const ObjCImplementationDecl *ImplD) {
  4052. #if 0 // HLSL Change
  4053. if (S->hasUnrecoverableErrorOccurred())
  4054. return;
  4055. for (const auto *CurMethod : ImplD->instance_methods()) {
  4056. unsigned DIAG = diag::warn_unused_property_backing_ivar;
  4057. SourceLocation Loc = CurMethod->getLocation();
  4058. if (Diags.isIgnored(DIAG, Loc))
  4059. continue;
  4060. const ObjCPropertyDecl *PDecl;
  4061. const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
  4062. if (!IV)
  4063. continue;
  4064. UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
  4065. Checker.TraverseStmt(CurMethod->getBody());
  4066. if (Checker.AccessedIvar)
  4067. continue;
  4068. // Do not issue this warning if backing ivar is used somewhere and accessor
  4069. // implementation makes a self call. This is to prevent false positive in
  4070. // cases where the ivar is accessed by another method that the accessor
  4071. // delegates to.
  4072. if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
  4073. Diag(Loc, DIAG) << IV;
  4074. Diag(PDecl->getLocation(), diag::note_property_declare);
  4075. }
  4076. }
  4077. #endif // HLSL Change
  4078. }