SemaExprObjC.cpp 177 KB

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