SemaDeclObjC.cpp 212 KB

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