SemaExprObjC.cpp 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758
  1. //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
  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 expressions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/DeclObjC.h"
  14. #include "clang/AST/ExprObjC.h"
  15. #include "clang/AST/StmtVisitor.h"
  16. #include "clang/AST/TypeLoc.h"
  17. #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
  18. #include "clang/Basic/Builtins.h"
  19. #include "clang/Edit/Commit.h"
  20. #include "clang/Edit/Rewriters.h"
  21. #include "clang/Lex/Preprocessor.h"
  22. #include "clang/Sema/Initialization.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/SmallString.h"
  28. #include "llvm/Support/ConvertUTF.h"
  29. #include <optional>
  30. using namespace clang;
  31. using namespace sema;
  32. using llvm::ArrayRef;
  33. ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
  34. ArrayRef<Expr *> Strings) {
  35. // Most ObjC strings are formed out of a single piece. However, we *can*
  36. // have strings formed out of multiple @ strings with multiple pptokens in
  37. // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
  38. // StringLiteral for ObjCStringLiteral to hold onto.
  39. StringLiteral *S = cast<StringLiteral>(Strings[0]);
  40. // If we have a multi-part string, merge it all together.
  41. if (Strings.size() != 1) {
  42. // Concatenate objc strings.
  43. SmallString<128> StrBuf;
  44. SmallVector<SourceLocation, 8> StrLocs;
  45. for (Expr *E : Strings) {
  46. S = cast<StringLiteral>(E);
  47. // ObjC strings can't be wide or UTF.
  48. if (!S->isOrdinary()) {
  49. Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
  50. << S->getSourceRange();
  51. return true;
  52. }
  53. // Append the string.
  54. StrBuf += S->getString();
  55. // Get the locations of the string tokens.
  56. StrLocs.append(S->tokloc_begin(), S->tokloc_end());
  57. }
  58. // Create the aggregate string with the appropriate content and location
  59. // information.
  60. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  61. assert(CAT && "String literal not of constant array type!");
  62. QualType StrTy = Context.getConstantArrayType(
  63. CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
  64. CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
  65. S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ordinary,
  66. /*Pascal=*/false, StrTy, &StrLocs[0],
  67. StrLocs.size());
  68. }
  69. return BuildObjCStringLiteral(AtLocs[0], S);
  70. }
  71. ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
  72. // Verify that this composite string is acceptable for ObjC strings.
  73. if (CheckObjCString(S))
  74. return true;
  75. // Initialize the constant string interface lazily. This assumes
  76. // the NSString interface is seen in this translation unit. Note: We
  77. // don't use NSConstantString, since the runtime team considers this
  78. // interface private (even though it appears in the header files).
  79. QualType Ty = Context.getObjCConstantStringInterface();
  80. if (!Ty.isNull()) {
  81. Ty = Context.getObjCObjectPointerType(Ty);
  82. } else if (getLangOpts().NoConstantCFStrings) {
  83. IdentifierInfo *NSIdent=nullptr;
  84. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  85. if (StringClass.empty())
  86. NSIdent = &Context.Idents.get("NSConstantString");
  87. else
  88. NSIdent = &Context.Idents.get(StringClass);
  89. NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
  90. LookupOrdinaryName);
  91. if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
  92. Context.setObjCConstantStringInterface(StrIF);
  93. Ty = Context.getObjCConstantStringInterface();
  94. Ty = Context.getObjCObjectPointerType(Ty);
  95. } else {
  96. // If there is no NSConstantString interface defined then treat this
  97. // as error and recover from it.
  98. Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
  99. << NSIdent << S->getSourceRange();
  100. Ty = Context.getObjCIdType();
  101. }
  102. } else {
  103. IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
  104. NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
  105. LookupOrdinaryName);
  106. if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
  107. Context.setObjCConstantStringInterface(StrIF);
  108. Ty = Context.getObjCConstantStringInterface();
  109. Ty = Context.getObjCObjectPointerType(Ty);
  110. } else {
  111. // If there is no NSString interface defined, implicitly declare
  112. // a @class NSString; and use that instead. This is to make sure
  113. // type of an NSString literal is represented correctly, instead of
  114. // being an 'id' type.
  115. Ty = Context.getObjCNSStringType();
  116. if (Ty.isNull()) {
  117. ObjCInterfaceDecl *NSStringIDecl =
  118. ObjCInterfaceDecl::Create (Context,
  119. Context.getTranslationUnitDecl(),
  120. SourceLocation(), NSIdent,
  121. nullptr, nullptr, SourceLocation());
  122. Ty = Context.getObjCInterfaceType(NSStringIDecl);
  123. Context.setObjCNSStringType(Ty);
  124. }
  125. Ty = Context.getObjCObjectPointerType(Ty);
  126. }
  127. }
  128. return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
  129. }
  130. /// Emits an error if the given method does not exist, or if the return
  131. /// type is not an Objective-C object.
  132. static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
  133. const ObjCInterfaceDecl *Class,
  134. Selector Sel, const ObjCMethodDecl *Method) {
  135. if (!Method) {
  136. // FIXME: Is there a better way to avoid quotes than using getName()?
  137. S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
  138. return false;
  139. }
  140. // Make sure the return type is reasonable.
  141. QualType ReturnType = Method->getReturnType();
  142. if (!ReturnType->isObjCObjectPointerType()) {
  143. S.Diag(Loc, diag::err_objc_literal_method_sig)
  144. << Sel;
  145. S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
  146. << ReturnType;
  147. return false;
  148. }
  149. return true;
  150. }
  151. /// Maps ObjCLiteralKind to NSClassIdKindKind
  152. static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
  153. Sema::ObjCLiteralKind LiteralKind) {
  154. switch (LiteralKind) {
  155. case Sema::LK_Array:
  156. return NSAPI::ClassId_NSArray;
  157. case Sema::LK_Dictionary:
  158. return NSAPI::ClassId_NSDictionary;
  159. case Sema::LK_Numeric:
  160. return NSAPI::ClassId_NSNumber;
  161. case Sema::LK_String:
  162. return NSAPI::ClassId_NSString;
  163. case Sema::LK_Boxed:
  164. return NSAPI::ClassId_NSValue;
  165. // there is no corresponding matching
  166. // between LK_None/LK_Block and NSClassIdKindKind
  167. case Sema::LK_Block:
  168. case Sema::LK_None:
  169. break;
  170. }
  171. llvm_unreachable("LiteralKind can't be converted into a ClassKind");
  172. }
  173. /// Validates ObjCInterfaceDecl availability.
  174. /// ObjCInterfaceDecl, used to create ObjC literals, should be defined
  175. /// if clang not in a debugger mode.
  176. static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
  177. SourceLocation Loc,
  178. Sema::ObjCLiteralKind LiteralKind) {
  179. if (!Decl) {
  180. NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
  181. IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
  182. S.Diag(Loc, diag::err_undeclared_objc_literal_class)
  183. << II->getName() << LiteralKind;
  184. return false;
  185. } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
  186. S.Diag(Loc, diag::err_undeclared_objc_literal_class)
  187. << Decl->getName() << LiteralKind;
  188. S.Diag(Decl->getLocation(), diag::note_forward_class);
  189. return false;
  190. }
  191. return true;
  192. }
  193. /// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
  194. /// Used to create ObjC literals, such as NSDictionary (@{}),
  195. /// NSArray (@[]) and Boxed Expressions (@())
  196. static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
  197. SourceLocation Loc,
  198. Sema::ObjCLiteralKind LiteralKind) {
  199. NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
  200. IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
  201. NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
  202. Sema::LookupOrdinaryName);
  203. ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
  204. if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
  205. ASTContext &Context = S.Context;
  206. TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  207. ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
  208. nullptr, nullptr, SourceLocation());
  209. }
  210. if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
  211. ID = nullptr;
  212. }
  213. return ID;
  214. }
  215. /// Retrieve the NSNumber factory method that should be used to create
  216. /// an Objective-C literal for the given type.
  217. static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
  218. QualType NumberType,
  219. bool isLiteral = false,
  220. SourceRange R = SourceRange()) {
  221. std::optional<NSAPI::NSNumberLiteralMethodKind> Kind =
  222. S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
  223. if (!Kind) {
  224. if (isLiteral) {
  225. S.Diag(Loc, diag::err_invalid_nsnumber_type)
  226. << NumberType << R;
  227. }
  228. return nullptr;
  229. }
  230. // If we already looked up this method, we're done.
  231. if (S.NSNumberLiteralMethods[*Kind])
  232. return S.NSNumberLiteralMethods[*Kind];
  233. Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
  234. /*Instance=*/false);
  235. ASTContext &CX = S.Context;
  236. // Look up the NSNumber class, if we haven't done so already. It's cached
  237. // in the Sema instance.
  238. if (!S.NSNumberDecl) {
  239. S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
  240. Sema::LK_Numeric);
  241. if (!S.NSNumberDecl) {
  242. return nullptr;
  243. }
  244. }
  245. if (S.NSNumberPointer.isNull()) {
  246. // generate the pointer to NSNumber type.
  247. QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
  248. S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
  249. }
  250. // Look for the appropriate method within NSNumber.
  251. ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
  252. if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
  253. // create a stub definition this NSNumber factory method.
  254. TypeSourceInfo *ReturnTInfo = nullptr;
  255. Method =
  256. ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
  257. S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
  258. /*isInstance=*/false, /*isVariadic=*/false,
  259. /*isPropertyAccessor=*/false,
  260. /*isSynthesizedAccessorStub=*/false,
  261. /*isImplicitlyDeclared=*/true,
  262. /*isDefined=*/false, ObjCMethodDecl::Required,
  263. /*HasRelatedResultType=*/false);
  264. ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
  265. SourceLocation(), SourceLocation(),
  266. &CX.Idents.get("value"),
  267. NumberType, /*TInfo=*/nullptr,
  268. SC_None, nullptr);
  269. Method->setMethodParams(S.Context, value, std::nullopt);
  270. }
  271. if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
  272. return nullptr;
  273. // Note: if the parameter type is out-of-line, we'll catch it later in the
  274. // implicit conversion.
  275. S.NSNumberLiteralMethods[*Kind] = Method;
  276. return Method;
  277. }
  278. /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
  279. /// numeric literal expression. Type of the expression will be "NSNumber *".
  280. ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
  281. // Determine the type of the literal.
  282. QualType NumberType = Number->getType();
  283. if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
  284. // In C, character literals have type 'int'. That's not the type we want
  285. // to use to determine the Objective-c literal kind.
  286. switch (Char->getKind()) {
  287. case CharacterLiteral::Ascii:
  288. case CharacterLiteral::UTF8:
  289. NumberType = Context.CharTy;
  290. break;
  291. case CharacterLiteral::Wide:
  292. NumberType = Context.getWideCharType();
  293. break;
  294. case CharacterLiteral::UTF16:
  295. NumberType = Context.Char16Ty;
  296. break;
  297. case CharacterLiteral::UTF32:
  298. NumberType = Context.Char32Ty;
  299. break;
  300. }
  301. }
  302. // Look for the appropriate method within NSNumber.
  303. // Construct the literal.
  304. SourceRange NR(Number->getSourceRange());
  305. ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
  306. true, NR);
  307. if (!Method)
  308. return ExprError();
  309. // Convert the number to the type that the parameter expects.
  310. ParmVarDecl *ParamDecl = Method->parameters()[0];
  311. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  312. ParamDecl);
  313. ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
  314. SourceLocation(),
  315. Number);
  316. if (ConvertedNumber.isInvalid())
  317. return ExprError();
  318. Number = ConvertedNumber.get();
  319. // Use the effective source range of the literal, including the leading '@'.
  320. return MaybeBindToTemporary(
  321. new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
  322. SourceRange(AtLoc, NR.getEnd())));
  323. }
  324. ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
  325. SourceLocation ValueLoc,
  326. bool Value) {
  327. ExprResult Inner;
  328. if (getLangOpts().CPlusPlus) {
  329. Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
  330. } else {
  331. // C doesn't actually have a way to represent literal values of type
  332. // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
  333. Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
  334. Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
  335. CK_IntegralToBoolean);
  336. }
  337. return BuildObjCNumericLiteral(AtLoc, Inner.get());
  338. }
  339. /// Check that the given expression is a valid element of an Objective-C
  340. /// collection literal.
  341. static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
  342. QualType T,
  343. bool ArrayLiteral = false) {
  344. // If the expression is type-dependent, there's nothing for us to do.
  345. if (Element->isTypeDependent())
  346. return Element;
  347. ExprResult Result = S.CheckPlaceholderExpr(Element);
  348. if (Result.isInvalid())
  349. return ExprError();
  350. Element = Result.get();
  351. // In C++, check for an implicit conversion to an Objective-C object pointer
  352. // type.
  353. if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
  354. InitializedEntity Entity
  355. = InitializedEntity::InitializeParameter(S.Context, T,
  356. /*Consumed=*/false);
  357. InitializationKind Kind = InitializationKind::CreateCopy(
  358. Element->getBeginLoc(), SourceLocation());
  359. InitializationSequence Seq(S, Entity, Kind, Element);
  360. if (!Seq.Failed())
  361. return Seq.Perform(S, Entity, Kind, Element);
  362. }
  363. Expr *OrigElement = Element;
  364. // Perform lvalue-to-rvalue conversion.
  365. Result = S.DefaultLvalueConversion(Element);
  366. if (Result.isInvalid())
  367. return ExprError();
  368. Element = Result.get();
  369. // Make sure that we have an Objective-C pointer type or block.
  370. if (!Element->getType()->isObjCObjectPointerType() &&
  371. !Element->getType()->isBlockPointerType()) {
  372. bool Recovered = false;
  373. // If this is potentially an Objective-C numeric literal, add the '@'.
  374. if (isa<IntegerLiteral>(OrigElement) ||
  375. isa<CharacterLiteral>(OrigElement) ||
  376. isa<FloatingLiteral>(OrigElement) ||
  377. isa<ObjCBoolLiteralExpr>(OrigElement) ||
  378. isa<CXXBoolLiteralExpr>(OrigElement)) {
  379. if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
  380. int Which = isa<CharacterLiteral>(OrigElement) ? 1
  381. : (isa<CXXBoolLiteralExpr>(OrigElement) ||
  382. isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
  383. : 3;
  384. S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
  385. << Which << OrigElement->getSourceRange()
  386. << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
  387. Result =
  388. S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
  389. if (Result.isInvalid())
  390. return ExprError();
  391. Element = Result.get();
  392. Recovered = true;
  393. }
  394. }
  395. // If this is potentially an Objective-C string literal, add the '@'.
  396. else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
  397. if (String->isOrdinary()) {
  398. S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
  399. << 0 << OrigElement->getSourceRange()
  400. << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
  401. Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
  402. if (Result.isInvalid())
  403. return ExprError();
  404. Element = Result.get();
  405. Recovered = true;
  406. }
  407. }
  408. if (!Recovered) {
  409. S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
  410. << Element->getType();
  411. return ExprError();
  412. }
  413. }
  414. if (ArrayLiteral)
  415. if (ObjCStringLiteral *getString =
  416. dyn_cast<ObjCStringLiteral>(OrigElement)) {
  417. if (StringLiteral *SL = getString->getString()) {
  418. unsigned numConcat = SL->getNumConcatenated();
  419. if (numConcat > 1) {
  420. // Only warn if the concatenated string doesn't come from a macro.
  421. bool hasMacro = false;
  422. for (unsigned i = 0; i < numConcat ; ++i)
  423. if (SL->getStrTokenLoc(i).isMacroID()) {
  424. hasMacro = true;
  425. break;
  426. }
  427. if (!hasMacro)
  428. S.Diag(Element->getBeginLoc(),
  429. diag::warn_concatenated_nsarray_literal)
  430. << Element->getType();
  431. }
  432. }
  433. }
  434. // Make sure that the element has the type that the container factory
  435. // function expects.
  436. return S.PerformCopyInitialization(
  437. InitializedEntity::InitializeParameter(S.Context, T,
  438. /*Consumed=*/false),
  439. Element->getBeginLoc(), Element);
  440. }
  441. ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
  442. if (ValueExpr->isTypeDependent()) {
  443. ObjCBoxedExpr *BoxedExpr =
  444. new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
  445. return BoxedExpr;
  446. }
  447. ObjCMethodDecl *BoxingMethod = nullptr;
  448. QualType BoxedType;
  449. // Convert the expression to an RValue, so we can check for pointer types...
  450. ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
  451. if (RValue.isInvalid()) {
  452. return ExprError();
  453. }
  454. SourceLocation Loc = SR.getBegin();
  455. ValueExpr = RValue.get();
  456. QualType ValueType(ValueExpr->getType());
  457. if (const PointerType *PT = ValueType->getAs<PointerType>()) {
  458. QualType PointeeType = PT->getPointeeType();
  459. if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
  460. if (!NSStringDecl) {
  461. NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
  462. Sema::LK_String);
  463. if (!NSStringDecl) {
  464. return ExprError();
  465. }
  466. QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
  467. NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
  468. }
  469. // The boxed expression can be emitted as a compile time constant if it is
  470. // a string literal whose character encoding is compatible with UTF-8.
  471. if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
  472. if (CE->getCastKind() == CK_ArrayToPointerDecay)
  473. if (auto *SL =
  474. dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
  475. assert((SL->isOrdinary() || SL->isUTF8()) &&
  476. "unexpected character encoding");
  477. StringRef Str = SL->getString();
  478. const llvm::UTF8 *StrBegin = Str.bytes_begin();
  479. const llvm::UTF8 *StrEnd = Str.bytes_end();
  480. // Check that this is a valid UTF-8 string.
  481. if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
  482. BoxedType = Context.getAttributedType(
  483. AttributedType::getNullabilityAttrKind(
  484. NullabilityKind::NonNull),
  485. NSStringPointer, NSStringPointer);
  486. return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
  487. }
  488. Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
  489. << NSStringPointer << SL->getSourceRange();
  490. }
  491. if (!StringWithUTF8StringMethod) {
  492. IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
  493. Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
  494. // Look for the appropriate method within NSString.
  495. BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
  496. if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
  497. // Debugger needs to work even if NSString hasn't been defined.
  498. TypeSourceInfo *ReturnTInfo = nullptr;
  499. ObjCMethodDecl *M = ObjCMethodDecl::Create(
  500. Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
  501. NSStringPointer, ReturnTInfo, NSStringDecl,
  502. /*isInstance=*/false, /*isVariadic=*/false,
  503. /*isPropertyAccessor=*/false,
  504. /*isSynthesizedAccessorStub=*/false,
  505. /*isImplicitlyDeclared=*/true,
  506. /*isDefined=*/false, ObjCMethodDecl::Required,
  507. /*HasRelatedResultType=*/false);
  508. QualType ConstCharType = Context.CharTy.withConst();
  509. ParmVarDecl *value =
  510. ParmVarDecl::Create(Context, M,
  511. SourceLocation(), SourceLocation(),
  512. &Context.Idents.get("value"),
  513. Context.getPointerType(ConstCharType),
  514. /*TInfo=*/nullptr,
  515. SC_None, nullptr);
  516. M->setMethodParams(Context, value, std::nullopt);
  517. BoxingMethod = M;
  518. }
  519. if (!validateBoxingMethod(*this, Loc, NSStringDecl,
  520. stringWithUTF8String, BoxingMethod))
  521. return ExprError();
  522. StringWithUTF8StringMethod = BoxingMethod;
  523. }
  524. BoxingMethod = StringWithUTF8StringMethod;
  525. BoxedType = NSStringPointer;
  526. // Transfer the nullability from method's return type.
  527. std::optional<NullabilityKind> Nullability =
  528. BoxingMethod->getReturnType()->getNullability();
  529. if (Nullability)
  530. BoxedType = Context.getAttributedType(
  531. AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
  532. BoxedType);
  533. }
  534. } else if (ValueType->isBuiltinType()) {
  535. // The other types we support are numeric, char and BOOL/bool. We could also
  536. // provide limited support for structure types, such as NSRange, NSRect, and
  537. // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
  538. // for more details.
  539. // Check for a top-level character literal.
  540. if (const CharacterLiteral *Char =
  541. dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
  542. // In C, character literals have type 'int'. That's not the type we want
  543. // to use to determine the Objective-c literal kind.
  544. switch (Char->getKind()) {
  545. case CharacterLiteral::Ascii:
  546. case CharacterLiteral::UTF8:
  547. ValueType = Context.CharTy;
  548. break;
  549. case CharacterLiteral::Wide:
  550. ValueType = Context.getWideCharType();
  551. break;
  552. case CharacterLiteral::UTF16:
  553. ValueType = Context.Char16Ty;
  554. break;
  555. case CharacterLiteral::UTF32:
  556. ValueType = Context.Char32Ty;
  557. break;
  558. }
  559. }
  560. // FIXME: Do I need to do anything special with BoolTy expressions?
  561. // Look for the appropriate method within NSNumber.
  562. BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
  563. BoxedType = NSNumberPointer;
  564. } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
  565. if (!ET->getDecl()->isComplete()) {
  566. Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
  567. << ValueType << ValueExpr->getSourceRange();
  568. return ExprError();
  569. }
  570. BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
  571. ET->getDecl()->getIntegerType());
  572. BoxedType = NSNumberPointer;
  573. } else if (ValueType->isObjCBoxableRecordType()) {
  574. // Support for structure types, that marked as objc_boxable
  575. // struct __attribute__((objc_boxable)) s { ... };
  576. // Look up the NSValue class, if we haven't done so already. It's cached
  577. // in the Sema instance.
  578. if (!NSValueDecl) {
  579. NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
  580. Sema::LK_Boxed);
  581. if (!NSValueDecl) {
  582. return ExprError();
  583. }
  584. // generate the pointer to NSValue type.
  585. QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
  586. NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
  587. }
  588. if (!ValueWithBytesObjCTypeMethod) {
  589. IdentifierInfo *II[] = {
  590. &Context.Idents.get("valueWithBytes"),
  591. &Context.Idents.get("objCType")
  592. };
  593. Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
  594. // Look for the appropriate method within NSValue.
  595. BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
  596. if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
  597. // Debugger needs to work even if NSValue hasn't been defined.
  598. TypeSourceInfo *ReturnTInfo = nullptr;
  599. ObjCMethodDecl *M = ObjCMethodDecl::Create(
  600. Context, SourceLocation(), SourceLocation(), ValueWithBytesObjCType,
  601. NSValuePointer, ReturnTInfo, NSValueDecl,
  602. /*isInstance=*/false,
  603. /*isVariadic=*/false,
  604. /*isPropertyAccessor=*/false,
  605. /*isSynthesizedAccessorStub=*/false,
  606. /*isImplicitlyDeclared=*/true,
  607. /*isDefined=*/false, ObjCMethodDecl::Required,
  608. /*HasRelatedResultType=*/false);
  609. SmallVector<ParmVarDecl *, 2> Params;
  610. ParmVarDecl *bytes =
  611. ParmVarDecl::Create(Context, M,
  612. SourceLocation(), SourceLocation(),
  613. &Context.Idents.get("bytes"),
  614. Context.VoidPtrTy.withConst(),
  615. /*TInfo=*/nullptr,
  616. SC_None, nullptr);
  617. Params.push_back(bytes);
  618. QualType ConstCharType = Context.CharTy.withConst();
  619. ParmVarDecl *type =
  620. ParmVarDecl::Create(Context, M,
  621. SourceLocation(), SourceLocation(),
  622. &Context.Idents.get("type"),
  623. Context.getPointerType(ConstCharType),
  624. /*TInfo=*/nullptr,
  625. SC_None, nullptr);
  626. Params.push_back(type);
  627. M->setMethodParams(Context, Params, std::nullopt);
  628. BoxingMethod = M;
  629. }
  630. if (!validateBoxingMethod(*this, Loc, NSValueDecl,
  631. ValueWithBytesObjCType, BoxingMethod))
  632. return ExprError();
  633. ValueWithBytesObjCTypeMethod = BoxingMethod;
  634. }
  635. if (!ValueType.isTriviallyCopyableType(Context)) {
  636. Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
  637. << ValueType << ValueExpr->getSourceRange();
  638. return ExprError();
  639. }
  640. BoxingMethod = ValueWithBytesObjCTypeMethod;
  641. BoxedType = NSValuePointer;
  642. }
  643. if (!BoxingMethod) {
  644. Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
  645. << ValueType << ValueExpr->getSourceRange();
  646. return ExprError();
  647. }
  648. DiagnoseUseOfDecl(BoxingMethod, Loc);
  649. ExprResult ConvertedValueExpr;
  650. if (ValueType->isObjCBoxableRecordType()) {
  651. InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
  652. ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
  653. ValueExpr);
  654. } else {
  655. // Convert the expression to the type that the parameter requires.
  656. ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
  657. InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
  658. ParamDecl);
  659. ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
  660. ValueExpr);
  661. }
  662. if (ConvertedValueExpr.isInvalid())
  663. return ExprError();
  664. ValueExpr = ConvertedValueExpr.get();
  665. ObjCBoxedExpr *BoxedExpr =
  666. new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
  667. BoxingMethod, SR);
  668. return MaybeBindToTemporary(BoxedExpr);
  669. }
  670. /// Build an ObjC subscript pseudo-object expression, given that
  671. /// that's supported by the runtime.
  672. ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
  673. Expr *IndexExpr,
  674. ObjCMethodDecl *getterMethod,
  675. ObjCMethodDecl *setterMethod) {
  676. assert(!LangOpts.isSubscriptPointerArithmetic());
  677. // We can't get dependent types here; our callers should have
  678. // filtered them out.
  679. assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
  680. "base or index cannot have dependent type here");
  681. // Filter out placeholders in the index. In theory, overloads could
  682. // be preserved here, although that might not actually work correctly.
  683. ExprResult Result = CheckPlaceholderExpr(IndexExpr);
  684. if (Result.isInvalid())
  685. return ExprError();
  686. IndexExpr = Result.get();
  687. // Perform lvalue-to-rvalue conversion on the base.
  688. Result = DefaultLvalueConversion(BaseExpr);
  689. if (Result.isInvalid())
  690. return ExprError();
  691. BaseExpr = Result.get();
  692. // Build the pseudo-object expression.
  693. return new (Context) ObjCSubscriptRefExpr(
  694. BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
  695. getterMethod, setterMethod, RB);
  696. }
  697. ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
  698. SourceLocation Loc = SR.getBegin();
  699. if (!NSArrayDecl) {
  700. NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
  701. Sema::LK_Array);
  702. if (!NSArrayDecl) {
  703. return ExprError();
  704. }
  705. }
  706. // Find the arrayWithObjects:count: method, if we haven't done so already.
  707. QualType IdT = Context.getObjCIdType();
  708. if (!ArrayWithObjectsMethod) {
  709. Selector
  710. Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
  711. ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
  712. if (!Method && getLangOpts().DebuggerObjCLiteral) {
  713. TypeSourceInfo *ReturnTInfo = nullptr;
  714. Method = ObjCMethodDecl::Create(
  715. Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
  716. Context.getTranslationUnitDecl(), false /*Instance*/,
  717. false /*isVariadic*/,
  718. /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
  719. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  720. ObjCMethodDecl::Required, false);
  721. SmallVector<ParmVarDecl *, 2> Params;
  722. ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
  723. SourceLocation(),
  724. SourceLocation(),
  725. &Context.Idents.get("objects"),
  726. Context.getPointerType(IdT),
  727. /*TInfo=*/nullptr,
  728. SC_None, nullptr);
  729. Params.push_back(objects);
  730. ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
  731. SourceLocation(),
  732. SourceLocation(),
  733. &Context.Idents.get("cnt"),
  734. Context.UnsignedLongTy,
  735. /*TInfo=*/nullptr, SC_None,
  736. nullptr);
  737. Params.push_back(cnt);
  738. Method->setMethodParams(Context, Params, std::nullopt);
  739. }
  740. if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
  741. return ExprError();
  742. // Dig out the type that all elements should be converted to.
  743. QualType T = Method->parameters()[0]->getType();
  744. const PointerType *PtrT = T->getAs<PointerType>();
  745. if (!PtrT ||
  746. !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
  747. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  748. << Sel;
  749. Diag(Method->parameters()[0]->getLocation(),
  750. diag::note_objc_literal_method_param)
  751. << 0 << T
  752. << Context.getPointerType(IdT.withConst());
  753. return ExprError();
  754. }
  755. // Check that the 'count' parameter is integral.
  756. if (!Method->parameters()[1]->getType()->isIntegerType()) {
  757. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  758. << Sel;
  759. Diag(Method->parameters()[1]->getLocation(),
  760. diag::note_objc_literal_method_param)
  761. << 1
  762. << Method->parameters()[1]->getType()
  763. << "integral";
  764. return ExprError();
  765. }
  766. // We've found a good +arrayWithObjects:count: method. Save it!
  767. ArrayWithObjectsMethod = Method;
  768. }
  769. QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
  770. QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
  771. // Check that each of the elements provided is valid in a collection literal,
  772. // performing conversions as necessary.
  773. Expr **ElementsBuffer = Elements.data();
  774. for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
  775. ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
  776. ElementsBuffer[I],
  777. RequiredType, true);
  778. if (Converted.isInvalid())
  779. return ExprError();
  780. ElementsBuffer[I] = Converted.get();
  781. }
  782. QualType Ty
  783. = Context.getObjCObjectPointerType(
  784. Context.getObjCInterfaceType(NSArrayDecl));
  785. return MaybeBindToTemporary(
  786. ObjCArrayLiteral::Create(Context, Elements, Ty,
  787. ArrayWithObjectsMethod, SR));
  788. }
  789. /// Check for duplicate keys in an ObjC dictionary literal. For instance:
  790. /// NSDictionary *nd = @{ @"foo" : @"bar", @"foo" : @"baz" };
  791. static void
  792. CheckObjCDictionaryLiteralDuplicateKeys(Sema &S,
  793. ObjCDictionaryLiteral *Literal) {
  794. if (Literal->isValueDependent() || Literal->isTypeDependent())
  795. return;
  796. // NSNumber has quite relaxed equality semantics (for instance, @YES is
  797. // considered equal to @1.0). For now, ignore floating points and just do a
  798. // bit-width and sign agnostic integer compare.
  799. struct APSIntCompare {
  800. bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const {
  801. return llvm::APSInt::compareValues(LHS, RHS) < 0;
  802. }
  803. };
  804. llvm::DenseMap<StringRef, SourceLocation> StringKeys;
  805. std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys;
  806. auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
  807. auto Pair = Map.insert({Key, Loc});
  808. if (!Pair.second) {
  809. S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
  810. S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
  811. }
  812. };
  813. for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; ++Idx) {
  814. Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts();
  815. if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) {
  816. StringRef Bytes = StrLit->getString()->getBytes();
  817. SourceLocation Loc = StrLit->getExprLoc();
  818. checkOneKey(StringKeys, Bytes, Loc);
  819. }
  820. if (auto *BE = dyn_cast<ObjCBoxedExpr>(Key)) {
  821. Expr *Boxed = BE->getSubExpr();
  822. SourceLocation Loc = BE->getExprLoc();
  823. // Check for @("foo").
  824. if (auto *Str = dyn_cast<StringLiteral>(Boxed->IgnoreParenImpCasts())) {
  825. checkOneKey(StringKeys, Str->getBytes(), Loc);
  826. continue;
  827. }
  828. Expr::EvalResult Result;
  829. if (Boxed->EvaluateAsInt(Result, S.getASTContext(),
  830. Expr::SE_AllowSideEffects)) {
  831. checkOneKey(IntegralKeys, Result.Val.getInt(), Loc);
  832. }
  833. }
  834. }
  835. }
  836. ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
  837. MutableArrayRef<ObjCDictionaryElement> Elements) {
  838. SourceLocation Loc = SR.getBegin();
  839. if (!NSDictionaryDecl) {
  840. NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
  841. Sema::LK_Dictionary);
  842. if (!NSDictionaryDecl) {
  843. return ExprError();
  844. }
  845. }
  846. // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
  847. // so already.
  848. QualType IdT = Context.getObjCIdType();
  849. if (!DictionaryWithObjectsMethod) {
  850. Selector Sel = NSAPIObj->getNSDictionarySelector(
  851. NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
  852. ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
  853. if (!Method && getLangOpts().DebuggerObjCLiteral) {
  854. Method = ObjCMethodDecl::Create(
  855. Context, SourceLocation(), SourceLocation(), Sel, IdT,
  856. nullptr /*TypeSourceInfo */, Context.getTranslationUnitDecl(),
  857. false /*Instance*/, false /*isVariadic*/,
  858. /*isPropertyAccessor=*/false,
  859. /*isSynthesizedAccessorStub=*/false,
  860. /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
  861. ObjCMethodDecl::Required, false);
  862. SmallVector<ParmVarDecl *, 3> Params;
  863. ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
  864. SourceLocation(),
  865. SourceLocation(),
  866. &Context.Idents.get("objects"),
  867. Context.getPointerType(IdT),
  868. /*TInfo=*/nullptr, SC_None,
  869. nullptr);
  870. Params.push_back(objects);
  871. ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
  872. SourceLocation(),
  873. SourceLocation(),
  874. &Context.Idents.get("keys"),
  875. Context.getPointerType(IdT),
  876. /*TInfo=*/nullptr, SC_None,
  877. nullptr);
  878. Params.push_back(keys);
  879. ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
  880. SourceLocation(),
  881. SourceLocation(),
  882. &Context.Idents.get("cnt"),
  883. Context.UnsignedLongTy,
  884. /*TInfo=*/nullptr, SC_None,
  885. nullptr);
  886. Params.push_back(cnt);
  887. Method->setMethodParams(Context, Params, std::nullopt);
  888. }
  889. if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
  890. Method))
  891. return ExprError();
  892. // Dig out the type that all values should be converted to.
  893. QualType ValueT = Method->parameters()[0]->getType();
  894. const PointerType *PtrValue = ValueT->getAs<PointerType>();
  895. if (!PtrValue ||
  896. !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
  897. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  898. << Sel;
  899. Diag(Method->parameters()[0]->getLocation(),
  900. diag::note_objc_literal_method_param)
  901. << 0 << ValueT
  902. << Context.getPointerType(IdT.withConst());
  903. return ExprError();
  904. }
  905. // Dig out the type that all keys should be converted to.
  906. QualType KeyT = Method->parameters()[1]->getType();
  907. const PointerType *PtrKey = KeyT->getAs<PointerType>();
  908. if (!PtrKey ||
  909. !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
  910. IdT)) {
  911. bool err = true;
  912. if (PtrKey) {
  913. if (QIDNSCopying.isNull()) {
  914. // key argument of selector is id<NSCopying>?
  915. if (ObjCProtocolDecl *NSCopyingPDecl =
  916. LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
  917. ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
  918. QIDNSCopying = Context.getObjCObjectType(
  919. Context.ObjCBuiltinIdTy, {},
  920. llvm::ArrayRef((ObjCProtocolDecl **)PQ, 1), false);
  921. QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
  922. }
  923. }
  924. if (!QIDNSCopying.isNull())
  925. err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
  926. QIDNSCopying);
  927. }
  928. if (err) {
  929. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  930. << Sel;
  931. Diag(Method->parameters()[1]->getLocation(),
  932. diag::note_objc_literal_method_param)
  933. << 1 << KeyT
  934. << Context.getPointerType(IdT.withConst());
  935. return ExprError();
  936. }
  937. }
  938. // Check that the 'count' parameter is integral.
  939. QualType CountType = Method->parameters()[2]->getType();
  940. if (!CountType->isIntegerType()) {
  941. Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
  942. << Sel;
  943. Diag(Method->parameters()[2]->getLocation(),
  944. diag::note_objc_literal_method_param)
  945. << 2 << CountType
  946. << "integral";
  947. return ExprError();
  948. }
  949. // We've found a good +dictionaryWithObjects:keys:count: method; save it!
  950. DictionaryWithObjectsMethod = Method;
  951. }
  952. QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
  953. QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
  954. QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
  955. QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
  956. // Check that each of the keys and values provided is valid in a collection
  957. // literal, performing conversions as necessary.
  958. bool HasPackExpansions = false;
  959. for (ObjCDictionaryElement &Element : Elements) {
  960. // Check the key.
  961. ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
  962. KeyT);
  963. if (Key.isInvalid())
  964. return ExprError();
  965. // Check the value.
  966. ExprResult Value
  967. = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
  968. if (Value.isInvalid())
  969. return ExprError();
  970. Element.Key = Key.get();
  971. Element.Value = Value.get();
  972. if (Element.EllipsisLoc.isInvalid())
  973. continue;
  974. if (!Element.Key->containsUnexpandedParameterPack() &&
  975. !Element.Value->containsUnexpandedParameterPack()) {
  976. Diag(Element.EllipsisLoc,
  977. diag::err_pack_expansion_without_parameter_packs)
  978. << SourceRange(Element.Key->getBeginLoc(),
  979. Element.Value->getEndLoc());
  980. return ExprError();
  981. }
  982. HasPackExpansions = true;
  983. }
  984. QualType Ty = Context.getObjCObjectPointerType(
  985. Context.getObjCInterfaceType(NSDictionaryDecl));
  986. auto *Literal =
  987. ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty,
  988. DictionaryWithObjectsMethod, SR);
  989. CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal);
  990. return MaybeBindToTemporary(Literal);
  991. }
  992. ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
  993. TypeSourceInfo *EncodedTypeInfo,
  994. SourceLocation RParenLoc) {
  995. QualType EncodedType = EncodedTypeInfo->getType();
  996. QualType StrTy;
  997. if (EncodedType->isDependentType())
  998. StrTy = Context.DependentTy;
  999. else {
  1000. if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
  1001. !EncodedType->isVoidType()) // void is handled too.
  1002. if (RequireCompleteType(AtLoc, EncodedType,
  1003. diag::err_incomplete_type_objc_at_encode,
  1004. EncodedTypeInfo->getTypeLoc()))
  1005. return ExprError();
  1006. std::string Str;
  1007. QualType NotEncodedT;
  1008. Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
  1009. if (!NotEncodedT.isNull())
  1010. Diag(AtLoc, diag::warn_incomplete_encoded_type)
  1011. << EncodedType << NotEncodedT;
  1012. // The type of @encode is the same as the type of the corresponding string,
  1013. // which is an array type.
  1014. StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
  1015. }
  1016. return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
  1017. }
  1018. ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
  1019. SourceLocation EncodeLoc,
  1020. SourceLocation LParenLoc,
  1021. ParsedType ty,
  1022. SourceLocation RParenLoc) {
  1023. // FIXME: Preserve type source info ?
  1024. TypeSourceInfo *TInfo;
  1025. QualType EncodedType = GetTypeFromParser(ty, &TInfo);
  1026. if (!TInfo)
  1027. TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
  1028. getLocForEndOfToken(LParenLoc));
  1029. return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
  1030. }
  1031. static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
  1032. SourceLocation AtLoc,
  1033. SourceLocation LParenLoc,
  1034. SourceLocation RParenLoc,
  1035. ObjCMethodDecl *Method,
  1036. ObjCMethodList &MethList) {
  1037. ObjCMethodList *M = &MethList;
  1038. bool Warned = false;
  1039. for (M = M->getNext(); M; M=M->getNext()) {
  1040. ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
  1041. if (MatchingMethodDecl == Method ||
  1042. isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
  1043. MatchingMethodDecl->getSelector() != Method->getSelector())
  1044. continue;
  1045. if (!S.MatchTwoMethodDeclarations(Method,
  1046. MatchingMethodDecl, Sema::MMS_loose)) {
  1047. if (!Warned) {
  1048. Warned = true;
  1049. S.Diag(AtLoc, diag::warn_multiple_selectors)
  1050. << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
  1051. << FixItHint::CreateInsertion(RParenLoc, ")");
  1052. S.Diag(Method->getLocation(), diag::note_method_declared_at)
  1053. << Method->getDeclName();
  1054. }
  1055. S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
  1056. << MatchingMethodDecl->getDeclName();
  1057. }
  1058. }
  1059. return Warned;
  1060. }
  1061. static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
  1062. ObjCMethodDecl *Method,
  1063. SourceLocation LParenLoc,
  1064. SourceLocation RParenLoc,
  1065. bool WarnMultipleSelectors) {
  1066. if (!WarnMultipleSelectors ||
  1067. S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
  1068. return;
  1069. bool Warned = false;
  1070. for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
  1071. e = S.MethodPool.end(); b != e; b++) {
  1072. // first, instance methods
  1073. ObjCMethodList &InstMethList = b->second.first;
  1074. if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
  1075. Method, InstMethList))
  1076. Warned = true;
  1077. // second, class methods
  1078. ObjCMethodList &ClsMethList = b->second.second;
  1079. if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
  1080. Method, ClsMethList) || Warned)
  1081. return;
  1082. }
  1083. }
  1084. static ObjCMethodDecl *LookupDirectMethodInMethodList(Sema &S, Selector Sel,
  1085. ObjCMethodList &MethList,
  1086. bool &onlyDirect,
  1087. bool &anyDirect) {
  1088. (void)Sel;
  1089. ObjCMethodList *M = &MethList;
  1090. ObjCMethodDecl *DirectMethod = nullptr;
  1091. for (; M; M = M->getNext()) {
  1092. ObjCMethodDecl *Method = M->getMethod();
  1093. if (!Method)
  1094. continue;
  1095. assert(Method->getSelector() == Sel && "Method with wrong selector in method list");
  1096. if (Method->isDirectMethod()) {
  1097. anyDirect = true;
  1098. DirectMethod = Method;
  1099. } else
  1100. onlyDirect = false;
  1101. }
  1102. return DirectMethod;
  1103. }
  1104. // Search the global pool for (potentially) direct methods matching the given
  1105. // selector. If a non-direct method is found, set \param onlyDirect to false. If
  1106. // a direct method is found, set \param anyDirect to true. Returns a direct
  1107. // method, if any.
  1108. static ObjCMethodDecl *LookupDirectMethodInGlobalPool(Sema &S, Selector Sel,
  1109. bool &onlyDirect,
  1110. bool &anyDirect) {
  1111. auto Iter = S.MethodPool.find(Sel);
  1112. if (Iter == S.MethodPool.end())
  1113. return nullptr;
  1114. ObjCMethodDecl *DirectInstance = LookupDirectMethodInMethodList(
  1115. S, Sel, Iter->second.first, onlyDirect, anyDirect);
  1116. ObjCMethodDecl *DirectClass = LookupDirectMethodInMethodList(
  1117. S, Sel, Iter->second.second, onlyDirect, anyDirect);
  1118. return DirectInstance ? DirectInstance : DirectClass;
  1119. }
  1120. static ObjCMethodDecl *findMethodInCurrentClass(Sema &S, Selector Sel) {
  1121. auto *CurMD = S.getCurMethodDecl();
  1122. if (!CurMD)
  1123. return nullptr;
  1124. ObjCInterfaceDecl *IFace = CurMD->getClassInterface();
  1125. // The language enforce that only one direct method is present in a given
  1126. // class, so we just need to find one method in the current class to know
  1127. // whether Sel is potentially direct in this context.
  1128. if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/true))
  1129. return MD;
  1130. if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*Instance=*/true))
  1131. return MD;
  1132. if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/false))
  1133. return MD;
  1134. if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*Instance=*/false))
  1135. return MD;
  1136. return nullptr;
  1137. }
  1138. ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
  1139. SourceLocation AtLoc,
  1140. SourceLocation SelLoc,
  1141. SourceLocation LParenLoc,
  1142. SourceLocation RParenLoc,
  1143. bool WarnMultipleSelectors) {
  1144. ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
  1145. SourceRange(LParenLoc, RParenLoc));
  1146. if (!Method)
  1147. Method = LookupFactoryMethodInGlobalPool(Sel,
  1148. SourceRange(LParenLoc, RParenLoc));
  1149. if (!Method) {
  1150. if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
  1151. Selector MatchedSel = OM->getSelector();
  1152. SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
  1153. RParenLoc.getLocWithOffset(-1));
  1154. Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
  1155. << Sel << MatchedSel
  1156. << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
  1157. } else
  1158. Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
  1159. } else {
  1160. DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
  1161. WarnMultipleSelectors);
  1162. bool onlyDirect = true;
  1163. bool anyDirect = false;
  1164. ObjCMethodDecl *GlobalDirectMethod =
  1165. LookupDirectMethodInGlobalPool(*this, Sel, onlyDirect, anyDirect);
  1166. if (onlyDirect) {
  1167. Diag(AtLoc, diag::err_direct_selector_expression)
  1168. << Method->getSelector();
  1169. Diag(Method->getLocation(), diag::note_direct_method_declared_at)
  1170. << Method->getDeclName();
  1171. } else if (anyDirect) {
  1172. // If we saw any direct methods, see if we see a direct member of the
  1173. // current class. If so, the @selector will likely be used to refer to
  1174. // this direct method.
  1175. ObjCMethodDecl *LikelyTargetMethod = findMethodInCurrentClass(*this, Sel);
  1176. if (LikelyTargetMethod && LikelyTargetMethod->isDirectMethod()) {
  1177. Diag(AtLoc, diag::warn_potentially_direct_selector_expression) << Sel;
  1178. Diag(LikelyTargetMethod->getLocation(),
  1179. diag::note_direct_method_declared_at)
  1180. << LikelyTargetMethod->getDeclName();
  1181. } else if (!LikelyTargetMethod) {
  1182. // Otherwise, emit the "strict" variant of this diagnostic, unless
  1183. // LikelyTargetMethod is non-direct.
  1184. Diag(AtLoc, diag::warn_strict_potentially_direct_selector_expression)
  1185. << Sel;
  1186. Diag(GlobalDirectMethod->getLocation(),
  1187. diag::note_direct_method_declared_at)
  1188. << GlobalDirectMethod->getDeclName();
  1189. }
  1190. }
  1191. }
  1192. if (Method &&
  1193. Method->getImplementationControl() != ObjCMethodDecl::Optional &&
  1194. !getSourceManager().isInSystemHeader(Method->getLocation()))
  1195. ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
  1196. // In ARC, forbid the user from using @selector for
  1197. // retain/release/autorelease/dealloc/retainCount.
  1198. if (getLangOpts().ObjCAutoRefCount) {
  1199. switch (Sel.getMethodFamily()) {
  1200. case OMF_retain:
  1201. case OMF_release:
  1202. case OMF_autorelease:
  1203. case OMF_retainCount:
  1204. case OMF_dealloc:
  1205. Diag(AtLoc, diag::err_arc_illegal_selector) <<
  1206. Sel << SourceRange(LParenLoc, RParenLoc);
  1207. break;
  1208. case OMF_None:
  1209. case OMF_alloc:
  1210. case OMF_copy:
  1211. case OMF_finalize:
  1212. case OMF_init:
  1213. case OMF_mutableCopy:
  1214. case OMF_new:
  1215. case OMF_self:
  1216. case OMF_initialize:
  1217. case OMF_performSelector:
  1218. break;
  1219. }
  1220. }
  1221. QualType Ty = Context.getObjCSelType();
  1222. return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
  1223. }
  1224. ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
  1225. SourceLocation AtLoc,
  1226. SourceLocation ProtoLoc,
  1227. SourceLocation LParenLoc,
  1228. SourceLocation ProtoIdLoc,
  1229. SourceLocation RParenLoc) {
  1230. ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
  1231. if (!PDecl) {
  1232. Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
  1233. return true;
  1234. }
  1235. if (PDecl->isNonRuntimeProtocol())
  1236. Diag(ProtoLoc, diag::err_objc_non_runtime_protocol_in_protocol_expr)
  1237. << PDecl;
  1238. if (!PDecl->hasDefinition()) {
  1239. Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
  1240. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  1241. } else {
  1242. PDecl = PDecl->getDefinition();
  1243. }
  1244. QualType Ty = Context.getObjCProtoType();
  1245. if (Ty.isNull())
  1246. return true;
  1247. Ty = Context.getObjCObjectPointerType(Ty);
  1248. return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
  1249. }
  1250. /// Try to capture an implicit reference to 'self'.
  1251. ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
  1252. DeclContext *DC = getFunctionLevelDeclContext();
  1253. // If we're not in an ObjC method, error out. Note that, unlike the
  1254. // C++ case, we don't require an instance method --- class methods
  1255. // still have a 'self', and we really do still need to capture it!
  1256. ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
  1257. if (!method)
  1258. return nullptr;
  1259. tryCaptureVariable(method->getSelfDecl(), Loc);
  1260. return method;
  1261. }
  1262. static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
  1263. QualType origType = T;
  1264. if (auto nullability = AttributedType::stripOuterNullability(T)) {
  1265. if (T == Context.getObjCInstanceType()) {
  1266. return Context.getAttributedType(
  1267. AttributedType::getNullabilityAttrKind(*nullability),
  1268. Context.getObjCIdType(),
  1269. Context.getObjCIdType());
  1270. }
  1271. return origType;
  1272. }
  1273. if (T == Context.getObjCInstanceType())
  1274. return Context.getObjCIdType();
  1275. return origType;
  1276. }
  1277. /// Determine the result type of a message send based on the receiver type,
  1278. /// method, and the kind of message send.
  1279. ///
  1280. /// This is the "base" result type, which will still need to be adjusted
  1281. /// to account for nullability.
  1282. static QualType getBaseMessageSendResultType(Sema &S,
  1283. QualType ReceiverType,
  1284. ObjCMethodDecl *Method,
  1285. bool isClassMessage,
  1286. bool isSuperMessage) {
  1287. assert(Method && "Must have a method");
  1288. if (!Method->hasRelatedResultType())
  1289. return Method->getSendResultType(ReceiverType);
  1290. ASTContext &Context = S.Context;
  1291. // Local function that transfers the nullability of the method's
  1292. // result type to the returned result.
  1293. auto transferNullability = [&](QualType type) -> QualType {
  1294. // If the method's result type has nullability, extract it.
  1295. if (auto nullability =
  1296. Method->getSendResultType(ReceiverType)->getNullability()) {
  1297. // Strip off any outer nullability sugar from the provided type.
  1298. (void)AttributedType::stripOuterNullability(type);
  1299. // Form a new attributed type using the method result type's nullability.
  1300. return Context.getAttributedType(
  1301. AttributedType::getNullabilityAttrKind(*nullability),
  1302. type,
  1303. type);
  1304. }
  1305. return type;
  1306. };
  1307. // If a method has a related return type:
  1308. // - if the method found is an instance method, but the message send
  1309. // was a class message send, T is the declared return type of the method
  1310. // found
  1311. if (Method->isInstanceMethod() && isClassMessage)
  1312. return stripObjCInstanceType(Context,
  1313. Method->getSendResultType(ReceiverType));
  1314. // - if the receiver is super, T is a pointer to the class of the
  1315. // enclosing method definition
  1316. if (isSuperMessage) {
  1317. if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
  1318. if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
  1319. return transferNullability(
  1320. Context.getObjCObjectPointerType(
  1321. Context.getObjCInterfaceType(Class)));
  1322. }
  1323. }
  1324. // - if the receiver is the name of a class U, T is a pointer to U
  1325. if (ReceiverType->getAsObjCInterfaceType())
  1326. return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
  1327. // - if the receiver is of type Class or qualified Class type,
  1328. // T is the declared return type of the method.
  1329. if (ReceiverType->isObjCClassType() ||
  1330. ReceiverType->isObjCQualifiedClassType())
  1331. return stripObjCInstanceType(Context,
  1332. Method->getSendResultType(ReceiverType));
  1333. // - if the receiver is id, qualified id, Class, or qualified Class, T
  1334. // is the receiver type, otherwise
  1335. // - T is the type of the receiver expression.
  1336. return transferNullability(ReceiverType);
  1337. }
  1338. QualType Sema::getMessageSendResultType(const Expr *Receiver,
  1339. QualType ReceiverType,
  1340. ObjCMethodDecl *Method,
  1341. bool isClassMessage,
  1342. bool isSuperMessage) {
  1343. // Produce the result type.
  1344. QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
  1345. Method,
  1346. isClassMessage,
  1347. isSuperMessage);
  1348. // If this is a class message, ignore the nullability of the receiver.
  1349. if (isClassMessage) {
  1350. // In a class method, class messages to 'self' that return instancetype can
  1351. // be typed as the current class. We can safely do this in ARC because self
  1352. // can't be reassigned, and we do it unsafely outside of ARC because in
  1353. // practice people never reassign self in class methods and there's some
  1354. // virtue in not being aggressively pedantic.
  1355. if (Receiver && Receiver->isObjCSelfExpr()) {
  1356. assert(ReceiverType->isObjCClassType() && "expected a Class self");
  1357. QualType T = Method->getSendResultType(ReceiverType);
  1358. AttributedType::stripOuterNullability(T);
  1359. if (T == Context.getObjCInstanceType()) {
  1360. const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
  1361. cast<ImplicitParamDecl>(
  1362. cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
  1363. ->getDeclContext());
  1364. assert(MD->isClassMethod() && "expected a class method");
  1365. QualType NewResultType = Context.getObjCObjectPointerType(
  1366. Context.getObjCInterfaceType(MD->getClassInterface()));
  1367. if (auto Nullability = resultType->getNullability())
  1368. NewResultType = Context.getAttributedType(
  1369. AttributedType::getNullabilityAttrKind(*Nullability),
  1370. NewResultType, NewResultType);
  1371. return NewResultType;
  1372. }
  1373. }
  1374. return resultType;
  1375. }
  1376. // There is nothing left to do if the result type cannot have a nullability
  1377. // specifier.
  1378. if (!resultType->canHaveNullability())
  1379. return resultType;
  1380. // Map the nullability of the result into a table index.
  1381. unsigned receiverNullabilityIdx = 0;
  1382. if (std::optional<NullabilityKind> nullability =
  1383. ReceiverType->getNullability()) {
  1384. if (*nullability == NullabilityKind::NullableResult)
  1385. nullability = NullabilityKind::Nullable;
  1386. receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
  1387. }
  1388. unsigned resultNullabilityIdx = 0;
  1389. if (std::optional<NullabilityKind> nullability =
  1390. resultType->getNullability()) {
  1391. if (*nullability == NullabilityKind::NullableResult)
  1392. nullability = NullabilityKind::Nullable;
  1393. resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
  1394. }
  1395. // The table of nullability mappings, indexed by the receiver's nullability
  1396. // and then the result type's nullability.
  1397. static const uint8_t None = 0;
  1398. static const uint8_t NonNull = 1;
  1399. static const uint8_t Nullable = 2;
  1400. static const uint8_t Unspecified = 3;
  1401. static const uint8_t nullabilityMap[4][4] = {
  1402. // None NonNull Nullable Unspecified
  1403. /* None */ { None, None, Nullable, None },
  1404. /* NonNull */ { None, NonNull, Nullable, Unspecified },
  1405. /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
  1406. /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
  1407. };
  1408. unsigned newResultNullabilityIdx
  1409. = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
  1410. if (newResultNullabilityIdx == resultNullabilityIdx)
  1411. return resultType;
  1412. // Strip off the existing nullability. This removes as little type sugar as
  1413. // possible.
  1414. do {
  1415. if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
  1416. resultType = attributed->getModifiedType();
  1417. } else {
  1418. resultType = resultType.getDesugaredType(Context);
  1419. }
  1420. } while (resultType->getNullability());
  1421. // Add nullability back if needed.
  1422. if (newResultNullabilityIdx > 0) {
  1423. auto newNullability
  1424. = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
  1425. return Context.getAttributedType(
  1426. AttributedType::getNullabilityAttrKind(newNullability),
  1427. resultType, resultType);
  1428. }
  1429. return resultType;
  1430. }
  1431. /// Look for an ObjC method whose result type exactly matches the given type.
  1432. static const ObjCMethodDecl *
  1433. findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
  1434. QualType instancetype) {
  1435. if (MD->getReturnType() == instancetype)
  1436. return MD;
  1437. // For these purposes, a method in an @implementation overrides a
  1438. // declaration in the @interface.
  1439. if (const ObjCImplDecl *impl =
  1440. dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
  1441. const ObjCContainerDecl *iface;
  1442. if (const ObjCCategoryImplDecl *catImpl =
  1443. dyn_cast<ObjCCategoryImplDecl>(impl)) {
  1444. iface = catImpl->getCategoryDecl();
  1445. } else {
  1446. iface = impl->getClassInterface();
  1447. }
  1448. const ObjCMethodDecl *ifaceMD =
  1449. iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
  1450. if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
  1451. }
  1452. SmallVector<const ObjCMethodDecl *, 4> overrides;
  1453. MD->getOverriddenMethods(overrides);
  1454. for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
  1455. if (const ObjCMethodDecl *result =
  1456. findExplicitInstancetypeDeclarer(overrides[i], instancetype))
  1457. return result;
  1458. }
  1459. return nullptr;
  1460. }
  1461. void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
  1462. // Only complain if we're in an ObjC method and the required return
  1463. // type doesn't match the method's declared return type.
  1464. ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
  1465. if (!MD || !MD->hasRelatedResultType() ||
  1466. Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
  1467. return;
  1468. // Look for a method overridden by this method which explicitly uses
  1469. // 'instancetype'.
  1470. if (const ObjCMethodDecl *overridden =
  1471. findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
  1472. SourceRange range = overridden->getReturnTypeSourceRange();
  1473. SourceLocation loc = range.getBegin();
  1474. if (loc.isInvalid())
  1475. loc = overridden->getLocation();
  1476. Diag(loc, diag::note_related_result_type_explicit)
  1477. << /*current method*/ 1 << range;
  1478. return;
  1479. }
  1480. // Otherwise, if we have an interesting method family, note that.
  1481. // This should always trigger if the above didn't.
  1482. if (ObjCMethodFamily family = MD->getMethodFamily())
  1483. Diag(MD->getLocation(), diag::note_related_result_type_family)
  1484. << /*current method*/ 1
  1485. << family;
  1486. }
  1487. void Sema::EmitRelatedResultTypeNote(const Expr *E) {
  1488. E = E->IgnoreParenImpCasts();
  1489. const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
  1490. if (!MsgSend)
  1491. return;
  1492. const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
  1493. if (!Method)
  1494. return;
  1495. if (!Method->hasRelatedResultType())
  1496. return;
  1497. if (Context.hasSameUnqualifiedType(
  1498. Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
  1499. return;
  1500. if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
  1501. Context.getObjCInstanceType()))
  1502. return;
  1503. Diag(Method->getLocation(), diag::note_related_result_type_inferred)
  1504. << Method->isInstanceMethod() << Method->getSelector()
  1505. << MsgSend->getType();
  1506. }
  1507. bool Sema::CheckMessageArgumentTypes(
  1508. const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
  1509. Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
  1510. bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
  1511. SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
  1512. ExprValueKind &VK) {
  1513. SourceLocation SelLoc;
  1514. if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
  1515. SelLoc = SelectorLocs.front();
  1516. else
  1517. SelLoc = lbrac;
  1518. if (!Method) {
  1519. // Apply default argument promotion as for (C99 6.5.2.2p6).
  1520. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  1521. if (Args[i]->isTypeDependent())
  1522. continue;
  1523. ExprResult result;
  1524. if (getLangOpts().DebuggerSupport) {
  1525. QualType paramTy; // ignored
  1526. result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
  1527. } else {
  1528. result = DefaultArgumentPromotion(Args[i]);
  1529. }
  1530. if (result.isInvalid())
  1531. return true;
  1532. Args[i] = result.get();
  1533. }
  1534. unsigned DiagID;
  1535. if (getLangOpts().ObjCAutoRefCount)
  1536. DiagID = diag::err_arc_method_not_found;
  1537. else
  1538. DiagID = isClassMessage ? diag::warn_class_method_not_found
  1539. : diag::warn_inst_method_not_found;
  1540. if (!getLangOpts().DebuggerSupport) {
  1541. const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
  1542. if (OMD && !OMD->isInvalidDecl()) {
  1543. if (getLangOpts().ObjCAutoRefCount)
  1544. DiagID = diag::err_method_not_found_with_typo;
  1545. else
  1546. DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
  1547. : diag::warn_instance_method_not_found_with_typo;
  1548. Selector MatchedSel = OMD->getSelector();
  1549. SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
  1550. if (MatchedSel.isUnarySelector())
  1551. Diag(SelLoc, DiagID)
  1552. << Sel<< isClassMessage << MatchedSel
  1553. << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
  1554. else
  1555. Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
  1556. }
  1557. else
  1558. Diag(SelLoc, DiagID)
  1559. << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
  1560. SelectorLocs.back());
  1561. // Find the class to which we are sending this message.
  1562. if (auto *ObjPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
  1563. if (ObjCInterfaceDecl *ThisClass = ObjPT->getInterfaceDecl()) {
  1564. Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
  1565. if (!RecRange.isInvalid())
  1566. if (ThisClass->lookupClassMethod(Sel))
  1567. Diag(RecRange.getBegin(), diag::note_receiver_expr_here)
  1568. << FixItHint::CreateReplacement(RecRange,
  1569. ThisClass->getNameAsString());
  1570. }
  1571. }
  1572. }
  1573. // In debuggers, we want to use __unknown_anytype for these
  1574. // results so that clients can cast them.
  1575. if (getLangOpts().DebuggerSupport) {
  1576. ReturnType = Context.UnknownAnyTy;
  1577. } else {
  1578. ReturnType = Context.getObjCIdType();
  1579. }
  1580. VK = VK_PRValue;
  1581. return false;
  1582. }
  1583. ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
  1584. isClassMessage, isSuperMessage);
  1585. VK = Expr::getValueKindForType(Method->getReturnType());
  1586. unsigned NumNamedArgs = Sel.getNumArgs();
  1587. // Method might have more arguments than selector indicates. This is due
  1588. // to addition of c-style arguments in method.
  1589. if (Method->param_size() > Sel.getNumArgs())
  1590. NumNamedArgs = Method->param_size();
  1591. // FIXME. This need be cleaned up.
  1592. if (Args.size() < NumNamedArgs) {
  1593. Diag(SelLoc, diag::err_typecheck_call_too_few_args)
  1594. << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
  1595. return false;
  1596. }
  1597. // Compute the set of type arguments to be substituted into each parameter
  1598. // type.
  1599. std::optional<ArrayRef<QualType>> typeArgs =
  1600. ReceiverType->getObjCSubstitutions(Method->getDeclContext());
  1601. bool IsError = false;
  1602. for (unsigned i = 0; i < NumNamedArgs; i++) {
  1603. // We can't do any type-checking on a type-dependent argument.
  1604. if (Args[i]->isTypeDependent())
  1605. continue;
  1606. Expr *argExpr = Args[i];
  1607. ParmVarDecl *param = Method->parameters()[i];
  1608. assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
  1609. if (param->hasAttr<NoEscapeAttr>() &&
  1610. param->getType()->isBlockPointerType())
  1611. if (auto *BE = dyn_cast<BlockExpr>(
  1612. argExpr->IgnoreParenNoopCasts(Context)))
  1613. BE->getBlockDecl()->setDoesNotEscape();
  1614. // Strip the unbridged-cast placeholder expression off unless it's
  1615. // a consumed argument.
  1616. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
  1617. !param->hasAttr<CFConsumedAttr>())
  1618. argExpr = stripARCUnbridgedCast(argExpr);
  1619. // If the parameter is __unknown_anytype, infer its type
  1620. // from the argument.
  1621. if (param->getType() == Context.UnknownAnyTy) {
  1622. QualType paramType;
  1623. ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
  1624. if (argE.isInvalid()) {
  1625. IsError = true;
  1626. } else {
  1627. Args[i] = argE.get();
  1628. // Update the parameter type in-place.
  1629. param->setType(paramType);
  1630. }
  1631. continue;
  1632. }
  1633. QualType origParamType = param->getType();
  1634. QualType paramType = param->getType();
  1635. if (typeArgs)
  1636. paramType = paramType.substObjCTypeArgs(
  1637. Context,
  1638. *typeArgs,
  1639. ObjCSubstitutionContext::Parameter);
  1640. if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
  1641. paramType,
  1642. diag::err_call_incomplete_argument, argExpr))
  1643. return true;
  1644. InitializedEntity Entity
  1645. = InitializedEntity::InitializeParameter(Context, param, paramType);
  1646. ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
  1647. if (ArgE.isInvalid())
  1648. IsError = true;
  1649. else {
  1650. Args[i] = ArgE.getAs<Expr>();
  1651. // If we are type-erasing a block to a block-compatible
  1652. // Objective-C pointer type, we may need to extend the lifetime
  1653. // of the block object.
  1654. if (typeArgs && Args[i]->isPRValue() && paramType->isBlockPointerType() &&
  1655. Args[i]->getType()->isBlockPointerType() &&
  1656. origParamType->isObjCObjectPointerType()) {
  1657. ExprResult arg = Args[i];
  1658. maybeExtendBlockObject(arg);
  1659. Args[i] = arg.get();
  1660. }
  1661. }
  1662. }
  1663. // Promote additional arguments to variadic methods.
  1664. if (Method->isVariadic()) {
  1665. for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
  1666. if (Args[i]->isTypeDependent())
  1667. continue;
  1668. ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
  1669. nullptr);
  1670. IsError |= Arg.isInvalid();
  1671. Args[i] = Arg.get();
  1672. }
  1673. } else {
  1674. // Check for extra arguments to non-variadic methods.
  1675. if (Args.size() != NumNamedArgs) {
  1676. Diag(Args[NumNamedArgs]->getBeginLoc(),
  1677. diag::err_typecheck_call_too_many_args)
  1678. << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
  1679. << Method->getSourceRange()
  1680. << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
  1681. Args.back()->getEndLoc());
  1682. }
  1683. }
  1684. DiagnoseSentinelCalls(Method, SelLoc, Args);
  1685. // Do additional checkings on method.
  1686. IsError |=
  1687. CheckObjCMethodCall(Method, SelLoc, ArrayRef(Args.data(), Args.size()));
  1688. return IsError;
  1689. }
  1690. bool Sema::isSelfExpr(Expr *RExpr) {
  1691. // 'self' is objc 'self' in an objc method only.
  1692. ObjCMethodDecl *Method =
  1693. dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
  1694. return isSelfExpr(RExpr, Method);
  1695. }
  1696. bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
  1697. if (!method) return false;
  1698. receiver = receiver->IgnoreParenLValueCasts();
  1699. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
  1700. if (DRE->getDecl() == method->getSelfDecl())
  1701. return true;
  1702. return false;
  1703. }
  1704. /// LookupMethodInType - Look up a method in an ObjCObjectType.
  1705. ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
  1706. bool isInstance) {
  1707. const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
  1708. if (ObjCInterfaceDecl *iface = objType->getInterface()) {
  1709. // Look it up in the main interface (and categories, etc.)
  1710. if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
  1711. return method;
  1712. // Okay, look for "private" methods declared in any
  1713. // @implementations we've seen.
  1714. if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
  1715. return method;
  1716. }
  1717. // Check qualifiers.
  1718. for (const auto *I : objType->quals())
  1719. if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
  1720. return method;
  1721. return nullptr;
  1722. }
  1723. /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
  1724. /// list of a qualified objective pointer type.
  1725. ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
  1726. const ObjCObjectPointerType *OPT,
  1727. bool Instance)
  1728. {
  1729. ObjCMethodDecl *MD = nullptr;
  1730. for (const auto *PROTO : OPT->quals()) {
  1731. if ((MD = PROTO->lookupMethod(Sel, Instance))) {
  1732. return MD;
  1733. }
  1734. }
  1735. return nullptr;
  1736. }
  1737. /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
  1738. /// objective C interface. This is a property reference expression.
  1739. ExprResult Sema::
  1740. HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
  1741. Expr *BaseExpr, SourceLocation OpLoc,
  1742. DeclarationName MemberName,
  1743. SourceLocation MemberLoc,
  1744. SourceLocation SuperLoc, QualType SuperType,
  1745. bool Super) {
  1746. const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
  1747. ObjCInterfaceDecl *IFace = IFaceT->getDecl();
  1748. if (!MemberName.isIdentifier()) {
  1749. Diag(MemberLoc, diag::err_invalid_property_name)
  1750. << MemberName << QualType(OPT, 0);
  1751. return ExprError();
  1752. }
  1753. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  1754. SourceRange BaseRange = Super? SourceRange(SuperLoc)
  1755. : BaseExpr->getSourceRange();
  1756. if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
  1757. diag::err_property_not_found_forward_class,
  1758. MemberName, BaseRange))
  1759. return ExprError();
  1760. if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
  1761. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  1762. // Check whether we can reference this property.
  1763. if (DiagnoseUseOfDecl(PD, MemberLoc))
  1764. return ExprError();
  1765. if (Super)
  1766. return new (Context)
  1767. ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
  1768. OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
  1769. else
  1770. return new (Context)
  1771. ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
  1772. OK_ObjCProperty, MemberLoc, BaseExpr);
  1773. }
  1774. // Check protocols on qualified interfaces.
  1775. for (const auto *I : OPT->quals())
  1776. if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
  1777. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  1778. // Check whether we can reference this property.
  1779. if (DiagnoseUseOfDecl(PD, MemberLoc))
  1780. return ExprError();
  1781. if (Super)
  1782. return new (Context) ObjCPropertyRefExpr(
  1783. PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
  1784. SuperLoc, SuperType);
  1785. else
  1786. return new (Context)
  1787. ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
  1788. OK_ObjCProperty, MemberLoc, BaseExpr);
  1789. }
  1790. // If that failed, look for an "implicit" property by seeing if the nullary
  1791. // selector is implemented.
  1792. // FIXME: The logic for looking up nullary and unary selectors should be
  1793. // shared with the code in ActOnInstanceMessage.
  1794. Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
  1795. ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
  1796. // May be found in property's qualified list.
  1797. if (!Getter)
  1798. Getter = LookupMethodInQualifiedType(Sel, OPT, true);
  1799. // If this reference is in an @implementation, check for 'private' methods.
  1800. if (!Getter)
  1801. Getter = IFace->lookupPrivateMethod(Sel);
  1802. if (Getter) {
  1803. // Check if we can reference this property.
  1804. if (DiagnoseUseOfDecl(Getter, MemberLoc))
  1805. return ExprError();
  1806. }
  1807. // If we found a getter then this may be a valid dot-reference, we
  1808. // will look for the matching setter, in case it is needed.
  1809. Selector SetterSel =
  1810. SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
  1811. PP.getSelectorTable(), Member);
  1812. ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
  1813. // May be found in property's qualified list.
  1814. if (!Setter)
  1815. Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
  1816. if (!Setter) {
  1817. // If this reference is in an @implementation, also check for 'private'
  1818. // methods.
  1819. Setter = IFace->lookupPrivateMethod(SetterSel);
  1820. }
  1821. if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
  1822. return ExprError();
  1823. // Special warning if member name used in a property-dot for a setter accessor
  1824. // does not use a property with same name; e.g. obj.X = ... for a property with
  1825. // name 'x'.
  1826. if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
  1827. !IFace->FindPropertyDeclaration(
  1828. Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  1829. if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
  1830. // Do not warn if user is using property-dot syntax to make call to
  1831. // user named setter.
  1832. if (!(PDecl->getPropertyAttributes() &
  1833. ObjCPropertyAttribute::kind_setter))
  1834. Diag(MemberLoc,
  1835. diag::warn_property_access_suggest)
  1836. << MemberName << QualType(OPT, 0) << PDecl->getName()
  1837. << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
  1838. }
  1839. }
  1840. if (Getter || Setter) {
  1841. if (Super)
  1842. return new (Context)
  1843. ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
  1844. OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
  1845. else
  1846. return new (Context)
  1847. ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
  1848. OK_ObjCProperty, MemberLoc, BaseExpr);
  1849. }
  1850. // Attempt to correct for typos in property names.
  1851. DeclFilterCCC<ObjCPropertyDecl> CCC{};
  1852. if (TypoCorrection Corrected = CorrectTypo(
  1853. DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
  1854. nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
  1855. DeclarationName TypoResult = Corrected.getCorrection();
  1856. if (TypoResult.isIdentifier() &&
  1857. TypoResult.getAsIdentifierInfo() == Member) {
  1858. // There is no need to try the correction if it is the same.
  1859. NamedDecl *ChosenDecl =
  1860. Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
  1861. if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
  1862. if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
  1863. // This is a class property, we should not use the instance to
  1864. // access it.
  1865. Diag(MemberLoc, diag::err_class_property_found) << MemberName
  1866. << OPT->getInterfaceDecl()->getName()
  1867. << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
  1868. OPT->getInterfaceDecl()->getName());
  1869. return ExprError();
  1870. }
  1871. } else {
  1872. diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
  1873. << MemberName << QualType(OPT, 0));
  1874. return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
  1875. TypoResult, MemberLoc,
  1876. SuperLoc, SuperType, Super);
  1877. }
  1878. }
  1879. ObjCInterfaceDecl *ClassDeclared;
  1880. if (ObjCIvarDecl *Ivar =
  1881. IFace->lookupInstanceVariable(Member, ClassDeclared)) {
  1882. QualType T = Ivar->getType();
  1883. if (const ObjCObjectPointerType * OBJPT =
  1884. T->getAsObjCInterfacePointerType()) {
  1885. if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
  1886. diag::err_property_not_as_forward_class,
  1887. MemberName, BaseExpr))
  1888. return ExprError();
  1889. }
  1890. Diag(MemberLoc,
  1891. diag::err_ivar_access_using_property_syntax_suggest)
  1892. << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
  1893. << FixItHint::CreateReplacement(OpLoc, "->");
  1894. return ExprError();
  1895. }
  1896. Diag(MemberLoc, diag::err_property_not_found)
  1897. << MemberName << QualType(OPT, 0);
  1898. if (Setter)
  1899. Diag(Setter->getLocation(), diag::note_getter_unavailable)
  1900. << MemberName << BaseExpr->getSourceRange();
  1901. return ExprError();
  1902. }
  1903. ExprResult Sema::
  1904. ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
  1905. IdentifierInfo &propertyName,
  1906. SourceLocation receiverNameLoc,
  1907. SourceLocation propertyNameLoc) {
  1908. IdentifierInfo *receiverNamePtr = &receiverName;
  1909. ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
  1910. receiverNameLoc);
  1911. QualType SuperType;
  1912. if (!IFace) {
  1913. // If the "receiver" is 'super' in a method, handle it as an expression-like
  1914. // property reference.
  1915. if (receiverNamePtr->isStr("super")) {
  1916. if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
  1917. if (auto classDecl = CurMethod->getClassInterface()) {
  1918. SuperType = QualType(classDecl->getSuperClassType(), 0);
  1919. if (CurMethod->isInstanceMethod()) {
  1920. if (SuperType.isNull()) {
  1921. // The current class does not have a superclass.
  1922. Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
  1923. << CurMethod->getClassInterface()->getIdentifier();
  1924. return ExprError();
  1925. }
  1926. QualType T = Context.getObjCObjectPointerType(SuperType);
  1927. return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
  1928. /*BaseExpr*/nullptr,
  1929. SourceLocation()/*OpLoc*/,
  1930. &propertyName,
  1931. propertyNameLoc,
  1932. receiverNameLoc, T, true);
  1933. }
  1934. // Otherwise, if this is a class method, try dispatching to our
  1935. // superclass.
  1936. IFace = CurMethod->getClassInterface()->getSuperClass();
  1937. }
  1938. }
  1939. }
  1940. if (!IFace) {
  1941. Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
  1942. << tok::l_paren;
  1943. return ExprError();
  1944. }
  1945. }
  1946. Selector GetterSel;
  1947. Selector SetterSel;
  1948. if (auto PD = IFace->FindPropertyDeclaration(
  1949. &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
  1950. GetterSel = PD->getGetterName();
  1951. SetterSel = PD->getSetterName();
  1952. } else {
  1953. GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
  1954. SetterSel = SelectorTable::constructSetterSelector(
  1955. PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
  1956. }
  1957. // Search for a declared property first.
  1958. ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
  1959. // If this reference is in an @implementation, check for 'private' methods.
  1960. if (!Getter)
  1961. Getter = IFace->lookupPrivateClassMethod(GetterSel);
  1962. if (Getter) {
  1963. // FIXME: refactor/share with ActOnMemberReference().
  1964. // Check if we can reference this property.
  1965. if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
  1966. return ExprError();
  1967. }
  1968. // Look for the matching setter, in case it is needed.
  1969. ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
  1970. if (!Setter) {
  1971. // If this reference is in an @implementation, also check for 'private'
  1972. // methods.
  1973. Setter = IFace->lookupPrivateClassMethod(SetterSel);
  1974. }
  1975. // Look through local category implementations associated with the class.
  1976. if (!Setter)
  1977. Setter = IFace->getCategoryClassMethod(SetterSel);
  1978. if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
  1979. return ExprError();
  1980. if (Getter || Setter) {
  1981. if (!SuperType.isNull())
  1982. return new (Context)
  1983. ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
  1984. OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
  1985. SuperType);
  1986. return new (Context) ObjCPropertyRefExpr(
  1987. Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
  1988. propertyNameLoc, receiverNameLoc, IFace);
  1989. }
  1990. return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
  1991. << &propertyName << Context.getObjCInterfaceType(IFace));
  1992. }
  1993. namespace {
  1994. class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
  1995. public:
  1996. ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
  1997. // Determine whether "super" is acceptable in the current context.
  1998. if (Method && Method->getClassInterface())
  1999. WantObjCSuper = Method->getClassInterface()->getSuperClass();
  2000. }
  2001. bool ValidateCandidate(const TypoCorrection &candidate) override {
  2002. return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
  2003. candidate.isKeyword("super");
  2004. }
  2005. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2006. return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
  2007. }
  2008. };
  2009. } // end anonymous namespace
  2010. Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
  2011. IdentifierInfo *Name,
  2012. SourceLocation NameLoc,
  2013. bool IsSuper,
  2014. bool HasTrailingDot,
  2015. ParsedType &ReceiverType) {
  2016. ReceiverType = nullptr;
  2017. // If the identifier is "super" and there is no trailing dot, we're
  2018. // messaging super. If the identifier is "super" and there is a
  2019. // trailing dot, it's an instance message.
  2020. if (IsSuper && S->isInObjcMethodScope())
  2021. return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
  2022. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  2023. LookupName(Result, S);
  2024. switch (Result.getResultKind()) {
  2025. case LookupResult::NotFound:
  2026. // Normal name lookup didn't find anything. If we're in an
  2027. // Objective-C method, look for ivars. If we find one, we're done!
  2028. // FIXME: This is a hack. Ivar lookup should be part of normal
  2029. // lookup.
  2030. if (ObjCMethodDecl *Method = getCurMethodDecl()) {
  2031. if (!Method->getClassInterface()) {
  2032. // Fall back: let the parser try to parse it as an instance message.
  2033. return ObjCInstanceMessage;
  2034. }
  2035. ObjCInterfaceDecl *ClassDeclared;
  2036. if (Method->getClassInterface()->lookupInstanceVariable(Name,
  2037. ClassDeclared))
  2038. return ObjCInstanceMessage;
  2039. }
  2040. // Break out; we'll perform typo correction below.
  2041. break;
  2042. case LookupResult::NotFoundInCurrentInstantiation:
  2043. case LookupResult::FoundOverloaded:
  2044. case LookupResult::FoundUnresolvedValue:
  2045. case LookupResult::Ambiguous:
  2046. Result.suppressDiagnostics();
  2047. return ObjCInstanceMessage;
  2048. case LookupResult::Found: {
  2049. // If the identifier is a class or not, and there is a trailing dot,
  2050. // it's an instance message.
  2051. if (HasTrailingDot)
  2052. return ObjCInstanceMessage;
  2053. // We found something. If it's a type, then we have a class
  2054. // message. Otherwise, it's an instance message.
  2055. NamedDecl *ND = Result.getFoundDecl();
  2056. QualType T;
  2057. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
  2058. T = Context.getObjCInterfaceType(Class);
  2059. else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
  2060. T = Context.getTypeDeclType(Type);
  2061. DiagnoseUseOfDecl(Type, NameLoc);
  2062. }
  2063. else
  2064. return ObjCInstanceMessage;
  2065. // We have a class message, and T is the type we're
  2066. // messaging. Build source-location information for it.
  2067. TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
  2068. ReceiverType = CreateParsedType(T, TSInfo);
  2069. return ObjCClassMessage;
  2070. }
  2071. }
  2072. ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
  2073. if (TypoCorrection Corrected = CorrectTypo(
  2074. Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
  2075. CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
  2076. if (Corrected.isKeyword()) {
  2077. // If we've found the keyword "super" (the only keyword that would be
  2078. // returned by CorrectTypo), this is a send to super.
  2079. diagnoseTypo(Corrected,
  2080. PDiag(diag::err_unknown_receiver_suggest) << Name);
  2081. return ObjCSuperMessage;
  2082. } else if (ObjCInterfaceDecl *Class =
  2083. Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
  2084. // If we found a declaration, correct when it refers to an Objective-C
  2085. // class.
  2086. diagnoseTypo(Corrected,
  2087. PDiag(diag::err_unknown_receiver_suggest) << Name);
  2088. QualType T = Context.getObjCInterfaceType(Class);
  2089. TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
  2090. ReceiverType = CreateParsedType(T, TSInfo);
  2091. return ObjCClassMessage;
  2092. }
  2093. }
  2094. // Fall back: let the parser try to parse it as an instance message.
  2095. return ObjCInstanceMessage;
  2096. }
  2097. ExprResult Sema::ActOnSuperMessage(Scope *S,
  2098. SourceLocation SuperLoc,
  2099. Selector Sel,
  2100. SourceLocation LBracLoc,
  2101. ArrayRef<SourceLocation> SelectorLocs,
  2102. SourceLocation RBracLoc,
  2103. MultiExprArg Args) {
  2104. // Determine whether we are inside a method or not.
  2105. ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
  2106. if (!Method) {
  2107. Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
  2108. return ExprError();
  2109. }
  2110. ObjCInterfaceDecl *Class = Method->getClassInterface();
  2111. if (!Class) {
  2112. Diag(SuperLoc, diag::err_no_super_class_message)
  2113. << Method->getDeclName();
  2114. return ExprError();
  2115. }
  2116. QualType SuperTy(Class->getSuperClassType(), 0);
  2117. if (SuperTy.isNull()) {
  2118. // The current class does not have a superclass.
  2119. Diag(SuperLoc, diag::err_root_class_cannot_use_super)
  2120. << Class->getIdentifier();
  2121. return ExprError();
  2122. }
  2123. // We are in a method whose class has a superclass, so 'super'
  2124. // is acting as a keyword.
  2125. if (Method->getSelector() == Sel)
  2126. getCurFunction()->ObjCShouldCallSuper = false;
  2127. if (Method->isInstanceMethod()) {
  2128. // Since we are in an instance method, this is an instance
  2129. // message to the superclass instance.
  2130. SuperTy = Context.getObjCObjectPointerType(SuperTy);
  2131. return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
  2132. Sel, /*Method=*/nullptr,
  2133. LBracLoc, SelectorLocs, RBracLoc, Args);
  2134. }
  2135. // Since we are in a class method, this is a class message to
  2136. // the superclass.
  2137. return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
  2138. SuperTy,
  2139. SuperLoc, Sel, /*Method=*/nullptr,
  2140. LBracLoc, SelectorLocs, RBracLoc, Args);
  2141. }
  2142. ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
  2143. bool isSuperReceiver,
  2144. SourceLocation Loc,
  2145. Selector Sel,
  2146. ObjCMethodDecl *Method,
  2147. MultiExprArg Args) {
  2148. TypeSourceInfo *receiverTypeInfo = nullptr;
  2149. if (!ReceiverType.isNull())
  2150. receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
  2151. return BuildClassMessage(receiverTypeInfo, ReceiverType,
  2152. /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
  2153. Sel, Method, Loc, Loc, Loc, Args,
  2154. /*isImplicit=*/true);
  2155. }
  2156. static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
  2157. unsigned DiagID,
  2158. bool (*refactor)(const ObjCMessageExpr *,
  2159. const NSAPI &, edit::Commit &)) {
  2160. SourceLocation MsgLoc = Msg->getExprLoc();
  2161. if (S.Diags.isIgnored(DiagID, MsgLoc))
  2162. return;
  2163. SourceManager &SM = S.SourceMgr;
  2164. edit::Commit ECommit(SM, S.LangOpts);
  2165. if (refactor(Msg,*S.NSAPIObj, ECommit)) {
  2166. auto Builder = S.Diag(MsgLoc, DiagID)
  2167. << Msg->getSelector() << Msg->getSourceRange();
  2168. // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
  2169. if (!ECommit.isCommitable())
  2170. return;
  2171. for (edit::Commit::edit_iterator
  2172. I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
  2173. const edit::Commit::Edit &Edit = *I;
  2174. switch (Edit.Kind) {
  2175. case edit::Commit::Act_Insert:
  2176. Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
  2177. Edit.Text,
  2178. Edit.BeforePrev));
  2179. break;
  2180. case edit::Commit::Act_InsertFromRange:
  2181. Builder.AddFixItHint(
  2182. FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
  2183. Edit.getInsertFromRange(SM),
  2184. Edit.BeforePrev));
  2185. break;
  2186. case edit::Commit::Act_Remove:
  2187. Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
  2188. break;
  2189. }
  2190. }
  2191. }
  2192. }
  2193. static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
  2194. applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
  2195. edit::rewriteObjCRedundantCallWithLiteral);
  2196. }
  2197. static void checkFoundationAPI(Sema &S, SourceLocation Loc,
  2198. const ObjCMethodDecl *Method,
  2199. ArrayRef<Expr *> Args, QualType ReceiverType,
  2200. bool IsClassObjectCall) {
  2201. // Check if this is a performSelector method that uses a selector that returns
  2202. // a record or a vector type.
  2203. if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
  2204. Args.empty())
  2205. return;
  2206. const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
  2207. if (!SE)
  2208. return;
  2209. ObjCMethodDecl *ImpliedMethod;
  2210. if (!IsClassObjectCall) {
  2211. const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
  2212. if (!OPT || !OPT->getInterfaceDecl())
  2213. return;
  2214. ImpliedMethod =
  2215. OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
  2216. if (!ImpliedMethod)
  2217. ImpliedMethod =
  2218. OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
  2219. } else {
  2220. const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
  2221. if (!IT)
  2222. return;
  2223. ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
  2224. if (!ImpliedMethod)
  2225. ImpliedMethod =
  2226. IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
  2227. }
  2228. if (!ImpliedMethod)
  2229. return;
  2230. QualType Ret = ImpliedMethod->getReturnType();
  2231. if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
  2232. S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
  2233. << Method->getSelector()
  2234. << (!Ret->isRecordType()
  2235. ? /*Vector*/ 2
  2236. : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
  2237. S.Diag(ImpliedMethod->getBeginLoc(),
  2238. diag::note_objc_unsafe_perform_selector_method_declared_here)
  2239. << ImpliedMethod->getSelector() << Ret;
  2240. }
  2241. }
  2242. /// Diagnose use of %s directive in an NSString which is being passed
  2243. /// as formatting string to formatting method.
  2244. static void
  2245. DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
  2246. ObjCMethodDecl *Method,
  2247. Selector Sel,
  2248. Expr **Args, unsigned NumArgs) {
  2249. unsigned Idx = 0;
  2250. bool Format = false;
  2251. ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
  2252. if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
  2253. Idx = 0;
  2254. Format = true;
  2255. }
  2256. else if (Method) {
  2257. for (const auto *I : Method->specific_attrs<FormatAttr>()) {
  2258. if (S.GetFormatNSStringIdx(I, Idx)) {
  2259. Format = true;
  2260. break;
  2261. }
  2262. }
  2263. }
  2264. if (!Format || NumArgs <= Idx)
  2265. return;
  2266. Expr *FormatExpr = Args[Idx];
  2267. if (ObjCStringLiteral *OSL =
  2268. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
  2269. StringLiteral *FormatString = OSL->getString();
  2270. if (S.FormatStringHasSArg(FormatString)) {
  2271. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  2272. << "%s" << 0 << 0;
  2273. if (Method)
  2274. S.Diag(Method->getLocation(), diag::note_method_declared_at)
  2275. << Method->getDeclName();
  2276. }
  2277. }
  2278. }
  2279. /// Build an Objective-C class message expression.
  2280. ///
  2281. /// This routine takes care of both normal class messages and
  2282. /// class messages to the superclass.
  2283. ///
  2284. /// \param ReceiverTypeInfo Type source information that describes the
  2285. /// receiver of this message. This may be NULL, in which case we are
  2286. /// sending to the superclass and \p SuperLoc must be a valid source
  2287. /// location.
  2288. /// \param ReceiverType The type of the object receiving the
  2289. /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
  2290. /// type as that refers to. For a superclass send, this is the type of
  2291. /// the superclass.
  2292. ///
  2293. /// \param SuperLoc The location of the "super" keyword in a
  2294. /// superclass message.
  2295. ///
  2296. /// \param Sel The selector to which the message is being sent.
  2297. ///
  2298. /// \param Method The method that this class message is invoking, if
  2299. /// already known.
  2300. ///
  2301. /// \param LBracLoc The location of the opening square bracket ']'.
  2302. ///
  2303. /// \param RBracLoc The location of the closing square bracket ']'.
  2304. ///
  2305. /// \param ArgsIn The message arguments.
  2306. ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
  2307. QualType ReceiverType,
  2308. SourceLocation SuperLoc,
  2309. Selector Sel,
  2310. ObjCMethodDecl *Method,
  2311. SourceLocation LBracLoc,
  2312. ArrayRef<SourceLocation> SelectorLocs,
  2313. SourceLocation RBracLoc,
  2314. MultiExprArg ArgsIn,
  2315. bool isImplicit) {
  2316. SourceLocation Loc = SuperLoc.isValid()? SuperLoc
  2317. : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
  2318. if (LBracLoc.isInvalid()) {
  2319. Diag(Loc, diag::err_missing_open_square_message_send)
  2320. << FixItHint::CreateInsertion(Loc, "[");
  2321. LBracLoc = Loc;
  2322. }
  2323. ArrayRef<SourceLocation> SelectorSlotLocs;
  2324. if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
  2325. SelectorSlotLocs = SelectorLocs;
  2326. else
  2327. SelectorSlotLocs = Loc;
  2328. SourceLocation SelLoc = SelectorSlotLocs.front();
  2329. if (ReceiverType->isDependentType()) {
  2330. // If the receiver type is dependent, we can't type-check anything
  2331. // at this point. Build a dependent expression.
  2332. unsigned NumArgs = ArgsIn.size();
  2333. Expr **Args = ArgsIn.data();
  2334. assert(SuperLoc.isInvalid() && "Message to super with dependent type");
  2335. return ObjCMessageExpr::Create(Context, ReceiverType, VK_PRValue, LBracLoc,
  2336. ReceiverTypeInfo, Sel, SelectorLocs,
  2337. /*Method=*/nullptr, ArrayRef(Args, NumArgs),
  2338. RBracLoc, isImplicit);
  2339. }
  2340. // Find the class to which we are sending this message.
  2341. ObjCInterfaceDecl *Class = nullptr;
  2342. const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
  2343. if (!ClassType || !(Class = ClassType->getInterface())) {
  2344. Diag(Loc, diag::err_invalid_receiver_class_message)
  2345. << ReceiverType;
  2346. return ExprError();
  2347. }
  2348. assert(Class && "We don't know which class we're messaging?");
  2349. // objc++ diagnoses during typename annotation.
  2350. if (!getLangOpts().CPlusPlus)
  2351. (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
  2352. // Find the method we are messaging.
  2353. if (!Method) {
  2354. SourceRange TypeRange
  2355. = SuperLoc.isValid()? SourceRange(SuperLoc)
  2356. : ReceiverTypeInfo->getTypeLoc().getSourceRange();
  2357. if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
  2358. (getLangOpts().ObjCAutoRefCount
  2359. ? diag::err_arc_receiver_forward_class
  2360. : diag::warn_receiver_forward_class),
  2361. TypeRange)) {
  2362. // A forward class used in messaging is treated as a 'Class'
  2363. Method = LookupFactoryMethodInGlobalPool(Sel,
  2364. SourceRange(LBracLoc, RBracLoc));
  2365. if (Method && !getLangOpts().ObjCAutoRefCount)
  2366. Diag(Method->getLocation(), diag::note_method_sent_forward_class)
  2367. << Method->getDeclName();
  2368. }
  2369. if (!Method)
  2370. Method = Class->lookupClassMethod(Sel);
  2371. // If we have an implementation in scope, check "private" methods.
  2372. if (!Method)
  2373. Method = Class->lookupPrivateClassMethod(Sel);
  2374. if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
  2375. nullptr, false, false, Class))
  2376. return ExprError();
  2377. }
  2378. // Check the argument types and determine the result type.
  2379. QualType ReturnType;
  2380. ExprValueKind VK = VK_PRValue;
  2381. unsigned NumArgs = ArgsIn.size();
  2382. Expr **Args = ArgsIn.data();
  2383. if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
  2384. MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
  2385. Method, true, SuperLoc.isValid(), LBracLoc,
  2386. RBracLoc, SourceRange(), ReturnType, VK))
  2387. return ExprError();
  2388. if (Method && !Method->getReturnType()->isVoidType() &&
  2389. RequireCompleteType(LBracLoc, Method->getReturnType(),
  2390. diag::err_illegal_message_expr_incomplete_type))
  2391. return ExprError();
  2392. if (Method && Method->isDirectMethod() && SuperLoc.isValid()) {
  2393. Diag(SuperLoc, diag::err_messaging_super_with_direct_method)
  2394. << FixItHint::CreateReplacement(
  2395. SuperLoc, getLangOpts().ObjCAutoRefCount
  2396. ? "self"
  2397. : Method->getClassInterface()->getName());
  2398. Diag(Method->getLocation(), diag::note_direct_method_declared_at)
  2399. << Method->getDeclName();
  2400. }
  2401. // Warn about explicit call of +initialize on its own class. But not on 'super'.
  2402. if (Method && Method->getMethodFamily() == OMF_initialize) {
  2403. if (!SuperLoc.isValid()) {
  2404. const ObjCInterfaceDecl *ID =
  2405. dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
  2406. if (ID == Class) {
  2407. Diag(Loc, diag::warn_direct_initialize_call);
  2408. Diag(Method->getLocation(), diag::note_method_declared_at)
  2409. << Method->getDeclName();
  2410. }
  2411. }
  2412. else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
  2413. // [super initialize] is allowed only within an +initialize implementation
  2414. if (CurMeth->getMethodFamily() != OMF_initialize) {
  2415. Diag(Loc, diag::warn_direct_super_initialize_call);
  2416. Diag(Method->getLocation(), diag::note_method_declared_at)
  2417. << Method->getDeclName();
  2418. Diag(CurMeth->getLocation(), diag::note_method_declared_at)
  2419. << CurMeth->getDeclName();
  2420. }
  2421. }
  2422. }
  2423. DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
  2424. // Construct the appropriate ObjCMessageExpr.
  2425. ObjCMessageExpr *Result;
  2426. if (SuperLoc.isValid())
  2427. Result = ObjCMessageExpr::Create(
  2428. Context, ReturnType, VK, LBracLoc, SuperLoc, /*IsInstanceSuper=*/false,
  2429. ReceiverType, Sel, SelectorLocs, Method, ArrayRef(Args, NumArgs),
  2430. RBracLoc, isImplicit);
  2431. else {
  2432. Result = ObjCMessageExpr::Create(
  2433. Context, ReturnType, VK, LBracLoc, ReceiverTypeInfo, Sel, SelectorLocs,
  2434. Method, ArrayRef(Args, NumArgs), RBracLoc, isImplicit);
  2435. if (!isImplicit)
  2436. checkCocoaAPI(*this, Result);
  2437. }
  2438. if (Method)
  2439. checkFoundationAPI(*this, SelLoc, Method, ArrayRef(Args, NumArgs),
  2440. ReceiverType, /*IsClassObjectCall=*/true);
  2441. return MaybeBindToTemporary(Result);
  2442. }
  2443. // ActOnClassMessage - used for both unary and keyword messages.
  2444. // ArgExprs is optional - if it is present, the number of expressions
  2445. // is obtained from Sel.getNumArgs().
  2446. ExprResult Sema::ActOnClassMessage(Scope *S,
  2447. ParsedType Receiver,
  2448. Selector Sel,
  2449. SourceLocation LBracLoc,
  2450. ArrayRef<SourceLocation> SelectorLocs,
  2451. SourceLocation RBracLoc,
  2452. MultiExprArg Args) {
  2453. TypeSourceInfo *ReceiverTypeInfo;
  2454. QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
  2455. if (ReceiverType.isNull())
  2456. return ExprError();
  2457. if (!ReceiverTypeInfo)
  2458. ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
  2459. return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
  2460. /*SuperLoc=*/SourceLocation(), Sel,
  2461. /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
  2462. Args);
  2463. }
  2464. ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
  2465. QualType ReceiverType,
  2466. SourceLocation Loc,
  2467. Selector Sel,
  2468. ObjCMethodDecl *Method,
  2469. MultiExprArg Args) {
  2470. return BuildInstanceMessage(Receiver, ReceiverType,
  2471. /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
  2472. Sel, Method, Loc, Loc, Loc, Args,
  2473. /*isImplicit=*/true);
  2474. }
  2475. static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
  2476. if (!S.NSAPIObj)
  2477. return false;
  2478. const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
  2479. if (!Protocol)
  2480. return false;
  2481. const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  2482. if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
  2483. S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
  2484. Sema::LookupOrdinaryName))) {
  2485. for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
  2486. if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
  2487. return true;
  2488. }
  2489. }
  2490. return false;
  2491. }
  2492. /// Build an Objective-C instance message expression.
  2493. ///
  2494. /// This routine takes care of both normal instance messages and
  2495. /// instance messages to the superclass instance.
  2496. ///
  2497. /// \param Receiver The expression that computes the object that will
  2498. /// receive this message. This may be empty, in which case we are
  2499. /// sending to the superclass instance and \p SuperLoc must be a valid
  2500. /// source location.
  2501. ///
  2502. /// \param ReceiverType The (static) type of the object receiving the
  2503. /// message. When a \p Receiver expression is provided, this is the
  2504. /// same type as that expression. For a superclass instance send, this
  2505. /// is a pointer to the type of the superclass.
  2506. ///
  2507. /// \param SuperLoc The location of the "super" keyword in a
  2508. /// superclass instance message.
  2509. ///
  2510. /// \param Sel The selector to which the message is being sent.
  2511. ///
  2512. /// \param Method The method that this instance message is invoking, if
  2513. /// already known.
  2514. ///
  2515. /// \param LBracLoc The location of the opening square bracket ']'.
  2516. ///
  2517. /// \param RBracLoc The location of the closing square bracket ']'.
  2518. ///
  2519. /// \param ArgsIn The message arguments.
  2520. ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
  2521. QualType ReceiverType,
  2522. SourceLocation SuperLoc,
  2523. Selector Sel,
  2524. ObjCMethodDecl *Method,
  2525. SourceLocation LBracLoc,
  2526. ArrayRef<SourceLocation> SelectorLocs,
  2527. SourceLocation RBracLoc,
  2528. MultiExprArg ArgsIn,
  2529. bool isImplicit) {
  2530. assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
  2531. "SuperLoc must be valid so we can "
  2532. "use it instead.");
  2533. // The location of the receiver.
  2534. SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
  2535. SourceRange RecRange =
  2536. SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
  2537. ArrayRef<SourceLocation> SelectorSlotLocs;
  2538. if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
  2539. SelectorSlotLocs = SelectorLocs;
  2540. else
  2541. SelectorSlotLocs = Loc;
  2542. SourceLocation SelLoc = SelectorSlotLocs.front();
  2543. if (LBracLoc.isInvalid()) {
  2544. Diag(Loc, diag::err_missing_open_square_message_send)
  2545. << FixItHint::CreateInsertion(Loc, "[");
  2546. LBracLoc = Loc;
  2547. }
  2548. // If we have a receiver expression, perform appropriate promotions
  2549. // and determine receiver type.
  2550. if (Receiver) {
  2551. if (Receiver->hasPlaceholderType()) {
  2552. ExprResult Result;
  2553. if (Receiver->getType() == Context.UnknownAnyTy)
  2554. Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
  2555. else
  2556. Result = CheckPlaceholderExpr(Receiver);
  2557. if (Result.isInvalid()) return ExprError();
  2558. Receiver = Result.get();
  2559. }
  2560. if (Receiver->isTypeDependent()) {
  2561. // If the receiver is type-dependent, we can't type-check anything
  2562. // at this point. Build a dependent expression.
  2563. unsigned NumArgs = ArgsIn.size();
  2564. Expr **Args = ArgsIn.data();
  2565. assert(SuperLoc.isInvalid() && "Message to super with dependent type");
  2566. return ObjCMessageExpr::Create(
  2567. Context, Context.DependentTy, VK_PRValue, LBracLoc, Receiver, Sel,
  2568. SelectorLocs, /*Method=*/nullptr, ArrayRef(Args, NumArgs), RBracLoc,
  2569. isImplicit);
  2570. }
  2571. // If necessary, apply function/array conversion to the receiver.
  2572. // C99 6.7.5.3p[7,8].
  2573. ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
  2574. if (Result.isInvalid())
  2575. return ExprError();
  2576. Receiver = Result.get();
  2577. ReceiverType = Receiver->getType();
  2578. // If the receiver is an ObjC pointer, a block pointer, or an
  2579. // __attribute__((NSObject)) pointer, we don't need to do any
  2580. // special conversion in order to look up a receiver.
  2581. if (ReceiverType->isObjCRetainableType()) {
  2582. // do nothing
  2583. } else if (!getLangOpts().ObjCAutoRefCount &&
  2584. !Context.getObjCIdType().isNull() &&
  2585. (ReceiverType->isPointerType() ||
  2586. ReceiverType->isIntegerType())) {
  2587. // Implicitly convert integers and pointers to 'id' but emit a warning.
  2588. // But not in ARC.
  2589. Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange;
  2590. if (ReceiverType->isPointerType()) {
  2591. Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
  2592. CK_CPointerToObjCPointerCast).get();
  2593. } else {
  2594. // TODO: specialized warning on null receivers?
  2595. bool IsNull = Receiver->isNullPointerConstant(Context,
  2596. Expr::NPC_ValueDependentIsNull);
  2597. CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
  2598. Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
  2599. Kind).get();
  2600. }
  2601. ReceiverType = Receiver->getType();
  2602. } else if (getLangOpts().CPlusPlus) {
  2603. // The receiver must be a complete type.
  2604. if (RequireCompleteType(Loc, Receiver->getType(),
  2605. diag::err_incomplete_receiver_type))
  2606. return ExprError();
  2607. ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
  2608. if (result.isUsable()) {
  2609. Receiver = result.get();
  2610. ReceiverType = Receiver->getType();
  2611. }
  2612. }
  2613. }
  2614. // There's a somewhat weird interaction here where we assume that we
  2615. // won't actually have a method unless we also don't need to do some
  2616. // of the more detailed type-checking on the receiver.
  2617. if (!Method) {
  2618. // Handle messages to id and __kindof types (where we use the
  2619. // global method pool).
  2620. const ObjCObjectType *typeBound = nullptr;
  2621. bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
  2622. typeBound);
  2623. if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
  2624. (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
  2625. SmallVector<ObjCMethodDecl*, 4> Methods;
  2626. // If we have a type bound, further filter the methods.
  2627. CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
  2628. true/*CheckTheOther*/, typeBound);
  2629. if (!Methods.empty()) {
  2630. // We choose the first method as the initial candidate, then try to
  2631. // select a better one.
  2632. Method = Methods[0];
  2633. if (ObjCMethodDecl *BestMethod =
  2634. SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
  2635. Method = BestMethod;
  2636. if (!AreMultipleMethodsInGlobalPool(Sel, Method,
  2637. SourceRange(LBracLoc, RBracLoc),
  2638. receiverIsIdLike, Methods))
  2639. DiagnoseUseOfDecl(Method, SelectorSlotLocs);
  2640. }
  2641. } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
  2642. ReceiverType->isObjCQualifiedClassType()) {
  2643. // Handle messages to Class.
  2644. // We allow sending a message to a qualified Class ("Class<foo>"), which
  2645. // is ok as long as one of the protocols implements the selector (if not,
  2646. // warn).
  2647. if (!ReceiverType->isObjCClassOrClassKindOfType()) {
  2648. const ObjCObjectPointerType *QClassTy
  2649. = ReceiverType->getAsObjCQualifiedClassType();
  2650. // Search protocols for class methods.
  2651. Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
  2652. if (!Method) {
  2653. Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
  2654. // warn if instance method found for a Class message.
  2655. if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
  2656. Diag(SelLoc, diag::warn_instance_method_on_class_found)
  2657. << Method->getSelector() << Sel;
  2658. Diag(Method->getLocation(), diag::note_method_declared_at)
  2659. << Method->getDeclName();
  2660. }
  2661. }
  2662. } else {
  2663. if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
  2664. if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
  2665. // As a guess, try looking for the method in the current interface.
  2666. // This very well may not produce the "right" method.
  2667. // First check the public methods in the class interface.
  2668. Method = ClassDecl->lookupClassMethod(Sel);
  2669. if (!Method)
  2670. Method = ClassDecl->lookupPrivateClassMethod(Sel);
  2671. if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
  2672. return ExprError();
  2673. }
  2674. }
  2675. if (!Method) {
  2676. // If not messaging 'self', look for any factory method named 'Sel'.
  2677. if (!Receiver || !isSelfExpr(Receiver)) {
  2678. // If no class (factory) method was found, check if an _instance_
  2679. // method of the same name exists in the root class only.
  2680. SmallVector<ObjCMethodDecl*, 4> Methods;
  2681. CollectMultipleMethodsInGlobalPool(Sel, Methods,
  2682. false/*InstanceFirst*/,
  2683. true/*CheckTheOther*/);
  2684. if (!Methods.empty()) {
  2685. // We choose the first method as the initial candidate, then try
  2686. // to select a better one.
  2687. Method = Methods[0];
  2688. // If we find an instance method, emit warning.
  2689. if (Method->isInstanceMethod()) {
  2690. if (const ObjCInterfaceDecl *ID =
  2691. dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
  2692. if (ID->getSuperClass())
  2693. Diag(SelLoc, diag::warn_root_inst_method_not_found)
  2694. << Sel << SourceRange(LBracLoc, RBracLoc);
  2695. }
  2696. }
  2697. if (ObjCMethodDecl *BestMethod =
  2698. SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
  2699. Methods))
  2700. Method = BestMethod;
  2701. }
  2702. }
  2703. }
  2704. }
  2705. } else {
  2706. ObjCInterfaceDecl *ClassDecl = nullptr;
  2707. // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
  2708. // long as one of the protocols implements the selector (if not, warn).
  2709. // And as long as message is not deprecated/unavailable (warn if it is).
  2710. if (const ObjCObjectPointerType *QIdTy
  2711. = ReceiverType->getAsObjCQualifiedIdType()) {
  2712. // Search protocols for instance methods.
  2713. Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
  2714. if (!Method)
  2715. Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
  2716. if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
  2717. return ExprError();
  2718. } else if (const ObjCObjectPointerType *OCIType
  2719. = ReceiverType->getAsObjCInterfacePointerType()) {
  2720. // We allow sending a message to a pointer to an interface (an object).
  2721. ClassDecl = OCIType->getInterfaceDecl();
  2722. // Try to complete the type. Under ARC, this is a hard error from which
  2723. // we don't try to recover.
  2724. // FIXME: In the non-ARC case, this will still be a hard error if the
  2725. // definition is found in a module that's not visible.
  2726. const ObjCInterfaceDecl *forwardClass = nullptr;
  2727. if (RequireCompleteType(Loc, OCIType->getPointeeType(),
  2728. getLangOpts().ObjCAutoRefCount
  2729. ? diag::err_arc_receiver_forward_instance
  2730. : diag::warn_receiver_forward_instance,
  2731. RecRange)) {
  2732. if (getLangOpts().ObjCAutoRefCount)
  2733. return ExprError();
  2734. forwardClass = OCIType->getInterfaceDecl();
  2735. Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
  2736. diag::note_receiver_is_id);
  2737. Method = nullptr;
  2738. } else {
  2739. Method = ClassDecl->lookupInstanceMethod(Sel);
  2740. }
  2741. if (!Method)
  2742. // Search protocol qualifiers.
  2743. Method = LookupMethodInQualifiedType(Sel, OCIType, true);
  2744. if (!Method) {
  2745. // If we have implementations in scope, check "private" methods.
  2746. Method = ClassDecl->lookupPrivateMethod(Sel);
  2747. if (!Method && getLangOpts().ObjCAutoRefCount) {
  2748. Diag(SelLoc, diag::err_arc_may_not_respond)
  2749. << OCIType->getPointeeType() << Sel << RecRange
  2750. << SourceRange(SelectorLocs.front(), SelectorLocs.back());
  2751. return ExprError();
  2752. }
  2753. if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
  2754. // If we still haven't found a method, look in the global pool. This
  2755. // behavior isn't very desirable, however we need it for GCC
  2756. // compatibility. FIXME: should we deviate??
  2757. if (OCIType->qual_empty()) {
  2758. SmallVector<ObjCMethodDecl*, 4> Methods;
  2759. CollectMultipleMethodsInGlobalPool(Sel, Methods,
  2760. true/*InstanceFirst*/,
  2761. false/*CheckTheOther*/);
  2762. if (!Methods.empty()) {
  2763. // We choose the first method as the initial candidate, then try
  2764. // to select a better one.
  2765. Method = Methods[0];
  2766. if (ObjCMethodDecl *BestMethod =
  2767. SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
  2768. Methods))
  2769. Method = BestMethod;
  2770. AreMultipleMethodsInGlobalPool(Sel, Method,
  2771. SourceRange(LBracLoc, RBracLoc),
  2772. true/*receiverIdOrClass*/,
  2773. Methods);
  2774. }
  2775. if (Method && !forwardClass)
  2776. Diag(SelLoc, diag::warn_maynot_respond)
  2777. << OCIType->getInterfaceDecl()->getIdentifier()
  2778. << Sel << RecRange;
  2779. }
  2780. }
  2781. }
  2782. if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
  2783. return ExprError();
  2784. } else {
  2785. // Reject other random receiver types (e.g. structs).
  2786. Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange;
  2787. return ExprError();
  2788. }
  2789. }
  2790. }
  2791. FunctionScopeInfo *DIFunctionScopeInfo =
  2792. (Method && Method->getMethodFamily() == OMF_init)
  2793. ? getEnclosingFunction() : nullptr;
  2794. if (Method && Method->isDirectMethod()) {
  2795. if (ReceiverType->isObjCIdType() && !isImplicit) {
  2796. Diag(Receiver->getExprLoc(),
  2797. diag::err_messaging_unqualified_id_with_direct_method);
  2798. Diag(Method->getLocation(), diag::note_direct_method_declared_at)
  2799. << Method->getDeclName();
  2800. }
  2801. // Under ARC, self can't be assigned, and doing a direct call to `self`
  2802. // when it's a Class is hence safe. For other cases, we can't trust `self`
  2803. // is what we think it is, so we reject it.
  2804. if (ReceiverType->isObjCClassType() && !isImplicit &&
  2805. !(Receiver->isObjCSelfExpr() && getLangOpts().ObjCAutoRefCount)) {
  2806. {
  2807. auto Builder = Diag(Receiver->getExprLoc(),
  2808. diag::err_messaging_class_with_direct_method);
  2809. if (Receiver->isObjCSelfExpr()) {
  2810. Builder.AddFixItHint(FixItHint::CreateReplacement(
  2811. RecRange, Method->getClassInterface()->getName()));
  2812. }
  2813. }
  2814. Diag(Method->getLocation(), diag::note_direct_method_declared_at)
  2815. << Method->getDeclName();
  2816. }
  2817. if (SuperLoc.isValid()) {
  2818. {
  2819. auto Builder =
  2820. Diag(SuperLoc, diag::err_messaging_super_with_direct_method);
  2821. if (ReceiverType->isObjCClassType()) {
  2822. Builder.AddFixItHint(FixItHint::CreateReplacement(
  2823. SuperLoc, Method->getClassInterface()->getName()));
  2824. } else {
  2825. Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self"));
  2826. }
  2827. }
  2828. Diag(Method->getLocation(), diag::note_direct_method_declared_at)
  2829. << Method->getDeclName();
  2830. }
  2831. } else if (ReceiverType->isObjCIdType() && !isImplicit) {
  2832. Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
  2833. }
  2834. if (DIFunctionScopeInfo &&
  2835. DIFunctionScopeInfo->ObjCIsDesignatedInit &&
  2836. (SuperLoc.isValid() || isSelfExpr(Receiver))) {
  2837. bool isDesignatedInitChain = false;
  2838. if (SuperLoc.isValid()) {
  2839. if (const ObjCObjectPointerType *
  2840. OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
  2841. if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
  2842. // Either we know this is a designated initializer or we
  2843. // conservatively assume it because we don't know for sure.
  2844. if (!ID->declaresOrInheritsDesignatedInitializers() ||
  2845. ID->isDesignatedInitializer(Sel)) {
  2846. isDesignatedInitChain = true;
  2847. DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
  2848. }
  2849. }
  2850. }
  2851. }
  2852. if (!isDesignatedInitChain) {
  2853. const ObjCMethodDecl *InitMethod = nullptr;
  2854. bool isDesignated =
  2855. getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
  2856. assert(isDesignated && InitMethod);
  2857. (void)isDesignated;
  2858. Diag(SelLoc, SuperLoc.isValid() ?
  2859. diag::warn_objc_designated_init_non_designated_init_call :
  2860. diag::warn_objc_designated_init_non_super_designated_init_call);
  2861. Diag(InitMethod->getLocation(),
  2862. diag::note_objc_designated_init_marked_here);
  2863. }
  2864. }
  2865. if (DIFunctionScopeInfo &&
  2866. DIFunctionScopeInfo->ObjCIsSecondaryInit &&
  2867. (SuperLoc.isValid() || isSelfExpr(Receiver))) {
  2868. if (SuperLoc.isValid()) {
  2869. Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
  2870. } else {
  2871. DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
  2872. }
  2873. }
  2874. // Check the message arguments.
  2875. unsigned NumArgs = ArgsIn.size();
  2876. Expr **Args = ArgsIn.data();
  2877. QualType ReturnType;
  2878. ExprValueKind VK = VK_PRValue;
  2879. bool ClassMessage = (ReceiverType->isObjCClassType() ||
  2880. ReceiverType->isObjCQualifiedClassType());
  2881. if (CheckMessageArgumentTypes(Receiver, ReceiverType,
  2882. MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
  2883. Method, ClassMessage, SuperLoc.isValid(),
  2884. LBracLoc, RBracLoc, RecRange, ReturnType, VK))
  2885. return ExprError();
  2886. if (Method && !Method->getReturnType()->isVoidType() &&
  2887. RequireCompleteType(LBracLoc, Method->getReturnType(),
  2888. diag::err_illegal_message_expr_incomplete_type))
  2889. return ExprError();
  2890. // In ARC, forbid the user from sending messages to
  2891. // retain/release/autorelease/dealloc/retainCount explicitly.
  2892. if (getLangOpts().ObjCAutoRefCount) {
  2893. ObjCMethodFamily family =
  2894. (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
  2895. switch (family) {
  2896. case OMF_init:
  2897. if (Method)
  2898. checkInitMethod(Method, ReceiverType);
  2899. break;
  2900. case OMF_None:
  2901. case OMF_alloc:
  2902. case OMF_copy:
  2903. case OMF_finalize:
  2904. case OMF_mutableCopy:
  2905. case OMF_new:
  2906. case OMF_self:
  2907. case OMF_initialize:
  2908. break;
  2909. case OMF_dealloc:
  2910. case OMF_retain:
  2911. case OMF_release:
  2912. case OMF_autorelease:
  2913. case OMF_retainCount:
  2914. Diag(SelLoc, diag::err_arc_illegal_explicit_message)
  2915. << Sel << RecRange;
  2916. break;
  2917. case OMF_performSelector:
  2918. if (Method && NumArgs >= 1) {
  2919. if (const auto *SelExp =
  2920. dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
  2921. Selector ArgSel = SelExp->getSelector();
  2922. ObjCMethodDecl *SelMethod =
  2923. LookupInstanceMethodInGlobalPool(ArgSel,
  2924. SelExp->getSourceRange());
  2925. if (!SelMethod)
  2926. SelMethod =
  2927. LookupFactoryMethodInGlobalPool(ArgSel,
  2928. SelExp->getSourceRange());
  2929. if (SelMethod) {
  2930. ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
  2931. switch (SelFamily) {
  2932. case OMF_alloc:
  2933. case OMF_copy:
  2934. case OMF_mutableCopy:
  2935. case OMF_new:
  2936. case OMF_init:
  2937. // Issue error, unless ns_returns_not_retained.
  2938. if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
  2939. // selector names a +1 method
  2940. Diag(SelLoc,
  2941. diag::err_arc_perform_selector_retains);
  2942. Diag(SelMethod->getLocation(), diag::note_method_declared_at)
  2943. << SelMethod->getDeclName();
  2944. }
  2945. break;
  2946. default:
  2947. // +0 call. OK. unless ns_returns_retained.
  2948. if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
  2949. // selector names a +1 method
  2950. Diag(SelLoc,
  2951. diag::err_arc_perform_selector_retains);
  2952. Diag(SelMethod->getLocation(), diag::note_method_declared_at)
  2953. << SelMethod->getDeclName();
  2954. }
  2955. break;
  2956. }
  2957. }
  2958. } else {
  2959. // error (may leak).
  2960. Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
  2961. Diag(Args[0]->getExprLoc(), diag::note_used_here);
  2962. }
  2963. }
  2964. break;
  2965. }
  2966. }
  2967. DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
  2968. // Construct the appropriate ObjCMessageExpr instance.
  2969. ObjCMessageExpr *Result;
  2970. if (SuperLoc.isValid())
  2971. Result = ObjCMessageExpr::Create(
  2972. Context, ReturnType, VK, LBracLoc, SuperLoc, /*IsInstanceSuper=*/true,
  2973. ReceiverType, Sel, SelectorLocs, Method, ArrayRef(Args, NumArgs),
  2974. RBracLoc, isImplicit);
  2975. else {
  2976. Result = ObjCMessageExpr::Create(
  2977. Context, ReturnType, VK, LBracLoc, Receiver, Sel, SelectorLocs, Method,
  2978. ArrayRef(Args, NumArgs), RBracLoc, isImplicit);
  2979. if (!isImplicit)
  2980. checkCocoaAPI(*this, Result);
  2981. }
  2982. if (Method) {
  2983. bool IsClassObjectCall = ClassMessage;
  2984. // 'self' message receivers in class methods should be treated as message
  2985. // sends to the class object in order for the semantic checks to be
  2986. // performed correctly. Messages to 'super' already count as class messages,
  2987. // so they don't need to be handled here.
  2988. if (Receiver && isSelfExpr(Receiver)) {
  2989. if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
  2990. if (OPT->getObjectType()->isObjCClass()) {
  2991. if (const auto *CurMeth = getCurMethodDecl()) {
  2992. IsClassObjectCall = true;
  2993. ReceiverType =
  2994. Context.getObjCInterfaceType(CurMeth->getClassInterface());
  2995. }
  2996. }
  2997. }
  2998. }
  2999. checkFoundationAPI(*this, SelLoc, Method, ArrayRef(Args, NumArgs),
  3000. ReceiverType, IsClassObjectCall);
  3001. }
  3002. if (getLangOpts().ObjCAutoRefCount) {
  3003. // In ARC, annotate delegate init calls.
  3004. if (Result->getMethodFamily() == OMF_init &&
  3005. (SuperLoc.isValid() || isSelfExpr(Receiver))) {
  3006. // Only consider init calls *directly* in init implementations,
  3007. // not within blocks.
  3008. ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
  3009. if (method && method->getMethodFamily() == OMF_init) {
  3010. // The implicit assignment to self means we also don't want to
  3011. // consume the result.
  3012. Result->setDelegateInitCall(true);
  3013. return Result;
  3014. }
  3015. }
  3016. // In ARC, check for message sends which are likely to introduce
  3017. // retain cycles.
  3018. checkRetainCycles(Result);
  3019. }
  3020. if (getLangOpts().ObjCWeak) {
  3021. if (!isImplicit && Method) {
  3022. if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
  3023. bool IsWeak =
  3024. Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak;
  3025. if (!IsWeak && Sel.isUnarySelector())
  3026. IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
  3027. if (IsWeak && !isUnevaluatedContext() &&
  3028. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
  3029. getCurFunction()->recordUseOfWeak(Result, Prop);
  3030. }
  3031. }
  3032. }
  3033. CheckObjCCircularContainer(Result);
  3034. return MaybeBindToTemporary(Result);
  3035. }
  3036. static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
  3037. if (ObjCSelectorExpr *OSE =
  3038. dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
  3039. Selector Sel = OSE->getSelector();
  3040. SourceLocation Loc = OSE->getAtLoc();
  3041. auto Pos = S.ReferencedSelectors.find(Sel);
  3042. if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
  3043. S.ReferencedSelectors.erase(Pos);
  3044. }
  3045. }
  3046. // ActOnInstanceMessage - used for both unary and keyword messages.
  3047. // ArgExprs is optional - if it is present, the number of expressions
  3048. // is obtained from Sel.getNumArgs().
  3049. ExprResult Sema::ActOnInstanceMessage(Scope *S,
  3050. Expr *Receiver,
  3051. Selector Sel,
  3052. SourceLocation LBracLoc,
  3053. ArrayRef<SourceLocation> SelectorLocs,
  3054. SourceLocation RBracLoc,
  3055. MultiExprArg Args) {
  3056. if (!Receiver)
  3057. return ExprError();
  3058. // A ParenListExpr can show up while doing error recovery with invalid code.
  3059. if (isa<ParenListExpr>(Receiver)) {
  3060. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
  3061. if (Result.isInvalid()) return ExprError();
  3062. Receiver = Result.get();
  3063. }
  3064. if (RespondsToSelectorSel.isNull()) {
  3065. IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
  3066. RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
  3067. }
  3068. if (Sel == RespondsToSelectorSel)
  3069. RemoveSelectorFromWarningCache(*this, Args[0]);
  3070. return BuildInstanceMessage(Receiver, Receiver->getType(),
  3071. /*SuperLoc=*/SourceLocation(), Sel,
  3072. /*Method=*/nullptr, LBracLoc, SelectorLocs,
  3073. RBracLoc, Args);
  3074. }
  3075. enum ARCConversionTypeClass {
  3076. /// int, void, struct A
  3077. ACTC_none,
  3078. /// id, void (^)()
  3079. ACTC_retainable,
  3080. /// id*, id***, void (^*)(),
  3081. ACTC_indirectRetainable,
  3082. /// void* might be a normal C type, or it might a CF type.
  3083. ACTC_voidPtr,
  3084. /// struct A*
  3085. ACTC_coreFoundation
  3086. };
  3087. static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
  3088. return (ACTC == ACTC_retainable ||
  3089. ACTC == ACTC_coreFoundation ||
  3090. ACTC == ACTC_voidPtr);
  3091. }
  3092. static bool isAnyCLike(ARCConversionTypeClass ACTC) {
  3093. return ACTC == ACTC_none ||
  3094. ACTC == ACTC_voidPtr ||
  3095. ACTC == ACTC_coreFoundation;
  3096. }
  3097. static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
  3098. bool isIndirect = false;
  3099. // Ignore an outermost reference type.
  3100. if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
  3101. type = ref->getPointeeType();
  3102. isIndirect = true;
  3103. }
  3104. // Drill through pointers and arrays recursively.
  3105. while (true) {
  3106. if (const PointerType *ptr = type->getAs<PointerType>()) {
  3107. type = ptr->getPointeeType();
  3108. // The first level of pointer may be the innermost pointer on a CF type.
  3109. if (!isIndirect) {
  3110. if (type->isVoidType()) return ACTC_voidPtr;
  3111. if (type->isRecordType()) return ACTC_coreFoundation;
  3112. }
  3113. } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
  3114. type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
  3115. } else {
  3116. break;
  3117. }
  3118. isIndirect = true;
  3119. }
  3120. if (isIndirect) {
  3121. if (type->isObjCARCBridgableType())
  3122. return ACTC_indirectRetainable;
  3123. return ACTC_none;
  3124. }
  3125. if (type->isObjCARCBridgableType())
  3126. return ACTC_retainable;
  3127. return ACTC_none;
  3128. }
  3129. namespace {
  3130. /// A result from the cast checker.
  3131. enum ACCResult {
  3132. /// Cannot be casted.
  3133. ACC_invalid,
  3134. /// Can be safely retained or not retained.
  3135. ACC_bottom,
  3136. /// Can be casted at +0.
  3137. ACC_plusZero,
  3138. /// Can be casted at +1.
  3139. ACC_plusOne
  3140. };
  3141. ACCResult merge(ACCResult left, ACCResult right) {
  3142. if (left == right) return left;
  3143. if (left == ACC_bottom) return right;
  3144. if (right == ACC_bottom) return left;
  3145. return ACC_invalid;
  3146. }
  3147. /// A checker which white-lists certain expressions whose conversion
  3148. /// to or from retainable type would otherwise be forbidden in ARC.
  3149. class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
  3150. typedef StmtVisitor<ARCCastChecker, ACCResult> super;
  3151. ASTContext &Context;
  3152. ARCConversionTypeClass SourceClass;
  3153. ARCConversionTypeClass TargetClass;
  3154. bool Diagnose;
  3155. static bool isCFType(QualType type) {
  3156. // Someday this can use ns_bridged. For now, it has to do this.
  3157. return type->isCARCBridgableType();
  3158. }
  3159. public:
  3160. ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
  3161. ARCConversionTypeClass target, bool diagnose)
  3162. : Context(Context), SourceClass(source), TargetClass(target),
  3163. Diagnose(diagnose) {}
  3164. using super::Visit;
  3165. ACCResult Visit(Expr *e) {
  3166. return super::Visit(e->IgnoreParens());
  3167. }
  3168. ACCResult VisitStmt(Stmt *s) {
  3169. return ACC_invalid;
  3170. }
  3171. /// Null pointer constants can be casted however you please.
  3172. ACCResult VisitExpr(Expr *e) {
  3173. if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
  3174. return ACC_bottom;
  3175. return ACC_invalid;
  3176. }
  3177. /// Objective-C string literals can be safely casted.
  3178. ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
  3179. // If we're casting to any retainable type, go ahead. Global
  3180. // strings are immune to retains, so this is bottom.
  3181. if (isAnyRetainable(TargetClass)) return ACC_bottom;
  3182. return ACC_invalid;
  3183. }
  3184. /// Look through certain implicit and explicit casts.
  3185. ACCResult VisitCastExpr(CastExpr *e) {
  3186. switch (e->getCastKind()) {
  3187. case CK_NullToPointer:
  3188. return ACC_bottom;
  3189. case CK_NoOp:
  3190. case CK_LValueToRValue:
  3191. case CK_BitCast:
  3192. case CK_CPointerToObjCPointerCast:
  3193. case CK_BlockPointerToObjCPointerCast:
  3194. case CK_AnyPointerToBlockPointerCast:
  3195. return Visit(e->getSubExpr());
  3196. default:
  3197. return ACC_invalid;
  3198. }
  3199. }
  3200. /// Look through unary extension.
  3201. ACCResult VisitUnaryExtension(UnaryOperator *e) {
  3202. return Visit(e->getSubExpr());
  3203. }
  3204. /// Ignore the LHS of a comma operator.
  3205. ACCResult VisitBinComma(BinaryOperator *e) {
  3206. return Visit(e->getRHS());
  3207. }
  3208. /// Conditional operators are okay if both sides are okay.
  3209. ACCResult VisitConditionalOperator(ConditionalOperator *e) {
  3210. ACCResult left = Visit(e->getTrueExpr());
  3211. if (left == ACC_invalid) return ACC_invalid;
  3212. return merge(left, Visit(e->getFalseExpr()));
  3213. }
  3214. /// Look through pseudo-objects.
  3215. ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
  3216. // If we're getting here, we should always have a result.
  3217. return Visit(e->getResultExpr());
  3218. }
  3219. /// Statement expressions are okay if their result expression is okay.
  3220. ACCResult VisitStmtExpr(StmtExpr *e) {
  3221. return Visit(e->getSubStmt()->body_back());
  3222. }
  3223. /// Some declaration references are okay.
  3224. ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
  3225. VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
  3226. // References to global constants are okay.
  3227. if (isAnyRetainable(TargetClass) &&
  3228. isAnyRetainable(SourceClass) &&
  3229. var &&
  3230. !var->hasDefinition(Context) &&
  3231. var->getType().isConstQualified()) {
  3232. // In system headers, they can also be assumed to be immune to retains.
  3233. // These are things like 'kCFStringTransformToLatin'.
  3234. if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
  3235. return ACC_bottom;
  3236. return ACC_plusZero;
  3237. }
  3238. // Nothing else.
  3239. return ACC_invalid;
  3240. }
  3241. /// Some calls are okay.
  3242. ACCResult VisitCallExpr(CallExpr *e) {
  3243. if (FunctionDecl *fn = e->getDirectCallee())
  3244. if (ACCResult result = checkCallToFunction(fn))
  3245. return result;
  3246. return super::VisitCallExpr(e);
  3247. }
  3248. ACCResult checkCallToFunction(FunctionDecl *fn) {
  3249. // Require a CF*Ref return type.
  3250. if (!isCFType(fn->getReturnType()))
  3251. return ACC_invalid;
  3252. if (!isAnyRetainable(TargetClass))
  3253. return ACC_invalid;
  3254. // Honor an explicit 'not retained' attribute.
  3255. if (fn->hasAttr<CFReturnsNotRetainedAttr>())
  3256. return ACC_plusZero;
  3257. // Honor an explicit 'retained' attribute, except that for
  3258. // now we're not going to permit implicit handling of +1 results,
  3259. // because it's a bit frightening.
  3260. if (fn->hasAttr<CFReturnsRetainedAttr>())
  3261. return Diagnose ? ACC_plusOne
  3262. : ACC_invalid; // ACC_plusOne if we start accepting this
  3263. // Recognize this specific builtin function, which is used by CFSTR.
  3264. unsigned builtinID = fn->getBuiltinID();
  3265. if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
  3266. return ACC_bottom;
  3267. // Otherwise, don't do anything implicit with an unaudited function.
  3268. if (!fn->hasAttr<CFAuditedTransferAttr>())
  3269. return ACC_invalid;
  3270. // Otherwise, it's +0 unless it follows the create convention.
  3271. if (ento::coreFoundation::followsCreateRule(fn))
  3272. return Diagnose ? ACC_plusOne
  3273. : ACC_invalid; // ACC_plusOne if we start accepting this
  3274. return ACC_plusZero;
  3275. }
  3276. ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
  3277. return checkCallToMethod(e->getMethodDecl());
  3278. }
  3279. ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
  3280. ObjCMethodDecl *method;
  3281. if (e->isExplicitProperty())
  3282. method = e->getExplicitProperty()->getGetterMethodDecl();
  3283. else
  3284. method = e->getImplicitPropertyGetter();
  3285. return checkCallToMethod(method);
  3286. }
  3287. ACCResult checkCallToMethod(ObjCMethodDecl *method) {
  3288. if (!method) return ACC_invalid;
  3289. // Check for message sends to functions returning CF types. We
  3290. // just obey the Cocoa conventions with these, even though the
  3291. // return type is CF.
  3292. if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
  3293. return ACC_invalid;
  3294. // If the method is explicitly marked not-retained, it's +0.
  3295. if (method->hasAttr<CFReturnsNotRetainedAttr>())
  3296. return ACC_plusZero;
  3297. // If the method is explicitly marked as returning retained, or its
  3298. // selector follows a +1 Cocoa convention, treat it as +1.
  3299. if (method->hasAttr<CFReturnsRetainedAttr>())
  3300. return ACC_plusOne;
  3301. switch (method->getSelector().getMethodFamily()) {
  3302. case OMF_alloc:
  3303. case OMF_copy:
  3304. case OMF_mutableCopy:
  3305. case OMF_new:
  3306. return ACC_plusOne;
  3307. default:
  3308. // Otherwise, treat it as +0.
  3309. return ACC_plusZero;
  3310. }
  3311. }
  3312. };
  3313. } // end anonymous namespace
  3314. bool Sema::isKnownName(StringRef name) {
  3315. if (name.empty())
  3316. return false;
  3317. LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
  3318. Sema::LookupOrdinaryName);
  3319. return LookupName(R, TUScope, false);
  3320. }
  3321. template <typename DiagBuilderT>
  3322. static void addFixitForObjCARCConversion(
  3323. Sema &S, DiagBuilderT &DiagB, Sema::CheckedConversionKind CCK,
  3324. SourceLocation afterLParen, QualType castType, Expr *castExpr,
  3325. Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName) {
  3326. // We handle C-style and implicit casts here.
  3327. switch (CCK) {
  3328. case Sema::CCK_ImplicitConversion:
  3329. case Sema::CCK_ForBuiltinOverloadedOp:
  3330. case Sema::CCK_CStyleCast:
  3331. case Sema::CCK_OtherCast:
  3332. break;
  3333. case Sema::CCK_FunctionalCast:
  3334. return;
  3335. }
  3336. if (CFBridgeName) {
  3337. if (CCK == Sema::CCK_OtherCast) {
  3338. if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
  3339. SourceRange range(NCE->getOperatorLoc(),
  3340. NCE->getAngleBrackets().getEnd());
  3341. SmallString<32> BridgeCall;
  3342. SourceManager &SM = S.getSourceManager();
  3343. char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
  3344. if (Lexer::isAsciiIdentifierContinueChar(PrevChar, S.getLangOpts()))
  3345. BridgeCall += ' ';
  3346. BridgeCall += CFBridgeName;
  3347. DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
  3348. }
  3349. return;
  3350. }
  3351. Expr *castedE = castExpr;
  3352. if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
  3353. castedE = CCE->getSubExpr();
  3354. castedE = castedE->IgnoreImpCasts();
  3355. SourceRange range = castedE->getSourceRange();
  3356. SmallString<32> BridgeCall;
  3357. SourceManager &SM = S.getSourceManager();
  3358. char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
  3359. if (Lexer::isAsciiIdentifierContinueChar(PrevChar, S.getLangOpts()))
  3360. BridgeCall += ' ';
  3361. BridgeCall += CFBridgeName;
  3362. if (isa<ParenExpr>(castedE)) {
  3363. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3364. BridgeCall));
  3365. } else {
  3366. BridgeCall += '(';
  3367. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3368. BridgeCall));
  3369. DiagB.AddFixItHint(FixItHint::CreateInsertion(
  3370. S.getLocForEndOfToken(range.getEnd()),
  3371. ")"));
  3372. }
  3373. return;
  3374. }
  3375. if (CCK == Sema::CCK_CStyleCast) {
  3376. DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
  3377. } else if (CCK == Sema::CCK_OtherCast) {
  3378. if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
  3379. std::string castCode = "(";
  3380. castCode += bridgeKeyword;
  3381. castCode += castType.getAsString();
  3382. castCode += ")";
  3383. SourceRange Range(NCE->getOperatorLoc(),
  3384. NCE->getAngleBrackets().getEnd());
  3385. DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
  3386. }
  3387. } else {
  3388. std::string castCode = "(";
  3389. castCode += bridgeKeyword;
  3390. castCode += castType.getAsString();
  3391. castCode += ")";
  3392. Expr *castedE = castExpr->IgnoreImpCasts();
  3393. SourceRange range = castedE->getSourceRange();
  3394. if (isa<ParenExpr>(castedE)) {
  3395. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3396. castCode));
  3397. } else {
  3398. castCode += "(";
  3399. DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
  3400. castCode));
  3401. DiagB.AddFixItHint(FixItHint::CreateInsertion(
  3402. S.getLocForEndOfToken(range.getEnd()),
  3403. ")"));
  3404. }
  3405. }
  3406. }
  3407. template <typename T>
  3408. static inline T *getObjCBridgeAttr(const TypedefType *TD) {
  3409. TypedefNameDecl *TDNDecl = TD->getDecl();
  3410. QualType QT = TDNDecl->getUnderlyingType();
  3411. if (QT->isPointerType()) {
  3412. QT = QT->getPointeeType();
  3413. if (const RecordType *RT = QT->getAs<RecordType>()) {
  3414. for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
  3415. if (auto *attr = Redecl->getAttr<T>())
  3416. return attr;
  3417. }
  3418. }
  3419. }
  3420. return nullptr;
  3421. }
  3422. static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
  3423. TypedefNameDecl *&TDNDecl) {
  3424. while (const auto *TD = T->getAs<TypedefType>()) {
  3425. TDNDecl = TD->getDecl();
  3426. if (ObjCBridgeRelatedAttr *ObjCBAttr =
  3427. getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
  3428. return ObjCBAttr;
  3429. T = TDNDecl->getUnderlyingType();
  3430. }
  3431. return nullptr;
  3432. }
  3433. static void
  3434. diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
  3435. QualType castType, ARCConversionTypeClass castACTC,
  3436. Expr *castExpr, Expr *realCast,
  3437. ARCConversionTypeClass exprACTC,
  3438. Sema::CheckedConversionKind CCK) {
  3439. SourceLocation loc =
  3440. (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
  3441. if (S.makeUnavailableInSystemHeader(loc,
  3442. UnavailableAttr::IR_ARCForbiddenConversion))
  3443. return;
  3444. QualType castExprType = castExpr->getType();
  3445. // Defer emitting a diagnostic for bridge-related casts; that will be
  3446. // handled by CheckObjCBridgeRelatedConversions.
  3447. TypedefNameDecl *TDNDecl = nullptr;
  3448. if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
  3449. ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
  3450. (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
  3451. ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
  3452. return;
  3453. unsigned srcKind = 0;
  3454. switch (exprACTC) {
  3455. case ACTC_none:
  3456. case ACTC_coreFoundation:
  3457. case ACTC_voidPtr:
  3458. srcKind = (castExprType->isPointerType() ? 1 : 0);
  3459. break;
  3460. case ACTC_retainable:
  3461. srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
  3462. break;
  3463. case ACTC_indirectRetainable:
  3464. srcKind = 4;
  3465. break;
  3466. }
  3467. // Check whether this could be fixed with a bridge cast.
  3468. SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
  3469. SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
  3470. unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
  3471. // Bridge from an ARC type to a CF type.
  3472. if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
  3473. S.Diag(loc, diag::err_arc_cast_requires_bridge)
  3474. << convKindForDiag
  3475. << 2 // of C pointer type
  3476. << castExprType
  3477. << unsigned(castType->isBlockPointerType()) // to ObjC|block type
  3478. << castType
  3479. << castRange
  3480. << castExpr->getSourceRange();
  3481. bool br = S.isKnownName("CFBridgingRelease");
  3482. ACCResult CreateRule =
  3483. ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
  3484. assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
  3485. if (CreateRule != ACC_plusOne)
  3486. {
  3487. auto DiagB = (CCK != Sema::CCK_OtherCast)
  3488. ? S.Diag(noteLoc, diag::note_arc_bridge)
  3489. : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
  3490. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3491. castType, castExpr, realCast, "__bridge ",
  3492. nullptr);
  3493. }
  3494. if (CreateRule != ACC_plusZero)
  3495. {
  3496. auto DiagB = (CCK == Sema::CCK_OtherCast && !br)
  3497. ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer)
  3498. << castExprType
  3499. : S.Diag(br ? castExpr->getExprLoc() : noteLoc,
  3500. diag::note_arc_bridge_transfer)
  3501. << castExprType << br;
  3502. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3503. castType, castExpr, realCast, "__bridge_transfer ",
  3504. br ? "CFBridgingRelease" : nullptr);
  3505. }
  3506. return;
  3507. }
  3508. // Bridge from a CF type to an ARC type.
  3509. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
  3510. bool br = S.isKnownName("CFBridgingRetain");
  3511. S.Diag(loc, diag::err_arc_cast_requires_bridge)
  3512. << convKindForDiag
  3513. << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
  3514. << castExprType
  3515. << 2 // to C pointer type
  3516. << castType
  3517. << castRange
  3518. << castExpr->getSourceRange();
  3519. ACCResult CreateRule =
  3520. ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
  3521. assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
  3522. if (CreateRule != ACC_plusOne)
  3523. {
  3524. auto DiagB = (CCK != Sema::CCK_OtherCast)
  3525. ? S.Diag(noteLoc, diag::note_arc_bridge)
  3526. : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
  3527. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3528. castType, castExpr, realCast, "__bridge ",
  3529. nullptr);
  3530. }
  3531. if (CreateRule != ACC_plusZero)
  3532. {
  3533. auto DiagB = (CCK == Sema::CCK_OtherCast && !br)
  3534. ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained)
  3535. << castType
  3536. : S.Diag(br ? castExpr->getExprLoc() : noteLoc,
  3537. diag::note_arc_bridge_retained)
  3538. << castType << br;
  3539. addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
  3540. castType, castExpr, realCast, "__bridge_retained ",
  3541. br ? "CFBridgingRetain" : nullptr);
  3542. }
  3543. return;
  3544. }
  3545. S.Diag(loc, diag::err_arc_mismatched_cast)
  3546. << !convKindForDiag
  3547. << srcKind << castExprType << castType
  3548. << castRange << castExpr->getSourceRange();
  3549. }
  3550. template <typename TB>
  3551. static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
  3552. bool &HadTheAttribute, bool warn) {
  3553. QualType T = castExpr->getType();
  3554. HadTheAttribute = false;
  3555. while (const auto *TD = T->getAs<TypedefType>()) {
  3556. TypedefNameDecl *TDNDecl = TD->getDecl();
  3557. if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
  3558. if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
  3559. HadTheAttribute = true;
  3560. if (Parm->isStr("id"))
  3561. return true;
  3562. // Check for an existing type with this name.
  3563. LookupResult R(S, DeclarationName(Parm), SourceLocation(),
  3564. Sema::LookupOrdinaryName);
  3565. if (S.LookupName(R, S.TUScope)) {
  3566. NamedDecl *Target = R.getFoundDecl();
  3567. if (Target && isa<ObjCInterfaceDecl>(Target)) {
  3568. ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
  3569. if (const ObjCObjectPointerType *InterfacePointerType =
  3570. castType->getAsObjCInterfacePointerType()) {
  3571. ObjCInterfaceDecl *CastClass
  3572. = InterfacePointerType->getObjectType()->getInterface();
  3573. if ((CastClass == ExprClass) ||
  3574. (CastClass && CastClass->isSuperClassOf(ExprClass)))
  3575. return true;
  3576. if (warn)
  3577. S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
  3578. << T << Target->getName() << castType->getPointeeType();
  3579. return false;
  3580. } else if (castType->isObjCIdType() ||
  3581. (S.Context.ObjCObjectAdoptsQTypeProtocols(
  3582. castType, ExprClass)))
  3583. // ok to cast to 'id'.
  3584. // casting to id<p-list> is ok if bridge type adopts all of
  3585. // p-list protocols.
  3586. return true;
  3587. else {
  3588. if (warn) {
  3589. S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
  3590. << T << Target->getName() << castType;
  3591. S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3592. S.Diag(Target->getBeginLoc(), diag::note_declared_at);
  3593. }
  3594. return false;
  3595. }
  3596. }
  3597. } else if (!castType->isObjCIdType()) {
  3598. S.Diag(castExpr->getBeginLoc(),
  3599. diag::err_objc_cf_bridged_not_interface)
  3600. << castExpr->getType() << Parm;
  3601. S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3602. }
  3603. return true;
  3604. }
  3605. return false;
  3606. }
  3607. T = TDNDecl->getUnderlyingType();
  3608. }
  3609. return true;
  3610. }
  3611. template <typename TB>
  3612. static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
  3613. bool &HadTheAttribute, bool warn) {
  3614. QualType T = castType;
  3615. HadTheAttribute = false;
  3616. while (const auto *TD = T->getAs<TypedefType>()) {
  3617. TypedefNameDecl *TDNDecl = TD->getDecl();
  3618. if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
  3619. if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
  3620. HadTheAttribute = true;
  3621. if (Parm->isStr("id"))
  3622. return true;
  3623. NamedDecl *Target = nullptr;
  3624. // Check for an existing type with this name.
  3625. LookupResult R(S, DeclarationName(Parm), SourceLocation(),
  3626. Sema::LookupOrdinaryName);
  3627. if (S.LookupName(R, S.TUScope)) {
  3628. Target = R.getFoundDecl();
  3629. if (Target && isa<ObjCInterfaceDecl>(Target)) {
  3630. ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
  3631. if (const ObjCObjectPointerType *InterfacePointerType =
  3632. castExpr->getType()->getAsObjCInterfacePointerType()) {
  3633. ObjCInterfaceDecl *ExprClass
  3634. = InterfacePointerType->getObjectType()->getInterface();
  3635. if ((CastClass == ExprClass) ||
  3636. (ExprClass && CastClass->isSuperClassOf(ExprClass)))
  3637. return true;
  3638. if (warn) {
  3639. S.Diag(castExpr->getBeginLoc(),
  3640. diag::warn_objc_invalid_bridge_to_cf)
  3641. << castExpr->getType()->getPointeeType() << T;
  3642. S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3643. }
  3644. return false;
  3645. } else if (castExpr->getType()->isObjCIdType() ||
  3646. (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
  3647. castExpr->getType(), CastClass)))
  3648. // ok to cast an 'id' expression to a CFtype.
  3649. // ok to cast an 'id<plist>' expression to CFtype provided plist
  3650. // adopts all of CFtype's ObjetiveC's class plist.
  3651. return true;
  3652. else {
  3653. if (warn) {
  3654. S.Diag(castExpr->getBeginLoc(),
  3655. diag::warn_objc_invalid_bridge_to_cf)
  3656. << castExpr->getType() << castType;
  3657. S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3658. S.Diag(Target->getBeginLoc(), diag::note_declared_at);
  3659. }
  3660. return false;
  3661. }
  3662. }
  3663. }
  3664. S.Diag(castExpr->getBeginLoc(),
  3665. diag::err_objc_ns_bridged_invalid_cfobject)
  3666. << castExpr->getType() << castType;
  3667. S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3668. if (Target)
  3669. S.Diag(Target->getBeginLoc(), diag::note_declared_at);
  3670. return true;
  3671. }
  3672. return false;
  3673. }
  3674. T = TDNDecl->getUnderlyingType();
  3675. }
  3676. return true;
  3677. }
  3678. void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
  3679. if (!getLangOpts().ObjC)
  3680. return;
  3681. // warn in presence of __bridge casting to or from a toll free bridge cast.
  3682. ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
  3683. ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
  3684. if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
  3685. bool HasObjCBridgeAttr;
  3686. bool ObjCBridgeAttrWillNotWarn =
  3687. CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3688. false);
  3689. if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
  3690. return;
  3691. bool HasObjCBridgeMutableAttr;
  3692. bool ObjCBridgeMutableAttrWillNotWarn =
  3693. CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3694. HasObjCBridgeMutableAttr, false);
  3695. if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
  3696. return;
  3697. if (HasObjCBridgeAttr)
  3698. CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3699. true);
  3700. else if (HasObjCBridgeMutableAttr)
  3701. CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3702. HasObjCBridgeMutableAttr, true);
  3703. }
  3704. else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
  3705. bool HasObjCBridgeAttr;
  3706. bool ObjCBridgeAttrWillNotWarn =
  3707. CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3708. false);
  3709. if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
  3710. return;
  3711. bool HasObjCBridgeMutableAttr;
  3712. bool ObjCBridgeMutableAttrWillNotWarn =
  3713. CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3714. HasObjCBridgeMutableAttr, false);
  3715. if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
  3716. return;
  3717. if (HasObjCBridgeAttr)
  3718. CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
  3719. true);
  3720. else if (HasObjCBridgeMutableAttr)
  3721. CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
  3722. HasObjCBridgeMutableAttr, true);
  3723. }
  3724. }
  3725. void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
  3726. QualType SrcType = castExpr->getType();
  3727. if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
  3728. if (PRE->isExplicitProperty()) {
  3729. if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
  3730. SrcType = PDecl->getType();
  3731. }
  3732. else if (PRE->isImplicitProperty()) {
  3733. if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
  3734. SrcType = Getter->getReturnType();
  3735. }
  3736. }
  3737. ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
  3738. ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
  3739. if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
  3740. return;
  3741. CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
  3742. castExpr);
  3743. }
  3744. bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
  3745. CastKind &Kind) {
  3746. if (!getLangOpts().ObjC)
  3747. return false;
  3748. ARCConversionTypeClass exprACTC =
  3749. classifyTypeForARCConversion(castExpr->getType());
  3750. ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
  3751. if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
  3752. (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
  3753. CheckTollFreeBridgeCast(castType, castExpr);
  3754. Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
  3755. : CK_CPointerToObjCPointerCast;
  3756. return true;
  3757. }
  3758. return false;
  3759. }
  3760. bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
  3761. QualType DestType, QualType SrcType,
  3762. ObjCInterfaceDecl *&RelatedClass,
  3763. ObjCMethodDecl *&ClassMethod,
  3764. ObjCMethodDecl *&InstanceMethod,
  3765. TypedefNameDecl *&TDNDecl,
  3766. bool CfToNs, bool Diagnose) {
  3767. QualType T = CfToNs ? SrcType : DestType;
  3768. ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
  3769. if (!ObjCBAttr)
  3770. return false;
  3771. IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
  3772. IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
  3773. IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
  3774. if (!RCId)
  3775. return false;
  3776. NamedDecl *Target = nullptr;
  3777. // Check for an existing type with this name.
  3778. LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
  3779. Sema::LookupOrdinaryName);
  3780. if (!LookupName(R, TUScope)) {
  3781. if (Diagnose) {
  3782. Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
  3783. << SrcType << DestType;
  3784. Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3785. }
  3786. return false;
  3787. }
  3788. Target = R.getFoundDecl();
  3789. if (Target && isa<ObjCInterfaceDecl>(Target))
  3790. RelatedClass = cast<ObjCInterfaceDecl>(Target);
  3791. else {
  3792. if (Diagnose) {
  3793. Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
  3794. << SrcType << DestType;
  3795. Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3796. if (Target)
  3797. Diag(Target->getBeginLoc(), diag::note_declared_at);
  3798. }
  3799. return false;
  3800. }
  3801. // Check for an existing class method with the given selector name.
  3802. if (CfToNs && CMId) {
  3803. Selector Sel = Context.Selectors.getUnarySelector(CMId);
  3804. ClassMethod = RelatedClass->lookupMethod(Sel, false);
  3805. if (!ClassMethod) {
  3806. if (Diagnose) {
  3807. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3808. << SrcType << DestType << Sel << false;
  3809. Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3810. }
  3811. return false;
  3812. }
  3813. }
  3814. // Check for an existing instance method with the given selector name.
  3815. if (!CfToNs && IMId) {
  3816. Selector Sel = Context.Selectors.getNullarySelector(IMId);
  3817. InstanceMethod = RelatedClass->lookupMethod(Sel, true);
  3818. if (!InstanceMethod) {
  3819. if (Diagnose) {
  3820. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3821. << SrcType << DestType << Sel << true;
  3822. Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3823. }
  3824. return false;
  3825. }
  3826. }
  3827. return true;
  3828. }
  3829. bool
  3830. Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
  3831. QualType DestType, QualType SrcType,
  3832. Expr *&SrcExpr, bool Diagnose) {
  3833. ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
  3834. ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
  3835. bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
  3836. bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
  3837. if (!CfToNs && !NsToCf)
  3838. return false;
  3839. ObjCInterfaceDecl *RelatedClass;
  3840. ObjCMethodDecl *ClassMethod = nullptr;
  3841. ObjCMethodDecl *InstanceMethod = nullptr;
  3842. TypedefNameDecl *TDNDecl = nullptr;
  3843. if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
  3844. ClassMethod, InstanceMethod, TDNDecl,
  3845. CfToNs, Diagnose))
  3846. return false;
  3847. if (CfToNs) {
  3848. // Implicit conversion from CF to ObjC object is needed.
  3849. if (ClassMethod) {
  3850. if (Diagnose) {
  3851. std::string ExpressionString = "[";
  3852. ExpressionString += RelatedClass->getNameAsString();
  3853. ExpressionString += " ";
  3854. ExpressionString += ClassMethod->getSelector().getAsString();
  3855. SourceLocation SrcExprEndLoc =
  3856. getLocForEndOfToken(SrcExpr->getEndLoc());
  3857. // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
  3858. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3859. << SrcType << DestType << ClassMethod->getSelector() << false
  3860. << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
  3861. ExpressionString)
  3862. << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
  3863. Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
  3864. Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3865. QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
  3866. // Argument.
  3867. Expr *args[] = { SrcExpr };
  3868. ExprResult msg = BuildClassMessageImplicit(receiverType, false,
  3869. ClassMethod->getLocation(),
  3870. ClassMethod->getSelector(), ClassMethod,
  3871. MultiExprArg(args, 1));
  3872. SrcExpr = msg.get();
  3873. }
  3874. return true;
  3875. }
  3876. }
  3877. else {
  3878. // Implicit conversion from ObjC type to CF object is needed.
  3879. if (InstanceMethod) {
  3880. if (Diagnose) {
  3881. std::string ExpressionString;
  3882. SourceLocation SrcExprEndLoc =
  3883. getLocForEndOfToken(SrcExpr->getEndLoc());
  3884. if (InstanceMethod->isPropertyAccessor())
  3885. if (const ObjCPropertyDecl *PDecl =
  3886. InstanceMethod->findPropertyDecl()) {
  3887. // fixit: ObjectExpr.propertyname when it is aproperty accessor.
  3888. ExpressionString = ".";
  3889. ExpressionString += PDecl->getNameAsString();
  3890. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3891. << SrcType << DestType << InstanceMethod->getSelector() << true
  3892. << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
  3893. }
  3894. if (ExpressionString.empty()) {
  3895. // Provide a fixit: [ObjectExpr InstanceMethod]
  3896. ExpressionString = " ";
  3897. ExpressionString += InstanceMethod->getSelector().getAsString();
  3898. ExpressionString += "]";
  3899. Diag(Loc, diag::err_objc_bridged_related_known_method)
  3900. << SrcType << DestType << InstanceMethod->getSelector() << true
  3901. << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
  3902. << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
  3903. }
  3904. Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
  3905. Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
  3906. ExprResult msg = BuildInstanceMessageImplicit(
  3907. SrcExpr, SrcType, InstanceMethod->getLocation(),
  3908. InstanceMethod->getSelector(), InstanceMethod, std::nullopt);
  3909. SrcExpr = msg.get();
  3910. }
  3911. return true;
  3912. }
  3913. }
  3914. return false;
  3915. }
  3916. Sema::ARCConversionResult
  3917. Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
  3918. Expr *&castExpr, CheckedConversionKind CCK,
  3919. bool Diagnose, bool DiagnoseCFAudited,
  3920. BinaryOperatorKind Opc) {
  3921. QualType castExprType = castExpr->getType();
  3922. // For the purposes of the classification, we assume reference types
  3923. // will bind to temporaries.
  3924. QualType effCastType = castType;
  3925. if (const ReferenceType *ref = castType->getAs<ReferenceType>())
  3926. effCastType = ref->getPointeeType();
  3927. ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
  3928. ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
  3929. if (exprACTC == castACTC) {
  3930. // Check for viability and report error if casting an rvalue to a
  3931. // life-time qualifier.
  3932. if (castACTC == ACTC_retainable &&
  3933. (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
  3934. castType != castExprType) {
  3935. const Type *DT = castType.getTypePtr();
  3936. QualType QDT = castType;
  3937. // We desugar some types but not others. We ignore those
  3938. // that cannot happen in a cast; i.e. auto, and those which
  3939. // should not be de-sugared; i.e typedef.
  3940. if (const ParenType *PT = dyn_cast<ParenType>(DT))
  3941. QDT = PT->desugar();
  3942. else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
  3943. QDT = TP->desugar();
  3944. else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
  3945. QDT = AT->desugar();
  3946. if (QDT != castType &&
  3947. QDT.getObjCLifetime() != Qualifiers::OCL_None) {
  3948. if (Diagnose) {
  3949. SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
  3950. : castExpr->getExprLoc());
  3951. Diag(loc, diag::err_arc_nolifetime_behavior);
  3952. }
  3953. return ACR_error;
  3954. }
  3955. }
  3956. return ACR_okay;
  3957. }
  3958. // The life-time qualifier cast check above is all we need for ObjCWeak.
  3959. // ObjCAutoRefCount has more restrictions on what is legal.
  3960. if (!getLangOpts().ObjCAutoRefCount)
  3961. return ACR_okay;
  3962. if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
  3963. // Allow all of these types to be cast to integer types (but not
  3964. // vice-versa).
  3965. if (castACTC == ACTC_none && castType->isIntegralType(Context))
  3966. return ACR_okay;
  3967. // Allow casts between pointers to lifetime types (e.g., __strong id*)
  3968. // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
  3969. // must be explicit.
  3970. // Allow conversions between pointers to lifetime types and coreFoundation
  3971. // pointers too, but only when the conversions are explicit.
  3972. if (exprACTC == ACTC_indirectRetainable &&
  3973. (castACTC == ACTC_voidPtr ||
  3974. (castACTC == ACTC_coreFoundation && isCast(CCK))))
  3975. return ACR_okay;
  3976. if (castACTC == ACTC_indirectRetainable &&
  3977. (exprACTC == ACTC_voidPtr || exprACTC == ACTC_coreFoundation) &&
  3978. isCast(CCK))
  3979. return ACR_okay;
  3980. switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
  3981. // For invalid casts, fall through.
  3982. case ACC_invalid:
  3983. break;
  3984. // Do nothing for both bottom and +0.
  3985. case ACC_bottom:
  3986. case ACC_plusZero:
  3987. return ACR_okay;
  3988. // If the result is +1, consume it here.
  3989. case ACC_plusOne:
  3990. castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
  3991. CK_ARCConsumeObject, castExpr, nullptr,
  3992. VK_PRValue, FPOptionsOverride());
  3993. Cleanup.setExprNeedsCleanups(true);
  3994. return ACR_okay;
  3995. }
  3996. // If this is a non-implicit cast from id or block type to a
  3997. // CoreFoundation type, delay complaining in case the cast is used
  3998. // in an acceptable context.
  3999. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
  4000. return ACR_unbridged;
  4001. // Issue a diagnostic about a missing @-sign when implicit casting a cstring
  4002. // to 'NSString *', instead of falling through to report a "bridge cast"
  4003. // diagnostic.
  4004. if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
  4005. CheckConversionToObjCLiteral(castType, castExpr, Diagnose))
  4006. return ACR_error;
  4007. // Do not issue "bridge cast" diagnostic when implicit casting
  4008. // a retainable object to a CF type parameter belonging to an audited
  4009. // CF API function. Let caller issue a normal type mismatched diagnostic
  4010. // instead.
  4011. if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
  4012. castACTC != ACTC_coreFoundation) &&
  4013. !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
  4014. (Opc == BO_NE || Opc == BO_EQ))) {
  4015. if (Diagnose)
  4016. diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
  4017. castExpr, exprACTC, CCK);
  4018. return ACR_error;
  4019. }
  4020. return ACR_okay;
  4021. }
  4022. /// Given that we saw an expression with the ARCUnbridgedCastTy
  4023. /// placeholder type, complain bitterly.
  4024. void Sema::diagnoseARCUnbridgedCast(Expr *e) {
  4025. // We expect the spurious ImplicitCastExpr to already have been stripped.
  4026. assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  4027. CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
  4028. SourceRange castRange;
  4029. QualType castType;
  4030. CheckedConversionKind CCK;
  4031. if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
  4032. castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
  4033. castType = cast->getTypeAsWritten();
  4034. CCK = CCK_CStyleCast;
  4035. } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
  4036. castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
  4037. castType = cast->getTypeAsWritten();
  4038. CCK = CCK_OtherCast;
  4039. } else {
  4040. llvm_unreachable("Unexpected ImplicitCastExpr");
  4041. }
  4042. ARCConversionTypeClass castACTC =
  4043. classifyTypeForARCConversion(castType.getNonReferenceType());
  4044. Expr *castExpr = realCast->getSubExpr();
  4045. assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
  4046. diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
  4047. castExpr, realCast, ACTC_retainable, CCK);
  4048. }
  4049. /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
  4050. /// type, remove the placeholder cast.
  4051. Expr *Sema::stripARCUnbridgedCast(Expr *e) {
  4052. assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
  4053. if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
  4054. Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
  4055. return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
  4056. } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
  4057. assert(uo->getOpcode() == UO_Extension);
  4058. Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
  4059. return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(),
  4060. sub->getValueKind(), sub->getObjectKind(),
  4061. uo->getOperatorLoc(), false,
  4062. CurFPFeatureOverrides());
  4063. } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
  4064. assert(!gse->isResultDependent());
  4065. unsigned n = gse->getNumAssocs();
  4066. SmallVector<Expr *, 4> subExprs;
  4067. SmallVector<TypeSourceInfo *, 4> subTypes;
  4068. subExprs.reserve(n);
  4069. subTypes.reserve(n);
  4070. for (const GenericSelectionExpr::Association assoc : gse->associations()) {
  4071. subTypes.push_back(assoc.getTypeSourceInfo());
  4072. Expr *sub = assoc.getAssociationExpr();
  4073. if (assoc.isSelected())
  4074. sub = stripARCUnbridgedCast(sub);
  4075. subExprs.push_back(sub);
  4076. }
  4077. return GenericSelectionExpr::Create(
  4078. Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
  4079. subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
  4080. gse->containsUnexpandedParameterPack(), gse->getResultIndex());
  4081. } else {
  4082. assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
  4083. return cast<ImplicitCastExpr>(e)->getSubExpr();
  4084. }
  4085. }
  4086. bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
  4087. QualType exprType) {
  4088. QualType canCastType =
  4089. Context.getCanonicalType(castType).getUnqualifiedType();
  4090. QualType canExprType =
  4091. Context.getCanonicalType(exprType).getUnqualifiedType();
  4092. if (isa<ObjCObjectPointerType>(canCastType) &&
  4093. castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
  4094. canExprType->isObjCObjectPointerType()) {
  4095. if (const ObjCObjectPointerType *ObjT =
  4096. canExprType->getAs<ObjCObjectPointerType>())
  4097. if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
  4098. return !ObjI->isArcWeakrefUnavailable();
  4099. }
  4100. return true;
  4101. }
  4102. /// Look for an ObjCReclaimReturnedObject cast and destroy it.
  4103. static Expr *maybeUndoReclaimObject(Expr *e) {
  4104. Expr *curExpr = e, *prevExpr = nullptr;
  4105. // Walk down the expression until we hit an implicit cast of kind
  4106. // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
  4107. while (true) {
  4108. if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
  4109. prevExpr = curExpr;
  4110. curExpr = pe->getSubExpr();
  4111. continue;
  4112. }
  4113. if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
  4114. if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
  4115. if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
  4116. if (!prevExpr)
  4117. return ice->getSubExpr();
  4118. if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
  4119. pe->setSubExpr(ice->getSubExpr());
  4120. else
  4121. cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
  4122. return e;
  4123. }
  4124. prevExpr = curExpr;
  4125. curExpr = ce->getSubExpr();
  4126. continue;
  4127. }
  4128. // Break out of the loop if curExpr is neither a Paren nor a Cast.
  4129. break;
  4130. }
  4131. return e;
  4132. }
  4133. ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
  4134. ObjCBridgeCastKind Kind,
  4135. SourceLocation BridgeKeywordLoc,
  4136. TypeSourceInfo *TSInfo,
  4137. Expr *SubExpr) {
  4138. ExprResult SubResult = UsualUnaryConversions(SubExpr);
  4139. if (SubResult.isInvalid()) return ExprError();
  4140. SubExpr = SubResult.get();
  4141. QualType T = TSInfo->getType();
  4142. QualType FromType = SubExpr->getType();
  4143. CastKind CK;
  4144. bool MustConsume = false;
  4145. if (T->isDependentType() || SubExpr->isTypeDependent()) {
  4146. // Okay: we'll build a dependent expression type.
  4147. CK = CK_Dependent;
  4148. } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
  4149. // Casting CF -> id
  4150. CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
  4151. : CK_CPointerToObjCPointerCast);
  4152. switch (Kind) {
  4153. case OBC_Bridge:
  4154. break;
  4155. case OBC_BridgeRetained: {
  4156. bool br = isKnownName("CFBridgingRelease");
  4157. Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
  4158. << 2
  4159. << FromType
  4160. << (T->isBlockPointerType()? 1 : 0)
  4161. << T
  4162. << SubExpr->getSourceRange()
  4163. << Kind;
  4164. Diag(BridgeKeywordLoc, diag::note_arc_bridge)
  4165. << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
  4166. Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
  4167. << FromType << br
  4168. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  4169. br ? "CFBridgingRelease "
  4170. : "__bridge_transfer ");
  4171. Kind = OBC_Bridge;
  4172. break;
  4173. }
  4174. case OBC_BridgeTransfer:
  4175. // We must consume the Objective-C object produced by the cast.
  4176. MustConsume = true;
  4177. break;
  4178. }
  4179. } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
  4180. // Okay: id -> CF
  4181. CK = CK_BitCast;
  4182. switch (Kind) {
  4183. case OBC_Bridge:
  4184. // Reclaiming a value that's going to be __bridge-casted to CF
  4185. // is very dangerous, so we don't do it.
  4186. SubExpr = maybeUndoReclaimObject(SubExpr);
  4187. break;
  4188. case OBC_BridgeRetained:
  4189. // Produce the object before casting it.
  4190. SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject,
  4191. SubExpr, nullptr, VK_PRValue,
  4192. FPOptionsOverride());
  4193. break;
  4194. case OBC_BridgeTransfer: {
  4195. bool br = isKnownName("CFBridgingRetain");
  4196. Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
  4197. << (FromType->isBlockPointerType()? 1 : 0)
  4198. << FromType
  4199. << 2
  4200. << T
  4201. << SubExpr->getSourceRange()
  4202. << Kind;
  4203. Diag(BridgeKeywordLoc, diag::note_arc_bridge)
  4204. << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
  4205. Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
  4206. << T << br
  4207. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  4208. br ? "CFBridgingRetain " : "__bridge_retained");
  4209. Kind = OBC_Bridge;
  4210. break;
  4211. }
  4212. }
  4213. } else {
  4214. Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
  4215. << FromType << T << Kind
  4216. << SubExpr->getSourceRange()
  4217. << TSInfo->getTypeLoc().getSourceRange();
  4218. return ExprError();
  4219. }
  4220. Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
  4221. BridgeKeywordLoc,
  4222. TSInfo, SubExpr);
  4223. if (MustConsume) {
  4224. Cleanup.setExprNeedsCleanups(true);
  4225. Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
  4226. nullptr, VK_PRValue, FPOptionsOverride());
  4227. }
  4228. return Result;
  4229. }
  4230. ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
  4231. SourceLocation LParenLoc,
  4232. ObjCBridgeCastKind Kind,
  4233. SourceLocation BridgeKeywordLoc,
  4234. ParsedType Type,
  4235. SourceLocation RParenLoc,
  4236. Expr *SubExpr) {
  4237. TypeSourceInfo *TSInfo = nullptr;
  4238. QualType T = GetTypeFromParser(Type, &TSInfo);
  4239. if (Kind == OBC_Bridge)
  4240. CheckTollFreeBridgeCast(T, SubExpr);
  4241. if (!TSInfo)
  4242. TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
  4243. return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
  4244. SubExpr);
  4245. }