SemaExprObjC.cpp 179 KB

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