RewriteModernObjC.cpp 288 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569
  1. //===-- RewriteModernObjC.cpp - Playground for the code rewriter ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Hacks and fun related to the code rewriter.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Rewrite/Frontend/ASTConsumers.h"
  13. #include "clang/AST/AST.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/ParentMap.h"
  17. #include "clang/Basic/CharInfo.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/IdentifierTable.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Basic/TargetInfo.h"
  22. #include "clang/Config/config.h"
  23. #include "clang/Lex/Lexer.h"
  24. #include "clang/Rewrite/Core/Rewriter.h"
  25. #include "llvm/ADT/DenseSet.h"
  26. #include "llvm/ADT/SetVector.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <memory>
  32. #if CLANG_ENABLE_OBJC_REWRITER
  33. using namespace clang;
  34. using llvm::utostr;
  35. namespace {
  36. class RewriteModernObjC : public ASTConsumer {
  37. protected:
  38. enum {
  39. BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
  40. block, ... */
  41. BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
  42. BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
  43. __block variable */
  44. BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
  45. helpers */
  46. BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
  47. support routines */
  48. BLOCK_BYREF_CURRENT_MAX = 256
  49. };
  50. enum {
  51. BLOCK_NEEDS_FREE = (1 << 24),
  52. BLOCK_HAS_COPY_DISPOSE = (1 << 25),
  53. BLOCK_HAS_CXX_OBJ = (1 << 26),
  54. BLOCK_IS_GC = (1 << 27),
  55. BLOCK_IS_GLOBAL = (1 << 28),
  56. BLOCK_HAS_DESCRIPTOR = (1 << 29)
  57. };
  58. Rewriter Rewrite;
  59. DiagnosticsEngine &Diags;
  60. const LangOptions &LangOpts;
  61. ASTContext *Context;
  62. SourceManager *SM;
  63. TranslationUnitDecl *TUDecl;
  64. FileID MainFileID;
  65. const char *MainFileStart, *MainFileEnd;
  66. Stmt *CurrentBody;
  67. ParentMap *PropParentMap; // created lazily.
  68. std::string InFileName;
  69. std::unique_ptr<raw_ostream> OutFile;
  70. std::string Preamble;
  71. TypeDecl *ProtocolTypeDecl;
  72. VarDecl *GlobalVarDecl;
  73. Expr *GlobalConstructionExp;
  74. unsigned RewriteFailedDiag;
  75. unsigned GlobalBlockRewriteFailedDiag;
  76. // ObjC string constant support.
  77. unsigned NumObjCStringLiterals;
  78. VarDecl *ConstantStringClassReference;
  79. RecordDecl *NSStringRecord;
  80. // ObjC foreach break/continue generation support.
  81. int BcLabelCount;
  82. unsigned TryFinallyContainsReturnDiag;
  83. // Needed for super.
  84. ObjCMethodDecl *CurMethodDef;
  85. RecordDecl *SuperStructDecl;
  86. RecordDecl *ConstantStringDecl;
  87. FunctionDecl *MsgSendFunctionDecl;
  88. FunctionDecl *MsgSendSuperFunctionDecl;
  89. FunctionDecl *MsgSendStretFunctionDecl;
  90. FunctionDecl *MsgSendSuperStretFunctionDecl;
  91. FunctionDecl *MsgSendFpretFunctionDecl;
  92. FunctionDecl *GetClassFunctionDecl;
  93. FunctionDecl *GetMetaClassFunctionDecl;
  94. FunctionDecl *GetSuperClassFunctionDecl;
  95. FunctionDecl *SelGetUidFunctionDecl;
  96. FunctionDecl *CFStringFunctionDecl;
  97. FunctionDecl *SuperConstructorFunctionDecl;
  98. FunctionDecl *CurFunctionDef;
  99. /* Misc. containers needed for meta-data rewrite. */
  100. SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
  101. SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
  102. llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
  103. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
  104. llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
  105. llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
  106. SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
  107. /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
  108. SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
  109. /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
  110. SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
  111. SmallVector<Stmt *, 32> Stmts;
  112. SmallVector<int, 8> ObjCBcLabelNo;
  113. // Remember all the @protocol(<expr>) expressions.
  114. llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
  115. llvm::DenseSet<uint64_t> CopyDestroyCache;
  116. // Block expressions.
  117. SmallVector<BlockExpr *, 32> Blocks;
  118. SmallVector<int, 32> InnerDeclRefsCount;
  119. SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
  120. SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
  121. // Block related declarations.
  122. SmallVector<ValueDecl *, 8> BlockByCopyDecls;
  123. llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
  124. SmallVector<ValueDecl *, 8> BlockByRefDecls;
  125. llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
  126. llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
  127. llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
  128. llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
  129. llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
  130. llvm::DenseMap<ObjCInterfaceDecl *,
  131. llvm::SmallSetVector<ObjCIvarDecl *, 8> > ReferencedIvars;
  132. // ivar bitfield grouping containers
  133. llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
  134. llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
  135. // This container maps an <class, group number for ivar> tuple to the type
  136. // of the struct where the bitfield belongs.
  137. llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
  138. SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
  139. // This maps an original source AST to it's rewritten form. This allows
  140. // us to avoid rewriting the same node twice (which is very uncommon).
  141. // This is needed to support some of the exotic property rewriting.
  142. llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
  143. // Needed for header files being rewritten
  144. bool IsHeader;
  145. bool SilenceRewriteMacroWarning;
  146. bool GenerateLineInfo;
  147. bool objc_impl_method;
  148. bool DisableReplaceStmt;
  149. class DisableReplaceStmtScope {
  150. RewriteModernObjC &R;
  151. bool SavedValue;
  152. public:
  153. DisableReplaceStmtScope(RewriteModernObjC &R)
  154. : R(R), SavedValue(R.DisableReplaceStmt) {
  155. R.DisableReplaceStmt = true;
  156. }
  157. ~DisableReplaceStmtScope() {
  158. R.DisableReplaceStmt = SavedValue;
  159. }
  160. };
  161. void InitializeCommon(ASTContext &context);
  162. public:
  163. llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
  164. // Top Level Driver code.
  165. bool HandleTopLevelDecl(DeclGroupRef D) override {
  166. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  167. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
  168. if (!Class->isThisDeclarationADefinition()) {
  169. RewriteForwardClassDecl(D);
  170. break;
  171. } else {
  172. // Keep track of all interface declarations seen.
  173. ObjCInterfacesSeen.push_back(Class);
  174. break;
  175. }
  176. }
  177. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
  178. if (!Proto->isThisDeclarationADefinition()) {
  179. RewriteForwardProtocolDecl(D);
  180. break;
  181. }
  182. }
  183. if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
  184. // Under modern abi, we cannot translate body of the function
  185. // yet until all class extensions and its implementation is seen.
  186. // This is because they may introduce new bitfields which must go
  187. // into their grouping struct.
  188. if (FDecl->isThisDeclarationADefinition() &&
  189. // Not c functions defined inside an objc container.
  190. !FDecl->isTopLevelDeclInObjCContainer()) {
  191. FunctionDefinitionsSeen.push_back(FDecl);
  192. break;
  193. }
  194. }
  195. HandleTopLevelSingleDecl(*I);
  196. }
  197. return true;
  198. }
  199. void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
  200. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  201. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
  202. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  203. RewriteBlockPointerDecl(TD);
  204. else if (TD->getUnderlyingType()->isFunctionPointerType())
  205. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  206. else
  207. RewriteObjCQualifiedInterfaceTypes(TD);
  208. }
  209. }
  210. }
  211. void HandleTopLevelSingleDecl(Decl *D);
  212. void HandleDeclInMainFile(Decl *D);
  213. RewriteModernObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
  214. DiagnosticsEngine &D, const LangOptions &LOpts,
  215. bool silenceMacroWarn, bool LineInfo);
  216. ~RewriteModernObjC() override {}
  217. void HandleTranslationUnit(ASTContext &C) override;
  218. void ReplaceStmt(Stmt *Old, Stmt *New) {
  219. ReplaceStmtWithRange(Old, New, Old->getSourceRange());
  220. }
  221. void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
  222. assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
  223. Stmt *ReplacingStmt = ReplacedNodes[Old];
  224. if (ReplacingStmt)
  225. return; // We can't rewrite the same node twice.
  226. if (DisableReplaceStmt)
  227. return;
  228. // Measure the old text.
  229. int Size = Rewrite.getRangeSize(SrcRange);
  230. if (Size == -1) {
  231. Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
  232. << Old->getSourceRange();
  233. return;
  234. }
  235. // Get the new text.
  236. std::string SStr;
  237. llvm::raw_string_ostream S(SStr);
  238. New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
  239. const std::string &Str = S.str();
  240. // If replacement succeeded or warning disabled return with no warning.
  241. if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
  242. ReplacedNodes[Old] = New;
  243. return;
  244. }
  245. if (SilenceRewriteMacroWarning)
  246. return;
  247. Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
  248. << Old->getSourceRange();
  249. }
  250. void InsertText(SourceLocation Loc, StringRef Str,
  251. bool InsertAfter = true) {
  252. // If insertion succeeded or warning disabled return with no warning.
  253. if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
  254. SilenceRewriteMacroWarning)
  255. return;
  256. Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
  257. }
  258. void ReplaceText(SourceLocation Start, unsigned OrigLength,
  259. StringRef Str) {
  260. // If removal succeeded or warning disabled return with no warning.
  261. if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
  262. SilenceRewriteMacroWarning)
  263. return;
  264. Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
  265. }
  266. // Syntactic Rewriting.
  267. void RewriteRecordBody(RecordDecl *RD);
  268. void RewriteInclude();
  269. void RewriteLineDirective(const Decl *D);
  270. void ConvertSourceLocationToLineDirective(SourceLocation Loc,
  271. std::string &LineString);
  272. void RewriteForwardClassDecl(DeclGroupRef D);
  273. void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
  274. void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
  275. const std::string &typedefString);
  276. void RewriteImplementations();
  277. void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
  278. ObjCImplementationDecl *IMD,
  279. ObjCCategoryImplDecl *CID);
  280. void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
  281. void RewriteImplementationDecl(Decl *Dcl);
  282. void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
  283. ObjCMethodDecl *MDecl, std::string &ResultStr);
  284. void RewriteTypeIntoString(QualType T, std::string &ResultStr,
  285. const FunctionType *&FPRetType);
  286. void RewriteByRefString(std::string &ResultStr, const std::string &Name,
  287. ValueDecl *VD, bool def=false);
  288. void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
  289. void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
  290. void RewriteForwardProtocolDecl(DeclGroupRef D);
  291. void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
  292. void RewriteMethodDeclaration(ObjCMethodDecl *Method);
  293. void RewriteProperty(ObjCPropertyDecl *prop);
  294. void RewriteFunctionDecl(FunctionDecl *FD);
  295. void RewriteBlockPointerType(std::string& Str, QualType Type);
  296. void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
  297. void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
  298. void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
  299. void RewriteTypeOfDecl(VarDecl *VD);
  300. void RewriteObjCQualifiedInterfaceTypes(Expr *E);
  301. std::string getIvarAccessString(ObjCIvarDecl *D);
  302. // Expression Rewriting.
  303. Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
  304. Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
  305. Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
  306. Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
  307. Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
  308. Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
  309. Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
  310. Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
  311. Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
  312. Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
  313. Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
  314. Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
  315. Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
  316. Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
  317. Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
  318. Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
  319. Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
  320. SourceLocation OrigEnd);
  321. Stmt *RewriteBreakStmt(BreakStmt *S);
  322. Stmt *RewriteContinueStmt(ContinueStmt *S);
  323. void RewriteCastExpr(CStyleCastExpr *CE);
  324. void RewriteImplicitCastObjCExpr(CastExpr *IE);
  325. // Computes ivar bitfield group no.
  326. unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
  327. // Names field decl. for ivar bitfield group.
  328. void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
  329. // Names struct type for ivar bitfield group.
  330. void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
  331. // Names symbol for ivar bitfield group field offset.
  332. void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
  333. // Given an ivar bitfield, it builds (or finds) its group record type.
  334. QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
  335. QualType SynthesizeBitfieldGroupStructType(
  336. ObjCIvarDecl *IV,
  337. SmallVectorImpl<ObjCIvarDecl *> &IVars);
  338. // Block rewriting.
  339. void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
  340. // Block specific rewrite rules.
  341. void RewriteBlockPointerDecl(NamedDecl *VD);
  342. void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
  343. Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
  344. Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
  345. void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
  346. void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
  347. std::string &Result);
  348. void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
  349. bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
  350. bool &IsNamedDefinition);
  351. void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
  352. std::string &Result);
  353. bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
  354. void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
  355. std::string &Result);
  356. void Initialize(ASTContext &context) override;
  357. // Misc. AST transformation routines. Sometimes they end up calling
  358. // rewriting routines on the new ASTs.
  359. CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
  360. ArrayRef<Expr *> Args,
  361. SourceLocation StartLoc=SourceLocation(),
  362. SourceLocation EndLoc=SourceLocation());
  363. Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
  364. QualType returnType,
  365. SmallVectorImpl<QualType> &ArgTypes,
  366. SmallVectorImpl<Expr*> &MsgExprs,
  367. ObjCMethodDecl *Method);
  368. Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
  369. SourceLocation StartLoc=SourceLocation(),
  370. SourceLocation EndLoc=SourceLocation());
  371. void SynthCountByEnumWithState(std::string &buf);
  372. void SynthMsgSendFunctionDecl();
  373. void SynthMsgSendSuperFunctionDecl();
  374. void SynthMsgSendStretFunctionDecl();
  375. void SynthMsgSendFpretFunctionDecl();
  376. void SynthMsgSendSuperStretFunctionDecl();
  377. void SynthGetClassFunctionDecl();
  378. void SynthGetMetaClassFunctionDecl();
  379. void SynthGetSuperClassFunctionDecl();
  380. void SynthSelGetUidFunctionDecl();
  381. void SynthSuperConstructorFunctionDecl();
  382. // Rewriting metadata
  383. template<typename MethodIterator>
  384. void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
  385. MethodIterator MethodEnd,
  386. bool IsInstanceMethod,
  387. StringRef prefix,
  388. StringRef ClassName,
  389. std::string &Result);
  390. void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
  391. std::string &Result);
  392. void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  393. std::string &Result);
  394. void RewriteClassSetupInitHook(std::string &Result);
  395. void RewriteMetaDataIntoBuffer(std::string &Result);
  396. void WriteImageInfo(std::string &Result);
  397. void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
  398. std::string &Result);
  399. void RewriteCategorySetupInitHook(std::string &Result);
  400. // Rewriting ivar
  401. void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  402. std::string &Result);
  403. Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
  404. std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
  405. std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
  406. StringRef funcName, std::string Tag);
  407. std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
  408. StringRef funcName, std::string Tag);
  409. std::string SynthesizeBlockImpl(BlockExpr *CE,
  410. std::string Tag, std::string Desc);
  411. std::string SynthesizeBlockDescriptor(std::string DescTag,
  412. std::string ImplTag,
  413. int i, StringRef funcName,
  414. unsigned hasCopy);
  415. Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
  416. void SynthesizeBlockLiterals(SourceLocation FunLocStart,
  417. StringRef FunName);
  418. FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
  419. Stmt *SynthBlockInitExpr(BlockExpr *Exp,
  420. const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
  421. // Misc. helper routines.
  422. QualType getProtocolType();
  423. void WarnAboutReturnGotoStmts(Stmt *S);
  424. void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
  425. void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
  426. void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
  427. bool IsDeclStmtInForeachHeader(DeclStmt *DS);
  428. void CollectBlockDeclRefInfo(BlockExpr *Exp);
  429. void GetBlockDeclRefExprs(Stmt *S);
  430. void GetInnerBlockDeclRefExprs(Stmt *S,
  431. SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
  432. llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
  433. // We avoid calling Type::isBlockPointerType(), since it operates on the
  434. // canonical type. We only care if the top-level type is a closure pointer.
  435. bool isTopLevelBlockPointerType(QualType T) {
  436. return isa<BlockPointerType>(T);
  437. }
  438. /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
  439. /// to a function pointer type and upon success, returns true; false
  440. /// otherwise.
  441. bool convertBlockPointerToFunctionPointer(QualType &T) {
  442. if (isTopLevelBlockPointerType(T)) {
  443. const auto *BPT = T->castAs<BlockPointerType>();
  444. T = Context->getPointerType(BPT->getPointeeType());
  445. return true;
  446. }
  447. return false;
  448. }
  449. bool convertObjCTypeToCStyleType(QualType &T);
  450. bool needToScanForQualifiers(QualType T);
  451. QualType getSuperStructType();
  452. QualType getConstantStringStructType();
  453. QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
  454. void convertToUnqualifiedObjCType(QualType &T) {
  455. if (T->isObjCQualifiedIdType()) {
  456. bool isConst = T.isConstQualified();
  457. T = isConst ? Context->getObjCIdType().withConst()
  458. : Context->getObjCIdType();
  459. }
  460. else if (T->isObjCQualifiedClassType())
  461. T = Context->getObjCClassType();
  462. else if (T->isObjCObjectPointerType() &&
  463. T->getPointeeType()->isObjCQualifiedInterfaceType()) {
  464. if (const ObjCObjectPointerType * OBJPT =
  465. T->getAsObjCInterfacePointerType()) {
  466. const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
  467. T = QualType(IFaceT, 0);
  468. T = Context->getPointerType(T);
  469. }
  470. }
  471. }
  472. // FIXME: This predicate seems like it would be useful to add to ASTContext.
  473. bool isObjCType(QualType T) {
  474. if (!LangOpts.ObjC)
  475. return false;
  476. QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
  477. if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
  478. OCT == Context->getCanonicalType(Context->getObjCClassType()))
  479. return true;
  480. if (const PointerType *PT = OCT->getAs<PointerType>()) {
  481. if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
  482. PT->getPointeeType()->isObjCQualifiedIdType())
  483. return true;
  484. }
  485. return false;
  486. }
  487. bool PointerTypeTakesAnyBlockArguments(QualType QT);
  488. bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
  489. void GetExtentOfArgList(const char *Name, const char *&LParen,
  490. const char *&RParen);
  491. void QuoteDoublequotes(std::string &From, std::string &To) {
  492. for (unsigned i = 0; i < From.length(); i++) {
  493. if (From[i] == '"')
  494. To += "\\\"";
  495. else
  496. To += From[i];
  497. }
  498. }
  499. QualType getSimpleFunctionType(QualType result,
  500. ArrayRef<QualType> args,
  501. bool variadic = false) {
  502. if (result == Context->getObjCInstanceType())
  503. result = Context->getObjCIdType();
  504. FunctionProtoType::ExtProtoInfo fpi;
  505. fpi.Variadic = variadic;
  506. return Context->getFunctionType(result, args, fpi);
  507. }
  508. // Helper function: create a CStyleCastExpr with trivial type source info.
  509. CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
  510. CastKind Kind, Expr *E) {
  511. TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
  512. return CStyleCastExpr::Create(*Ctx, Ty, VK_PRValue, Kind, E, nullptr,
  513. FPOptionsOverride(), TInfo,
  514. SourceLocation(), SourceLocation());
  515. }
  516. bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
  517. IdentifierInfo* II = &Context->Idents.get("load");
  518. Selector LoadSel = Context->Selectors.getSelector(0, &II);
  519. return OD->getClassMethod(LoadSel) != nullptr;
  520. }
  521. StringLiteral *getStringLiteral(StringRef Str) {
  522. QualType StrType = Context->getConstantArrayType(
  523. Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
  524. ArrayType::Normal, 0);
  525. return StringLiteral::Create(*Context, Str, StringLiteral::Ordinary,
  526. /*Pascal=*/false, StrType, SourceLocation());
  527. }
  528. };
  529. } // end anonymous namespace
  530. void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
  531. NamedDecl *D) {
  532. if (const FunctionProtoType *fproto
  533. = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
  534. for (const auto &I : fproto->param_types())
  535. if (isTopLevelBlockPointerType(I)) {
  536. // All the args are checked/rewritten. Don't call twice!
  537. RewriteBlockPointerDecl(D);
  538. break;
  539. }
  540. }
  541. }
  542. void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
  543. const PointerType *PT = funcType->getAs<PointerType>();
  544. if (PT && PointerTypeTakesAnyBlockArguments(funcType))
  545. RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
  546. }
  547. static bool IsHeaderFile(const std::string &Filename) {
  548. std::string::size_type DotPos = Filename.rfind('.');
  549. if (DotPos == std::string::npos) {
  550. // no file extension
  551. return false;
  552. }
  553. std::string Ext = Filename.substr(DotPos + 1);
  554. // C header: .h
  555. // C++ header: .hh or .H;
  556. return Ext == "h" || Ext == "hh" || Ext == "H";
  557. }
  558. RewriteModernObjC::RewriteModernObjC(std::string inFile,
  559. std::unique_ptr<raw_ostream> OS,
  560. DiagnosticsEngine &D,
  561. const LangOptions &LOpts,
  562. bool silenceMacroWarn, bool LineInfo)
  563. : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
  564. SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
  565. IsHeader = IsHeaderFile(inFile);
  566. RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  567. "rewriting sub-expression within a macro (may not be correct)");
  568. // FIXME. This should be an error. But if block is not called, it is OK. And it
  569. // may break including some headers.
  570. GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  571. "rewriting block literal declared in global scope is not implemented");
  572. TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
  573. DiagnosticsEngine::Warning,
  574. "rewriter doesn't support user-specified control flow semantics "
  575. "for @try/@finally (code may not execute properly)");
  576. }
  577. std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
  578. const std::string &InFile, std::unique_ptr<raw_ostream> OS,
  579. DiagnosticsEngine &Diags, const LangOptions &LOpts,
  580. bool SilenceRewriteMacroWarning, bool LineInfo) {
  581. return std::make_unique<RewriteModernObjC>(InFile, std::move(OS), Diags,
  582. LOpts, SilenceRewriteMacroWarning,
  583. LineInfo);
  584. }
  585. void RewriteModernObjC::InitializeCommon(ASTContext &context) {
  586. Context = &context;
  587. SM = &Context->getSourceManager();
  588. TUDecl = Context->getTranslationUnitDecl();
  589. MsgSendFunctionDecl = nullptr;
  590. MsgSendSuperFunctionDecl = nullptr;
  591. MsgSendStretFunctionDecl = nullptr;
  592. MsgSendSuperStretFunctionDecl = nullptr;
  593. MsgSendFpretFunctionDecl = nullptr;
  594. GetClassFunctionDecl = nullptr;
  595. GetMetaClassFunctionDecl = nullptr;
  596. GetSuperClassFunctionDecl = nullptr;
  597. SelGetUidFunctionDecl = nullptr;
  598. CFStringFunctionDecl = nullptr;
  599. ConstantStringClassReference = nullptr;
  600. NSStringRecord = nullptr;
  601. CurMethodDef = nullptr;
  602. CurFunctionDef = nullptr;
  603. GlobalVarDecl = nullptr;
  604. GlobalConstructionExp = nullptr;
  605. SuperStructDecl = nullptr;
  606. ProtocolTypeDecl = nullptr;
  607. ConstantStringDecl = nullptr;
  608. BcLabelCount = 0;
  609. SuperConstructorFunctionDecl = nullptr;
  610. NumObjCStringLiterals = 0;
  611. PropParentMap = nullptr;
  612. CurrentBody = nullptr;
  613. DisableReplaceStmt = false;
  614. objc_impl_method = false;
  615. // Get the ID and start/end of the main file.
  616. MainFileID = SM->getMainFileID();
  617. llvm::MemoryBufferRef MainBuf = SM->getBufferOrFake(MainFileID);
  618. MainFileStart = MainBuf.getBufferStart();
  619. MainFileEnd = MainBuf.getBufferEnd();
  620. Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
  621. }
  622. //===----------------------------------------------------------------------===//
  623. // Top Level Driver Code
  624. //===----------------------------------------------------------------------===//
  625. void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
  626. if (Diags.hasErrorOccurred())
  627. return;
  628. // Two cases: either the decl could be in the main file, or it could be in a
  629. // #included file. If the former, rewrite it now. If the later, check to see
  630. // if we rewrote the #include/#import.
  631. SourceLocation Loc = D->getLocation();
  632. Loc = SM->getExpansionLoc(Loc);
  633. // If this is for a builtin, ignore it.
  634. if (Loc.isInvalid()) return;
  635. // Look for built-in declarations that we need to refer during the rewrite.
  636. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  637. RewriteFunctionDecl(FD);
  638. } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
  639. // declared in <Foundation/NSString.h>
  640. if (FVD->getName() == "_NSConstantStringClassReference") {
  641. ConstantStringClassReference = FVD;
  642. return;
  643. }
  644. } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  645. RewriteCategoryDecl(CD);
  646. } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
  647. if (PD->isThisDeclarationADefinition())
  648. RewriteProtocolDecl(PD);
  649. } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
  650. // Recurse into linkage specifications
  651. for (DeclContext::decl_iterator DI = LSD->decls_begin(),
  652. DIEnd = LSD->decls_end();
  653. DI != DIEnd; ) {
  654. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
  655. if (!IFace->isThisDeclarationADefinition()) {
  656. SmallVector<Decl *, 8> DG;
  657. SourceLocation StartLoc = IFace->getBeginLoc();
  658. do {
  659. if (isa<ObjCInterfaceDecl>(*DI) &&
  660. !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
  661. StartLoc == (*DI)->getBeginLoc())
  662. DG.push_back(*DI);
  663. else
  664. break;
  665. ++DI;
  666. } while (DI != DIEnd);
  667. RewriteForwardClassDecl(DG);
  668. continue;
  669. }
  670. else {
  671. // Keep track of all interface declarations seen.
  672. ObjCInterfacesSeen.push_back(IFace);
  673. ++DI;
  674. continue;
  675. }
  676. }
  677. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
  678. if (!Proto->isThisDeclarationADefinition()) {
  679. SmallVector<Decl *, 8> DG;
  680. SourceLocation StartLoc = Proto->getBeginLoc();
  681. do {
  682. if (isa<ObjCProtocolDecl>(*DI) &&
  683. !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
  684. StartLoc == (*DI)->getBeginLoc())
  685. DG.push_back(*DI);
  686. else
  687. break;
  688. ++DI;
  689. } while (DI != DIEnd);
  690. RewriteForwardProtocolDecl(DG);
  691. continue;
  692. }
  693. }
  694. HandleTopLevelSingleDecl(*DI);
  695. ++DI;
  696. }
  697. }
  698. // If we have a decl in the main file, see if we should rewrite it.
  699. if (SM->isWrittenInMainFile(Loc))
  700. return HandleDeclInMainFile(D);
  701. }
  702. //===----------------------------------------------------------------------===//
  703. // Syntactic (non-AST) Rewriting Code
  704. //===----------------------------------------------------------------------===//
  705. void RewriteModernObjC::RewriteInclude() {
  706. SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
  707. StringRef MainBuf = SM->getBufferData(MainFileID);
  708. const char *MainBufStart = MainBuf.begin();
  709. const char *MainBufEnd = MainBuf.end();
  710. size_t ImportLen = strlen("import");
  711. // Loop over the whole file, looking for includes.
  712. for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
  713. if (*BufPtr == '#') {
  714. if (++BufPtr == MainBufEnd)
  715. return;
  716. while (*BufPtr == ' ' || *BufPtr == '\t')
  717. if (++BufPtr == MainBufEnd)
  718. return;
  719. if (!strncmp(BufPtr, "import", ImportLen)) {
  720. // replace import with include
  721. SourceLocation ImportLoc =
  722. LocStart.getLocWithOffset(BufPtr-MainBufStart);
  723. ReplaceText(ImportLoc, ImportLen, "include");
  724. BufPtr += ImportLen;
  725. }
  726. }
  727. }
  728. }
  729. static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
  730. ObjCIvarDecl *IvarDecl, std::string &Result) {
  731. Result += "OBJC_IVAR_$_";
  732. Result += IDecl->getName();
  733. Result += "$";
  734. Result += IvarDecl->getName();
  735. }
  736. std::string
  737. RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
  738. const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
  739. // Build name of symbol holding ivar offset.
  740. std::string IvarOffsetName;
  741. if (D->isBitField())
  742. ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
  743. else
  744. WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
  745. std::string S = "(*(";
  746. QualType IvarT = D->getType();
  747. if (D->isBitField())
  748. IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
  749. if (!IvarT->getAs<TypedefType>() && IvarT->isRecordType()) {
  750. RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
  751. RD = RD->getDefinition();
  752. if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
  753. // decltype(((Foo_IMPL*)0)->bar) *
  754. auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
  755. // ivar in class extensions requires special treatment.
  756. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
  757. CDecl = CatDecl->getClassInterface();
  758. std::string RecName = std::string(CDecl->getName());
  759. RecName += "_IMPL";
  760. RecordDecl *RD =
  761. RecordDecl::Create(*Context, TTK_Struct, TUDecl, SourceLocation(),
  762. SourceLocation(), &Context->Idents.get(RecName));
  763. QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
  764. unsigned UnsignedIntSize =
  765. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  766. Expr *Zero = IntegerLiteral::Create(*Context,
  767. llvm::APInt(UnsignedIntSize, 0),
  768. Context->UnsignedIntTy, SourceLocation());
  769. Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
  770. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  771. Zero);
  772. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  773. SourceLocation(),
  774. &Context->Idents.get(D->getNameAsString()),
  775. IvarT, nullptr,
  776. /*BitWidth=*/nullptr, /*Mutable=*/true,
  777. ICIS_NoInit);
  778. MemberExpr *ME = MemberExpr::CreateImplicit(
  779. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  780. IvarT = Context->getDecltypeType(ME, ME->getType());
  781. }
  782. }
  783. convertObjCTypeToCStyleType(IvarT);
  784. QualType castT = Context->getPointerType(IvarT);
  785. std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
  786. S += TypeString;
  787. S += ")";
  788. // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
  789. S += "((char *)self + ";
  790. S += IvarOffsetName;
  791. S += "))";
  792. if (D->isBitField()) {
  793. S += ".";
  794. S += D->getNameAsString();
  795. }
  796. ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
  797. return S;
  798. }
  799. /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
  800. /// been found in the class implementation. In this case, it must be synthesized.
  801. static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
  802. ObjCPropertyDecl *PD,
  803. bool getter) {
  804. auto *OMD = IMP->getInstanceMethod(getter ? PD->getGetterName()
  805. : PD->getSetterName());
  806. return !OMD || OMD->isSynthesizedAccessorStub();
  807. }
  808. void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
  809. ObjCImplementationDecl *IMD,
  810. ObjCCategoryImplDecl *CID) {
  811. static bool objcGetPropertyDefined = false;
  812. static bool objcSetPropertyDefined = false;
  813. SourceLocation startGetterSetterLoc;
  814. if (PID->getBeginLoc().isValid()) {
  815. SourceLocation startLoc = PID->getBeginLoc();
  816. InsertText(startLoc, "// ");
  817. const char *startBuf = SM->getCharacterData(startLoc);
  818. assert((*startBuf == '@') && "bogus @synthesize location");
  819. const char *semiBuf = strchr(startBuf, ';');
  820. assert((*semiBuf == ';') && "@synthesize: can't find ';'");
  821. startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
  822. } else
  823. startGetterSetterLoc = IMD ? IMD->getEndLoc() : CID->getEndLoc();
  824. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  825. return; // FIXME: is this correct?
  826. // Generate the 'getter' function.
  827. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  828. ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
  829. assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
  830. unsigned Attributes = PD->getPropertyAttributes();
  831. if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
  832. bool GenGetProperty =
  833. !(Attributes & ObjCPropertyAttribute::kind_nonatomic) &&
  834. (Attributes & (ObjCPropertyAttribute::kind_retain |
  835. ObjCPropertyAttribute::kind_copy));
  836. std::string Getr;
  837. if (GenGetProperty && !objcGetPropertyDefined) {
  838. objcGetPropertyDefined = true;
  839. // FIXME. Is this attribute correct in all cases?
  840. Getr = "\nextern \"C\" __declspec(dllimport) "
  841. "id objc_getProperty(id, SEL, long, bool);\n";
  842. }
  843. RewriteObjCMethodDecl(OID->getContainingInterface(),
  844. PID->getGetterMethodDecl(), Getr);
  845. Getr += "{ ";
  846. // Synthesize an explicit cast to gain access to the ivar.
  847. // See objc-act.c:objc_synthesize_new_getter() for details.
  848. if (GenGetProperty) {
  849. // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
  850. Getr += "typedef ";
  851. const FunctionType *FPRetType = nullptr;
  852. RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
  853. FPRetType);
  854. Getr += " _TYPE";
  855. if (FPRetType) {
  856. Getr += ")"; // close the precedence "scope" for "*".
  857. // Now, emit the argument types (if any).
  858. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
  859. Getr += "(";
  860. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  861. if (i) Getr += ", ";
  862. std::string ParamStr =
  863. FT->getParamType(i).getAsString(Context->getPrintingPolicy());
  864. Getr += ParamStr;
  865. }
  866. if (FT->isVariadic()) {
  867. if (FT->getNumParams())
  868. Getr += ", ";
  869. Getr += "...";
  870. }
  871. Getr += ")";
  872. } else
  873. Getr += "()";
  874. }
  875. Getr += ";\n";
  876. Getr += "return (_TYPE)";
  877. Getr += "objc_getProperty(self, _cmd, ";
  878. RewriteIvarOffsetComputation(OID, Getr);
  879. Getr += ", 1)";
  880. }
  881. else
  882. Getr += "return " + getIvarAccessString(OID);
  883. Getr += "; }";
  884. InsertText(startGetterSetterLoc, Getr);
  885. }
  886. if (PD->isReadOnly() ||
  887. !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
  888. return;
  889. // Generate the 'setter' function.
  890. std::string Setr;
  891. bool GenSetProperty = Attributes & (ObjCPropertyAttribute::kind_retain |
  892. ObjCPropertyAttribute::kind_copy);
  893. if (GenSetProperty && !objcSetPropertyDefined) {
  894. objcSetPropertyDefined = true;
  895. // FIXME. Is this attribute correct in all cases?
  896. Setr = "\nextern \"C\" __declspec(dllimport) "
  897. "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
  898. }
  899. RewriteObjCMethodDecl(OID->getContainingInterface(),
  900. PID->getSetterMethodDecl(), Setr);
  901. Setr += "{ ";
  902. // Synthesize an explicit cast to initialize the ivar.
  903. // See objc-act.c:objc_synthesize_new_setter() for details.
  904. if (GenSetProperty) {
  905. Setr += "objc_setProperty (self, _cmd, ";
  906. RewriteIvarOffsetComputation(OID, Setr);
  907. Setr += ", (id)";
  908. Setr += PD->getName();
  909. Setr += ", ";
  910. if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
  911. Setr += "0, ";
  912. else
  913. Setr += "1, ";
  914. if (Attributes & ObjCPropertyAttribute::kind_copy)
  915. Setr += "1)";
  916. else
  917. Setr += "0)";
  918. }
  919. else {
  920. Setr += getIvarAccessString(OID) + " = ";
  921. Setr += PD->getName();
  922. }
  923. Setr += "; }\n";
  924. InsertText(startGetterSetterLoc, Setr);
  925. }
  926. static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
  927. std::string &typedefString) {
  928. typedefString += "\n#ifndef _REWRITER_typedef_";
  929. typedefString += ForwardDecl->getNameAsString();
  930. typedefString += "\n";
  931. typedefString += "#define _REWRITER_typedef_";
  932. typedefString += ForwardDecl->getNameAsString();
  933. typedefString += "\n";
  934. typedefString += "typedef struct objc_object ";
  935. typedefString += ForwardDecl->getNameAsString();
  936. // typedef struct { } _objc_exc_Classname;
  937. typedefString += ";\ntypedef struct {} _objc_exc_";
  938. typedefString += ForwardDecl->getNameAsString();
  939. typedefString += ";\n#endif\n";
  940. }
  941. void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
  942. const std::string &typedefString) {
  943. SourceLocation startLoc = ClassDecl->getBeginLoc();
  944. const char *startBuf = SM->getCharacterData(startLoc);
  945. const char *semiPtr = strchr(startBuf, ';');
  946. // Replace the @class with typedefs corresponding to the classes.
  947. ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
  948. }
  949. void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
  950. std::string typedefString;
  951. for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
  952. if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
  953. if (I == D.begin()) {
  954. // Translate to typedef's that forward reference structs with the same name
  955. // as the class. As a convenience, we include the original declaration
  956. // as a comment.
  957. typedefString += "// @class ";
  958. typedefString += ForwardDecl->getNameAsString();
  959. typedefString += ";";
  960. }
  961. RewriteOneForwardClassDecl(ForwardDecl, typedefString);
  962. }
  963. else
  964. HandleTopLevelSingleDecl(*I);
  965. }
  966. DeclGroupRef::iterator I = D.begin();
  967. RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
  968. }
  969. void RewriteModernObjC::RewriteForwardClassDecl(
  970. const SmallVectorImpl<Decl *> &D) {
  971. std::string typedefString;
  972. for (unsigned i = 0; i < D.size(); i++) {
  973. ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
  974. if (i == 0) {
  975. typedefString += "// @class ";
  976. typedefString += ForwardDecl->getNameAsString();
  977. typedefString += ";";
  978. }
  979. RewriteOneForwardClassDecl(ForwardDecl, typedefString);
  980. }
  981. RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
  982. }
  983. void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
  984. // When method is a synthesized one, such as a getter/setter there is
  985. // nothing to rewrite.
  986. if (Method->isImplicit())
  987. return;
  988. SourceLocation LocStart = Method->getBeginLoc();
  989. SourceLocation LocEnd = Method->getEndLoc();
  990. if (SM->getExpansionLineNumber(LocEnd) >
  991. SM->getExpansionLineNumber(LocStart)) {
  992. InsertText(LocStart, "#if 0\n");
  993. ReplaceText(LocEnd, 1, ";\n#endif\n");
  994. } else {
  995. InsertText(LocStart, "// ");
  996. }
  997. }
  998. void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
  999. SourceLocation Loc = prop->getAtLoc();
  1000. ReplaceText(Loc, 0, "// ");
  1001. // FIXME: handle properties that are declared across multiple lines.
  1002. }
  1003. void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
  1004. SourceLocation LocStart = CatDecl->getBeginLoc();
  1005. // FIXME: handle category headers that are declared across multiple lines.
  1006. if (CatDecl->getIvarRBraceLoc().isValid()) {
  1007. ReplaceText(LocStart, 1, "/** ");
  1008. ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
  1009. }
  1010. else {
  1011. ReplaceText(LocStart, 0, "// ");
  1012. }
  1013. for (auto *I : CatDecl->instance_properties())
  1014. RewriteProperty(I);
  1015. for (auto *I : CatDecl->instance_methods())
  1016. RewriteMethodDeclaration(I);
  1017. for (auto *I : CatDecl->class_methods())
  1018. RewriteMethodDeclaration(I);
  1019. // Lastly, comment out the @end.
  1020. ReplaceText(CatDecl->getAtEndRange().getBegin(),
  1021. strlen("@end"), "/* @end */\n");
  1022. }
  1023. void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
  1024. SourceLocation LocStart = PDecl->getBeginLoc();
  1025. assert(PDecl->isThisDeclarationADefinition());
  1026. // FIXME: handle protocol headers that are declared across multiple lines.
  1027. ReplaceText(LocStart, 0, "// ");
  1028. for (auto *I : PDecl->instance_methods())
  1029. RewriteMethodDeclaration(I);
  1030. for (auto *I : PDecl->class_methods())
  1031. RewriteMethodDeclaration(I);
  1032. for (auto *I : PDecl->instance_properties())
  1033. RewriteProperty(I);
  1034. // Lastly, comment out the @end.
  1035. SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
  1036. ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
  1037. // Must comment out @optional/@required
  1038. const char *startBuf = SM->getCharacterData(LocStart);
  1039. const char *endBuf = SM->getCharacterData(LocEnd);
  1040. for (const char *p = startBuf; p < endBuf; p++) {
  1041. if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
  1042. SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
  1043. ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
  1044. }
  1045. else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
  1046. SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
  1047. ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
  1048. }
  1049. }
  1050. }
  1051. void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
  1052. SourceLocation LocStart = (*D.begin())->getBeginLoc();
  1053. if (LocStart.isInvalid())
  1054. llvm_unreachable("Invalid SourceLocation");
  1055. // FIXME: handle forward protocol that are declared across multiple lines.
  1056. ReplaceText(LocStart, 0, "// ");
  1057. }
  1058. void
  1059. RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
  1060. SourceLocation LocStart = DG[0]->getBeginLoc();
  1061. if (LocStart.isInvalid())
  1062. llvm_unreachable("Invalid SourceLocation");
  1063. // FIXME: handle forward protocol that are declared across multiple lines.
  1064. ReplaceText(LocStart, 0, "// ");
  1065. }
  1066. void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
  1067. const FunctionType *&FPRetType) {
  1068. if (T->isObjCQualifiedIdType())
  1069. ResultStr += "id";
  1070. else if (T->isFunctionPointerType() ||
  1071. T->isBlockPointerType()) {
  1072. // needs special handling, since pointer-to-functions have special
  1073. // syntax (where a decaration models use).
  1074. QualType retType = T;
  1075. QualType PointeeTy;
  1076. if (const PointerType* PT = retType->getAs<PointerType>())
  1077. PointeeTy = PT->getPointeeType();
  1078. else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
  1079. PointeeTy = BPT->getPointeeType();
  1080. if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
  1081. ResultStr +=
  1082. FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
  1083. ResultStr += "(*";
  1084. }
  1085. } else
  1086. ResultStr += T.getAsString(Context->getPrintingPolicy());
  1087. }
  1088. void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
  1089. ObjCMethodDecl *OMD,
  1090. std::string &ResultStr) {
  1091. //fprintf(stderr,"In RewriteObjCMethodDecl\n");
  1092. const FunctionType *FPRetType = nullptr;
  1093. ResultStr += "\nstatic ";
  1094. RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
  1095. ResultStr += " ";
  1096. // Unique method name
  1097. std::string NameStr;
  1098. if (OMD->isInstanceMethod())
  1099. NameStr += "_I_";
  1100. else
  1101. NameStr += "_C_";
  1102. NameStr += IDecl->getNameAsString();
  1103. NameStr += "_";
  1104. if (ObjCCategoryImplDecl *CID =
  1105. dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
  1106. NameStr += CID->getNameAsString();
  1107. NameStr += "_";
  1108. }
  1109. // Append selector names, replacing ':' with '_'
  1110. {
  1111. std::string selString = OMD->getSelector().getAsString();
  1112. int len = selString.size();
  1113. for (int i = 0; i < len; i++)
  1114. if (selString[i] == ':')
  1115. selString[i] = '_';
  1116. NameStr += selString;
  1117. }
  1118. // Remember this name for metadata emission
  1119. MethodInternalNames[OMD] = NameStr;
  1120. ResultStr += NameStr;
  1121. // Rewrite arguments
  1122. ResultStr += "(";
  1123. // invisible arguments
  1124. if (OMD->isInstanceMethod()) {
  1125. QualType selfTy = Context->getObjCInterfaceType(IDecl);
  1126. selfTy = Context->getPointerType(selfTy);
  1127. if (!LangOpts.MicrosoftExt) {
  1128. if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
  1129. ResultStr += "struct ";
  1130. }
  1131. // When rewriting for Microsoft, explicitly omit the structure name.
  1132. ResultStr += IDecl->getNameAsString();
  1133. ResultStr += " *";
  1134. }
  1135. else
  1136. ResultStr += Context->getObjCClassType().getAsString(
  1137. Context->getPrintingPolicy());
  1138. ResultStr += " self, ";
  1139. ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
  1140. ResultStr += " _cmd";
  1141. // Method arguments.
  1142. for (const auto *PDecl : OMD->parameters()) {
  1143. ResultStr += ", ";
  1144. if (PDecl->getType()->isObjCQualifiedIdType()) {
  1145. ResultStr += "id ";
  1146. ResultStr += PDecl->getNameAsString();
  1147. } else {
  1148. std::string Name = PDecl->getNameAsString();
  1149. QualType QT = PDecl->getType();
  1150. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  1151. (void)convertBlockPointerToFunctionPointer(QT);
  1152. QT.getAsStringInternal(Name, Context->getPrintingPolicy());
  1153. ResultStr += Name;
  1154. }
  1155. }
  1156. if (OMD->isVariadic())
  1157. ResultStr += ", ...";
  1158. ResultStr += ") ";
  1159. if (FPRetType) {
  1160. ResultStr += ")"; // close the precedence "scope" for "*".
  1161. // Now, emit the argument types (if any).
  1162. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
  1163. ResultStr += "(";
  1164. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1165. if (i) ResultStr += ", ";
  1166. std::string ParamStr =
  1167. FT->getParamType(i).getAsString(Context->getPrintingPolicy());
  1168. ResultStr += ParamStr;
  1169. }
  1170. if (FT->isVariadic()) {
  1171. if (FT->getNumParams())
  1172. ResultStr += ", ";
  1173. ResultStr += "...";
  1174. }
  1175. ResultStr += ")";
  1176. } else {
  1177. ResultStr += "()";
  1178. }
  1179. }
  1180. }
  1181. void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
  1182. ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
  1183. ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
  1184. assert((IMD || CID) && "Unknown implementation type");
  1185. if (IMD) {
  1186. if (IMD->getIvarRBraceLoc().isValid()) {
  1187. ReplaceText(IMD->getBeginLoc(), 1, "/** ");
  1188. ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
  1189. }
  1190. else {
  1191. InsertText(IMD->getBeginLoc(), "// ");
  1192. }
  1193. }
  1194. else
  1195. InsertText(CID->getBeginLoc(), "// ");
  1196. for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
  1197. if (!OMD->getBody())
  1198. continue;
  1199. std::string ResultStr;
  1200. RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
  1201. SourceLocation LocStart = OMD->getBeginLoc();
  1202. SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
  1203. const char *startBuf = SM->getCharacterData(LocStart);
  1204. const char *endBuf = SM->getCharacterData(LocEnd);
  1205. ReplaceText(LocStart, endBuf-startBuf, ResultStr);
  1206. }
  1207. for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
  1208. if (!OMD->getBody())
  1209. continue;
  1210. std::string ResultStr;
  1211. RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
  1212. SourceLocation LocStart = OMD->getBeginLoc();
  1213. SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
  1214. const char *startBuf = SM->getCharacterData(LocStart);
  1215. const char *endBuf = SM->getCharacterData(LocEnd);
  1216. ReplaceText(LocStart, endBuf-startBuf, ResultStr);
  1217. }
  1218. for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
  1219. RewritePropertyImplDecl(I, IMD, CID);
  1220. InsertText(IMD ? IMD->getEndLoc() : CID->getEndLoc(), "// ");
  1221. }
  1222. void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
  1223. // Do not synthesize more than once.
  1224. if (ObjCSynthesizedStructs.count(ClassDecl))
  1225. return;
  1226. // Make sure super class's are written before current class is written.
  1227. ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
  1228. while (SuperClass) {
  1229. RewriteInterfaceDecl(SuperClass);
  1230. SuperClass = SuperClass->getSuperClass();
  1231. }
  1232. std::string ResultStr;
  1233. if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
  1234. // we haven't seen a forward decl - generate a typedef.
  1235. RewriteOneForwardClassDecl(ClassDecl, ResultStr);
  1236. RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
  1237. RewriteObjCInternalStruct(ClassDecl, ResultStr);
  1238. // Mark this typedef as having been written into its c++ equivalent.
  1239. ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
  1240. for (auto *I : ClassDecl->instance_properties())
  1241. RewriteProperty(I);
  1242. for (auto *I : ClassDecl->instance_methods())
  1243. RewriteMethodDeclaration(I);
  1244. for (auto *I : ClassDecl->class_methods())
  1245. RewriteMethodDeclaration(I);
  1246. // Lastly, comment out the @end.
  1247. ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
  1248. "/* @end */\n");
  1249. }
  1250. }
  1251. Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
  1252. SourceRange OldRange = PseudoOp->getSourceRange();
  1253. // We just magically know some things about the structure of this
  1254. // expression.
  1255. ObjCMessageExpr *OldMsg =
  1256. cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
  1257. PseudoOp->getNumSemanticExprs() - 1));
  1258. // Because the rewriter doesn't allow us to rewrite rewritten code,
  1259. // we need to suppress rewriting the sub-statements.
  1260. Expr *Base;
  1261. SmallVector<Expr*, 2> Args;
  1262. {
  1263. DisableReplaceStmtScope S(*this);
  1264. // Rebuild the base expression if we have one.
  1265. Base = nullptr;
  1266. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
  1267. Base = OldMsg->getInstanceReceiver();
  1268. Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
  1269. Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
  1270. }
  1271. unsigned numArgs = OldMsg->getNumArgs();
  1272. for (unsigned i = 0; i < numArgs; i++) {
  1273. Expr *Arg = OldMsg->getArg(i);
  1274. if (isa<OpaqueValueExpr>(Arg))
  1275. Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
  1276. Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
  1277. Args.push_back(Arg);
  1278. }
  1279. }
  1280. // TODO: avoid this copy.
  1281. SmallVector<SourceLocation, 1> SelLocs;
  1282. OldMsg->getSelectorLocs(SelLocs);
  1283. ObjCMessageExpr *NewMsg = nullptr;
  1284. switch (OldMsg->getReceiverKind()) {
  1285. case ObjCMessageExpr::Class:
  1286. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1287. OldMsg->getValueKind(),
  1288. OldMsg->getLeftLoc(),
  1289. OldMsg->getClassReceiverTypeInfo(),
  1290. OldMsg->getSelector(),
  1291. SelLocs,
  1292. OldMsg->getMethodDecl(),
  1293. Args,
  1294. OldMsg->getRightLoc(),
  1295. OldMsg->isImplicit());
  1296. break;
  1297. case ObjCMessageExpr::Instance:
  1298. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1299. OldMsg->getValueKind(),
  1300. OldMsg->getLeftLoc(),
  1301. Base,
  1302. OldMsg->getSelector(),
  1303. SelLocs,
  1304. OldMsg->getMethodDecl(),
  1305. Args,
  1306. OldMsg->getRightLoc(),
  1307. OldMsg->isImplicit());
  1308. break;
  1309. case ObjCMessageExpr::SuperClass:
  1310. case ObjCMessageExpr::SuperInstance:
  1311. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1312. OldMsg->getValueKind(),
  1313. OldMsg->getLeftLoc(),
  1314. OldMsg->getSuperLoc(),
  1315. OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
  1316. OldMsg->getSuperType(),
  1317. OldMsg->getSelector(),
  1318. SelLocs,
  1319. OldMsg->getMethodDecl(),
  1320. Args,
  1321. OldMsg->getRightLoc(),
  1322. OldMsg->isImplicit());
  1323. break;
  1324. }
  1325. Stmt *Replacement = SynthMessageExpr(NewMsg);
  1326. ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
  1327. return Replacement;
  1328. }
  1329. Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
  1330. SourceRange OldRange = PseudoOp->getSourceRange();
  1331. // We just magically know some things about the structure of this
  1332. // expression.
  1333. ObjCMessageExpr *OldMsg =
  1334. cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
  1335. // Because the rewriter doesn't allow us to rewrite rewritten code,
  1336. // we need to suppress rewriting the sub-statements.
  1337. Expr *Base = nullptr;
  1338. SmallVector<Expr*, 1> Args;
  1339. {
  1340. DisableReplaceStmtScope S(*this);
  1341. // Rebuild the base expression if we have one.
  1342. if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
  1343. Base = OldMsg->getInstanceReceiver();
  1344. Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
  1345. Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
  1346. }
  1347. unsigned numArgs = OldMsg->getNumArgs();
  1348. for (unsigned i = 0; i < numArgs; i++) {
  1349. Expr *Arg = OldMsg->getArg(i);
  1350. if (isa<OpaqueValueExpr>(Arg))
  1351. Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
  1352. Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
  1353. Args.push_back(Arg);
  1354. }
  1355. }
  1356. // Intentionally empty.
  1357. SmallVector<SourceLocation, 1> SelLocs;
  1358. ObjCMessageExpr *NewMsg = nullptr;
  1359. switch (OldMsg->getReceiverKind()) {
  1360. case ObjCMessageExpr::Class:
  1361. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1362. OldMsg->getValueKind(),
  1363. OldMsg->getLeftLoc(),
  1364. OldMsg->getClassReceiverTypeInfo(),
  1365. OldMsg->getSelector(),
  1366. SelLocs,
  1367. OldMsg->getMethodDecl(),
  1368. Args,
  1369. OldMsg->getRightLoc(),
  1370. OldMsg->isImplicit());
  1371. break;
  1372. case ObjCMessageExpr::Instance:
  1373. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1374. OldMsg->getValueKind(),
  1375. OldMsg->getLeftLoc(),
  1376. Base,
  1377. OldMsg->getSelector(),
  1378. SelLocs,
  1379. OldMsg->getMethodDecl(),
  1380. Args,
  1381. OldMsg->getRightLoc(),
  1382. OldMsg->isImplicit());
  1383. break;
  1384. case ObjCMessageExpr::SuperClass:
  1385. case ObjCMessageExpr::SuperInstance:
  1386. NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
  1387. OldMsg->getValueKind(),
  1388. OldMsg->getLeftLoc(),
  1389. OldMsg->getSuperLoc(),
  1390. OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
  1391. OldMsg->getSuperType(),
  1392. OldMsg->getSelector(),
  1393. SelLocs,
  1394. OldMsg->getMethodDecl(),
  1395. Args,
  1396. OldMsg->getRightLoc(),
  1397. OldMsg->isImplicit());
  1398. break;
  1399. }
  1400. Stmt *Replacement = SynthMessageExpr(NewMsg);
  1401. ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
  1402. return Replacement;
  1403. }
  1404. /// SynthCountByEnumWithState - To print:
  1405. /// ((NSUInteger (*)
  1406. /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
  1407. /// (void *)objc_msgSend)((id)l_collection,
  1408. /// sel_registerName(
  1409. /// "countByEnumeratingWithState:objects:count:"),
  1410. /// &enumState,
  1411. /// (id *)__rw_items, (NSUInteger)16)
  1412. ///
  1413. void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
  1414. buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
  1415. "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
  1416. buf += "\n\t\t";
  1417. buf += "((id)l_collection,\n\t\t";
  1418. buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
  1419. buf += "\n\t\t";
  1420. buf += "&enumState, "
  1421. "(id *)__rw_items, (_WIN_NSUInteger)16)";
  1422. }
  1423. /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
  1424. /// statement to exit to its outer synthesized loop.
  1425. ///
  1426. Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
  1427. if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
  1428. return S;
  1429. // replace break with goto __break_label
  1430. std::string buf;
  1431. SourceLocation startLoc = S->getBeginLoc();
  1432. buf = "goto __break_label_";
  1433. buf += utostr(ObjCBcLabelNo.back());
  1434. ReplaceText(startLoc, strlen("break"), buf);
  1435. return nullptr;
  1436. }
  1437. void RewriteModernObjC::ConvertSourceLocationToLineDirective(
  1438. SourceLocation Loc,
  1439. std::string &LineString) {
  1440. if (Loc.isFileID() && GenerateLineInfo) {
  1441. LineString += "\n#line ";
  1442. PresumedLoc PLoc = SM->getPresumedLoc(Loc);
  1443. LineString += utostr(PLoc.getLine());
  1444. LineString += " \"";
  1445. LineString += Lexer::Stringify(PLoc.getFilename());
  1446. LineString += "\"\n";
  1447. }
  1448. }
  1449. /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
  1450. /// statement to continue with its inner synthesized loop.
  1451. ///
  1452. Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
  1453. if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
  1454. return S;
  1455. // replace continue with goto __continue_label
  1456. std::string buf;
  1457. SourceLocation startLoc = S->getBeginLoc();
  1458. buf = "goto __continue_label_";
  1459. buf += utostr(ObjCBcLabelNo.back());
  1460. ReplaceText(startLoc, strlen("continue"), buf);
  1461. return nullptr;
  1462. }
  1463. /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
  1464. /// It rewrites:
  1465. /// for ( type elem in collection) { stmts; }
  1466. /// Into:
  1467. /// {
  1468. /// type elem;
  1469. /// struct __objcFastEnumerationState enumState = { 0 };
  1470. /// id __rw_items[16];
  1471. /// id l_collection = (id)collection;
  1472. /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
  1473. /// objects:__rw_items count:16];
  1474. /// if (limit) {
  1475. /// unsigned long startMutations = *enumState.mutationsPtr;
  1476. /// do {
  1477. /// unsigned long counter = 0;
  1478. /// do {
  1479. /// if (startMutations != *enumState.mutationsPtr)
  1480. /// objc_enumerationMutation(l_collection);
  1481. /// elem = (type)enumState.itemsPtr[counter++];
  1482. /// stmts;
  1483. /// __continue_label: ;
  1484. /// } while (counter < limit);
  1485. /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
  1486. /// objects:__rw_items count:16]));
  1487. /// elem = nil;
  1488. /// __break_label: ;
  1489. /// }
  1490. /// else
  1491. /// elem = nil;
  1492. /// }
  1493. ///
  1494. Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
  1495. SourceLocation OrigEnd) {
  1496. assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
  1497. assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
  1498. "ObjCForCollectionStmt Statement stack mismatch");
  1499. assert(!ObjCBcLabelNo.empty() &&
  1500. "ObjCForCollectionStmt - Label No stack empty");
  1501. SourceLocation startLoc = S->getBeginLoc();
  1502. const char *startBuf = SM->getCharacterData(startLoc);
  1503. StringRef elementName;
  1504. std::string elementTypeAsString;
  1505. std::string buf;
  1506. // line directive first.
  1507. SourceLocation ForEachLoc = S->getForLoc();
  1508. ConvertSourceLocationToLineDirective(ForEachLoc, buf);
  1509. buf += "{\n\t";
  1510. if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
  1511. // type elem;
  1512. NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
  1513. QualType ElementType = cast<ValueDecl>(D)->getType();
  1514. if (ElementType->isObjCQualifiedIdType() ||
  1515. ElementType->isObjCQualifiedInterfaceType())
  1516. // Simply use 'id' for all qualified types.
  1517. elementTypeAsString = "id";
  1518. else
  1519. elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
  1520. buf += elementTypeAsString;
  1521. buf += " ";
  1522. elementName = D->getName();
  1523. buf += elementName;
  1524. buf += ";\n\t";
  1525. }
  1526. else {
  1527. DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
  1528. elementName = DR->getDecl()->getName();
  1529. ValueDecl *VD = DR->getDecl();
  1530. if (VD->getType()->isObjCQualifiedIdType() ||
  1531. VD->getType()->isObjCQualifiedInterfaceType())
  1532. // Simply use 'id' for all qualified types.
  1533. elementTypeAsString = "id";
  1534. else
  1535. elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
  1536. }
  1537. // struct __objcFastEnumerationState enumState = { 0 };
  1538. buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
  1539. // id __rw_items[16];
  1540. buf += "id __rw_items[16];\n\t";
  1541. // id l_collection = (id)
  1542. buf += "id l_collection = (id)";
  1543. // Find start location of 'collection' the hard way!
  1544. const char *startCollectionBuf = startBuf;
  1545. startCollectionBuf += 3; // skip 'for'
  1546. startCollectionBuf = strchr(startCollectionBuf, '(');
  1547. startCollectionBuf++; // skip '('
  1548. // find 'in' and skip it.
  1549. while (*startCollectionBuf != ' ' ||
  1550. *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
  1551. (*(startCollectionBuf+3) != ' ' &&
  1552. *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
  1553. startCollectionBuf++;
  1554. startCollectionBuf += 3;
  1555. // Replace: "for (type element in" with string constructed thus far.
  1556. ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
  1557. // Replace ')' in for '(' type elem in collection ')' with ';'
  1558. SourceLocation rightParenLoc = S->getRParenLoc();
  1559. const char *rparenBuf = SM->getCharacterData(rightParenLoc);
  1560. SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
  1561. buf = ";\n\t";
  1562. // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
  1563. // objects:__rw_items count:16];
  1564. // which is synthesized into:
  1565. // NSUInteger limit =
  1566. // ((NSUInteger (*)
  1567. // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
  1568. // (void *)objc_msgSend)((id)l_collection,
  1569. // sel_registerName(
  1570. // "countByEnumeratingWithState:objects:count:"),
  1571. // (struct __objcFastEnumerationState *)&state,
  1572. // (id *)__rw_items, (NSUInteger)16);
  1573. buf += "_WIN_NSUInteger limit =\n\t\t";
  1574. SynthCountByEnumWithState(buf);
  1575. buf += ";\n\t";
  1576. /// if (limit) {
  1577. /// unsigned long startMutations = *enumState.mutationsPtr;
  1578. /// do {
  1579. /// unsigned long counter = 0;
  1580. /// do {
  1581. /// if (startMutations != *enumState.mutationsPtr)
  1582. /// objc_enumerationMutation(l_collection);
  1583. /// elem = (type)enumState.itemsPtr[counter++];
  1584. buf += "if (limit) {\n\t";
  1585. buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
  1586. buf += "do {\n\t\t";
  1587. buf += "unsigned long counter = 0;\n\t\t";
  1588. buf += "do {\n\t\t\t";
  1589. buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
  1590. buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
  1591. buf += elementName;
  1592. buf += " = (";
  1593. buf += elementTypeAsString;
  1594. buf += ")enumState.itemsPtr[counter++];";
  1595. // Replace ')' in for '(' type elem in collection ')' with all of these.
  1596. ReplaceText(lparenLoc, 1, buf);
  1597. /// __continue_label: ;
  1598. /// } while (counter < limit);
  1599. /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
  1600. /// objects:__rw_items count:16]));
  1601. /// elem = nil;
  1602. /// __break_label: ;
  1603. /// }
  1604. /// else
  1605. /// elem = nil;
  1606. /// }
  1607. ///
  1608. buf = ";\n\t";
  1609. buf += "__continue_label_";
  1610. buf += utostr(ObjCBcLabelNo.back());
  1611. buf += ": ;";
  1612. buf += "\n\t\t";
  1613. buf += "} while (counter < limit);\n\t";
  1614. buf += "} while ((limit = ";
  1615. SynthCountByEnumWithState(buf);
  1616. buf += "));\n\t";
  1617. buf += elementName;
  1618. buf += " = ((";
  1619. buf += elementTypeAsString;
  1620. buf += ")0);\n\t";
  1621. buf += "__break_label_";
  1622. buf += utostr(ObjCBcLabelNo.back());
  1623. buf += ": ;\n\t";
  1624. buf += "}\n\t";
  1625. buf += "else\n\t\t";
  1626. buf += elementName;
  1627. buf += " = ((";
  1628. buf += elementTypeAsString;
  1629. buf += ")0);\n\t";
  1630. buf += "}\n";
  1631. // Insert all these *after* the statement body.
  1632. // FIXME: If this should support Obj-C++, support CXXTryStmt
  1633. if (isa<CompoundStmt>(S->getBody())) {
  1634. SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
  1635. InsertText(endBodyLoc, buf);
  1636. } else {
  1637. /* Need to treat single statements specially. For example:
  1638. *
  1639. * for (A *a in b) if (stuff()) break;
  1640. * for (A *a in b) xxxyy;
  1641. *
  1642. * The following code simply scans ahead to the semi to find the actual end.
  1643. */
  1644. const char *stmtBuf = SM->getCharacterData(OrigEnd);
  1645. const char *semiBuf = strchr(stmtBuf, ';');
  1646. assert(semiBuf && "Can't find ';'");
  1647. SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
  1648. InsertText(endBodyLoc, buf);
  1649. }
  1650. Stmts.pop_back();
  1651. ObjCBcLabelNo.pop_back();
  1652. return nullptr;
  1653. }
  1654. static void Write_RethrowObject(std::string &buf) {
  1655. buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
  1656. buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
  1657. buf += "\tid rethrow;\n";
  1658. buf += "\t} _fin_force_rethow(_rethrow);";
  1659. }
  1660. /// RewriteObjCSynchronizedStmt -
  1661. /// This routine rewrites @synchronized(expr) stmt;
  1662. /// into:
  1663. /// objc_sync_enter(expr);
  1664. /// @try stmt @finally { objc_sync_exit(expr); }
  1665. ///
  1666. Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
  1667. // Get the start location and compute the semi location.
  1668. SourceLocation startLoc = S->getBeginLoc();
  1669. const char *startBuf = SM->getCharacterData(startLoc);
  1670. assert((*startBuf == '@') && "bogus @synchronized location");
  1671. std::string buf;
  1672. SourceLocation SynchLoc = S->getAtSynchronizedLoc();
  1673. ConvertSourceLocationToLineDirective(SynchLoc, buf);
  1674. buf += "{ id _rethrow = 0; id _sync_obj = (id)";
  1675. const char *lparenBuf = startBuf;
  1676. while (*lparenBuf != '(') lparenBuf++;
  1677. ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
  1678. buf = "; objc_sync_enter(_sync_obj);\n";
  1679. buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
  1680. buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
  1681. buf += "\n\tid sync_exit;";
  1682. buf += "\n\t} _sync_exit(_sync_obj);\n";
  1683. // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
  1684. // the sync expression is typically a message expression that's already
  1685. // been rewritten! (which implies the SourceLocation's are invalid).
  1686. SourceLocation RParenExprLoc = S->getSynchBody()->getBeginLoc();
  1687. const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
  1688. while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
  1689. RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
  1690. SourceLocation LBranceLoc = S->getSynchBody()->getBeginLoc();
  1691. const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
  1692. assert (*LBraceLocBuf == '{');
  1693. ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
  1694. SourceLocation startRBraceLoc = S->getSynchBody()->getEndLoc();
  1695. assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
  1696. "bogus @synchronized block");
  1697. buf = "} catch (id e) {_rethrow = e;}\n";
  1698. Write_RethrowObject(buf);
  1699. buf += "}\n";
  1700. buf += "}\n";
  1701. ReplaceText(startRBraceLoc, 1, buf);
  1702. return nullptr;
  1703. }
  1704. void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
  1705. {
  1706. // Perform a bottom up traversal of all children.
  1707. for (Stmt *SubStmt : S->children())
  1708. if (SubStmt)
  1709. WarnAboutReturnGotoStmts(SubStmt);
  1710. if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
  1711. Diags.Report(Context->getFullLoc(S->getBeginLoc()),
  1712. TryFinallyContainsReturnDiag);
  1713. }
  1714. }
  1715. Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
  1716. SourceLocation startLoc = S->getAtLoc();
  1717. ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
  1718. ReplaceText(S->getSubStmt()->getBeginLoc(), 1,
  1719. "{ __AtAutoreleasePool __autoreleasepool; ");
  1720. return nullptr;
  1721. }
  1722. Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
  1723. ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
  1724. bool noCatch = S->getNumCatchStmts() == 0;
  1725. std::string buf;
  1726. SourceLocation TryLocation = S->getAtTryLoc();
  1727. ConvertSourceLocationToLineDirective(TryLocation, buf);
  1728. if (finalStmt) {
  1729. if (noCatch)
  1730. buf += "{ id volatile _rethrow = 0;\n";
  1731. else {
  1732. buf += "{ id volatile _rethrow = 0;\ntry {\n";
  1733. }
  1734. }
  1735. // Get the start location and compute the semi location.
  1736. SourceLocation startLoc = S->getBeginLoc();
  1737. const char *startBuf = SM->getCharacterData(startLoc);
  1738. assert((*startBuf == '@') && "bogus @try location");
  1739. if (finalStmt)
  1740. ReplaceText(startLoc, 1, buf);
  1741. else
  1742. // @try -> try
  1743. ReplaceText(startLoc, 1, "");
  1744. for (ObjCAtCatchStmt *Catch : S->catch_stmts()) {
  1745. VarDecl *catchDecl = Catch->getCatchParamDecl();
  1746. startLoc = Catch->getBeginLoc();
  1747. bool AtRemoved = false;
  1748. if (catchDecl) {
  1749. QualType t = catchDecl->getType();
  1750. if (const ObjCObjectPointerType *Ptr =
  1751. t->getAs<ObjCObjectPointerType>()) {
  1752. // Should be a pointer to a class.
  1753. ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
  1754. if (IDecl) {
  1755. std::string Result;
  1756. ConvertSourceLocationToLineDirective(Catch->getBeginLoc(), Result);
  1757. startBuf = SM->getCharacterData(startLoc);
  1758. assert((*startBuf == '@') && "bogus @catch location");
  1759. SourceLocation rParenLoc = Catch->getRParenLoc();
  1760. const char *rParenBuf = SM->getCharacterData(rParenLoc);
  1761. // _objc_exc_Foo *_e as argument to catch.
  1762. Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
  1763. Result += " *_"; Result += catchDecl->getNameAsString();
  1764. Result += ")";
  1765. ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
  1766. // Foo *e = (Foo *)_e;
  1767. Result.clear();
  1768. Result = "{ ";
  1769. Result += IDecl->getNameAsString();
  1770. Result += " *"; Result += catchDecl->getNameAsString();
  1771. Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
  1772. Result += "_"; Result += catchDecl->getNameAsString();
  1773. Result += "; ";
  1774. SourceLocation lBraceLoc = Catch->getCatchBody()->getBeginLoc();
  1775. ReplaceText(lBraceLoc, 1, Result);
  1776. AtRemoved = true;
  1777. }
  1778. }
  1779. }
  1780. if (!AtRemoved)
  1781. // @catch -> catch
  1782. ReplaceText(startLoc, 1, "");
  1783. }
  1784. if (finalStmt) {
  1785. buf.clear();
  1786. SourceLocation FinallyLoc = finalStmt->getBeginLoc();
  1787. if (noCatch) {
  1788. ConvertSourceLocationToLineDirective(FinallyLoc, buf);
  1789. buf += "catch (id e) {_rethrow = e;}\n";
  1790. }
  1791. else {
  1792. buf += "}\n";
  1793. ConvertSourceLocationToLineDirective(FinallyLoc, buf);
  1794. buf += "catch (id e) {_rethrow = e;}\n";
  1795. }
  1796. SourceLocation startFinalLoc = finalStmt->getBeginLoc();
  1797. ReplaceText(startFinalLoc, 8, buf);
  1798. Stmt *body = finalStmt->getFinallyBody();
  1799. SourceLocation startFinalBodyLoc = body->getBeginLoc();
  1800. buf.clear();
  1801. Write_RethrowObject(buf);
  1802. ReplaceText(startFinalBodyLoc, 1, buf);
  1803. SourceLocation endFinalBodyLoc = body->getEndLoc();
  1804. ReplaceText(endFinalBodyLoc, 1, "}\n}");
  1805. // Now check for any return/continue/go statements within the @try.
  1806. WarnAboutReturnGotoStmts(S->getTryBody());
  1807. }
  1808. return nullptr;
  1809. }
  1810. // This can't be done with ReplaceStmt(S, ThrowExpr), since
  1811. // the throw expression is typically a message expression that's already
  1812. // been rewritten! (which implies the SourceLocation's are invalid).
  1813. Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
  1814. // Get the start location and compute the semi location.
  1815. SourceLocation startLoc = S->getBeginLoc();
  1816. const char *startBuf = SM->getCharacterData(startLoc);
  1817. assert((*startBuf == '@') && "bogus @throw location");
  1818. std::string buf;
  1819. /* void objc_exception_throw(id) __attribute__((noreturn)); */
  1820. if (S->getThrowExpr())
  1821. buf = "objc_exception_throw(";
  1822. else
  1823. buf = "throw";
  1824. // handle "@ throw" correctly.
  1825. const char *wBuf = strchr(startBuf, 'w');
  1826. assert((*wBuf == 'w') && "@throw: can't find 'w'");
  1827. ReplaceText(startLoc, wBuf-startBuf+1, buf);
  1828. SourceLocation endLoc = S->getEndLoc();
  1829. const char *endBuf = SM->getCharacterData(endLoc);
  1830. const char *semiBuf = strchr(endBuf, ';');
  1831. assert((*semiBuf == ';') && "@throw: can't find ';'");
  1832. SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
  1833. if (S->getThrowExpr())
  1834. ReplaceText(semiLoc, 1, ");");
  1835. return nullptr;
  1836. }
  1837. Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
  1838. // Create a new string expression.
  1839. std::string StrEncoding;
  1840. Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
  1841. Expr *Replacement = getStringLiteral(StrEncoding);
  1842. ReplaceStmt(Exp, Replacement);
  1843. // Replace this subexpr in the parent.
  1844. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  1845. return Replacement;
  1846. }
  1847. Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
  1848. if (!SelGetUidFunctionDecl)
  1849. SynthSelGetUidFunctionDecl();
  1850. assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
  1851. // Create a call to sel_registerName("selName").
  1852. SmallVector<Expr*, 8> SelExprs;
  1853. SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
  1854. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  1855. SelExprs);
  1856. ReplaceStmt(Exp, SelExp);
  1857. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  1858. return SelExp;
  1859. }
  1860. CallExpr *
  1861. RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
  1862. ArrayRef<Expr *> Args,
  1863. SourceLocation StartLoc,
  1864. SourceLocation EndLoc) {
  1865. // Get the type, we will need to reference it in a couple spots.
  1866. QualType msgSendType = FD->getType();
  1867. // Create a reference to the objc_msgSend() declaration.
  1868. DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
  1869. VK_LValue, SourceLocation());
  1870. // Now, we cast the reference to a pointer to the objc_msgSend type.
  1871. QualType pToFunc = Context->getPointerType(msgSendType);
  1872. ImplicitCastExpr *ICE =
  1873. ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
  1874. DRE, nullptr, VK_PRValue, FPOptionsOverride());
  1875. const auto *FT = msgSendType->castAs<FunctionType>();
  1876. CallExpr *Exp =
  1877. CallExpr::Create(*Context, ICE, Args, FT->getCallResultType(*Context),
  1878. VK_PRValue, EndLoc, FPOptionsOverride());
  1879. return Exp;
  1880. }
  1881. static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
  1882. const char *&startRef, const char *&endRef) {
  1883. while (startBuf < endBuf) {
  1884. if (*startBuf == '<')
  1885. startRef = startBuf; // mark the start.
  1886. if (*startBuf == '>') {
  1887. if (startRef && *startRef == '<') {
  1888. endRef = startBuf; // mark the end.
  1889. return true;
  1890. }
  1891. return false;
  1892. }
  1893. startBuf++;
  1894. }
  1895. return false;
  1896. }
  1897. static void scanToNextArgument(const char *&argRef) {
  1898. int angle = 0;
  1899. while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
  1900. if (*argRef == '<')
  1901. angle++;
  1902. else if (*argRef == '>')
  1903. angle--;
  1904. argRef++;
  1905. }
  1906. assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
  1907. }
  1908. bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
  1909. if (T->isObjCQualifiedIdType())
  1910. return true;
  1911. if (const PointerType *PT = T->getAs<PointerType>()) {
  1912. if (PT->getPointeeType()->isObjCQualifiedIdType())
  1913. return true;
  1914. }
  1915. if (T->isObjCObjectPointerType()) {
  1916. T = T->getPointeeType();
  1917. return T->isObjCQualifiedInterfaceType();
  1918. }
  1919. if (T->isArrayType()) {
  1920. QualType ElemTy = Context->getBaseElementType(T);
  1921. return needToScanForQualifiers(ElemTy);
  1922. }
  1923. return false;
  1924. }
  1925. void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
  1926. QualType Type = E->getType();
  1927. if (needToScanForQualifiers(Type)) {
  1928. SourceLocation Loc, EndLoc;
  1929. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
  1930. Loc = ECE->getLParenLoc();
  1931. EndLoc = ECE->getRParenLoc();
  1932. } else {
  1933. Loc = E->getBeginLoc();
  1934. EndLoc = E->getEndLoc();
  1935. }
  1936. // This will defend against trying to rewrite synthesized expressions.
  1937. if (Loc.isInvalid() || EndLoc.isInvalid())
  1938. return;
  1939. const char *startBuf = SM->getCharacterData(Loc);
  1940. const char *endBuf = SM->getCharacterData(EndLoc);
  1941. const char *startRef = nullptr, *endRef = nullptr;
  1942. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1943. // Get the locations of the startRef, endRef.
  1944. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
  1945. SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
  1946. // Comment out the protocol references.
  1947. InsertText(LessLoc, "/*");
  1948. InsertText(GreaterLoc, "*/");
  1949. }
  1950. }
  1951. }
  1952. void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
  1953. SourceLocation Loc;
  1954. QualType Type;
  1955. const FunctionProtoType *proto = nullptr;
  1956. if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
  1957. Loc = VD->getLocation();
  1958. Type = VD->getType();
  1959. }
  1960. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
  1961. Loc = FD->getLocation();
  1962. // Check for ObjC 'id' and class types that have been adorned with protocol
  1963. // information (id<p>, C<p>*). The protocol references need to be rewritten!
  1964. const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
  1965. assert(funcType && "missing function type");
  1966. proto = dyn_cast<FunctionProtoType>(funcType);
  1967. if (!proto)
  1968. return;
  1969. Type = proto->getReturnType();
  1970. }
  1971. else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
  1972. Loc = FD->getLocation();
  1973. Type = FD->getType();
  1974. }
  1975. else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
  1976. Loc = TD->getLocation();
  1977. Type = TD->getUnderlyingType();
  1978. }
  1979. else
  1980. return;
  1981. if (needToScanForQualifiers(Type)) {
  1982. // Since types are unique, we need to scan the buffer.
  1983. const char *endBuf = SM->getCharacterData(Loc);
  1984. const char *startBuf = endBuf;
  1985. while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
  1986. startBuf--; // scan backward (from the decl location) for return type.
  1987. const char *startRef = nullptr, *endRef = nullptr;
  1988. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  1989. // Get the locations of the startRef, endRef.
  1990. SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
  1991. SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
  1992. // Comment out the protocol references.
  1993. InsertText(LessLoc, "/*");
  1994. InsertText(GreaterLoc, "*/");
  1995. }
  1996. }
  1997. if (!proto)
  1998. return; // most likely, was a variable
  1999. // Now check arguments.
  2000. const char *startBuf = SM->getCharacterData(Loc);
  2001. const char *startFuncBuf = startBuf;
  2002. for (unsigned i = 0; i < proto->getNumParams(); i++) {
  2003. if (needToScanForQualifiers(proto->getParamType(i))) {
  2004. // Since types are unique, we need to scan the buffer.
  2005. const char *endBuf = startBuf;
  2006. // scan forward (from the decl location) for argument types.
  2007. scanToNextArgument(endBuf);
  2008. const char *startRef = nullptr, *endRef = nullptr;
  2009. if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
  2010. // Get the locations of the startRef, endRef.
  2011. SourceLocation LessLoc =
  2012. Loc.getLocWithOffset(startRef-startFuncBuf);
  2013. SourceLocation GreaterLoc =
  2014. Loc.getLocWithOffset(endRef-startFuncBuf+1);
  2015. // Comment out the protocol references.
  2016. InsertText(LessLoc, "/*");
  2017. InsertText(GreaterLoc, "*/");
  2018. }
  2019. startBuf = ++endBuf;
  2020. }
  2021. else {
  2022. // If the function name is derived from a macro expansion, then the
  2023. // argument buffer will not follow the name. Need to speak with Chris.
  2024. while (*startBuf && *startBuf != ')' && *startBuf != ',')
  2025. startBuf++; // scan forward (from the decl location) for argument types.
  2026. startBuf++;
  2027. }
  2028. }
  2029. }
  2030. void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
  2031. QualType QT = ND->getType();
  2032. const Type* TypePtr = QT->getAs<Type>();
  2033. if (!isa<TypeOfExprType>(TypePtr))
  2034. return;
  2035. while (isa<TypeOfExprType>(TypePtr)) {
  2036. const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
  2037. QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
  2038. TypePtr = QT->getAs<Type>();
  2039. }
  2040. // FIXME. This will not work for multiple declarators; as in:
  2041. // __typeof__(a) b,c,d;
  2042. std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
  2043. SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
  2044. const char *startBuf = SM->getCharacterData(DeclLoc);
  2045. if (ND->getInit()) {
  2046. std::string Name(ND->getNameAsString());
  2047. TypeAsString += " " + Name + " = ";
  2048. Expr *E = ND->getInit();
  2049. SourceLocation startLoc;
  2050. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
  2051. startLoc = ECE->getLParenLoc();
  2052. else
  2053. startLoc = E->getBeginLoc();
  2054. startLoc = SM->getExpansionLoc(startLoc);
  2055. const char *endBuf = SM->getCharacterData(startLoc);
  2056. ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
  2057. }
  2058. else {
  2059. SourceLocation X = ND->getEndLoc();
  2060. X = SM->getExpansionLoc(X);
  2061. const char *endBuf = SM->getCharacterData(X);
  2062. ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
  2063. }
  2064. }
  2065. // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
  2066. void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
  2067. IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
  2068. SmallVector<QualType, 16> ArgTys;
  2069. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2070. QualType getFuncType =
  2071. getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
  2072. SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2073. SourceLocation(),
  2074. SourceLocation(),
  2075. SelGetUidIdent, getFuncType,
  2076. nullptr, SC_Extern);
  2077. }
  2078. void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
  2079. // declared in <objc/objc.h>
  2080. if (FD->getIdentifier() &&
  2081. FD->getName() == "sel_registerName") {
  2082. SelGetUidFunctionDecl = FD;
  2083. return;
  2084. }
  2085. RewriteObjCQualifiedInterfaceTypes(FD);
  2086. }
  2087. void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
  2088. std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
  2089. const char *argPtr = TypeString.c_str();
  2090. if (!strchr(argPtr, '^')) {
  2091. Str += TypeString;
  2092. return;
  2093. }
  2094. while (*argPtr) {
  2095. Str += (*argPtr == '^' ? '*' : *argPtr);
  2096. argPtr++;
  2097. }
  2098. }
  2099. // FIXME. Consolidate this routine with RewriteBlockPointerType.
  2100. void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
  2101. ValueDecl *VD) {
  2102. QualType Type = VD->getType();
  2103. std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
  2104. const char *argPtr = TypeString.c_str();
  2105. int paren = 0;
  2106. while (*argPtr) {
  2107. switch (*argPtr) {
  2108. case '(':
  2109. Str += *argPtr;
  2110. paren++;
  2111. break;
  2112. case ')':
  2113. Str += *argPtr;
  2114. paren--;
  2115. break;
  2116. case '^':
  2117. Str += '*';
  2118. if (paren == 1)
  2119. Str += VD->getNameAsString();
  2120. break;
  2121. default:
  2122. Str += *argPtr;
  2123. break;
  2124. }
  2125. argPtr++;
  2126. }
  2127. }
  2128. void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
  2129. SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
  2130. const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
  2131. const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
  2132. if (!proto)
  2133. return;
  2134. QualType Type = proto->getReturnType();
  2135. std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
  2136. FdStr += " ";
  2137. FdStr += FD->getName();
  2138. FdStr += "(";
  2139. unsigned numArgs = proto->getNumParams();
  2140. for (unsigned i = 0; i < numArgs; i++) {
  2141. QualType ArgType = proto->getParamType(i);
  2142. RewriteBlockPointerType(FdStr, ArgType);
  2143. if (i+1 < numArgs)
  2144. FdStr += ", ";
  2145. }
  2146. if (FD->isVariadic()) {
  2147. FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
  2148. }
  2149. else
  2150. FdStr += ");\n";
  2151. InsertText(FunLocStart, FdStr);
  2152. }
  2153. // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
  2154. void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
  2155. if (SuperConstructorFunctionDecl)
  2156. return;
  2157. IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
  2158. SmallVector<QualType, 16> ArgTys;
  2159. QualType argT = Context->getObjCIdType();
  2160. assert(!argT.isNull() && "Can't find 'id' type");
  2161. ArgTys.push_back(argT);
  2162. ArgTys.push_back(argT);
  2163. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2164. ArgTys);
  2165. SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2166. SourceLocation(),
  2167. SourceLocation(),
  2168. msgSendIdent, msgSendType,
  2169. nullptr, SC_Extern);
  2170. }
  2171. // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
  2172. void RewriteModernObjC::SynthMsgSendFunctionDecl() {
  2173. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
  2174. SmallVector<QualType, 16> ArgTys;
  2175. QualType argT = Context->getObjCIdType();
  2176. assert(!argT.isNull() && "Can't find 'id' type");
  2177. ArgTys.push_back(argT);
  2178. argT = Context->getObjCSelType();
  2179. assert(!argT.isNull() && "Can't find 'SEL' type");
  2180. ArgTys.push_back(argT);
  2181. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2182. ArgTys, /*variadic=*/true);
  2183. MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2184. SourceLocation(),
  2185. SourceLocation(),
  2186. msgSendIdent, msgSendType, nullptr,
  2187. SC_Extern);
  2188. }
  2189. // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
  2190. void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
  2191. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
  2192. SmallVector<QualType, 2> ArgTys;
  2193. ArgTys.push_back(Context->VoidTy);
  2194. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2195. ArgTys, /*variadic=*/true);
  2196. MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2197. SourceLocation(),
  2198. SourceLocation(),
  2199. msgSendIdent, msgSendType,
  2200. nullptr, SC_Extern);
  2201. }
  2202. // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
  2203. void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
  2204. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
  2205. SmallVector<QualType, 16> ArgTys;
  2206. QualType argT = Context->getObjCIdType();
  2207. assert(!argT.isNull() && "Can't find 'id' type");
  2208. ArgTys.push_back(argT);
  2209. argT = Context->getObjCSelType();
  2210. assert(!argT.isNull() && "Can't find 'SEL' type");
  2211. ArgTys.push_back(argT);
  2212. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2213. ArgTys, /*variadic=*/true);
  2214. MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2215. SourceLocation(),
  2216. SourceLocation(),
  2217. msgSendIdent, msgSendType,
  2218. nullptr, SC_Extern);
  2219. }
  2220. // SynthMsgSendSuperStretFunctionDecl -
  2221. // id objc_msgSendSuper_stret(void);
  2222. void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
  2223. IdentifierInfo *msgSendIdent =
  2224. &Context->Idents.get("objc_msgSendSuper_stret");
  2225. SmallVector<QualType, 2> ArgTys;
  2226. ArgTys.push_back(Context->VoidTy);
  2227. QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
  2228. ArgTys, /*variadic=*/true);
  2229. MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2230. SourceLocation(),
  2231. SourceLocation(),
  2232. msgSendIdent,
  2233. msgSendType, nullptr,
  2234. SC_Extern);
  2235. }
  2236. // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
  2237. void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
  2238. IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
  2239. SmallVector<QualType, 16> ArgTys;
  2240. QualType argT = Context->getObjCIdType();
  2241. assert(!argT.isNull() && "Can't find 'id' type");
  2242. ArgTys.push_back(argT);
  2243. argT = Context->getObjCSelType();
  2244. assert(!argT.isNull() && "Can't find 'SEL' type");
  2245. ArgTys.push_back(argT);
  2246. QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
  2247. ArgTys, /*variadic=*/true);
  2248. MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2249. SourceLocation(),
  2250. SourceLocation(),
  2251. msgSendIdent, msgSendType,
  2252. nullptr, SC_Extern);
  2253. }
  2254. // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
  2255. void RewriteModernObjC::SynthGetClassFunctionDecl() {
  2256. IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
  2257. SmallVector<QualType, 16> ArgTys;
  2258. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2259. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2260. ArgTys);
  2261. GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2262. SourceLocation(),
  2263. SourceLocation(),
  2264. getClassIdent, getClassType,
  2265. nullptr, SC_Extern);
  2266. }
  2267. // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
  2268. void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
  2269. IdentifierInfo *getSuperClassIdent =
  2270. &Context->Idents.get("class_getSuperclass");
  2271. SmallVector<QualType, 16> ArgTys;
  2272. ArgTys.push_back(Context->getObjCClassType());
  2273. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2274. ArgTys);
  2275. GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2276. SourceLocation(),
  2277. SourceLocation(),
  2278. getSuperClassIdent,
  2279. getClassType, nullptr,
  2280. SC_Extern);
  2281. }
  2282. // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
  2283. void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
  2284. IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
  2285. SmallVector<QualType, 16> ArgTys;
  2286. ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
  2287. QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
  2288. ArgTys);
  2289. GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
  2290. SourceLocation(),
  2291. SourceLocation(),
  2292. getClassIdent, getClassType,
  2293. nullptr, SC_Extern);
  2294. }
  2295. Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
  2296. assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
  2297. QualType strType = getConstantStringStructType();
  2298. std::string S = "__NSConstantStringImpl_";
  2299. std::string tmpName = InFileName;
  2300. unsigned i;
  2301. for (i=0; i < tmpName.length(); i++) {
  2302. char c = tmpName.at(i);
  2303. // replace any non-alphanumeric characters with '_'.
  2304. if (!isAlphanumeric(c))
  2305. tmpName[i] = '_';
  2306. }
  2307. S += tmpName;
  2308. S += "_";
  2309. S += utostr(NumObjCStringLiterals++);
  2310. Preamble += "static __NSConstantStringImpl " + S;
  2311. Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
  2312. Preamble += "0x000007c8,"; // utf8_str
  2313. // The pretty printer for StringLiteral handles escape characters properly.
  2314. std::string prettyBufS;
  2315. llvm::raw_string_ostream prettyBuf(prettyBufS);
  2316. Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
  2317. Preamble += prettyBuf.str();
  2318. Preamble += ",";
  2319. Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
  2320. VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  2321. SourceLocation(), &Context->Idents.get(S),
  2322. strType, nullptr, SC_Static);
  2323. DeclRefExpr *DRE = new (Context)
  2324. DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
  2325. Expr *Unop = UnaryOperator::Create(
  2326. const_cast<ASTContext &>(*Context), DRE, UO_AddrOf,
  2327. Context->getPointerType(DRE->getType()), VK_PRValue, OK_Ordinary,
  2328. SourceLocation(), false, FPOptionsOverride());
  2329. // cast to NSConstantString *
  2330. CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
  2331. CK_CPointerToObjCPointerCast, Unop);
  2332. ReplaceStmt(Exp, cast);
  2333. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  2334. return cast;
  2335. }
  2336. Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
  2337. unsigned IntSize =
  2338. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  2339. Expr *FlagExp = IntegerLiteral::Create(*Context,
  2340. llvm::APInt(IntSize, Exp->getValue()),
  2341. Context->IntTy, Exp->getLocation());
  2342. CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
  2343. CK_BitCast, FlagExp);
  2344. ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
  2345. cast);
  2346. ReplaceStmt(Exp, PE);
  2347. return PE;
  2348. }
  2349. Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
  2350. // synthesize declaration of helper functions needed in this routine.
  2351. if (!SelGetUidFunctionDecl)
  2352. SynthSelGetUidFunctionDecl();
  2353. // use objc_msgSend() for all.
  2354. if (!MsgSendFunctionDecl)
  2355. SynthMsgSendFunctionDecl();
  2356. if (!GetClassFunctionDecl)
  2357. SynthGetClassFunctionDecl();
  2358. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2359. SourceLocation StartLoc = Exp->getBeginLoc();
  2360. SourceLocation EndLoc = Exp->getEndLoc();
  2361. // Synthesize a call to objc_msgSend().
  2362. SmallVector<Expr*, 4> MsgExprs;
  2363. SmallVector<Expr*, 4> ClsExprs;
  2364. // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
  2365. ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
  2366. ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
  2367. IdentifierInfo *clsName = BoxingClass->getIdentifier();
  2368. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2369. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2370. StartLoc, EndLoc);
  2371. MsgExprs.push_back(Cls);
  2372. // Create a call to sel_registerName("<BoxingMethod>:"), etc.
  2373. // it will be the 2nd argument.
  2374. SmallVector<Expr*, 4> SelExprs;
  2375. SelExprs.push_back(
  2376. getStringLiteral(BoxingMethod->getSelector().getAsString()));
  2377. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2378. SelExprs, StartLoc, EndLoc);
  2379. MsgExprs.push_back(SelExp);
  2380. // User provided sub-expression is the 3rd, and last, argument.
  2381. Expr *subExpr = Exp->getSubExpr();
  2382. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
  2383. QualType type = ICE->getType();
  2384. const Expr *SubExpr = ICE->IgnoreParenImpCasts();
  2385. CastKind CK = CK_BitCast;
  2386. if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
  2387. CK = CK_IntegralToBoolean;
  2388. subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
  2389. }
  2390. MsgExprs.push_back(subExpr);
  2391. SmallVector<QualType, 4> ArgTypes;
  2392. ArgTypes.push_back(Context->getObjCClassType());
  2393. ArgTypes.push_back(Context->getObjCSelType());
  2394. for (const auto PI : BoxingMethod->parameters())
  2395. ArgTypes.push_back(PI->getType());
  2396. QualType returnType = Exp->getType();
  2397. // Get the type, we will need to reference it in a couple spots.
  2398. QualType msgSendType = MsgSendFlavor->getType();
  2399. // Create a reference to the objc_msgSend() declaration.
  2400. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2401. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2402. CastExpr *cast = NoTypeInfoCStyleCastExpr(
  2403. Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
  2404. // Now do the "normal" pointer to function cast.
  2405. QualType castType =
  2406. getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
  2407. castType = Context->getPointerType(castType);
  2408. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2409. cast);
  2410. // Don't forget the parens to enforce the proper binding.
  2411. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2412. auto *FT = msgSendType->castAs<FunctionType>();
  2413. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2414. VK_PRValue, EndLoc, FPOptionsOverride());
  2415. ReplaceStmt(Exp, CE);
  2416. return CE;
  2417. }
  2418. Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
  2419. // synthesize declaration of helper functions needed in this routine.
  2420. if (!SelGetUidFunctionDecl)
  2421. SynthSelGetUidFunctionDecl();
  2422. // use objc_msgSend() for all.
  2423. if (!MsgSendFunctionDecl)
  2424. SynthMsgSendFunctionDecl();
  2425. if (!GetClassFunctionDecl)
  2426. SynthGetClassFunctionDecl();
  2427. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2428. SourceLocation StartLoc = Exp->getBeginLoc();
  2429. SourceLocation EndLoc = Exp->getEndLoc();
  2430. // Build the expression: __NSContainer_literal(int, ...).arr
  2431. QualType IntQT = Context->IntTy;
  2432. QualType NSArrayFType =
  2433. getSimpleFunctionType(Context->VoidTy, IntQT, true);
  2434. std::string NSArrayFName("__NSContainer_literal");
  2435. FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
  2436. DeclRefExpr *NSArrayDRE = new (Context) DeclRefExpr(
  2437. *Context, NSArrayFD, false, NSArrayFType, VK_PRValue, SourceLocation());
  2438. SmallVector<Expr*, 16> InitExprs;
  2439. unsigned NumElements = Exp->getNumElements();
  2440. unsigned UnsignedIntSize =
  2441. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  2442. Expr *count = IntegerLiteral::Create(*Context,
  2443. llvm::APInt(UnsignedIntSize, NumElements),
  2444. Context->UnsignedIntTy, SourceLocation());
  2445. InitExprs.push_back(count);
  2446. for (unsigned i = 0; i < NumElements; i++)
  2447. InitExprs.push_back(Exp->getElement(i));
  2448. Expr *NSArrayCallExpr =
  2449. CallExpr::Create(*Context, NSArrayDRE, InitExprs, NSArrayFType, VK_LValue,
  2450. SourceLocation(), FPOptionsOverride());
  2451. FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  2452. SourceLocation(),
  2453. &Context->Idents.get("arr"),
  2454. Context->getPointerType(Context->VoidPtrTy),
  2455. nullptr, /*BitWidth=*/nullptr,
  2456. /*Mutable=*/true, ICIS_NoInit);
  2457. MemberExpr *ArrayLiteralME =
  2458. MemberExpr::CreateImplicit(*Context, NSArrayCallExpr, false, ARRFD,
  2459. ARRFD->getType(), VK_LValue, OK_Ordinary);
  2460. QualType ConstIdT = Context->getObjCIdType().withConst();
  2461. CStyleCastExpr * ArrayLiteralObjects =
  2462. NoTypeInfoCStyleCastExpr(Context,
  2463. Context->getPointerType(ConstIdT),
  2464. CK_BitCast,
  2465. ArrayLiteralME);
  2466. // Synthesize a call to objc_msgSend().
  2467. SmallVector<Expr*, 32> MsgExprs;
  2468. SmallVector<Expr*, 4> ClsExprs;
  2469. QualType expType = Exp->getType();
  2470. // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
  2471. ObjCInterfaceDecl *Class =
  2472. expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
  2473. IdentifierInfo *clsName = Class->getIdentifier();
  2474. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2475. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2476. StartLoc, EndLoc);
  2477. MsgExprs.push_back(Cls);
  2478. // Create a call to sel_registerName("arrayWithObjects:count:").
  2479. // it will be the 2nd argument.
  2480. SmallVector<Expr*, 4> SelExprs;
  2481. ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
  2482. SelExprs.push_back(
  2483. getStringLiteral(ArrayMethod->getSelector().getAsString()));
  2484. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2485. SelExprs, StartLoc, EndLoc);
  2486. MsgExprs.push_back(SelExp);
  2487. // (const id [])objects
  2488. MsgExprs.push_back(ArrayLiteralObjects);
  2489. // (NSUInteger)cnt
  2490. Expr *cnt = IntegerLiteral::Create(*Context,
  2491. llvm::APInt(UnsignedIntSize, NumElements),
  2492. Context->UnsignedIntTy, SourceLocation());
  2493. MsgExprs.push_back(cnt);
  2494. SmallVector<QualType, 4> ArgTypes;
  2495. ArgTypes.push_back(Context->getObjCClassType());
  2496. ArgTypes.push_back(Context->getObjCSelType());
  2497. for (const auto *PI : ArrayMethod->parameters())
  2498. ArgTypes.push_back(PI->getType());
  2499. QualType returnType = Exp->getType();
  2500. // Get the type, we will need to reference it in a couple spots.
  2501. QualType msgSendType = MsgSendFlavor->getType();
  2502. // Create a reference to the objc_msgSend() declaration.
  2503. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2504. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2505. CastExpr *cast = NoTypeInfoCStyleCastExpr(
  2506. Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
  2507. // Now do the "normal" pointer to function cast.
  2508. QualType castType =
  2509. getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
  2510. castType = Context->getPointerType(castType);
  2511. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2512. cast);
  2513. // Don't forget the parens to enforce the proper binding.
  2514. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2515. const FunctionType *FT = msgSendType->castAs<FunctionType>();
  2516. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2517. VK_PRValue, EndLoc, FPOptionsOverride());
  2518. ReplaceStmt(Exp, CE);
  2519. return CE;
  2520. }
  2521. Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
  2522. // synthesize declaration of helper functions needed in this routine.
  2523. if (!SelGetUidFunctionDecl)
  2524. SynthSelGetUidFunctionDecl();
  2525. // use objc_msgSend() for all.
  2526. if (!MsgSendFunctionDecl)
  2527. SynthMsgSendFunctionDecl();
  2528. if (!GetClassFunctionDecl)
  2529. SynthGetClassFunctionDecl();
  2530. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2531. SourceLocation StartLoc = Exp->getBeginLoc();
  2532. SourceLocation EndLoc = Exp->getEndLoc();
  2533. // Build the expression: __NSContainer_literal(int, ...).arr
  2534. QualType IntQT = Context->IntTy;
  2535. QualType NSDictFType =
  2536. getSimpleFunctionType(Context->VoidTy, IntQT, true);
  2537. std::string NSDictFName("__NSContainer_literal");
  2538. FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
  2539. DeclRefExpr *NSDictDRE = new (Context) DeclRefExpr(
  2540. *Context, NSDictFD, false, NSDictFType, VK_PRValue, SourceLocation());
  2541. SmallVector<Expr*, 16> KeyExprs;
  2542. SmallVector<Expr*, 16> ValueExprs;
  2543. unsigned NumElements = Exp->getNumElements();
  2544. unsigned UnsignedIntSize =
  2545. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  2546. Expr *count = IntegerLiteral::Create(*Context,
  2547. llvm::APInt(UnsignedIntSize, NumElements),
  2548. Context->UnsignedIntTy, SourceLocation());
  2549. KeyExprs.push_back(count);
  2550. ValueExprs.push_back(count);
  2551. for (unsigned i = 0; i < NumElements; i++) {
  2552. ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
  2553. KeyExprs.push_back(Element.Key);
  2554. ValueExprs.push_back(Element.Value);
  2555. }
  2556. // (const id [])objects
  2557. Expr *NSValueCallExpr =
  2558. CallExpr::Create(*Context, NSDictDRE, ValueExprs, NSDictFType, VK_LValue,
  2559. SourceLocation(), FPOptionsOverride());
  2560. FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  2561. SourceLocation(),
  2562. &Context->Idents.get("arr"),
  2563. Context->getPointerType(Context->VoidPtrTy),
  2564. nullptr, /*BitWidth=*/nullptr,
  2565. /*Mutable=*/true, ICIS_NoInit);
  2566. MemberExpr *DictLiteralValueME =
  2567. MemberExpr::CreateImplicit(*Context, NSValueCallExpr, false, ARRFD,
  2568. ARRFD->getType(), VK_LValue, OK_Ordinary);
  2569. QualType ConstIdT = Context->getObjCIdType().withConst();
  2570. CStyleCastExpr * DictValueObjects =
  2571. NoTypeInfoCStyleCastExpr(Context,
  2572. Context->getPointerType(ConstIdT),
  2573. CK_BitCast,
  2574. DictLiteralValueME);
  2575. // (const id <NSCopying> [])keys
  2576. Expr *NSKeyCallExpr =
  2577. CallExpr::Create(*Context, NSDictDRE, KeyExprs, NSDictFType, VK_LValue,
  2578. SourceLocation(), FPOptionsOverride());
  2579. MemberExpr *DictLiteralKeyME =
  2580. MemberExpr::CreateImplicit(*Context, NSKeyCallExpr, false, ARRFD,
  2581. ARRFD->getType(), VK_LValue, OK_Ordinary);
  2582. CStyleCastExpr * DictKeyObjects =
  2583. NoTypeInfoCStyleCastExpr(Context,
  2584. Context->getPointerType(ConstIdT),
  2585. CK_BitCast,
  2586. DictLiteralKeyME);
  2587. // Synthesize a call to objc_msgSend().
  2588. SmallVector<Expr*, 32> MsgExprs;
  2589. SmallVector<Expr*, 4> ClsExprs;
  2590. QualType expType = Exp->getType();
  2591. // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
  2592. ObjCInterfaceDecl *Class =
  2593. expType->getPointeeType()->castAs<ObjCObjectType>()->getInterface();
  2594. IdentifierInfo *clsName = Class->getIdentifier();
  2595. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2596. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2597. StartLoc, EndLoc);
  2598. MsgExprs.push_back(Cls);
  2599. // Create a call to sel_registerName("arrayWithObjects:count:").
  2600. // it will be the 2nd argument.
  2601. SmallVector<Expr*, 4> SelExprs;
  2602. ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
  2603. SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
  2604. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  2605. SelExprs, StartLoc, EndLoc);
  2606. MsgExprs.push_back(SelExp);
  2607. // (const id [])objects
  2608. MsgExprs.push_back(DictValueObjects);
  2609. // (const id <NSCopying> [])keys
  2610. MsgExprs.push_back(DictKeyObjects);
  2611. // (NSUInteger)cnt
  2612. Expr *cnt = IntegerLiteral::Create(*Context,
  2613. llvm::APInt(UnsignedIntSize, NumElements),
  2614. Context->UnsignedIntTy, SourceLocation());
  2615. MsgExprs.push_back(cnt);
  2616. SmallVector<QualType, 8> ArgTypes;
  2617. ArgTypes.push_back(Context->getObjCClassType());
  2618. ArgTypes.push_back(Context->getObjCSelType());
  2619. for (const auto *PI : DictMethod->parameters()) {
  2620. QualType T = PI->getType();
  2621. if (const PointerType* PT = T->getAs<PointerType>()) {
  2622. QualType PointeeTy = PT->getPointeeType();
  2623. convertToUnqualifiedObjCType(PointeeTy);
  2624. T = Context->getPointerType(PointeeTy);
  2625. }
  2626. ArgTypes.push_back(T);
  2627. }
  2628. QualType returnType = Exp->getType();
  2629. // Get the type, we will need to reference it in a couple spots.
  2630. QualType msgSendType = MsgSendFlavor->getType();
  2631. // Create a reference to the objc_msgSend() declaration.
  2632. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  2633. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  2634. CastExpr *cast = NoTypeInfoCStyleCastExpr(
  2635. Context, Context->getPointerType(Context->VoidTy), CK_BitCast, DRE);
  2636. // Now do the "normal" pointer to function cast.
  2637. QualType castType =
  2638. getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
  2639. castType = Context->getPointerType(castType);
  2640. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  2641. cast);
  2642. // Don't forget the parens to enforce the proper binding.
  2643. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  2644. const FunctionType *FT = msgSendType->castAs<FunctionType>();
  2645. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  2646. VK_PRValue, EndLoc, FPOptionsOverride());
  2647. ReplaceStmt(Exp, CE);
  2648. return CE;
  2649. }
  2650. // struct __rw_objc_super {
  2651. // struct objc_object *object; struct objc_object *superClass;
  2652. // };
  2653. QualType RewriteModernObjC::getSuperStructType() {
  2654. if (!SuperStructDecl) {
  2655. SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2656. SourceLocation(), SourceLocation(),
  2657. &Context->Idents.get("__rw_objc_super"));
  2658. QualType FieldTypes[2];
  2659. // struct objc_object *object;
  2660. FieldTypes[0] = Context->getObjCIdType();
  2661. // struct objc_object *superClass;
  2662. FieldTypes[1] = Context->getObjCIdType();
  2663. // Create fields
  2664. for (unsigned i = 0; i < 2; ++i) {
  2665. SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
  2666. SourceLocation(),
  2667. SourceLocation(), nullptr,
  2668. FieldTypes[i], nullptr,
  2669. /*BitWidth=*/nullptr,
  2670. /*Mutable=*/false,
  2671. ICIS_NoInit));
  2672. }
  2673. SuperStructDecl->completeDefinition();
  2674. }
  2675. return Context->getTagDeclType(SuperStructDecl);
  2676. }
  2677. QualType RewriteModernObjC::getConstantStringStructType() {
  2678. if (!ConstantStringDecl) {
  2679. ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  2680. SourceLocation(), SourceLocation(),
  2681. &Context->Idents.get("__NSConstantStringImpl"));
  2682. QualType FieldTypes[4];
  2683. // struct objc_object *receiver;
  2684. FieldTypes[0] = Context->getObjCIdType();
  2685. // int flags;
  2686. FieldTypes[1] = Context->IntTy;
  2687. // char *str;
  2688. FieldTypes[2] = Context->getPointerType(Context->CharTy);
  2689. // long length;
  2690. FieldTypes[3] = Context->LongTy;
  2691. // Create fields
  2692. for (unsigned i = 0; i < 4; ++i) {
  2693. ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
  2694. ConstantStringDecl,
  2695. SourceLocation(),
  2696. SourceLocation(), nullptr,
  2697. FieldTypes[i], nullptr,
  2698. /*BitWidth=*/nullptr,
  2699. /*Mutable=*/true,
  2700. ICIS_NoInit));
  2701. }
  2702. ConstantStringDecl->completeDefinition();
  2703. }
  2704. return Context->getTagDeclType(ConstantStringDecl);
  2705. }
  2706. /// getFunctionSourceLocation - returns start location of a function
  2707. /// definition. Complication arises when function has declared as
  2708. /// extern "C" or extern "C" {...}
  2709. static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
  2710. FunctionDecl *FD) {
  2711. if (FD->isExternC() && !FD->isMain()) {
  2712. const DeclContext *DC = FD->getDeclContext();
  2713. if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
  2714. // if it is extern "C" {...}, return function decl's own location.
  2715. if (!LSD->getRBraceLoc().isValid())
  2716. return LSD->getExternLoc();
  2717. }
  2718. if (FD->getStorageClass() != SC_None)
  2719. R.RewriteBlockLiteralFunctionDecl(FD);
  2720. return FD->getTypeSpecStartLoc();
  2721. }
  2722. void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
  2723. SourceLocation Location = D->getLocation();
  2724. if (Location.isFileID() && GenerateLineInfo) {
  2725. std::string LineString("\n#line ");
  2726. PresumedLoc PLoc = SM->getPresumedLoc(Location);
  2727. LineString += utostr(PLoc.getLine());
  2728. LineString += " \"";
  2729. LineString += Lexer::Stringify(PLoc.getFilename());
  2730. if (isa<ObjCMethodDecl>(D))
  2731. LineString += "\"";
  2732. else LineString += "\"\n";
  2733. Location = D->getBeginLoc();
  2734. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2735. if (FD->isExternC() && !FD->isMain()) {
  2736. const DeclContext *DC = FD->getDeclContext();
  2737. if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
  2738. // if it is extern "C" {...}, return function decl's own location.
  2739. if (!LSD->getRBraceLoc().isValid())
  2740. Location = LSD->getExternLoc();
  2741. }
  2742. }
  2743. InsertText(Location, LineString);
  2744. }
  2745. }
  2746. /// SynthMsgSendStretCallExpr - This routine translates message expression
  2747. /// into a call to objc_msgSend_stret() entry point. Tricky part is that
  2748. /// nil check on receiver must be performed before calling objc_msgSend_stret.
  2749. /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
  2750. /// msgSendType - function type of objc_msgSend_stret(...)
  2751. /// returnType - Result type of the method being synthesized.
  2752. /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
  2753. /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
  2754. /// starting with receiver.
  2755. /// Method - Method being rewritten.
  2756. Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
  2757. QualType returnType,
  2758. SmallVectorImpl<QualType> &ArgTypes,
  2759. SmallVectorImpl<Expr*> &MsgExprs,
  2760. ObjCMethodDecl *Method) {
  2761. // Now do the "normal" pointer to function cast.
  2762. QualType FuncType = getSimpleFunctionType(
  2763. returnType, ArgTypes, Method ? Method->isVariadic() : false);
  2764. QualType castType = Context->getPointerType(FuncType);
  2765. // build type for containing the objc_msgSend_stret object.
  2766. static unsigned stretCount=0;
  2767. std::string name = "__Stret"; name += utostr(stretCount);
  2768. std::string str =
  2769. "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
  2770. str += "namespace {\n";
  2771. str += "struct "; str += name;
  2772. str += " {\n\t";
  2773. str += name;
  2774. str += "(id receiver, SEL sel";
  2775. for (unsigned i = 2; i < ArgTypes.size(); i++) {
  2776. std::string ArgName = "arg"; ArgName += utostr(i);
  2777. ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
  2778. str += ", "; str += ArgName;
  2779. }
  2780. // could be vararg.
  2781. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
  2782. std::string ArgName = "arg"; ArgName += utostr(i);
  2783. MsgExprs[i]->getType().getAsStringInternal(ArgName,
  2784. Context->getPrintingPolicy());
  2785. str += ", "; str += ArgName;
  2786. }
  2787. str += ") {\n";
  2788. str += "\t unsigned size = sizeof(";
  2789. str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
  2790. str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
  2791. str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
  2792. str += ")(void *)objc_msgSend)(receiver, sel";
  2793. for (unsigned i = 2; i < ArgTypes.size(); i++) {
  2794. str += ", arg"; str += utostr(i);
  2795. }
  2796. // could be vararg.
  2797. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
  2798. str += ", arg"; str += utostr(i);
  2799. }
  2800. str+= ");\n";
  2801. str += "\t else if (receiver == 0)\n";
  2802. str += "\t memset((void*)&s, 0, sizeof(s));\n";
  2803. str += "\t else\n";
  2804. str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
  2805. str += ")(void *)objc_msgSend_stret)(receiver, sel";
  2806. for (unsigned i = 2; i < ArgTypes.size(); i++) {
  2807. str += ", arg"; str += utostr(i);
  2808. }
  2809. // could be vararg.
  2810. for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
  2811. str += ", arg"; str += utostr(i);
  2812. }
  2813. str += ");\n";
  2814. str += "\t}\n";
  2815. str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
  2816. str += " s;\n";
  2817. str += "};\n};\n\n";
  2818. SourceLocation FunLocStart;
  2819. if (CurFunctionDef)
  2820. FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
  2821. else {
  2822. assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
  2823. FunLocStart = CurMethodDef->getBeginLoc();
  2824. }
  2825. InsertText(FunLocStart, str);
  2826. ++stretCount;
  2827. // AST for __Stretn(receiver, args).s;
  2828. IdentifierInfo *ID = &Context->Idents.get(name);
  2829. FunctionDecl *FD =
  2830. FunctionDecl::Create(*Context, TUDecl, SourceLocation(), SourceLocation(),
  2831. ID, FuncType, nullptr, SC_Extern, false, false);
  2832. DeclRefExpr *DRE = new (Context)
  2833. DeclRefExpr(*Context, FD, false, castType, VK_PRValue, SourceLocation());
  2834. CallExpr *STCE =
  2835. CallExpr::Create(*Context, DRE, MsgExprs, castType, VK_LValue,
  2836. SourceLocation(), FPOptionsOverride());
  2837. FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  2838. SourceLocation(),
  2839. &Context->Idents.get("s"),
  2840. returnType, nullptr,
  2841. /*BitWidth=*/nullptr,
  2842. /*Mutable=*/true, ICIS_NoInit);
  2843. MemberExpr *ME = MemberExpr::CreateImplicit(
  2844. *Context, STCE, false, FieldD, FieldD->getType(), VK_LValue, OK_Ordinary);
  2845. return ME;
  2846. }
  2847. Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
  2848. SourceLocation StartLoc,
  2849. SourceLocation EndLoc) {
  2850. if (!SelGetUidFunctionDecl)
  2851. SynthSelGetUidFunctionDecl();
  2852. if (!MsgSendFunctionDecl)
  2853. SynthMsgSendFunctionDecl();
  2854. if (!MsgSendSuperFunctionDecl)
  2855. SynthMsgSendSuperFunctionDecl();
  2856. if (!MsgSendStretFunctionDecl)
  2857. SynthMsgSendStretFunctionDecl();
  2858. if (!MsgSendSuperStretFunctionDecl)
  2859. SynthMsgSendSuperStretFunctionDecl();
  2860. if (!MsgSendFpretFunctionDecl)
  2861. SynthMsgSendFpretFunctionDecl();
  2862. if (!GetClassFunctionDecl)
  2863. SynthGetClassFunctionDecl();
  2864. if (!GetSuperClassFunctionDecl)
  2865. SynthGetSuperClassFunctionDecl();
  2866. if (!GetMetaClassFunctionDecl)
  2867. SynthGetMetaClassFunctionDecl();
  2868. // default to objc_msgSend().
  2869. FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
  2870. // May need to use objc_msgSend_stret() as well.
  2871. FunctionDecl *MsgSendStretFlavor = nullptr;
  2872. if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
  2873. QualType resultType = mDecl->getReturnType();
  2874. if (resultType->isRecordType())
  2875. MsgSendStretFlavor = MsgSendStretFunctionDecl;
  2876. else if (resultType->isRealFloatingType())
  2877. MsgSendFlavor = MsgSendFpretFunctionDecl;
  2878. }
  2879. // Synthesize a call to objc_msgSend().
  2880. SmallVector<Expr*, 8> MsgExprs;
  2881. switch (Exp->getReceiverKind()) {
  2882. case ObjCMessageExpr::SuperClass: {
  2883. MsgSendFlavor = MsgSendSuperFunctionDecl;
  2884. if (MsgSendStretFlavor)
  2885. MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
  2886. assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
  2887. ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
  2888. SmallVector<Expr*, 4> InitExprs;
  2889. // set the receiver to self, the first argument to all methods.
  2890. InitExprs.push_back(NoTypeInfoCStyleCastExpr(
  2891. Context, Context->getObjCIdType(), CK_BitCast,
  2892. new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
  2893. Context->getObjCIdType(), VK_PRValue,
  2894. SourceLocation()))); // set the 'receiver'.
  2895. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2896. SmallVector<Expr*, 8> ClsExprs;
  2897. ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
  2898. // (Class)objc_getClass("CurrentClass")
  2899. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
  2900. ClsExprs, StartLoc, EndLoc);
  2901. ClsExprs.clear();
  2902. ClsExprs.push_back(Cls);
  2903. Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
  2904. StartLoc, EndLoc);
  2905. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2906. // To turn off a warning, type-cast to 'id'
  2907. InitExprs.push_back( // set 'super class', using class_getSuperclass().
  2908. NoTypeInfoCStyleCastExpr(Context,
  2909. Context->getObjCIdType(),
  2910. CK_BitCast, Cls));
  2911. // struct __rw_objc_super
  2912. QualType superType = getSuperStructType();
  2913. Expr *SuperRep;
  2914. if (LangOpts.MicrosoftExt) {
  2915. SynthSuperConstructorFunctionDecl();
  2916. // Simulate a constructor call...
  2917. DeclRefExpr *DRE = new (Context)
  2918. DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
  2919. VK_LValue, SourceLocation());
  2920. SuperRep =
  2921. CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
  2922. SourceLocation(), FPOptionsOverride());
  2923. // The code for super is a little tricky to prevent collision with
  2924. // the structure definition in the header. The rewriter has it's own
  2925. // internal definition (__rw_objc_super) that is uses. This is why
  2926. // we need the cast below. For example:
  2927. // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
  2928. //
  2929. SuperRep = UnaryOperator::Create(
  2930. const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
  2931. Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
  2932. SourceLocation(), false, FPOptionsOverride());
  2933. SuperRep = NoTypeInfoCStyleCastExpr(Context,
  2934. Context->getPointerType(superType),
  2935. CK_BitCast, SuperRep);
  2936. } else {
  2937. // (struct __rw_objc_super) { <exprs from above> }
  2938. InitListExpr *ILE =
  2939. new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
  2940. SourceLocation());
  2941. TypeSourceInfo *superTInfo
  2942. = Context->getTrivialTypeSourceInfo(superType);
  2943. SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
  2944. superType, VK_LValue,
  2945. ILE, false);
  2946. // struct __rw_objc_super *
  2947. SuperRep = UnaryOperator::Create(
  2948. const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
  2949. Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
  2950. SourceLocation(), false, FPOptionsOverride());
  2951. }
  2952. MsgExprs.push_back(SuperRep);
  2953. break;
  2954. }
  2955. case ObjCMessageExpr::Class: {
  2956. SmallVector<Expr*, 8> ClsExprs;
  2957. ObjCInterfaceDecl *Class
  2958. = Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
  2959. IdentifierInfo *clsName = Class->getIdentifier();
  2960. ClsExprs.push_back(getStringLiteral(clsName->getName()));
  2961. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2962. StartLoc, EndLoc);
  2963. CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
  2964. Context->getObjCIdType(),
  2965. CK_BitCast, Cls);
  2966. MsgExprs.push_back(ArgExpr);
  2967. break;
  2968. }
  2969. case ObjCMessageExpr::SuperInstance:{
  2970. MsgSendFlavor = MsgSendSuperFunctionDecl;
  2971. if (MsgSendStretFlavor)
  2972. MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
  2973. assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
  2974. ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
  2975. SmallVector<Expr*, 4> InitExprs;
  2976. InitExprs.push_back(NoTypeInfoCStyleCastExpr(
  2977. Context, Context->getObjCIdType(), CK_BitCast,
  2978. new (Context) DeclRefExpr(*Context, CurMethodDef->getSelfDecl(), false,
  2979. Context->getObjCIdType(), VK_PRValue,
  2980. SourceLocation()))); // set the 'receiver'.
  2981. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2982. SmallVector<Expr*, 8> ClsExprs;
  2983. ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
  2984. // (Class)objc_getClass("CurrentClass")
  2985. CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
  2986. StartLoc, EndLoc);
  2987. ClsExprs.clear();
  2988. ClsExprs.push_back(Cls);
  2989. Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
  2990. StartLoc, EndLoc);
  2991. // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
  2992. // To turn off a warning, type-cast to 'id'
  2993. InitExprs.push_back(
  2994. // set 'super class', using class_getSuperclass().
  2995. NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  2996. CK_BitCast, Cls));
  2997. // struct __rw_objc_super
  2998. QualType superType = getSuperStructType();
  2999. Expr *SuperRep;
  3000. if (LangOpts.MicrosoftExt) {
  3001. SynthSuperConstructorFunctionDecl();
  3002. // Simulate a constructor call...
  3003. DeclRefExpr *DRE = new (Context)
  3004. DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
  3005. VK_LValue, SourceLocation());
  3006. SuperRep =
  3007. CallExpr::Create(*Context, DRE, InitExprs, superType, VK_LValue,
  3008. SourceLocation(), FPOptionsOverride());
  3009. // The code for super is a little tricky to prevent collision with
  3010. // the structure definition in the header. The rewriter has it's own
  3011. // internal definition (__rw_objc_super) that is uses. This is why
  3012. // we need the cast below. For example:
  3013. // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
  3014. //
  3015. SuperRep = UnaryOperator::Create(
  3016. const_cast<ASTContext &>(*Context), SuperRep, UO_AddrOf,
  3017. Context->getPointerType(SuperRep->getType()), VK_PRValue, OK_Ordinary,
  3018. SourceLocation(), false, FPOptionsOverride());
  3019. SuperRep = NoTypeInfoCStyleCastExpr(Context,
  3020. Context->getPointerType(superType),
  3021. CK_BitCast, SuperRep);
  3022. } else {
  3023. // (struct __rw_objc_super) { <exprs from above> }
  3024. InitListExpr *ILE =
  3025. new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
  3026. SourceLocation());
  3027. TypeSourceInfo *superTInfo
  3028. = Context->getTrivialTypeSourceInfo(superType);
  3029. SuperRep = new (Context) CompoundLiteralExpr(
  3030. SourceLocation(), superTInfo, superType, VK_PRValue, ILE, false);
  3031. }
  3032. MsgExprs.push_back(SuperRep);
  3033. break;
  3034. }
  3035. case ObjCMessageExpr::Instance: {
  3036. // Remove all type-casts because it may contain objc-style types; e.g.
  3037. // Foo<Proto> *.
  3038. Expr *recExpr = Exp->getInstanceReceiver();
  3039. while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
  3040. recExpr = CE->getSubExpr();
  3041. CastKind CK = recExpr->getType()->isObjCObjectPointerType()
  3042. ? CK_BitCast : recExpr->getType()->isBlockPointerType()
  3043. ? CK_BlockPointerToObjCPointerCast
  3044. : CK_CPointerToObjCPointerCast;
  3045. recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  3046. CK, recExpr);
  3047. MsgExprs.push_back(recExpr);
  3048. break;
  3049. }
  3050. }
  3051. // Create a call to sel_registerName("selName"), it will be the 2nd argument.
  3052. SmallVector<Expr*, 8> SelExprs;
  3053. SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
  3054. CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
  3055. SelExprs, StartLoc, EndLoc);
  3056. MsgExprs.push_back(SelExp);
  3057. // Now push any user supplied arguments.
  3058. for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
  3059. Expr *userExpr = Exp->getArg(i);
  3060. // Make all implicit casts explicit...ICE comes in handy:-)
  3061. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
  3062. // Reuse the ICE type, it is exactly what the doctor ordered.
  3063. QualType type = ICE->getType();
  3064. if (needToScanForQualifiers(type))
  3065. type = Context->getObjCIdType();
  3066. // Make sure we convert "type (^)(...)" to "type (*)(...)".
  3067. (void)convertBlockPointerToFunctionPointer(type);
  3068. const Expr *SubExpr = ICE->IgnoreParenImpCasts();
  3069. CastKind CK;
  3070. if (SubExpr->getType()->isIntegralType(*Context) &&
  3071. type->isBooleanType()) {
  3072. CK = CK_IntegralToBoolean;
  3073. } else if (type->isObjCObjectPointerType()) {
  3074. if (SubExpr->getType()->isBlockPointerType()) {
  3075. CK = CK_BlockPointerToObjCPointerCast;
  3076. } else if (SubExpr->getType()->isPointerType()) {
  3077. CK = CK_CPointerToObjCPointerCast;
  3078. } else {
  3079. CK = CK_BitCast;
  3080. }
  3081. } else {
  3082. CK = CK_BitCast;
  3083. }
  3084. userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
  3085. }
  3086. // Make id<P...> cast into an 'id' cast.
  3087. else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
  3088. if (CE->getType()->isObjCQualifiedIdType()) {
  3089. while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
  3090. userExpr = CE->getSubExpr();
  3091. CastKind CK;
  3092. if (userExpr->getType()->isIntegralType(*Context)) {
  3093. CK = CK_IntegralToPointer;
  3094. } else if (userExpr->getType()->isBlockPointerType()) {
  3095. CK = CK_BlockPointerToObjCPointerCast;
  3096. } else if (userExpr->getType()->isPointerType()) {
  3097. CK = CK_CPointerToObjCPointerCast;
  3098. } else {
  3099. CK = CK_BitCast;
  3100. }
  3101. userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
  3102. CK, userExpr);
  3103. }
  3104. }
  3105. MsgExprs.push_back(userExpr);
  3106. // We've transferred the ownership to MsgExprs. For now, we *don't* null
  3107. // out the argument in the original expression (since we aren't deleting
  3108. // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
  3109. //Exp->setArg(i, 0);
  3110. }
  3111. // Generate the funky cast.
  3112. CastExpr *cast;
  3113. SmallVector<QualType, 8> ArgTypes;
  3114. QualType returnType;
  3115. // Push 'id' and 'SEL', the 2 implicit arguments.
  3116. if (MsgSendFlavor == MsgSendSuperFunctionDecl)
  3117. ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
  3118. else
  3119. ArgTypes.push_back(Context->getObjCIdType());
  3120. ArgTypes.push_back(Context->getObjCSelType());
  3121. if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
  3122. // Push any user argument types.
  3123. for (const auto *PI : OMD->parameters()) {
  3124. QualType t = PI->getType()->isObjCQualifiedIdType()
  3125. ? Context->getObjCIdType()
  3126. : PI->getType();
  3127. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  3128. (void)convertBlockPointerToFunctionPointer(t);
  3129. ArgTypes.push_back(t);
  3130. }
  3131. returnType = Exp->getType();
  3132. convertToUnqualifiedObjCType(returnType);
  3133. (void)convertBlockPointerToFunctionPointer(returnType);
  3134. } else {
  3135. returnType = Context->getObjCIdType();
  3136. }
  3137. // Get the type, we will need to reference it in a couple spots.
  3138. QualType msgSendType = MsgSendFlavor->getType();
  3139. // Create a reference to the objc_msgSend() declaration.
  3140. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  3141. *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
  3142. // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
  3143. // If we don't do this cast, we get the following bizarre warning/note:
  3144. // xx.m:13: warning: function called through a non-compatible type
  3145. // xx.m:13: note: if this code is reached, the program will abort
  3146. cast = NoTypeInfoCStyleCastExpr(Context,
  3147. Context->getPointerType(Context->VoidTy),
  3148. CK_BitCast, DRE);
  3149. // Now do the "normal" pointer to function cast.
  3150. // If we don't have a method decl, force a variadic cast.
  3151. const ObjCMethodDecl *MD = Exp->getMethodDecl();
  3152. QualType castType =
  3153. getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
  3154. castType = Context->getPointerType(castType);
  3155. cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
  3156. cast);
  3157. // Don't forget the parens to enforce the proper binding.
  3158. ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
  3159. const FunctionType *FT = msgSendType->castAs<FunctionType>();
  3160. CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
  3161. VK_PRValue, EndLoc, FPOptionsOverride());
  3162. Stmt *ReplacingStmt = CE;
  3163. if (MsgSendStretFlavor) {
  3164. // We have the method which returns a struct/union. Must also generate
  3165. // call to objc_msgSend_stret and hang both varieties on a conditional
  3166. // expression which dictate which one to envoke depending on size of
  3167. // method's return type.
  3168. Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
  3169. returnType,
  3170. ArgTypes, MsgExprs,
  3171. Exp->getMethodDecl());
  3172. ReplacingStmt = STCE;
  3173. }
  3174. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  3175. return ReplacingStmt;
  3176. }
  3177. Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
  3178. Stmt *ReplacingStmt =
  3179. SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
  3180. // Now do the actual rewrite.
  3181. ReplaceStmt(Exp, ReplacingStmt);
  3182. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  3183. return ReplacingStmt;
  3184. }
  3185. // typedef struct objc_object Protocol;
  3186. QualType RewriteModernObjC::getProtocolType() {
  3187. if (!ProtocolTypeDecl) {
  3188. TypeSourceInfo *TInfo
  3189. = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
  3190. ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
  3191. SourceLocation(), SourceLocation(),
  3192. &Context->Idents.get("Protocol"),
  3193. TInfo);
  3194. }
  3195. return Context->getTypeDeclType(ProtocolTypeDecl);
  3196. }
  3197. /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
  3198. /// a synthesized/forward data reference (to the protocol's metadata).
  3199. /// The forward references (and metadata) are generated in
  3200. /// RewriteModernObjC::HandleTranslationUnit().
  3201. Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
  3202. std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
  3203. Exp->getProtocol()->getNameAsString();
  3204. IdentifierInfo *ID = &Context->Idents.get(Name);
  3205. VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  3206. SourceLocation(), ID, getProtocolType(),
  3207. nullptr, SC_Extern);
  3208. DeclRefExpr *DRE = new (Context) DeclRefExpr(
  3209. *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
  3210. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(
  3211. Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
  3212. ReplaceStmt(Exp, castExpr);
  3213. ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
  3214. // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
  3215. return castExpr;
  3216. }
  3217. /// IsTagDefinedInsideClass - This routine checks that a named tagged type
  3218. /// is defined inside an objective-c class. If so, it returns true.
  3219. bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
  3220. TagDecl *Tag,
  3221. bool &IsNamedDefinition) {
  3222. if (!IDecl)
  3223. return false;
  3224. SourceLocation TagLocation;
  3225. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
  3226. RD = RD->getDefinition();
  3227. if (!RD || !RD->getDeclName().getAsIdentifierInfo())
  3228. return false;
  3229. IsNamedDefinition = true;
  3230. TagLocation = RD->getLocation();
  3231. return Context->getSourceManager().isBeforeInTranslationUnit(
  3232. IDecl->getLocation(), TagLocation);
  3233. }
  3234. if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
  3235. if (!ED || !ED->getDeclName().getAsIdentifierInfo())
  3236. return false;
  3237. IsNamedDefinition = true;
  3238. TagLocation = ED->getLocation();
  3239. return Context->getSourceManager().isBeforeInTranslationUnit(
  3240. IDecl->getLocation(), TagLocation);
  3241. }
  3242. return false;
  3243. }
  3244. /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
  3245. /// It handles elaborated types, as well as enum types in the process.
  3246. bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
  3247. std::string &Result) {
  3248. if (Type->getAs<TypedefType>()) {
  3249. Result += "\t";
  3250. return false;
  3251. }
  3252. if (Type->isArrayType()) {
  3253. QualType ElemTy = Context->getBaseElementType(Type);
  3254. return RewriteObjCFieldDeclType(ElemTy, Result);
  3255. }
  3256. else if (Type->isRecordType()) {
  3257. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  3258. if (RD->isCompleteDefinition()) {
  3259. if (RD->isStruct())
  3260. Result += "\n\tstruct ";
  3261. else if (RD->isUnion())
  3262. Result += "\n\tunion ";
  3263. else
  3264. assert(false && "class not allowed as an ivar type");
  3265. Result += RD->getName();
  3266. if (GlobalDefinedTags.count(RD)) {
  3267. // struct/union is defined globally, use it.
  3268. Result += " ";
  3269. return true;
  3270. }
  3271. Result += " {\n";
  3272. for (auto *FD : RD->fields())
  3273. RewriteObjCFieldDecl(FD, Result);
  3274. Result += "\t} ";
  3275. return true;
  3276. }
  3277. }
  3278. else if (Type->isEnumeralType()) {
  3279. EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
  3280. if (ED->isCompleteDefinition()) {
  3281. Result += "\n\tenum ";
  3282. Result += ED->getName();
  3283. if (GlobalDefinedTags.count(ED)) {
  3284. // Enum is globall defined, use it.
  3285. Result += " ";
  3286. return true;
  3287. }
  3288. Result += " {\n";
  3289. for (const auto *EC : ED->enumerators()) {
  3290. Result += "\t"; Result += EC->getName(); Result += " = ";
  3291. Result += toString(EC->getInitVal(), 10);
  3292. Result += ",\n";
  3293. }
  3294. Result += "\t} ";
  3295. return true;
  3296. }
  3297. }
  3298. Result += "\t";
  3299. convertObjCTypeToCStyleType(Type);
  3300. return false;
  3301. }
  3302. /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
  3303. /// It handles elaborated types, as well as enum types in the process.
  3304. void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
  3305. std::string &Result) {
  3306. QualType Type = fieldDecl->getType();
  3307. std::string Name = fieldDecl->getNameAsString();
  3308. bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
  3309. if (!EleboratedType)
  3310. Type.getAsStringInternal(Name, Context->getPrintingPolicy());
  3311. Result += Name;
  3312. if (fieldDecl->isBitField()) {
  3313. Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
  3314. }
  3315. else if (EleboratedType && Type->isArrayType()) {
  3316. const ArrayType *AT = Context->getAsArrayType(Type);
  3317. do {
  3318. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
  3319. Result += "[";
  3320. llvm::APInt Dim = CAT->getSize();
  3321. Result += utostr(Dim.getZExtValue());
  3322. Result += "]";
  3323. }
  3324. AT = Context->getAsArrayType(AT->getElementType());
  3325. } while (AT);
  3326. }
  3327. Result += ";\n";
  3328. }
  3329. /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
  3330. /// named aggregate types into the input buffer.
  3331. void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
  3332. std::string &Result) {
  3333. QualType Type = fieldDecl->getType();
  3334. if (Type->getAs<TypedefType>())
  3335. return;
  3336. if (Type->isArrayType())
  3337. Type = Context->getBaseElementType(Type);
  3338. auto *IDecl = dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
  3339. TagDecl *TD = nullptr;
  3340. if (Type->isRecordType()) {
  3341. TD = Type->castAs<RecordType>()->getDecl();
  3342. }
  3343. else if (Type->isEnumeralType()) {
  3344. TD = Type->castAs<EnumType>()->getDecl();
  3345. }
  3346. if (TD) {
  3347. if (GlobalDefinedTags.count(TD))
  3348. return;
  3349. bool IsNamedDefinition = false;
  3350. if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
  3351. RewriteObjCFieldDeclType(Type, Result);
  3352. Result += ";";
  3353. }
  3354. if (IsNamedDefinition)
  3355. GlobalDefinedTags.insert(TD);
  3356. }
  3357. }
  3358. unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
  3359. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3360. if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
  3361. return IvarGroupNumber[IV];
  3362. }
  3363. unsigned GroupNo = 0;
  3364. SmallVector<const ObjCIvarDecl *, 8> IVars;
  3365. for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  3366. IVD; IVD = IVD->getNextIvar())
  3367. IVars.push_back(IVD);
  3368. for (unsigned i = 0, e = IVars.size(); i < e; i++)
  3369. if (IVars[i]->isBitField()) {
  3370. IvarGroupNumber[IVars[i++]] = ++GroupNo;
  3371. while (i < e && IVars[i]->isBitField())
  3372. IvarGroupNumber[IVars[i++]] = GroupNo;
  3373. if (i < e)
  3374. --i;
  3375. }
  3376. ObjCInterefaceHasBitfieldGroups.insert(CDecl);
  3377. return IvarGroupNumber[IV];
  3378. }
  3379. QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
  3380. ObjCIvarDecl *IV,
  3381. SmallVectorImpl<ObjCIvarDecl *> &IVars) {
  3382. std::string StructTagName;
  3383. ObjCIvarBitfieldGroupType(IV, StructTagName);
  3384. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
  3385. Context->getTranslationUnitDecl(),
  3386. SourceLocation(), SourceLocation(),
  3387. &Context->Idents.get(StructTagName));
  3388. for (unsigned i=0, e = IVars.size(); i < e; i++) {
  3389. ObjCIvarDecl *Ivar = IVars[i];
  3390. RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
  3391. &Context->Idents.get(Ivar->getName()),
  3392. Ivar->getType(),
  3393. nullptr, /*Expr *BW */Ivar->getBitWidth(),
  3394. false, ICIS_NoInit));
  3395. }
  3396. RD->completeDefinition();
  3397. return Context->getTagDeclType(RD);
  3398. }
  3399. QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
  3400. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3401. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
  3402. std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
  3403. if (GroupRecordType.count(tuple))
  3404. return GroupRecordType[tuple];
  3405. SmallVector<ObjCIvarDecl *, 8> IVars;
  3406. for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  3407. IVD; IVD = IVD->getNextIvar()) {
  3408. if (IVD->isBitField())
  3409. IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
  3410. else {
  3411. if (!IVars.empty()) {
  3412. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
  3413. // Generate the struct type for this group of bitfield ivars.
  3414. GroupRecordType[std::make_pair(CDecl, GroupNo)] =
  3415. SynthesizeBitfieldGroupStructType(IVars[0], IVars);
  3416. IVars.clear();
  3417. }
  3418. }
  3419. }
  3420. if (!IVars.empty()) {
  3421. // Do the last one.
  3422. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
  3423. GroupRecordType[std::make_pair(CDecl, GroupNo)] =
  3424. SynthesizeBitfieldGroupStructType(IVars[0], IVars);
  3425. }
  3426. QualType RetQT = GroupRecordType[tuple];
  3427. assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
  3428. return RetQT;
  3429. }
  3430. /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
  3431. /// Name would be: classname__GRBF_n where n is the group number for this ivar.
  3432. void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
  3433. std::string &Result) {
  3434. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3435. Result += CDecl->getName();
  3436. Result += "__GRBF_";
  3437. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
  3438. Result += utostr(GroupNo);
  3439. }
  3440. /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
  3441. /// Name of the struct would be: classname__T_n where n is the group number for
  3442. /// this ivar.
  3443. void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
  3444. std::string &Result) {
  3445. const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
  3446. Result += CDecl->getName();
  3447. Result += "__T_";
  3448. unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
  3449. Result += utostr(GroupNo);
  3450. }
  3451. /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
  3452. /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
  3453. /// this ivar.
  3454. void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
  3455. std::string &Result) {
  3456. Result += "OBJC_IVAR_$_";
  3457. ObjCIvarBitfieldGroupDecl(IV, Result);
  3458. }
  3459. #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
  3460. while ((IX < ENDIX) && VEC[IX]->isBitField()) \
  3461. ++IX; \
  3462. if (IX < ENDIX) \
  3463. --IX; \
  3464. }
  3465. /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
  3466. /// an objective-c class with ivars.
  3467. void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
  3468. std::string &Result) {
  3469. assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
  3470. assert(CDecl->getName() != "" &&
  3471. "Name missing in SynthesizeObjCInternalStruct");
  3472. ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
  3473. SmallVector<ObjCIvarDecl *, 8> IVars;
  3474. for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  3475. IVD; IVD = IVD->getNextIvar())
  3476. IVars.push_back(IVD);
  3477. SourceLocation LocStart = CDecl->getBeginLoc();
  3478. SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
  3479. const char *startBuf = SM->getCharacterData(LocStart);
  3480. const char *endBuf = SM->getCharacterData(LocEnd);
  3481. // If no ivars and no root or if its root, directly or indirectly,
  3482. // have no ivars (thus not synthesized) then no need to synthesize this class.
  3483. if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
  3484. (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
  3485. endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
  3486. ReplaceText(LocStart, endBuf-startBuf, Result);
  3487. return;
  3488. }
  3489. // Insert named struct/union definitions inside class to
  3490. // outer scope. This follows semantics of locally defined
  3491. // struct/unions in objective-c classes.
  3492. for (unsigned i = 0, e = IVars.size(); i < e; i++)
  3493. RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
  3494. // Insert named structs which are syntheized to group ivar bitfields
  3495. // to outer scope as well.
  3496. for (unsigned i = 0, e = IVars.size(); i < e; i++)
  3497. if (IVars[i]->isBitField()) {
  3498. ObjCIvarDecl *IV = IVars[i];
  3499. QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
  3500. RewriteObjCFieldDeclType(QT, Result);
  3501. Result += ";";
  3502. // skip over ivar bitfields in this group.
  3503. SKIP_BITFIELDS(i , e, IVars);
  3504. }
  3505. Result += "\nstruct ";
  3506. Result += CDecl->getNameAsString();
  3507. Result += "_IMPL {\n";
  3508. if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
  3509. Result += "\tstruct "; Result += RCDecl->getNameAsString();
  3510. Result += "_IMPL "; Result += RCDecl->getNameAsString();
  3511. Result += "_IVARS;\n";
  3512. }
  3513. for (unsigned i = 0, e = IVars.size(); i < e; i++) {
  3514. if (IVars[i]->isBitField()) {
  3515. ObjCIvarDecl *IV = IVars[i];
  3516. Result += "\tstruct ";
  3517. ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
  3518. ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
  3519. // skip over ivar bitfields in this group.
  3520. SKIP_BITFIELDS(i , e, IVars);
  3521. }
  3522. else
  3523. RewriteObjCFieldDecl(IVars[i], Result);
  3524. }
  3525. Result += "};\n";
  3526. endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
  3527. ReplaceText(LocStart, endBuf-startBuf, Result);
  3528. // Mark this struct as having been generated.
  3529. if (!ObjCSynthesizedStructs.insert(CDecl).second)
  3530. llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
  3531. }
  3532. /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
  3533. /// have been referenced in an ivar access expression.
  3534. void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
  3535. std::string &Result) {
  3536. // write out ivar offset symbols which have been referenced in an ivar
  3537. // access expression.
  3538. llvm::SmallSetVector<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
  3539. if (Ivars.empty())
  3540. return;
  3541. llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
  3542. for (ObjCIvarDecl *IvarDecl : Ivars) {
  3543. const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
  3544. unsigned GroupNo = 0;
  3545. if (IvarDecl->isBitField()) {
  3546. GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
  3547. if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
  3548. continue;
  3549. }
  3550. Result += "\n";
  3551. if (LangOpts.MicrosoftExt)
  3552. Result += "__declspec(allocate(\".objc_ivar$B\")) ";
  3553. Result += "extern \"C\" ";
  3554. if (LangOpts.MicrosoftExt &&
  3555. IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
  3556. IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
  3557. Result += "__declspec(dllimport) ";
  3558. Result += "unsigned long ";
  3559. if (IvarDecl->isBitField()) {
  3560. ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
  3561. GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
  3562. }
  3563. else
  3564. WriteInternalIvarName(CDecl, IvarDecl, Result);
  3565. Result += ";";
  3566. }
  3567. }
  3568. //===----------------------------------------------------------------------===//
  3569. // Meta Data Emission
  3570. //===----------------------------------------------------------------------===//
  3571. /// RewriteImplementations - This routine rewrites all method implementations
  3572. /// and emits meta-data.
  3573. void RewriteModernObjC::RewriteImplementations() {
  3574. int ClsDefCount = ClassImplementation.size();
  3575. int CatDefCount = CategoryImplementation.size();
  3576. // Rewrite implemented methods
  3577. for (int i = 0; i < ClsDefCount; i++) {
  3578. ObjCImplementationDecl *OIMP = ClassImplementation[i];
  3579. ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
  3580. if (CDecl->isImplicitInterfaceDecl())
  3581. assert(false &&
  3582. "Legacy implicit interface rewriting not supported in moder abi");
  3583. RewriteImplementationDecl(OIMP);
  3584. }
  3585. for (int i = 0; i < CatDefCount; i++) {
  3586. ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
  3587. ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
  3588. if (CDecl->isImplicitInterfaceDecl())
  3589. assert(false &&
  3590. "Legacy implicit interface rewriting not supported in moder abi");
  3591. RewriteImplementationDecl(CIMP);
  3592. }
  3593. }
  3594. void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
  3595. const std::string &Name,
  3596. ValueDecl *VD, bool def) {
  3597. assert(BlockByRefDeclNo.count(VD) &&
  3598. "RewriteByRefString: ByRef decl missing");
  3599. if (def)
  3600. ResultStr += "struct ";
  3601. ResultStr += "__Block_byref_" + Name +
  3602. "_" + utostr(BlockByRefDeclNo[VD]) ;
  3603. }
  3604. static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
  3605. if (VarDecl *Var = dyn_cast<VarDecl>(VD))
  3606. return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
  3607. return false;
  3608. }
  3609. std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
  3610. StringRef funcName,
  3611. std::string Tag) {
  3612. const FunctionType *AFT = CE->getFunctionType();
  3613. QualType RT = AFT->getReturnType();
  3614. std::string StructRef = "struct " + Tag;
  3615. SourceLocation BlockLoc = CE->getExprLoc();
  3616. std::string S;
  3617. ConvertSourceLocationToLineDirective(BlockLoc, S);
  3618. S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
  3619. funcName.str() + "_block_func_" + utostr(i);
  3620. BlockDecl *BD = CE->getBlockDecl();
  3621. if (isa<FunctionNoProtoType>(AFT)) {
  3622. // No user-supplied arguments. Still need to pass in a pointer to the
  3623. // block (to reference imported block decl refs).
  3624. S += "(" + StructRef + " *__cself)";
  3625. } else if (BD->param_empty()) {
  3626. S += "(" + StructRef + " *__cself)";
  3627. } else {
  3628. const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
  3629. assert(FT && "SynthesizeBlockFunc: No function proto");
  3630. S += '(';
  3631. // first add the implicit argument.
  3632. S += StructRef + " *__cself, ";
  3633. std::string ParamStr;
  3634. for (BlockDecl::param_iterator AI = BD->param_begin(),
  3635. E = BD->param_end(); AI != E; ++AI) {
  3636. if (AI != BD->param_begin()) S += ", ";
  3637. ParamStr = (*AI)->getNameAsString();
  3638. QualType QT = (*AI)->getType();
  3639. (void)convertBlockPointerToFunctionPointer(QT);
  3640. QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
  3641. S += ParamStr;
  3642. }
  3643. if (FT->isVariadic()) {
  3644. if (!BD->param_empty()) S += ", ";
  3645. S += "...";
  3646. }
  3647. S += ')';
  3648. }
  3649. S += " {\n";
  3650. // Create local declarations to avoid rewriting all closure decl ref exprs.
  3651. // First, emit a declaration for all "by ref" decls.
  3652. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3653. E = BlockByRefDecls.end(); I != E; ++I) {
  3654. S += " ";
  3655. std::string Name = (*I)->getNameAsString();
  3656. std::string TypeString;
  3657. RewriteByRefString(TypeString, Name, (*I));
  3658. TypeString += " *";
  3659. Name = TypeString + Name;
  3660. S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
  3661. }
  3662. // Next, emit a declaration for all "by copy" declarations.
  3663. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3664. E = BlockByCopyDecls.end(); I != E; ++I) {
  3665. S += " ";
  3666. // Handle nested closure invocation. For example:
  3667. //
  3668. // void (^myImportedClosure)(void);
  3669. // myImportedClosure = ^(void) { setGlobalInt(x + y); };
  3670. //
  3671. // void (^anotherClosure)(void);
  3672. // anotherClosure = ^(void) {
  3673. // myImportedClosure(); // import and invoke the closure
  3674. // };
  3675. //
  3676. if (isTopLevelBlockPointerType((*I)->getType())) {
  3677. RewriteBlockPointerTypeVariable(S, (*I));
  3678. S += " = (";
  3679. RewriteBlockPointerType(S, (*I)->getType());
  3680. S += ")";
  3681. S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
  3682. }
  3683. else {
  3684. std::string Name = (*I)->getNameAsString();
  3685. QualType QT = (*I)->getType();
  3686. if (HasLocalVariableExternalStorage(*I))
  3687. QT = Context->getPointerType(QT);
  3688. QT.getAsStringInternal(Name, Context->getPrintingPolicy());
  3689. S += Name + " = __cself->" +
  3690. (*I)->getNameAsString() + "; // bound by copy\n";
  3691. }
  3692. }
  3693. std::string RewrittenStr = RewrittenBlockExprs[CE];
  3694. const char *cstr = RewrittenStr.c_str();
  3695. while (*cstr++ != '{') ;
  3696. S += cstr;
  3697. S += "\n";
  3698. return S;
  3699. }
  3700. std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
  3701. StringRef funcName,
  3702. std::string Tag) {
  3703. std::string StructRef = "struct " + Tag;
  3704. std::string S = "static void __";
  3705. S += funcName;
  3706. S += "_block_copy_" + utostr(i);
  3707. S += "(" + StructRef;
  3708. S += "*dst, " + StructRef;
  3709. S += "*src) {";
  3710. for (ValueDecl *VD : ImportedBlockDecls) {
  3711. S += "_Block_object_assign((void*)&dst->";
  3712. S += VD->getNameAsString();
  3713. S += ", (void*)src->";
  3714. S += VD->getNameAsString();
  3715. if (BlockByRefDeclsPtrSet.count(VD))
  3716. S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
  3717. else if (VD->getType()->isBlockPointerType())
  3718. S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
  3719. else
  3720. S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
  3721. }
  3722. S += "}\n";
  3723. S += "\nstatic void __";
  3724. S += funcName;
  3725. S += "_block_dispose_" + utostr(i);
  3726. S += "(" + StructRef;
  3727. S += "*src) {";
  3728. for (ValueDecl *VD : ImportedBlockDecls) {
  3729. S += "_Block_object_dispose((void*)src->";
  3730. S += VD->getNameAsString();
  3731. if (BlockByRefDeclsPtrSet.count(VD))
  3732. S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
  3733. else if (VD->getType()->isBlockPointerType())
  3734. S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
  3735. else
  3736. S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
  3737. }
  3738. S += "}\n";
  3739. return S;
  3740. }
  3741. std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
  3742. std::string Desc) {
  3743. std::string S = "\nstruct " + Tag;
  3744. std::string Constructor = " " + Tag;
  3745. S += " {\n struct __block_impl impl;\n";
  3746. S += " struct " + Desc;
  3747. S += "* Desc;\n";
  3748. Constructor += "(void *fp, "; // Invoke function pointer.
  3749. Constructor += "struct " + Desc; // Descriptor pointer.
  3750. Constructor += " *desc";
  3751. if (BlockDeclRefs.size()) {
  3752. // Output all "by copy" declarations.
  3753. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3754. E = BlockByCopyDecls.end(); I != E; ++I) {
  3755. S += " ";
  3756. std::string FieldName = (*I)->getNameAsString();
  3757. std::string ArgName = "_" + FieldName;
  3758. // Handle nested closure invocation. For example:
  3759. //
  3760. // void (^myImportedBlock)(void);
  3761. // myImportedBlock = ^(void) { setGlobalInt(x + y); };
  3762. //
  3763. // void (^anotherBlock)(void);
  3764. // anotherBlock = ^(void) {
  3765. // myImportedBlock(); // import and invoke the closure
  3766. // };
  3767. //
  3768. if (isTopLevelBlockPointerType((*I)->getType())) {
  3769. S += "struct __block_impl *";
  3770. Constructor += ", void *" + ArgName;
  3771. } else {
  3772. QualType QT = (*I)->getType();
  3773. if (HasLocalVariableExternalStorage(*I))
  3774. QT = Context->getPointerType(QT);
  3775. QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
  3776. QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
  3777. Constructor += ", " + ArgName;
  3778. }
  3779. S += FieldName + ";\n";
  3780. }
  3781. // Output all "by ref" declarations.
  3782. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3783. E = BlockByRefDecls.end(); I != E; ++I) {
  3784. S += " ";
  3785. std::string FieldName = (*I)->getNameAsString();
  3786. std::string ArgName = "_" + FieldName;
  3787. {
  3788. std::string TypeString;
  3789. RewriteByRefString(TypeString, FieldName, (*I));
  3790. TypeString += " *";
  3791. FieldName = TypeString + FieldName;
  3792. ArgName = TypeString + ArgName;
  3793. Constructor += ", " + ArgName;
  3794. }
  3795. S += FieldName + "; // by ref\n";
  3796. }
  3797. // Finish writing the constructor.
  3798. Constructor += ", int flags=0)";
  3799. // Initialize all "by copy" arguments.
  3800. bool firsTime = true;
  3801. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  3802. E = BlockByCopyDecls.end(); I != E; ++I) {
  3803. std::string Name = (*I)->getNameAsString();
  3804. if (firsTime) {
  3805. Constructor += " : ";
  3806. firsTime = false;
  3807. }
  3808. else
  3809. Constructor += ", ";
  3810. if (isTopLevelBlockPointerType((*I)->getType()))
  3811. Constructor += Name + "((struct __block_impl *)_" + Name + ")";
  3812. else
  3813. Constructor += Name + "(_" + Name + ")";
  3814. }
  3815. // Initialize all "by ref" arguments.
  3816. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  3817. E = BlockByRefDecls.end(); I != E; ++I) {
  3818. std::string Name = (*I)->getNameAsString();
  3819. if (firsTime) {
  3820. Constructor += " : ";
  3821. firsTime = false;
  3822. }
  3823. else
  3824. Constructor += ", ";
  3825. Constructor += Name + "(_" + Name + "->__forwarding)";
  3826. }
  3827. Constructor += " {\n";
  3828. if (GlobalVarDecl)
  3829. Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
  3830. else
  3831. Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
  3832. Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
  3833. Constructor += " Desc = desc;\n";
  3834. } else {
  3835. // Finish writing the constructor.
  3836. Constructor += ", int flags=0) {\n";
  3837. if (GlobalVarDecl)
  3838. Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
  3839. else
  3840. Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
  3841. Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
  3842. Constructor += " Desc = desc;\n";
  3843. }
  3844. Constructor += " ";
  3845. Constructor += "}\n";
  3846. S += Constructor;
  3847. S += "};\n";
  3848. return S;
  3849. }
  3850. std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
  3851. std::string ImplTag, int i,
  3852. StringRef FunName,
  3853. unsigned hasCopy) {
  3854. std::string S = "\nstatic struct " + DescTag;
  3855. S += " {\n size_t reserved;\n";
  3856. S += " size_t Block_size;\n";
  3857. if (hasCopy) {
  3858. S += " void (*copy)(struct ";
  3859. S += ImplTag; S += "*, struct ";
  3860. S += ImplTag; S += "*);\n";
  3861. S += " void (*dispose)(struct ";
  3862. S += ImplTag; S += "*);\n";
  3863. }
  3864. S += "} ";
  3865. S += DescTag + "_DATA = { 0, sizeof(struct ";
  3866. S += ImplTag + ")";
  3867. if (hasCopy) {
  3868. S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
  3869. S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
  3870. }
  3871. S += "};\n";
  3872. return S;
  3873. }
  3874. void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
  3875. StringRef FunName) {
  3876. bool RewriteSC = (GlobalVarDecl &&
  3877. !Blocks.empty() &&
  3878. GlobalVarDecl->getStorageClass() == SC_Static &&
  3879. GlobalVarDecl->getType().getCVRQualifiers());
  3880. if (RewriteSC) {
  3881. std::string SC(" void __");
  3882. SC += GlobalVarDecl->getNameAsString();
  3883. SC += "() {}";
  3884. InsertText(FunLocStart, SC);
  3885. }
  3886. // Insert closures that were part of the function.
  3887. for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
  3888. CollectBlockDeclRefInfo(Blocks[i]);
  3889. // Need to copy-in the inner copied-in variables not actually used in this
  3890. // block.
  3891. for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
  3892. DeclRefExpr *Exp = InnerDeclRefs[count++];
  3893. ValueDecl *VD = Exp->getDecl();
  3894. BlockDeclRefs.push_back(Exp);
  3895. if (!VD->hasAttr<BlocksAttr>()) {
  3896. if (!BlockByCopyDeclsPtrSet.count(VD)) {
  3897. BlockByCopyDeclsPtrSet.insert(VD);
  3898. BlockByCopyDecls.push_back(VD);
  3899. }
  3900. continue;
  3901. }
  3902. if (!BlockByRefDeclsPtrSet.count(VD)) {
  3903. BlockByRefDeclsPtrSet.insert(VD);
  3904. BlockByRefDecls.push_back(VD);
  3905. }
  3906. // imported objects in the inner blocks not used in the outer
  3907. // blocks must be copied/disposed in the outer block as well.
  3908. if (VD->getType()->isObjCObjectPointerType() ||
  3909. VD->getType()->isBlockPointerType())
  3910. ImportedBlockDecls.insert(VD);
  3911. }
  3912. std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
  3913. std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
  3914. std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
  3915. InsertText(FunLocStart, CI);
  3916. std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
  3917. InsertText(FunLocStart, CF);
  3918. if (ImportedBlockDecls.size()) {
  3919. std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
  3920. InsertText(FunLocStart, HF);
  3921. }
  3922. std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
  3923. ImportedBlockDecls.size() > 0);
  3924. InsertText(FunLocStart, BD);
  3925. BlockDeclRefs.clear();
  3926. BlockByRefDecls.clear();
  3927. BlockByRefDeclsPtrSet.clear();
  3928. BlockByCopyDecls.clear();
  3929. BlockByCopyDeclsPtrSet.clear();
  3930. ImportedBlockDecls.clear();
  3931. }
  3932. if (RewriteSC) {
  3933. // Must insert any 'const/volatile/static here. Since it has been
  3934. // removed as result of rewriting of block literals.
  3935. std::string SC;
  3936. if (GlobalVarDecl->getStorageClass() == SC_Static)
  3937. SC = "static ";
  3938. if (GlobalVarDecl->getType().isConstQualified())
  3939. SC += "const ";
  3940. if (GlobalVarDecl->getType().isVolatileQualified())
  3941. SC += "volatile ";
  3942. if (GlobalVarDecl->getType().isRestrictQualified())
  3943. SC += "restrict ";
  3944. InsertText(FunLocStart, SC);
  3945. }
  3946. if (GlobalConstructionExp) {
  3947. // extra fancy dance for global literal expression.
  3948. // Always the latest block expression on the block stack.
  3949. std::string Tag = "__";
  3950. Tag += FunName;
  3951. Tag += "_block_impl_";
  3952. Tag += utostr(Blocks.size()-1);
  3953. std::string globalBuf = "static ";
  3954. globalBuf += Tag; globalBuf += " ";
  3955. std::string SStr;
  3956. llvm::raw_string_ostream constructorExprBuf(SStr);
  3957. GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
  3958. PrintingPolicy(LangOpts));
  3959. globalBuf += constructorExprBuf.str();
  3960. globalBuf += ";\n";
  3961. InsertText(FunLocStart, globalBuf);
  3962. GlobalConstructionExp = nullptr;
  3963. }
  3964. Blocks.clear();
  3965. InnerDeclRefsCount.clear();
  3966. InnerDeclRefs.clear();
  3967. RewrittenBlockExprs.clear();
  3968. }
  3969. void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
  3970. SourceLocation FunLocStart =
  3971. (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
  3972. : FD->getTypeSpecStartLoc();
  3973. StringRef FuncName = FD->getName();
  3974. SynthesizeBlockLiterals(FunLocStart, FuncName);
  3975. }
  3976. static void BuildUniqueMethodName(std::string &Name,
  3977. ObjCMethodDecl *MD) {
  3978. ObjCInterfaceDecl *IFace = MD->getClassInterface();
  3979. Name = std::string(IFace->getName());
  3980. Name += "__" + MD->getSelector().getAsString();
  3981. // Convert colons to underscores.
  3982. std::string::size_type loc = 0;
  3983. while ((loc = Name.find(':', loc)) != std::string::npos)
  3984. Name.replace(loc, 1, "_");
  3985. }
  3986. void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
  3987. // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
  3988. // SourceLocation FunLocStart = MD->getBeginLoc();
  3989. SourceLocation FunLocStart = MD->getBeginLoc();
  3990. std::string FuncName;
  3991. BuildUniqueMethodName(FuncName, MD);
  3992. SynthesizeBlockLiterals(FunLocStart, FuncName);
  3993. }
  3994. void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
  3995. for (Stmt *SubStmt : S->children())
  3996. if (SubStmt) {
  3997. if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
  3998. GetBlockDeclRefExprs(CBE->getBody());
  3999. else
  4000. GetBlockDeclRefExprs(SubStmt);
  4001. }
  4002. // Handle specific things.
  4003. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
  4004. if (DRE->refersToEnclosingVariableOrCapture() ||
  4005. HasLocalVariableExternalStorage(DRE->getDecl()))
  4006. // FIXME: Handle enums.
  4007. BlockDeclRefs.push_back(DRE);
  4008. }
  4009. void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
  4010. SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
  4011. llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
  4012. for (Stmt *SubStmt : S->children())
  4013. if (SubStmt) {
  4014. if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
  4015. InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
  4016. GetInnerBlockDeclRefExprs(CBE->getBody(),
  4017. InnerBlockDeclRefs,
  4018. InnerContexts);
  4019. }
  4020. else
  4021. GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
  4022. }
  4023. // Handle specific things.
  4024. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
  4025. if (DRE->refersToEnclosingVariableOrCapture() ||
  4026. HasLocalVariableExternalStorage(DRE->getDecl())) {
  4027. if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
  4028. InnerBlockDeclRefs.push_back(DRE);
  4029. if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
  4030. if (Var->isFunctionOrMethodVarDecl())
  4031. ImportedLocalExternalDecls.insert(Var);
  4032. }
  4033. }
  4034. }
  4035. /// convertObjCTypeToCStyleType - This routine converts such objc types
  4036. /// as qualified objects, and blocks to their closest c/c++ types that
  4037. /// it can. It returns true if input type was modified.
  4038. bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
  4039. QualType oldT = T;
  4040. convertBlockPointerToFunctionPointer(T);
  4041. if (T->isFunctionPointerType()) {
  4042. QualType PointeeTy;
  4043. if (const PointerType* PT = T->getAs<PointerType>()) {
  4044. PointeeTy = PT->getPointeeType();
  4045. if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
  4046. T = convertFunctionTypeOfBlocks(FT);
  4047. T = Context->getPointerType(T);
  4048. }
  4049. }
  4050. }
  4051. convertToUnqualifiedObjCType(T);
  4052. return T != oldT;
  4053. }
  4054. /// convertFunctionTypeOfBlocks - This routine converts a function type
  4055. /// whose result type may be a block pointer or whose argument type(s)
  4056. /// might be block pointers to an equivalent function type replacing
  4057. /// all block pointers to function pointers.
  4058. QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
  4059. const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
  4060. // FTP will be null for closures that don't take arguments.
  4061. // Generate a funky cast.
  4062. SmallVector<QualType, 8> ArgTypes;
  4063. QualType Res = FT->getReturnType();
  4064. bool modified = convertObjCTypeToCStyleType(Res);
  4065. if (FTP) {
  4066. for (auto &I : FTP->param_types()) {
  4067. QualType t = I;
  4068. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  4069. if (convertObjCTypeToCStyleType(t))
  4070. modified = true;
  4071. ArgTypes.push_back(t);
  4072. }
  4073. }
  4074. QualType FuncType;
  4075. if (modified)
  4076. FuncType = getSimpleFunctionType(Res, ArgTypes);
  4077. else FuncType = QualType(FT, 0);
  4078. return FuncType;
  4079. }
  4080. Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
  4081. // Navigate to relevant type information.
  4082. const BlockPointerType *CPT = nullptr;
  4083. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
  4084. CPT = DRE->getType()->getAs<BlockPointerType>();
  4085. } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
  4086. CPT = MExpr->getType()->getAs<BlockPointerType>();
  4087. }
  4088. else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
  4089. return SynthesizeBlockCall(Exp, PRE->getSubExpr());
  4090. }
  4091. else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
  4092. CPT = IEXPR->getType()->getAs<BlockPointerType>();
  4093. else if (const ConditionalOperator *CEXPR =
  4094. dyn_cast<ConditionalOperator>(BlockExp)) {
  4095. Expr *LHSExp = CEXPR->getLHS();
  4096. Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
  4097. Expr *RHSExp = CEXPR->getRHS();
  4098. Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
  4099. Expr *CONDExp = CEXPR->getCond();
  4100. ConditionalOperator *CondExpr = new (Context) ConditionalOperator(
  4101. CONDExp, SourceLocation(), cast<Expr>(LHSStmt), SourceLocation(),
  4102. cast<Expr>(RHSStmt), Exp->getType(), VK_PRValue, OK_Ordinary);
  4103. return CondExpr;
  4104. } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
  4105. CPT = IRE->getType()->getAs<BlockPointerType>();
  4106. } else if (const PseudoObjectExpr *POE
  4107. = dyn_cast<PseudoObjectExpr>(BlockExp)) {
  4108. CPT = POE->getType()->castAs<BlockPointerType>();
  4109. } else {
  4110. assert(false && "RewriteBlockClass: Bad type");
  4111. }
  4112. assert(CPT && "RewriteBlockClass: Bad type");
  4113. const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
  4114. assert(FT && "RewriteBlockClass: Bad type");
  4115. const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
  4116. // FTP will be null for closures that don't take arguments.
  4117. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  4118. SourceLocation(), SourceLocation(),
  4119. &Context->Idents.get("__block_impl"));
  4120. QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
  4121. // Generate a funky cast.
  4122. SmallVector<QualType, 8> ArgTypes;
  4123. // Push the block argument type.
  4124. ArgTypes.push_back(PtrBlock);
  4125. if (FTP) {
  4126. for (auto &I : FTP->param_types()) {
  4127. QualType t = I;
  4128. // Make sure we convert "t (^)(...)" to "t (*)(...)".
  4129. if (!convertBlockPointerToFunctionPointer(t))
  4130. convertToUnqualifiedObjCType(t);
  4131. ArgTypes.push_back(t);
  4132. }
  4133. }
  4134. // Now do the pointer to function cast.
  4135. QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
  4136. PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
  4137. CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
  4138. CK_BitCast,
  4139. const_cast<Expr*>(BlockExp));
  4140. // Don't forget the parens to enforce the proper binding.
  4141. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  4142. BlkCast);
  4143. //PE->dump();
  4144. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  4145. SourceLocation(),
  4146. &Context->Idents.get("FuncPtr"),
  4147. Context->VoidPtrTy, nullptr,
  4148. /*BitWidth=*/nullptr, /*Mutable=*/true,
  4149. ICIS_NoInit);
  4150. MemberExpr *ME = MemberExpr::CreateImplicit(
  4151. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  4152. CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
  4153. CK_BitCast, ME);
  4154. PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
  4155. SmallVector<Expr*, 8> BlkExprs;
  4156. // Add the implicit argument.
  4157. BlkExprs.push_back(BlkCast);
  4158. // Add the user arguments.
  4159. for (CallExpr::arg_iterator I = Exp->arg_begin(),
  4160. E = Exp->arg_end(); I != E; ++I) {
  4161. BlkExprs.push_back(*I);
  4162. }
  4163. CallExpr *CE =
  4164. CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(), VK_PRValue,
  4165. SourceLocation(), FPOptionsOverride());
  4166. return CE;
  4167. }
  4168. // We need to return the rewritten expression to handle cases where the
  4169. // DeclRefExpr is embedded in another expression being rewritten.
  4170. // For example:
  4171. //
  4172. // int main() {
  4173. // __block Foo *f;
  4174. // __block int i;
  4175. //
  4176. // void (^myblock)() = ^() {
  4177. // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
  4178. // i = 77;
  4179. // };
  4180. //}
  4181. Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
  4182. // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
  4183. // for each DeclRefExp where BYREFVAR is name of the variable.
  4184. ValueDecl *VD = DeclRefExp->getDecl();
  4185. bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
  4186. HasLocalVariableExternalStorage(DeclRefExp->getDecl());
  4187. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  4188. SourceLocation(),
  4189. &Context->Idents.get("__forwarding"),
  4190. Context->VoidPtrTy, nullptr,
  4191. /*BitWidth=*/nullptr, /*Mutable=*/true,
  4192. ICIS_NoInit);
  4193. MemberExpr *ME = MemberExpr::CreateImplicit(
  4194. *Context, DeclRefExp, isArrow, FD, FD->getType(), VK_LValue, OK_Ordinary);
  4195. StringRef Name = VD->getName();
  4196. FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
  4197. &Context->Idents.get(Name),
  4198. Context->VoidPtrTy, nullptr,
  4199. /*BitWidth=*/nullptr, /*Mutable=*/true,
  4200. ICIS_NoInit);
  4201. ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
  4202. VK_LValue, OK_Ordinary);
  4203. // Need parens to enforce precedence.
  4204. ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
  4205. DeclRefExp->getExprLoc(),
  4206. ME);
  4207. ReplaceStmt(DeclRefExp, PE);
  4208. return PE;
  4209. }
  4210. // Rewrites the imported local variable V with external storage
  4211. // (static, extern, etc.) as *V
  4212. //
  4213. Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
  4214. ValueDecl *VD = DRE->getDecl();
  4215. if (VarDecl *Var = dyn_cast<VarDecl>(VD))
  4216. if (!ImportedLocalExternalDecls.count(Var))
  4217. return DRE;
  4218. Expr *Exp = UnaryOperator::Create(
  4219. const_cast<ASTContext &>(*Context), DRE, UO_Deref, DRE->getType(),
  4220. VK_LValue, OK_Ordinary, DRE->getLocation(), false, FPOptionsOverride());
  4221. // Need parens to enforce precedence.
  4222. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  4223. Exp);
  4224. ReplaceStmt(DRE, PE);
  4225. return PE;
  4226. }
  4227. void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
  4228. SourceLocation LocStart = CE->getLParenLoc();
  4229. SourceLocation LocEnd = CE->getRParenLoc();
  4230. // Need to avoid trying to rewrite synthesized casts.
  4231. if (LocStart.isInvalid())
  4232. return;
  4233. // Need to avoid trying to rewrite casts contained in macros.
  4234. if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
  4235. return;
  4236. const char *startBuf = SM->getCharacterData(LocStart);
  4237. const char *endBuf = SM->getCharacterData(LocEnd);
  4238. QualType QT = CE->getType();
  4239. const Type* TypePtr = QT->getAs<Type>();
  4240. if (isa<TypeOfExprType>(TypePtr)) {
  4241. const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
  4242. QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
  4243. std::string TypeAsString = "(";
  4244. RewriteBlockPointerType(TypeAsString, QT);
  4245. TypeAsString += ")";
  4246. ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
  4247. return;
  4248. }
  4249. // advance the location to startArgList.
  4250. const char *argPtr = startBuf;
  4251. while (*argPtr++ && (argPtr < endBuf)) {
  4252. switch (*argPtr) {
  4253. case '^':
  4254. // Replace the '^' with '*'.
  4255. LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
  4256. ReplaceText(LocStart, 1, "*");
  4257. break;
  4258. }
  4259. }
  4260. }
  4261. void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
  4262. CastKind CastKind = IC->getCastKind();
  4263. if (CastKind != CK_BlockPointerToObjCPointerCast &&
  4264. CastKind != CK_AnyPointerToBlockPointerCast)
  4265. return;
  4266. QualType QT = IC->getType();
  4267. (void)convertBlockPointerToFunctionPointer(QT);
  4268. std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
  4269. std::string Str = "(";
  4270. Str += TypeString;
  4271. Str += ")";
  4272. InsertText(IC->getSubExpr()->getBeginLoc(), Str);
  4273. }
  4274. void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
  4275. SourceLocation DeclLoc = FD->getLocation();
  4276. unsigned parenCount = 0;
  4277. // We have 1 or more arguments that have closure pointers.
  4278. const char *startBuf = SM->getCharacterData(DeclLoc);
  4279. const char *startArgList = strchr(startBuf, '(');
  4280. assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
  4281. parenCount++;
  4282. // advance the location to startArgList.
  4283. DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
  4284. assert((DeclLoc.isValid()) && "Invalid DeclLoc");
  4285. const char *argPtr = startArgList;
  4286. while (*argPtr++ && parenCount) {
  4287. switch (*argPtr) {
  4288. case '^':
  4289. // Replace the '^' with '*'.
  4290. DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
  4291. ReplaceText(DeclLoc, 1, "*");
  4292. break;
  4293. case '(':
  4294. parenCount++;
  4295. break;
  4296. case ')':
  4297. parenCount--;
  4298. break;
  4299. }
  4300. }
  4301. }
  4302. bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
  4303. const FunctionProtoType *FTP;
  4304. const PointerType *PT = QT->getAs<PointerType>();
  4305. if (PT) {
  4306. FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
  4307. } else {
  4308. const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
  4309. assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
  4310. FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
  4311. }
  4312. if (FTP) {
  4313. for (const auto &I : FTP->param_types())
  4314. if (isTopLevelBlockPointerType(I))
  4315. return true;
  4316. }
  4317. return false;
  4318. }
  4319. bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
  4320. const FunctionProtoType *FTP;
  4321. const PointerType *PT = QT->getAs<PointerType>();
  4322. if (PT) {
  4323. FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
  4324. } else {
  4325. const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
  4326. assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
  4327. FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
  4328. }
  4329. if (FTP) {
  4330. for (const auto &I : FTP->param_types()) {
  4331. if (I->isObjCQualifiedIdType())
  4332. return true;
  4333. if (I->isObjCObjectPointerType() &&
  4334. I->getPointeeType()->isObjCQualifiedInterfaceType())
  4335. return true;
  4336. }
  4337. }
  4338. return false;
  4339. }
  4340. void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
  4341. const char *&RParen) {
  4342. const char *argPtr = strchr(Name, '(');
  4343. assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
  4344. LParen = argPtr; // output the start.
  4345. argPtr++; // skip past the left paren.
  4346. unsigned parenCount = 1;
  4347. while (*argPtr && parenCount) {
  4348. switch (*argPtr) {
  4349. case '(': parenCount++; break;
  4350. case ')': parenCount--; break;
  4351. default: break;
  4352. }
  4353. if (parenCount) argPtr++;
  4354. }
  4355. assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
  4356. RParen = argPtr; // output the end
  4357. }
  4358. void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
  4359. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  4360. RewriteBlockPointerFunctionArgs(FD);
  4361. return;
  4362. }
  4363. // Handle Variables and Typedefs.
  4364. SourceLocation DeclLoc = ND->getLocation();
  4365. QualType DeclT;
  4366. if (VarDecl *VD = dyn_cast<VarDecl>(ND))
  4367. DeclT = VD->getType();
  4368. else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
  4369. DeclT = TDD->getUnderlyingType();
  4370. else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
  4371. DeclT = FD->getType();
  4372. else
  4373. llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
  4374. const char *startBuf = SM->getCharacterData(DeclLoc);
  4375. const char *endBuf = startBuf;
  4376. // scan backward (from the decl location) for the end of the previous decl.
  4377. while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
  4378. startBuf--;
  4379. SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
  4380. std::string buf;
  4381. unsigned OrigLength=0;
  4382. // *startBuf != '^' if we are dealing with a pointer to function that
  4383. // may take block argument types (which will be handled below).
  4384. if (*startBuf == '^') {
  4385. // Replace the '^' with '*', computing a negative offset.
  4386. buf = '*';
  4387. startBuf++;
  4388. OrigLength++;
  4389. }
  4390. while (*startBuf != ')') {
  4391. buf += *startBuf;
  4392. startBuf++;
  4393. OrigLength++;
  4394. }
  4395. buf += ')';
  4396. OrigLength++;
  4397. if (PointerTypeTakesAnyBlockArguments(DeclT) ||
  4398. PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
  4399. // Replace the '^' with '*' for arguments.
  4400. // Replace id<P> with id/*<>*/
  4401. DeclLoc = ND->getLocation();
  4402. startBuf = SM->getCharacterData(DeclLoc);
  4403. const char *argListBegin, *argListEnd;
  4404. GetExtentOfArgList(startBuf, argListBegin, argListEnd);
  4405. while (argListBegin < argListEnd) {
  4406. if (*argListBegin == '^')
  4407. buf += '*';
  4408. else if (*argListBegin == '<') {
  4409. buf += "/*";
  4410. buf += *argListBegin++;
  4411. OrigLength++;
  4412. while (*argListBegin != '>') {
  4413. buf += *argListBegin++;
  4414. OrigLength++;
  4415. }
  4416. buf += *argListBegin;
  4417. buf += "*/";
  4418. }
  4419. else
  4420. buf += *argListBegin;
  4421. argListBegin++;
  4422. OrigLength++;
  4423. }
  4424. buf += ')';
  4425. OrigLength++;
  4426. }
  4427. ReplaceText(Start, OrigLength, buf);
  4428. }
  4429. /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
  4430. /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
  4431. /// struct Block_byref_id_object *src) {
  4432. /// _Block_object_assign (&_dest->object, _src->object,
  4433. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
  4434. /// [|BLOCK_FIELD_IS_WEAK]) // object
  4435. /// _Block_object_assign(&_dest->object, _src->object,
  4436. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
  4437. /// [|BLOCK_FIELD_IS_WEAK]) // block
  4438. /// }
  4439. /// And:
  4440. /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
  4441. /// _Block_object_dispose(_src->object,
  4442. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
  4443. /// [|BLOCK_FIELD_IS_WEAK]) // object
  4444. /// _Block_object_dispose(_src->object,
  4445. /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
  4446. /// [|BLOCK_FIELD_IS_WEAK]) // block
  4447. /// }
  4448. std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
  4449. int flag) {
  4450. std::string S;
  4451. if (CopyDestroyCache.count(flag))
  4452. return S;
  4453. CopyDestroyCache.insert(flag);
  4454. S = "static void __Block_byref_id_object_copy_";
  4455. S += utostr(flag);
  4456. S += "(void *dst, void *src) {\n";
  4457. // offset into the object pointer is computed as:
  4458. // void * + void* + int + int + void* + void *
  4459. unsigned IntSize =
  4460. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  4461. unsigned VoidPtrSize =
  4462. static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
  4463. unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
  4464. S += " _Block_object_assign((char*)dst + ";
  4465. S += utostr(offset);
  4466. S += ", *(void * *) ((char*)src + ";
  4467. S += utostr(offset);
  4468. S += "), ";
  4469. S += utostr(flag);
  4470. S += ");\n}\n";
  4471. S += "static void __Block_byref_id_object_dispose_";
  4472. S += utostr(flag);
  4473. S += "(void *src) {\n";
  4474. S += " _Block_object_dispose(*(void * *) ((char*)src + ";
  4475. S += utostr(offset);
  4476. S += "), ";
  4477. S += utostr(flag);
  4478. S += ");\n}\n";
  4479. return S;
  4480. }
  4481. /// RewriteByRefVar - For each __block typex ND variable this routine transforms
  4482. /// the declaration into:
  4483. /// struct __Block_byref_ND {
  4484. /// void *__isa; // NULL for everything except __weak pointers
  4485. /// struct __Block_byref_ND *__forwarding;
  4486. /// int32_t __flags;
  4487. /// int32_t __size;
  4488. /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
  4489. /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
  4490. /// typex ND;
  4491. /// };
  4492. ///
  4493. /// It then replaces declaration of ND variable with:
  4494. /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
  4495. /// __size=sizeof(struct __Block_byref_ND),
  4496. /// ND=initializer-if-any};
  4497. ///
  4498. ///
  4499. void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
  4500. bool lastDecl) {
  4501. int flag = 0;
  4502. int isa = 0;
  4503. SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
  4504. if (DeclLoc.isInvalid())
  4505. // If type location is missing, it is because of missing type (a warning).
  4506. // Use variable's location which is good for this case.
  4507. DeclLoc = ND->getLocation();
  4508. const char *startBuf = SM->getCharacterData(DeclLoc);
  4509. SourceLocation X = ND->getEndLoc();
  4510. X = SM->getExpansionLoc(X);
  4511. const char *endBuf = SM->getCharacterData(X);
  4512. std::string Name(ND->getNameAsString());
  4513. std::string ByrefType;
  4514. RewriteByRefString(ByrefType, Name, ND, true);
  4515. ByrefType += " {\n";
  4516. ByrefType += " void *__isa;\n";
  4517. RewriteByRefString(ByrefType, Name, ND);
  4518. ByrefType += " *__forwarding;\n";
  4519. ByrefType += " int __flags;\n";
  4520. ByrefType += " int __size;\n";
  4521. // Add void *__Block_byref_id_object_copy;
  4522. // void *__Block_byref_id_object_dispose; if needed.
  4523. QualType Ty = ND->getType();
  4524. bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
  4525. if (HasCopyAndDispose) {
  4526. ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
  4527. ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
  4528. }
  4529. QualType T = Ty;
  4530. (void)convertBlockPointerToFunctionPointer(T);
  4531. T.getAsStringInternal(Name, Context->getPrintingPolicy());
  4532. ByrefType += " " + Name + ";\n";
  4533. ByrefType += "};\n";
  4534. // Insert this type in global scope. It is needed by helper function.
  4535. SourceLocation FunLocStart;
  4536. if (CurFunctionDef)
  4537. FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
  4538. else {
  4539. assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
  4540. FunLocStart = CurMethodDef->getBeginLoc();
  4541. }
  4542. InsertText(FunLocStart, ByrefType);
  4543. if (Ty.isObjCGCWeak()) {
  4544. flag |= BLOCK_FIELD_IS_WEAK;
  4545. isa = 1;
  4546. }
  4547. if (HasCopyAndDispose) {
  4548. flag = BLOCK_BYREF_CALLER;
  4549. QualType Ty = ND->getType();
  4550. // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
  4551. if (Ty->isBlockPointerType())
  4552. flag |= BLOCK_FIELD_IS_BLOCK;
  4553. else
  4554. flag |= BLOCK_FIELD_IS_OBJECT;
  4555. std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
  4556. if (!HF.empty())
  4557. Preamble += HF;
  4558. }
  4559. // struct __Block_byref_ND ND =
  4560. // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
  4561. // initializer-if-any};
  4562. bool hasInit = (ND->getInit() != nullptr);
  4563. // FIXME. rewriter does not support __block c++ objects which
  4564. // require construction.
  4565. if (hasInit)
  4566. if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
  4567. CXXConstructorDecl *CXXDecl = CExp->getConstructor();
  4568. if (CXXDecl && CXXDecl->isDefaultConstructor())
  4569. hasInit = false;
  4570. }
  4571. unsigned flags = 0;
  4572. if (HasCopyAndDispose)
  4573. flags |= BLOCK_HAS_COPY_DISPOSE;
  4574. Name = ND->getNameAsString();
  4575. ByrefType.clear();
  4576. RewriteByRefString(ByrefType, Name, ND);
  4577. std::string ForwardingCastType("(");
  4578. ForwardingCastType += ByrefType + " *)";
  4579. ByrefType += " " + Name + " = {(void*)";
  4580. ByrefType += utostr(isa);
  4581. ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
  4582. ByrefType += utostr(flags);
  4583. ByrefType += ", ";
  4584. ByrefType += "sizeof(";
  4585. RewriteByRefString(ByrefType, Name, ND);
  4586. ByrefType += ")";
  4587. if (HasCopyAndDispose) {
  4588. ByrefType += ", __Block_byref_id_object_copy_";
  4589. ByrefType += utostr(flag);
  4590. ByrefType += ", __Block_byref_id_object_dispose_";
  4591. ByrefType += utostr(flag);
  4592. }
  4593. if (!firstDecl) {
  4594. // In multiple __block declarations, and for all but 1st declaration,
  4595. // find location of the separating comma. This would be start location
  4596. // where new text is to be inserted.
  4597. DeclLoc = ND->getLocation();
  4598. const char *startDeclBuf = SM->getCharacterData(DeclLoc);
  4599. const char *commaBuf = startDeclBuf;
  4600. while (*commaBuf != ',')
  4601. commaBuf--;
  4602. assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
  4603. DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
  4604. startBuf = commaBuf;
  4605. }
  4606. if (!hasInit) {
  4607. ByrefType += "};\n";
  4608. unsigned nameSize = Name.size();
  4609. // for block or function pointer declaration. Name is already
  4610. // part of the declaration.
  4611. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
  4612. nameSize = 1;
  4613. ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
  4614. }
  4615. else {
  4616. ByrefType += ", ";
  4617. SourceLocation startLoc;
  4618. Expr *E = ND->getInit();
  4619. if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
  4620. startLoc = ECE->getLParenLoc();
  4621. else
  4622. startLoc = E->getBeginLoc();
  4623. startLoc = SM->getExpansionLoc(startLoc);
  4624. endBuf = SM->getCharacterData(startLoc);
  4625. ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
  4626. const char separator = lastDecl ? ';' : ',';
  4627. const char *startInitializerBuf = SM->getCharacterData(startLoc);
  4628. const char *separatorBuf = strchr(startInitializerBuf, separator);
  4629. assert((*separatorBuf == separator) &&
  4630. "RewriteByRefVar: can't find ';' or ','");
  4631. SourceLocation separatorLoc =
  4632. startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
  4633. InsertText(separatorLoc, lastDecl ? "}" : "};\n");
  4634. }
  4635. }
  4636. void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
  4637. // Add initializers for any closure decl refs.
  4638. GetBlockDeclRefExprs(Exp->getBody());
  4639. if (BlockDeclRefs.size()) {
  4640. // Unique all "by copy" declarations.
  4641. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  4642. if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
  4643. if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
  4644. BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
  4645. BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
  4646. }
  4647. }
  4648. // Unique all "by ref" declarations.
  4649. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  4650. if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
  4651. if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
  4652. BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
  4653. BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
  4654. }
  4655. }
  4656. // Find any imported blocks...they will need special attention.
  4657. for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
  4658. if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
  4659. BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
  4660. BlockDeclRefs[i]->getType()->isBlockPointerType())
  4661. ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
  4662. }
  4663. }
  4664. FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
  4665. IdentifierInfo *ID = &Context->Idents.get(name);
  4666. QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
  4667. return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
  4668. SourceLocation(), ID, FType, nullptr, SC_Extern,
  4669. false, false);
  4670. }
  4671. Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
  4672. const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
  4673. const BlockDecl *block = Exp->getBlockDecl();
  4674. Blocks.push_back(Exp);
  4675. CollectBlockDeclRefInfo(Exp);
  4676. // Add inner imported variables now used in current block.
  4677. int countOfInnerDecls = 0;
  4678. if (!InnerBlockDeclRefs.empty()) {
  4679. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
  4680. DeclRefExpr *Exp = InnerBlockDeclRefs[i];
  4681. ValueDecl *VD = Exp->getDecl();
  4682. if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
  4683. // We need to save the copied-in variables in nested
  4684. // blocks because it is needed at the end for some of the API generations.
  4685. // See SynthesizeBlockLiterals routine.
  4686. InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
  4687. BlockDeclRefs.push_back(Exp);
  4688. BlockByCopyDeclsPtrSet.insert(VD);
  4689. BlockByCopyDecls.push_back(VD);
  4690. }
  4691. if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
  4692. InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
  4693. BlockDeclRefs.push_back(Exp);
  4694. BlockByRefDeclsPtrSet.insert(VD);
  4695. BlockByRefDecls.push_back(VD);
  4696. }
  4697. }
  4698. // Find any imported blocks...they will need special attention.
  4699. for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
  4700. if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
  4701. InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
  4702. InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
  4703. ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
  4704. }
  4705. InnerDeclRefsCount.push_back(countOfInnerDecls);
  4706. std::string FuncName;
  4707. if (CurFunctionDef)
  4708. FuncName = CurFunctionDef->getNameAsString();
  4709. else if (CurMethodDef)
  4710. BuildUniqueMethodName(FuncName, CurMethodDef);
  4711. else if (GlobalVarDecl)
  4712. FuncName = std::string(GlobalVarDecl->getNameAsString());
  4713. bool GlobalBlockExpr =
  4714. block->getDeclContext()->getRedeclContext()->isFileContext();
  4715. if (GlobalBlockExpr && !GlobalVarDecl) {
  4716. Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
  4717. GlobalBlockExpr = false;
  4718. }
  4719. std::string BlockNumber = utostr(Blocks.size()-1);
  4720. std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
  4721. // Get a pointer to the function type so we can cast appropriately.
  4722. QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
  4723. QualType FType = Context->getPointerType(BFT);
  4724. FunctionDecl *FD;
  4725. Expr *NewRep;
  4726. // Simulate a constructor call...
  4727. std::string Tag;
  4728. if (GlobalBlockExpr)
  4729. Tag = "__global_";
  4730. else
  4731. Tag = "__";
  4732. Tag += FuncName + "_block_impl_" + BlockNumber;
  4733. FD = SynthBlockInitFunctionDecl(Tag);
  4734. DeclRefExpr *DRE = new (Context)
  4735. DeclRefExpr(*Context, FD, false, FType, VK_PRValue, SourceLocation());
  4736. SmallVector<Expr*, 4> InitExprs;
  4737. // Initialize the block function.
  4738. FD = SynthBlockInitFunctionDecl(Func);
  4739. DeclRefExpr *Arg = new (Context) DeclRefExpr(
  4740. *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
  4741. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
  4742. CK_BitCast, Arg);
  4743. InitExprs.push_back(castExpr);
  4744. // Initialize the block descriptor.
  4745. std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
  4746. VarDecl *NewVD = VarDecl::Create(
  4747. *Context, TUDecl, SourceLocation(), SourceLocation(),
  4748. &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
  4749. UnaryOperator *DescRefExpr = UnaryOperator::Create(
  4750. const_cast<ASTContext &>(*Context),
  4751. new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
  4752. VK_LValue, SourceLocation()),
  4753. UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_PRValue,
  4754. OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
  4755. InitExprs.push_back(DescRefExpr);
  4756. // Add initializers for any closure decl refs.
  4757. if (BlockDeclRefs.size()) {
  4758. Expr *Exp;
  4759. // Output all "by copy" declarations.
  4760. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
  4761. E = BlockByCopyDecls.end(); I != E; ++I) {
  4762. if (isObjCType((*I)->getType())) {
  4763. // FIXME: Conform to ABI ([[obj retain] autorelease]).
  4764. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4765. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4766. VK_LValue, SourceLocation());
  4767. if (HasLocalVariableExternalStorage(*I)) {
  4768. QualType QT = (*I)->getType();
  4769. QT = Context->getPointerType(QT);
  4770. Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
  4771. UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
  4772. SourceLocation(), false,
  4773. FPOptionsOverride());
  4774. }
  4775. } else if (isTopLevelBlockPointerType((*I)->getType())) {
  4776. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4777. Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4778. VK_LValue, SourceLocation());
  4779. Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
  4780. CK_BitCast, Arg);
  4781. } else {
  4782. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4783. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4784. VK_LValue, SourceLocation());
  4785. if (HasLocalVariableExternalStorage(*I)) {
  4786. QualType QT = (*I)->getType();
  4787. QT = Context->getPointerType(QT);
  4788. Exp = UnaryOperator::Create(const_cast<ASTContext &>(*Context), Exp,
  4789. UO_AddrOf, QT, VK_PRValue, OK_Ordinary,
  4790. SourceLocation(), false,
  4791. FPOptionsOverride());
  4792. }
  4793. }
  4794. InitExprs.push_back(Exp);
  4795. }
  4796. // Output all "by ref" declarations.
  4797. for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
  4798. E = BlockByRefDecls.end(); I != E; ++I) {
  4799. ValueDecl *ND = (*I);
  4800. std::string Name(ND->getNameAsString());
  4801. std::string RecName;
  4802. RewriteByRefString(RecName, Name, ND, true);
  4803. IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
  4804. + sizeof("struct"));
  4805. RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
  4806. SourceLocation(), SourceLocation(),
  4807. II);
  4808. assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
  4809. QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
  4810. FD = SynthBlockInitFunctionDecl((*I)->getName());
  4811. Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
  4812. VK_LValue, SourceLocation());
  4813. bool isNestedCapturedVar = false;
  4814. for (const auto &CI : block->captures()) {
  4815. const VarDecl *variable = CI.getVariable();
  4816. if (variable == ND && CI.isNested()) {
  4817. assert(CI.isByRef() &&
  4818. "SynthBlockInitExpr - captured block variable is not byref");
  4819. isNestedCapturedVar = true;
  4820. break;
  4821. }
  4822. }
  4823. // captured nested byref variable has its address passed. Do not take
  4824. // its address again.
  4825. if (!isNestedCapturedVar)
  4826. Exp = UnaryOperator::Create(
  4827. const_cast<ASTContext &>(*Context), Exp, UO_AddrOf,
  4828. Context->getPointerType(Exp->getType()), VK_PRValue, OK_Ordinary,
  4829. SourceLocation(), false, FPOptionsOverride());
  4830. Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
  4831. InitExprs.push_back(Exp);
  4832. }
  4833. }
  4834. if (ImportedBlockDecls.size()) {
  4835. // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
  4836. int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
  4837. unsigned IntSize =
  4838. static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
  4839. Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
  4840. Context->IntTy, SourceLocation());
  4841. InitExprs.push_back(FlagExp);
  4842. }
  4843. NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
  4844. SourceLocation(), FPOptionsOverride());
  4845. if (GlobalBlockExpr) {
  4846. assert (!GlobalConstructionExp &&
  4847. "SynthBlockInitExpr - GlobalConstructionExp must be null");
  4848. GlobalConstructionExp = NewRep;
  4849. NewRep = DRE;
  4850. }
  4851. NewRep = UnaryOperator::Create(
  4852. const_cast<ASTContext &>(*Context), NewRep, UO_AddrOf,
  4853. Context->getPointerType(NewRep->getType()), VK_PRValue, OK_Ordinary,
  4854. SourceLocation(), false, FPOptionsOverride());
  4855. NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
  4856. NewRep);
  4857. // Put Paren around the call.
  4858. NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  4859. NewRep);
  4860. BlockDeclRefs.clear();
  4861. BlockByRefDecls.clear();
  4862. BlockByRefDeclsPtrSet.clear();
  4863. BlockByCopyDecls.clear();
  4864. BlockByCopyDeclsPtrSet.clear();
  4865. ImportedBlockDecls.clear();
  4866. return NewRep;
  4867. }
  4868. bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
  4869. if (const ObjCForCollectionStmt * CS =
  4870. dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
  4871. return CS->getElement() == DS;
  4872. return false;
  4873. }
  4874. //===----------------------------------------------------------------------===//
  4875. // Function Body / Expression rewriting
  4876. //===----------------------------------------------------------------------===//
  4877. Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
  4878. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  4879. isa<DoStmt>(S) || isa<ForStmt>(S))
  4880. Stmts.push_back(S);
  4881. else if (isa<ObjCForCollectionStmt>(S)) {
  4882. Stmts.push_back(S);
  4883. ObjCBcLabelNo.push_back(++BcLabelCount);
  4884. }
  4885. // Pseudo-object operations and ivar references need special
  4886. // treatment because we're going to recursively rewrite them.
  4887. if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
  4888. if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
  4889. return RewritePropertyOrImplicitSetter(PseudoOp);
  4890. } else {
  4891. return RewritePropertyOrImplicitGetter(PseudoOp);
  4892. }
  4893. } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
  4894. return RewriteObjCIvarRefExpr(IvarRefExpr);
  4895. }
  4896. else if (isa<OpaqueValueExpr>(S))
  4897. S = cast<OpaqueValueExpr>(S)->getSourceExpr();
  4898. SourceRange OrigStmtRange = S->getSourceRange();
  4899. // Perform a bottom up rewrite of all children.
  4900. for (Stmt *&childStmt : S->children())
  4901. if (childStmt) {
  4902. Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
  4903. if (newStmt) {
  4904. childStmt = newStmt;
  4905. }
  4906. }
  4907. if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
  4908. SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
  4909. llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
  4910. InnerContexts.insert(BE->getBlockDecl());
  4911. ImportedLocalExternalDecls.clear();
  4912. GetInnerBlockDeclRefExprs(BE->getBody(),
  4913. InnerBlockDeclRefs, InnerContexts);
  4914. // Rewrite the block body in place.
  4915. Stmt *SaveCurrentBody = CurrentBody;
  4916. CurrentBody = BE->getBody();
  4917. PropParentMap = nullptr;
  4918. // block literal on rhs of a property-dot-sytax assignment
  4919. // must be replaced by its synthesize ast so getRewrittenText
  4920. // works as expected. In this case, what actually ends up on RHS
  4921. // is the blockTranscribed which is the helper function for the
  4922. // block literal; as in: self.c = ^() {[ace ARR];};
  4923. bool saveDisableReplaceStmt = DisableReplaceStmt;
  4924. DisableReplaceStmt = false;
  4925. RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
  4926. DisableReplaceStmt = saveDisableReplaceStmt;
  4927. CurrentBody = SaveCurrentBody;
  4928. PropParentMap = nullptr;
  4929. ImportedLocalExternalDecls.clear();
  4930. // Now we snarf the rewritten text and stash it away for later use.
  4931. std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
  4932. RewrittenBlockExprs[BE] = Str;
  4933. Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
  4934. //blockTranscribed->dump();
  4935. ReplaceStmt(S, blockTranscribed);
  4936. return blockTranscribed;
  4937. }
  4938. // Handle specific things.
  4939. if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
  4940. return RewriteAtEncode(AtEncode);
  4941. if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
  4942. return RewriteAtSelector(AtSelector);
  4943. if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
  4944. return RewriteObjCStringLiteral(AtString);
  4945. if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
  4946. return RewriteObjCBoolLiteralExpr(BoolLitExpr);
  4947. if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
  4948. return RewriteObjCBoxedExpr(BoxedExpr);
  4949. if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
  4950. return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
  4951. if (ObjCDictionaryLiteral *DictionaryLitExpr =
  4952. dyn_cast<ObjCDictionaryLiteral>(S))
  4953. return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
  4954. if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
  4955. #if 0
  4956. // Before we rewrite it, put the original message expression in a comment.
  4957. SourceLocation startLoc = MessExpr->getBeginLoc();
  4958. SourceLocation endLoc = MessExpr->getEndLoc();
  4959. const char *startBuf = SM->getCharacterData(startLoc);
  4960. const char *endBuf = SM->getCharacterData(endLoc);
  4961. std::string messString;
  4962. messString += "// ";
  4963. messString.append(startBuf, endBuf-startBuf+1);
  4964. messString += "\n";
  4965. // FIXME: Missing definition of
  4966. // InsertText(clang::SourceLocation, char const*, unsigned int).
  4967. // InsertText(startLoc, messString);
  4968. // Tried this, but it didn't work either...
  4969. // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
  4970. #endif
  4971. return RewriteMessageExpr(MessExpr);
  4972. }
  4973. if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
  4974. dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
  4975. return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
  4976. }
  4977. if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
  4978. return RewriteObjCTryStmt(StmtTry);
  4979. if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
  4980. return RewriteObjCSynchronizedStmt(StmtTry);
  4981. if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
  4982. return RewriteObjCThrowStmt(StmtThrow);
  4983. if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
  4984. return RewriteObjCProtocolExpr(ProtocolExp);
  4985. if (ObjCForCollectionStmt *StmtForCollection =
  4986. dyn_cast<ObjCForCollectionStmt>(S))
  4987. return RewriteObjCForCollectionStmt(StmtForCollection,
  4988. OrigStmtRange.getEnd());
  4989. if (BreakStmt *StmtBreakStmt =
  4990. dyn_cast<BreakStmt>(S))
  4991. return RewriteBreakStmt(StmtBreakStmt);
  4992. if (ContinueStmt *StmtContinueStmt =
  4993. dyn_cast<ContinueStmt>(S))
  4994. return RewriteContinueStmt(StmtContinueStmt);
  4995. // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
  4996. // and cast exprs.
  4997. if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  4998. // FIXME: What we're doing here is modifying the type-specifier that
  4999. // precedes the first Decl. In the future the DeclGroup should have
  5000. // a separate type-specifier that we can rewrite.
  5001. // NOTE: We need to avoid rewriting the DeclStmt if it is within
  5002. // the context of an ObjCForCollectionStmt. For example:
  5003. // NSArray *someArray;
  5004. // for (id <FooProtocol> index in someArray) ;
  5005. // This is because RewriteObjCForCollectionStmt() does textual rewriting
  5006. // and it depends on the original text locations/positions.
  5007. if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
  5008. RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
  5009. // Blocks rewrite rules.
  5010. for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
  5011. DI != DE; ++DI) {
  5012. Decl *SD = *DI;
  5013. if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
  5014. if (isTopLevelBlockPointerType(ND->getType()))
  5015. RewriteBlockPointerDecl(ND);
  5016. else if (ND->getType()->isFunctionPointerType())
  5017. CheckFunctionPointerDecl(ND->getType(), ND);
  5018. if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
  5019. if (VD->hasAttr<BlocksAttr>()) {
  5020. static unsigned uniqueByrefDeclCount = 0;
  5021. assert(!BlockByRefDeclNo.count(ND) &&
  5022. "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
  5023. BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
  5024. RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
  5025. }
  5026. else
  5027. RewriteTypeOfDecl(VD);
  5028. }
  5029. }
  5030. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
  5031. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  5032. RewriteBlockPointerDecl(TD);
  5033. else if (TD->getUnderlyingType()->isFunctionPointerType())
  5034. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  5035. }
  5036. }
  5037. }
  5038. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
  5039. RewriteObjCQualifiedInterfaceTypes(CE);
  5040. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  5041. isa<DoStmt>(S) || isa<ForStmt>(S)) {
  5042. assert(!Stmts.empty() && "Statement stack is empty");
  5043. assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
  5044. isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
  5045. && "Statement stack mismatch");
  5046. Stmts.pop_back();
  5047. }
  5048. // Handle blocks rewriting.
  5049. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
  5050. ValueDecl *VD = DRE->getDecl();
  5051. if (VD->hasAttr<BlocksAttr>())
  5052. return RewriteBlockDeclRefExpr(DRE);
  5053. if (HasLocalVariableExternalStorage(VD))
  5054. return RewriteLocalVariableExternalStorage(DRE);
  5055. }
  5056. if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  5057. if (CE->getCallee()->getType()->isBlockPointerType()) {
  5058. Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
  5059. ReplaceStmt(S, BlockCall);
  5060. return BlockCall;
  5061. }
  5062. }
  5063. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
  5064. RewriteCastExpr(CE);
  5065. }
  5066. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
  5067. RewriteImplicitCastObjCExpr(ICE);
  5068. }
  5069. #if 0
  5070. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
  5071. CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
  5072. ICE->getSubExpr(),
  5073. SourceLocation());
  5074. // Get the new text.
  5075. std::string SStr;
  5076. llvm::raw_string_ostream Buf(SStr);
  5077. Replacement->printPretty(Buf);
  5078. const std::string &Str = Buf.str();
  5079. printf("CAST = %s\n", &Str[0]);
  5080. InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
  5081. delete S;
  5082. return Replacement;
  5083. }
  5084. #endif
  5085. // Return this stmt unmodified.
  5086. return S;
  5087. }
  5088. void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
  5089. for (auto *FD : RD->fields()) {
  5090. if (isTopLevelBlockPointerType(FD->getType()))
  5091. RewriteBlockPointerDecl(FD);
  5092. if (FD->getType()->isObjCQualifiedIdType() ||
  5093. FD->getType()->isObjCQualifiedInterfaceType())
  5094. RewriteObjCQualifiedInterfaceTypes(FD);
  5095. }
  5096. }
  5097. /// HandleDeclInMainFile - This is called for each top-level decl defined in the
  5098. /// main file of the input.
  5099. void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
  5100. switch (D->getKind()) {
  5101. case Decl::Function: {
  5102. FunctionDecl *FD = cast<FunctionDecl>(D);
  5103. if (FD->isOverloadedOperator())
  5104. return;
  5105. // Since function prototypes don't have ParmDecl's, we check the function
  5106. // prototype. This enables us to rewrite function declarations and
  5107. // definitions using the same code.
  5108. RewriteBlocksInFunctionProtoType(FD->getType(), FD);
  5109. if (!FD->isThisDeclarationADefinition())
  5110. break;
  5111. // FIXME: If this should support Obj-C++, support CXXTryStmt
  5112. if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
  5113. CurFunctionDef = FD;
  5114. CurrentBody = Body;
  5115. Body =
  5116. cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
  5117. FD->setBody(Body);
  5118. CurrentBody = nullptr;
  5119. if (PropParentMap) {
  5120. delete PropParentMap;
  5121. PropParentMap = nullptr;
  5122. }
  5123. // This synthesizes and inserts the block "impl" struct, invoke function,
  5124. // and any copy/dispose helper functions.
  5125. InsertBlockLiteralsWithinFunction(FD);
  5126. RewriteLineDirective(D);
  5127. CurFunctionDef = nullptr;
  5128. }
  5129. break;
  5130. }
  5131. case Decl::ObjCMethod: {
  5132. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
  5133. if (CompoundStmt *Body = MD->getCompoundBody()) {
  5134. CurMethodDef = MD;
  5135. CurrentBody = Body;
  5136. Body =
  5137. cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
  5138. MD->setBody(Body);
  5139. CurrentBody = nullptr;
  5140. if (PropParentMap) {
  5141. delete PropParentMap;
  5142. PropParentMap = nullptr;
  5143. }
  5144. InsertBlockLiteralsWithinMethod(MD);
  5145. RewriteLineDirective(D);
  5146. CurMethodDef = nullptr;
  5147. }
  5148. break;
  5149. }
  5150. case Decl::ObjCImplementation: {
  5151. ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
  5152. ClassImplementation.push_back(CI);
  5153. break;
  5154. }
  5155. case Decl::ObjCCategoryImpl: {
  5156. ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
  5157. CategoryImplementation.push_back(CI);
  5158. break;
  5159. }
  5160. case Decl::Var: {
  5161. VarDecl *VD = cast<VarDecl>(D);
  5162. RewriteObjCQualifiedInterfaceTypes(VD);
  5163. if (isTopLevelBlockPointerType(VD->getType()))
  5164. RewriteBlockPointerDecl(VD);
  5165. else if (VD->getType()->isFunctionPointerType()) {
  5166. CheckFunctionPointerDecl(VD->getType(), VD);
  5167. if (VD->getInit()) {
  5168. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
  5169. RewriteCastExpr(CE);
  5170. }
  5171. }
  5172. } else if (VD->getType()->isRecordType()) {
  5173. RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
  5174. if (RD->isCompleteDefinition())
  5175. RewriteRecordBody(RD);
  5176. }
  5177. if (VD->getInit()) {
  5178. GlobalVarDecl = VD;
  5179. CurrentBody = VD->getInit();
  5180. RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
  5181. CurrentBody = nullptr;
  5182. if (PropParentMap) {
  5183. delete PropParentMap;
  5184. PropParentMap = nullptr;
  5185. }
  5186. SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
  5187. GlobalVarDecl = nullptr;
  5188. // This is needed for blocks.
  5189. if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
  5190. RewriteCastExpr(CE);
  5191. }
  5192. }
  5193. break;
  5194. }
  5195. case Decl::TypeAlias:
  5196. case Decl::Typedef: {
  5197. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  5198. if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
  5199. RewriteBlockPointerDecl(TD);
  5200. else if (TD->getUnderlyingType()->isFunctionPointerType())
  5201. CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
  5202. else
  5203. RewriteObjCQualifiedInterfaceTypes(TD);
  5204. }
  5205. break;
  5206. }
  5207. case Decl::CXXRecord:
  5208. case Decl::Record: {
  5209. RecordDecl *RD = cast<RecordDecl>(D);
  5210. if (RD->isCompleteDefinition())
  5211. RewriteRecordBody(RD);
  5212. break;
  5213. }
  5214. default:
  5215. break;
  5216. }
  5217. // Nothing yet.
  5218. }
  5219. /// Write_ProtocolExprReferencedMetadata - This routine writer out the
  5220. /// protocol reference symbols in the for of:
  5221. /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
  5222. static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
  5223. ObjCProtocolDecl *PDecl,
  5224. std::string &Result) {
  5225. // Also output .objc_protorefs$B section and its meta-data.
  5226. if (Context->getLangOpts().MicrosoftExt)
  5227. Result += "static ";
  5228. Result += "struct _protocol_t *";
  5229. Result += "_OBJC_PROTOCOL_REFERENCE_$_";
  5230. Result += PDecl->getNameAsString();
  5231. Result += " = &";
  5232. Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
  5233. Result += ";\n";
  5234. }
  5235. void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
  5236. if (Diags.hasErrorOccurred())
  5237. return;
  5238. RewriteInclude();
  5239. for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
  5240. // translation of function bodies were postponed until all class and
  5241. // their extensions and implementations are seen. This is because, we
  5242. // cannot build grouping structs for bitfields until they are all seen.
  5243. FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
  5244. HandleTopLevelSingleDecl(FDecl);
  5245. }
  5246. // Here's a great place to add any extra declarations that may be needed.
  5247. // Write out meta data for each @protocol(<expr>).
  5248. for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
  5249. RewriteObjCProtocolMetaData(ProtDecl, Preamble);
  5250. Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
  5251. }
  5252. InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
  5253. if (ClassImplementation.size() || CategoryImplementation.size())
  5254. RewriteImplementations();
  5255. for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
  5256. ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
  5257. // Write struct declaration for the class matching its ivar declarations.
  5258. // Note that for modern abi, this is postponed until the end of TU
  5259. // because class extensions and the implementation might declare their own
  5260. // private ivars.
  5261. RewriteInterfaceDecl(CDecl);
  5262. }
  5263. // Get the buffer corresponding to MainFileID. If we haven't changed it, then
  5264. // we are done.
  5265. if (const RewriteBuffer *RewriteBuf =
  5266. Rewrite.getRewriteBufferFor(MainFileID)) {
  5267. //printf("Changed:\n");
  5268. *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
  5269. } else {
  5270. llvm::errs() << "No changes\n";
  5271. }
  5272. if (ClassImplementation.size() || CategoryImplementation.size() ||
  5273. ProtocolExprDecls.size()) {
  5274. // Rewrite Objective-c meta data*
  5275. std::string ResultStr;
  5276. RewriteMetaDataIntoBuffer(ResultStr);
  5277. // Emit metadata.
  5278. *OutFile << ResultStr;
  5279. }
  5280. // Emit ImageInfo;
  5281. {
  5282. std::string ResultStr;
  5283. WriteImageInfo(ResultStr);
  5284. *OutFile << ResultStr;
  5285. }
  5286. OutFile->flush();
  5287. }
  5288. void RewriteModernObjC::Initialize(ASTContext &context) {
  5289. InitializeCommon(context);
  5290. Preamble += "#ifndef __OBJC2__\n";
  5291. Preamble += "#define __OBJC2__\n";
  5292. Preamble += "#endif\n";
  5293. // declaring objc_selector outside the parameter list removes a silly
  5294. // scope related warning...
  5295. if (IsHeader)
  5296. Preamble = "#pragma once\n";
  5297. Preamble += "struct objc_selector; struct objc_class;\n";
  5298. Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
  5299. Preamble += "\n\tstruct objc_object *superClass; ";
  5300. // Add a constructor for creating temporary objects.
  5301. Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
  5302. Preamble += ": object(o), superClass(s) {} ";
  5303. Preamble += "\n};\n";
  5304. if (LangOpts.MicrosoftExt) {
  5305. // Define all sections using syntax that makes sense.
  5306. // These are currently generated.
  5307. Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
  5308. Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
  5309. Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
  5310. Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
  5311. Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
  5312. // These are generated but not necessary for functionality.
  5313. Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
  5314. Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
  5315. Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
  5316. Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
  5317. // These need be generated for performance. Currently they are not,
  5318. // using API calls instead.
  5319. Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
  5320. Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
  5321. Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
  5322. }
  5323. Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
  5324. Preamble += "typedef struct objc_object Protocol;\n";
  5325. Preamble += "#define _REWRITER_typedef_Protocol\n";
  5326. Preamble += "#endif\n";
  5327. if (LangOpts.MicrosoftExt) {
  5328. Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
  5329. Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
  5330. }
  5331. else
  5332. Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
  5333. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
  5334. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
  5335. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
  5336. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
  5337. Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
  5338. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
  5339. Preamble += "(const char *);\n";
  5340. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
  5341. Preamble += "(struct objc_class *);\n";
  5342. Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
  5343. Preamble += "(const char *);\n";
  5344. Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
  5345. // @synchronized hooks.
  5346. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
  5347. Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
  5348. Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
  5349. Preamble += "#ifdef _WIN64\n";
  5350. Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
  5351. Preamble += "#else\n";
  5352. Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
  5353. Preamble += "#endif\n";
  5354. Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
  5355. Preamble += "struct __objcFastEnumerationState {\n\t";
  5356. Preamble += "unsigned long state;\n\t";
  5357. Preamble += "void **itemsPtr;\n\t";
  5358. Preamble += "unsigned long *mutationsPtr;\n\t";
  5359. Preamble += "unsigned long extra[5];\n};\n";
  5360. Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
  5361. Preamble += "#define __FASTENUMERATIONSTATE\n";
  5362. Preamble += "#endif\n";
  5363. Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
  5364. Preamble += "struct __NSConstantStringImpl {\n";
  5365. Preamble += " int *isa;\n";
  5366. Preamble += " int flags;\n";
  5367. Preamble += " char *str;\n";
  5368. Preamble += "#if _WIN64\n";
  5369. Preamble += " long long length;\n";
  5370. Preamble += "#else\n";
  5371. Preamble += " long length;\n";
  5372. Preamble += "#endif\n";
  5373. Preamble += "};\n";
  5374. Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
  5375. Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
  5376. Preamble += "#else\n";
  5377. Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
  5378. Preamble += "#endif\n";
  5379. Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
  5380. Preamble += "#endif\n";
  5381. // Blocks preamble.
  5382. Preamble += "#ifndef BLOCK_IMPL\n";
  5383. Preamble += "#define BLOCK_IMPL\n";
  5384. Preamble += "struct __block_impl {\n";
  5385. Preamble += " void *isa;\n";
  5386. Preamble += " int Flags;\n";
  5387. Preamble += " int Reserved;\n";
  5388. Preamble += " void *FuncPtr;\n";
  5389. Preamble += "};\n";
  5390. Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
  5391. Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
  5392. Preamble += "extern \"C\" __declspec(dllexport) "
  5393. "void _Block_object_assign(void *, const void *, const int);\n";
  5394. Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
  5395. Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
  5396. Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
  5397. Preamble += "#else\n";
  5398. Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
  5399. Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
  5400. Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
  5401. Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
  5402. Preamble += "#endif\n";
  5403. Preamble += "#endif\n";
  5404. if (LangOpts.MicrosoftExt) {
  5405. Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
  5406. Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
  5407. Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
  5408. Preamble += "#define __attribute__(X)\n";
  5409. Preamble += "#endif\n";
  5410. Preamble += "#ifndef __weak\n";
  5411. Preamble += "#define __weak\n";
  5412. Preamble += "#endif\n";
  5413. Preamble += "#ifndef __block\n";
  5414. Preamble += "#define __block\n";
  5415. Preamble += "#endif\n";
  5416. }
  5417. else {
  5418. Preamble += "#define __block\n";
  5419. Preamble += "#define __weak\n";
  5420. }
  5421. // Declarations required for modern objective-c array and dictionary literals.
  5422. Preamble += "\n#include <stdarg.h>\n";
  5423. Preamble += "struct __NSContainer_literal {\n";
  5424. Preamble += " void * *arr;\n";
  5425. Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
  5426. Preamble += "\tva_list marker;\n";
  5427. Preamble += "\tva_start(marker, count);\n";
  5428. Preamble += "\tarr = new void *[count];\n";
  5429. Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
  5430. Preamble += "\t arr[i] = va_arg(marker, void *);\n";
  5431. Preamble += "\tva_end( marker );\n";
  5432. Preamble += " };\n";
  5433. Preamble += " ~__NSContainer_literal() {\n";
  5434. Preamble += "\tdelete[] arr;\n";
  5435. Preamble += " }\n";
  5436. Preamble += "};\n";
  5437. // Declaration required for implementation of @autoreleasepool statement.
  5438. Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
  5439. Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
  5440. Preamble += "struct __AtAutoreleasePool {\n";
  5441. Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
  5442. Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
  5443. Preamble += " void * atautoreleasepoolobj;\n";
  5444. Preamble += "};\n";
  5445. // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
  5446. // as this avoids warning in any 64bit/32bit compilation model.
  5447. Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
  5448. }
  5449. /// RewriteIvarOffsetComputation - This routine synthesizes computation of
  5450. /// ivar offset.
  5451. void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
  5452. std::string &Result) {
  5453. Result += "__OFFSETOFIVAR__(struct ";
  5454. Result += ivar->getContainingInterface()->getNameAsString();
  5455. if (LangOpts.MicrosoftExt)
  5456. Result += "_IMPL";
  5457. Result += ", ";
  5458. if (ivar->isBitField())
  5459. ObjCIvarBitfieldGroupDecl(ivar, Result);
  5460. else
  5461. Result += ivar->getNameAsString();
  5462. Result += ")";
  5463. }
  5464. /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
  5465. /// struct _prop_t {
  5466. /// const char *name;
  5467. /// char *attributes;
  5468. /// }
  5469. /// struct _prop_list_t {
  5470. /// uint32_t entsize; // sizeof(struct _prop_t)
  5471. /// uint32_t count_of_properties;
  5472. /// struct _prop_t prop_list[count_of_properties];
  5473. /// }
  5474. /// struct _protocol_t;
  5475. /// struct _protocol_list_t {
  5476. /// long protocol_count; // Note, this is 32/64 bit
  5477. /// struct _protocol_t * protocol_list[protocol_count];
  5478. /// }
  5479. /// struct _objc_method {
  5480. /// SEL _cmd;
  5481. /// const char *method_type;
  5482. /// char *_imp;
  5483. /// }
  5484. /// struct _method_list_t {
  5485. /// uint32_t entsize; // sizeof(struct _objc_method)
  5486. /// uint32_t method_count;
  5487. /// struct _objc_method method_list[method_count];
  5488. /// }
  5489. /// struct _protocol_t {
  5490. /// id isa; // NULL
  5491. /// const char *protocol_name;
  5492. /// const struct _protocol_list_t * protocol_list; // super protocols
  5493. /// const struct method_list_t *instance_methods;
  5494. /// const struct method_list_t *class_methods;
  5495. /// const struct method_list_t *optionalInstanceMethods;
  5496. /// const struct method_list_t *optionalClassMethods;
  5497. /// const struct _prop_list_t * properties;
  5498. /// const uint32_t size; // sizeof(struct _protocol_t)
  5499. /// const uint32_t flags; // = 0
  5500. /// const char ** extendedMethodTypes;
  5501. /// }
  5502. /// struct _ivar_t {
  5503. /// unsigned long int *offset; // pointer to ivar offset location
  5504. /// const char *name;
  5505. /// const char *type;
  5506. /// uint32_t alignment;
  5507. /// uint32_t size;
  5508. /// }
  5509. /// struct _ivar_list_t {
  5510. /// uint32 entsize; // sizeof(struct _ivar_t)
  5511. /// uint32 count;
  5512. /// struct _ivar_t list[count];
  5513. /// }
  5514. /// struct _class_ro_t {
  5515. /// uint32_t flags;
  5516. /// uint32_t instanceStart;
  5517. /// uint32_t instanceSize;
  5518. /// uint32_t reserved; // only when building for 64bit targets
  5519. /// const uint8_t *ivarLayout;
  5520. /// const char *name;
  5521. /// const struct _method_list_t *baseMethods;
  5522. /// const struct _protocol_list_t *baseProtocols;
  5523. /// const struct _ivar_list_t *ivars;
  5524. /// const uint8_t *weakIvarLayout;
  5525. /// const struct _prop_list_t *properties;
  5526. /// }
  5527. /// struct _class_t {
  5528. /// struct _class_t *isa;
  5529. /// struct _class_t *superclass;
  5530. /// void *cache;
  5531. /// IMP *vtable;
  5532. /// struct _class_ro_t *ro;
  5533. /// }
  5534. /// struct _category_t {
  5535. /// const char *name;
  5536. /// struct _class_t *cls;
  5537. /// const struct _method_list_t *instance_methods;
  5538. /// const struct _method_list_t *class_methods;
  5539. /// const struct _protocol_list_t *protocols;
  5540. /// const struct _prop_list_t *properties;
  5541. /// }
  5542. /// MessageRefTy - LLVM for:
  5543. /// struct _message_ref_t {
  5544. /// IMP messenger;
  5545. /// SEL name;
  5546. /// };
  5547. /// SuperMessageRefTy - LLVM for:
  5548. /// struct _super_message_ref_t {
  5549. /// SUPER_IMP messenger;
  5550. /// SEL name;
  5551. /// };
  5552. static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
  5553. static bool meta_data_declared = false;
  5554. if (meta_data_declared)
  5555. return;
  5556. Result += "\nstruct _prop_t {\n";
  5557. Result += "\tconst char *name;\n";
  5558. Result += "\tconst char *attributes;\n";
  5559. Result += "};\n";
  5560. Result += "\nstruct _protocol_t;\n";
  5561. Result += "\nstruct _objc_method {\n";
  5562. Result += "\tstruct objc_selector * _cmd;\n";
  5563. Result += "\tconst char *method_type;\n";
  5564. Result += "\tvoid *_imp;\n";
  5565. Result += "};\n";
  5566. Result += "\nstruct _protocol_t {\n";
  5567. Result += "\tvoid * isa; // NULL\n";
  5568. Result += "\tconst char *protocol_name;\n";
  5569. Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
  5570. Result += "\tconst struct method_list_t *instance_methods;\n";
  5571. Result += "\tconst struct method_list_t *class_methods;\n";
  5572. Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
  5573. Result += "\tconst struct method_list_t *optionalClassMethods;\n";
  5574. Result += "\tconst struct _prop_list_t * properties;\n";
  5575. Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
  5576. Result += "\tconst unsigned int flags; // = 0\n";
  5577. Result += "\tconst char ** extendedMethodTypes;\n";
  5578. Result += "};\n";
  5579. Result += "\nstruct _ivar_t {\n";
  5580. Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
  5581. Result += "\tconst char *name;\n";
  5582. Result += "\tconst char *type;\n";
  5583. Result += "\tunsigned int alignment;\n";
  5584. Result += "\tunsigned int size;\n";
  5585. Result += "};\n";
  5586. Result += "\nstruct _class_ro_t {\n";
  5587. Result += "\tunsigned int flags;\n";
  5588. Result += "\tunsigned int instanceStart;\n";
  5589. Result += "\tunsigned int instanceSize;\n";
  5590. const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
  5591. if (Triple.getArch() == llvm::Triple::x86_64)
  5592. Result += "\tunsigned int reserved;\n";
  5593. Result += "\tconst unsigned char *ivarLayout;\n";
  5594. Result += "\tconst char *name;\n";
  5595. Result += "\tconst struct _method_list_t *baseMethods;\n";
  5596. Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
  5597. Result += "\tconst struct _ivar_list_t *ivars;\n";
  5598. Result += "\tconst unsigned char *weakIvarLayout;\n";
  5599. Result += "\tconst struct _prop_list_t *properties;\n";
  5600. Result += "};\n";
  5601. Result += "\nstruct _class_t {\n";
  5602. Result += "\tstruct _class_t *isa;\n";
  5603. Result += "\tstruct _class_t *superclass;\n";
  5604. Result += "\tvoid *cache;\n";
  5605. Result += "\tvoid *vtable;\n";
  5606. Result += "\tstruct _class_ro_t *ro;\n";
  5607. Result += "};\n";
  5608. Result += "\nstruct _category_t {\n";
  5609. Result += "\tconst char *name;\n";
  5610. Result += "\tstruct _class_t *cls;\n";
  5611. Result += "\tconst struct _method_list_t *instance_methods;\n";
  5612. Result += "\tconst struct _method_list_t *class_methods;\n";
  5613. Result += "\tconst struct _protocol_list_t *protocols;\n";
  5614. Result += "\tconst struct _prop_list_t *properties;\n";
  5615. Result += "};\n";
  5616. Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
  5617. Result += "#pragma warning(disable:4273)\n";
  5618. meta_data_declared = true;
  5619. }
  5620. static void Write_protocol_list_t_TypeDecl(std::string &Result,
  5621. long super_protocol_count) {
  5622. Result += "struct /*_protocol_list_t*/"; Result += " {\n";
  5623. Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
  5624. Result += "\tstruct _protocol_t *super_protocols[";
  5625. Result += utostr(super_protocol_count); Result += "];\n";
  5626. Result += "}";
  5627. }
  5628. static void Write_method_list_t_TypeDecl(std::string &Result,
  5629. unsigned int method_count) {
  5630. Result += "struct /*_method_list_t*/"; Result += " {\n";
  5631. Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
  5632. Result += "\tunsigned int method_count;\n";
  5633. Result += "\tstruct _objc_method method_list[";
  5634. Result += utostr(method_count); Result += "];\n";
  5635. Result += "}";
  5636. }
  5637. static void Write__prop_list_t_TypeDecl(std::string &Result,
  5638. unsigned int property_count) {
  5639. Result += "struct /*_prop_list_t*/"; Result += " {\n";
  5640. Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
  5641. Result += "\tunsigned int count_of_properties;\n";
  5642. Result += "\tstruct _prop_t prop_list[";
  5643. Result += utostr(property_count); Result += "];\n";
  5644. Result += "}";
  5645. }
  5646. static void Write__ivar_list_t_TypeDecl(std::string &Result,
  5647. unsigned int ivar_count) {
  5648. Result += "struct /*_ivar_list_t*/"; Result += " {\n";
  5649. Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
  5650. Result += "\tunsigned int count;\n";
  5651. Result += "\tstruct _ivar_t ivar_list[";
  5652. Result += utostr(ivar_count); Result += "];\n";
  5653. Result += "}";
  5654. }
  5655. static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
  5656. ArrayRef<ObjCProtocolDecl *> SuperProtocols,
  5657. StringRef VarName,
  5658. StringRef ProtocolName) {
  5659. if (SuperProtocols.size() > 0) {
  5660. Result += "\nstatic ";
  5661. Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
  5662. Result += " "; Result += VarName;
  5663. Result += ProtocolName;
  5664. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5665. Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
  5666. for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
  5667. ObjCProtocolDecl *SuperPD = SuperProtocols[i];
  5668. Result += "\t&"; Result += "_OBJC_PROTOCOL_";
  5669. Result += SuperPD->getNameAsString();
  5670. if (i == e-1)
  5671. Result += "\n};\n";
  5672. else
  5673. Result += ",\n";
  5674. }
  5675. }
  5676. }
  5677. static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
  5678. ASTContext *Context, std::string &Result,
  5679. ArrayRef<ObjCMethodDecl *> Methods,
  5680. StringRef VarName,
  5681. StringRef TopLevelDeclName,
  5682. bool MethodImpl) {
  5683. if (Methods.size() > 0) {
  5684. Result += "\nstatic ";
  5685. Write_method_list_t_TypeDecl(Result, Methods.size());
  5686. Result += " "; Result += VarName;
  5687. Result += TopLevelDeclName;
  5688. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5689. Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
  5690. Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
  5691. for (unsigned i = 0, e = Methods.size(); i < e; i++) {
  5692. ObjCMethodDecl *MD = Methods[i];
  5693. if (i == 0)
  5694. Result += "\t{{(struct objc_selector *)\"";
  5695. else
  5696. Result += "\t{(struct objc_selector *)\"";
  5697. Result += (MD)->getSelector().getAsString(); Result += "\"";
  5698. Result += ", ";
  5699. std::string MethodTypeString = Context->getObjCEncodingForMethodDecl(MD);
  5700. Result += "\""; Result += MethodTypeString; Result += "\"";
  5701. Result += ", ";
  5702. if (!MethodImpl)
  5703. Result += "0";
  5704. else {
  5705. Result += "(void *)";
  5706. Result += RewriteObj.MethodInternalNames[MD];
  5707. }
  5708. if (i == e-1)
  5709. Result += "}}\n";
  5710. else
  5711. Result += "},\n";
  5712. }
  5713. Result += "};\n";
  5714. }
  5715. }
  5716. static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
  5717. ASTContext *Context, std::string &Result,
  5718. ArrayRef<ObjCPropertyDecl *> Properties,
  5719. const Decl *Container,
  5720. StringRef VarName,
  5721. StringRef ProtocolName) {
  5722. if (Properties.size() > 0) {
  5723. Result += "\nstatic ";
  5724. Write__prop_list_t_TypeDecl(Result, Properties.size());
  5725. Result += " "; Result += VarName;
  5726. Result += ProtocolName;
  5727. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5728. Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
  5729. Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
  5730. for (unsigned i = 0, e = Properties.size(); i < e; i++) {
  5731. ObjCPropertyDecl *PropDecl = Properties[i];
  5732. if (i == 0)
  5733. Result += "\t{{\"";
  5734. else
  5735. Result += "\t{\"";
  5736. Result += PropDecl->getName(); Result += "\",";
  5737. std::string PropertyTypeString =
  5738. Context->getObjCEncodingForPropertyDecl(PropDecl, Container);
  5739. std::string QuotePropertyTypeString;
  5740. RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
  5741. Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
  5742. if (i == e-1)
  5743. Result += "}}\n";
  5744. else
  5745. Result += "},\n";
  5746. }
  5747. Result += "};\n";
  5748. }
  5749. }
  5750. // Metadata flags
  5751. enum MetaDataDlags {
  5752. CLS = 0x0,
  5753. CLS_META = 0x1,
  5754. CLS_ROOT = 0x2,
  5755. OBJC2_CLS_HIDDEN = 0x10,
  5756. CLS_EXCEPTION = 0x20,
  5757. /// (Obsolete) ARC-specific: this class has a .release_ivars method
  5758. CLS_HAS_IVAR_RELEASER = 0x40,
  5759. /// class was compiled with -fobjc-arr
  5760. CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
  5761. };
  5762. static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
  5763. unsigned int flags,
  5764. const std::string &InstanceStart,
  5765. const std::string &InstanceSize,
  5766. ArrayRef<ObjCMethodDecl *>baseMethods,
  5767. ArrayRef<ObjCProtocolDecl *>baseProtocols,
  5768. ArrayRef<ObjCIvarDecl *>ivars,
  5769. ArrayRef<ObjCPropertyDecl *>Properties,
  5770. StringRef VarName,
  5771. StringRef ClassName) {
  5772. Result += "\nstatic struct _class_ro_t ";
  5773. Result += VarName; Result += ClassName;
  5774. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  5775. Result += "\t";
  5776. Result += llvm::utostr(flags); Result += ", ";
  5777. Result += InstanceStart; Result += ", ";
  5778. Result += InstanceSize; Result += ", \n";
  5779. Result += "\t";
  5780. const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
  5781. if (Triple.getArch() == llvm::Triple::x86_64)
  5782. // uint32_t const reserved; // only when building for 64bit targets
  5783. Result += "(unsigned int)0, \n\t";
  5784. // const uint8_t * const ivarLayout;
  5785. Result += "0, \n\t";
  5786. Result += "\""; Result += ClassName; Result += "\",\n\t";
  5787. bool metaclass = ((flags & CLS_META) != 0);
  5788. if (baseMethods.size() > 0) {
  5789. Result += "(const struct _method_list_t *)&";
  5790. if (metaclass)
  5791. Result += "_OBJC_$_CLASS_METHODS_";
  5792. else
  5793. Result += "_OBJC_$_INSTANCE_METHODS_";
  5794. Result += ClassName;
  5795. Result += ",\n\t";
  5796. }
  5797. else
  5798. Result += "0, \n\t";
  5799. if (!metaclass && baseProtocols.size() > 0) {
  5800. Result += "(const struct _objc_protocol_list *)&";
  5801. Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
  5802. Result += ",\n\t";
  5803. }
  5804. else
  5805. Result += "0, \n\t";
  5806. if (!metaclass && ivars.size() > 0) {
  5807. Result += "(const struct _ivar_list_t *)&";
  5808. Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
  5809. Result += ",\n\t";
  5810. }
  5811. else
  5812. Result += "0, \n\t";
  5813. // weakIvarLayout
  5814. Result += "0, \n\t";
  5815. if (!metaclass && Properties.size() > 0) {
  5816. Result += "(const struct _prop_list_t *)&";
  5817. Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
  5818. Result += ",\n";
  5819. }
  5820. else
  5821. Result += "0, \n";
  5822. Result += "};\n";
  5823. }
  5824. static void Write_class_t(ASTContext *Context, std::string &Result,
  5825. StringRef VarName,
  5826. const ObjCInterfaceDecl *CDecl, bool metaclass) {
  5827. bool rootClass = (!CDecl->getSuperClass());
  5828. const ObjCInterfaceDecl *RootClass = CDecl;
  5829. if (!rootClass) {
  5830. // Find the Root class
  5831. RootClass = CDecl->getSuperClass();
  5832. while (RootClass->getSuperClass()) {
  5833. RootClass = RootClass->getSuperClass();
  5834. }
  5835. }
  5836. if (metaclass && rootClass) {
  5837. // Need to handle a case of use of forward declaration.
  5838. Result += "\n";
  5839. Result += "extern \"C\" ";
  5840. if (CDecl->getImplementation())
  5841. Result += "__declspec(dllexport) ";
  5842. else
  5843. Result += "__declspec(dllimport) ";
  5844. Result += "struct _class_t OBJC_CLASS_$_";
  5845. Result += CDecl->getNameAsString();
  5846. Result += ";\n";
  5847. }
  5848. // Also, for possibility of 'super' metadata class not having been defined yet.
  5849. if (!rootClass) {
  5850. ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
  5851. Result += "\n";
  5852. Result += "extern \"C\" ";
  5853. if (SuperClass->getImplementation())
  5854. Result += "__declspec(dllexport) ";
  5855. else
  5856. Result += "__declspec(dllimport) ";
  5857. Result += "struct _class_t ";
  5858. Result += VarName;
  5859. Result += SuperClass->getNameAsString();
  5860. Result += ";\n";
  5861. if (metaclass && RootClass != SuperClass) {
  5862. Result += "extern \"C\" ";
  5863. if (RootClass->getImplementation())
  5864. Result += "__declspec(dllexport) ";
  5865. else
  5866. Result += "__declspec(dllimport) ";
  5867. Result += "struct _class_t ";
  5868. Result += VarName;
  5869. Result += RootClass->getNameAsString();
  5870. Result += ";\n";
  5871. }
  5872. }
  5873. Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
  5874. Result += VarName; Result += CDecl->getNameAsString();
  5875. Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
  5876. Result += "\t";
  5877. if (metaclass) {
  5878. if (!rootClass) {
  5879. Result += "0, // &"; Result += VarName;
  5880. Result += RootClass->getNameAsString();
  5881. Result += ",\n\t";
  5882. Result += "0, // &"; Result += VarName;
  5883. Result += CDecl->getSuperClass()->getNameAsString();
  5884. Result += ",\n\t";
  5885. }
  5886. else {
  5887. Result += "0, // &"; Result += VarName;
  5888. Result += CDecl->getNameAsString();
  5889. Result += ",\n\t";
  5890. Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5891. Result += ",\n\t";
  5892. }
  5893. }
  5894. else {
  5895. Result += "0, // &OBJC_METACLASS_$_";
  5896. Result += CDecl->getNameAsString();
  5897. Result += ",\n\t";
  5898. if (!rootClass) {
  5899. Result += "0, // &"; Result += VarName;
  5900. Result += CDecl->getSuperClass()->getNameAsString();
  5901. Result += ",\n\t";
  5902. }
  5903. else
  5904. Result += "0,\n\t";
  5905. }
  5906. Result += "0, // (void *)&_objc_empty_cache,\n\t";
  5907. Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
  5908. if (metaclass)
  5909. Result += "&_OBJC_METACLASS_RO_$_";
  5910. else
  5911. Result += "&_OBJC_CLASS_RO_$_";
  5912. Result += CDecl->getNameAsString();
  5913. Result += ",\n};\n";
  5914. // Add static function to initialize some of the meta-data fields.
  5915. // avoid doing it twice.
  5916. if (metaclass)
  5917. return;
  5918. const ObjCInterfaceDecl *SuperClass =
  5919. rootClass ? CDecl : CDecl->getSuperClass();
  5920. Result += "static void OBJC_CLASS_SETUP_$_";
  5921. Result += CDecl->getNameAsString();
  5922. Result += "(void ) {\n";
  5923. Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
  5924. Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
  5925. Result += RootClass->getNameAsString(); Result += ";\n";
  5926. Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
  5927. Result += ".superclass = ";
  5928. if (rootClass)
  5929. Result += "&OBJC_CLASS_$_";
  5930. else
  5931. Result += "&OBJC_METACLASS_$_";
  5932. Result += SuperClass->getNameAsString(); Result += ";\n";
  5933. Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
  5934. Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
  5935. Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5936. Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
  5937. Result += CDecl->getNameAsString(); Result += ";\n";
  5938. if (!rootClass) {
  5939. Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5940. Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
  5941. Result += SuperClass->getNameAsString(); Result += ";\n";
  5942. }
  5943. Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
  5944. Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
  5945. Result += "}\n";
  5946. }
  5947. static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
  5948. std::string &Result,
  5949. ObjCCategoryDecl *CatDecl,
  5950. ObjCInterfaceDecl *ClassDecl,
  5951. ArrayRef<ObjCMethodDecl *> InstanceMethods,
  5952. ArrayRef<ObjCMethodDecl *> ClassMethods,
  5953. ArrayRef<ObjCProtocolDecl *> RefedProtocols,
  5954. ArrayRef<ObjCPropertyDecl *> ClassProperties) {
  5955. StringRef CatName = CatDecl->getName();
  5956. StringRef ClassName = ClassDecl->getName();
  5957. // must declare an extern class object in case this class is not implemented
  5958. // in this TU.
  5959. Result += "\n";
  5960. Result += "extern \"C\" ";
  5961. if (ClassDecl->getImplementation())
  5962. Result += "__declspec(dllexport) ";
  5963. else
  5964. Result += "__declspec(dllimport) ";
  5965. Result += "struct _class_t ";
  5966. Result += "OBJC_CLASS_$_"; Result += ClassName;
  5967. Result += ";\n";
  5968. Result += "\nstatic struct _category_t ";
  5969. Result += "_OBJC_$_CATEGORY_";
  5970. Result += ClassName; Result += "_$_"; Result += CatName;
  5971. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
  5972. Result += "{\n";
  5973. Result += "\t\""; Result += ClassName; Result += "\",\n";
  5974. Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
  5975. Result += ",\n";
  5976. if (InstanceMethods.size() > 0) {
  5977. Result += "\t(const struct _method_list_t *)&";
  5978. Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
  5979. Result += ClassName; Result += "_$_"; Result += CatName;
  5980. Result += ",\n";
  5981. }
  5982. else
  5983. Result += "\t0,\n";
  5984. if (ClassMethods.size() > 0) {
  5985. Result += "\t(const struct _method_list_t *)&";
  5986. Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
  5987. Result += ClassName; Result += "_$_"; Result += CatName;
  5988. Result += ",\n";
  5989. }
  5990. else
  5991. Result += "\t0,\n";
  5992. if (RefedProtocols.size() > 0) {
  5993. Result += "\t(const struct _protocol_list_t *)&";
  5994. Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
  5995. Result += ClassName; Result += "_$_"; Result += CatName;
  5996. Result += ",\n";
  5997. }
  5998. else
  5999. Result += "\t0,\n";
  6000. if (ClassProperties.size() > 0) {
  6001. Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
  6002. Result += ClassName; Result += "_$_"; Result += CatName;
  6003. Result += ",\n";
  6004. }
  6005. else
  6006. Result += "\t0,\n";
  6007. Result += "};\n";
  6008. // Add static function to initialize the class pointer in the category structure.
  6009. Result += "static void OBJC_CATEGORY_SETUP_$_";
  6010. Result += ClassDecl->getNameAsString();
  6011. Result += "_$_";
  6012. Result += CatName;
  6013. Result += "(void ) {\n";
  6014. Result += "\t_OBJC_$_CATEGORY_";
  6015. Result += ClassDecl->getNameAsString();
  6016. Result += "_$_";
  6017. Result += CatName;
  6018. Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
  6019. Result += ";\n}\n";
  6020. }
  6021. static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
  6022. ASTContext *Context, std::string &Result,
  6023. ArrayRef<ObjCMethodDecl *> Methods,
  6024. StringRef VarName,
  6025. StringRef ProtocolName) {
  6026. if (Methods.size() == 0)
  6027. return;
  6028. Result += "\nstatic const char *";
  6029. Result += VarName; Result += ProtocolName;
  6030. Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
  6031. Result += "{\n";
  6032. for (unsigned i = 0, e = Methods.size(); i < e; i++) {
  6033. ObjCMethodDecl *MD = Methods[i];
  6034. std::string MethodTypeString =
  6035. Context->getObjCEncodingForMethodDecl(MD, true);
  6036. std::string QuoteMethodTypeString;
  6037. RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
  6038. Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
  6039. if (i == e-1)
  6040. Result += "\n};\n";
  6041. else {
  6042. Result += ",\n";
  6043. }
  6044. }
  6045. }
  6046. static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
  6047. ASTContext *Context,
  6048. std::string &Result,
  6049. ArrayRef<ObjCIvarDecl *> Ivars,
  6050. ObjCInterfaceDecl *CDecl) {
  6051. // FIXME. visibility of offset symbols may have to be set; for Darwin
  6052. // this is what happens:
  6053. /**
  6054. if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
  6055. Ivar->getAccessControl() == ObjCIvarDecl::Package ||
  6056. Class->getVisibility() == HiddenVisibility)
  6057. Visibility should be: HiddenVisibility;
  6058. else
  6059. Visibility should be: DefaultVisibility;
  6060. */
  6061. Result += "\n";
  6062. for (unsigned i =0, e = Ivars.size(); i < e; i++) {
  6063. ObjCIvarDecl *IvarDecl = Ivars[i];
  6064. if (Context->getLangOpts().MicrosoftExt)
  6065. Result += "__declspec(allocate(\".objc_ivar$B\")) ";
  6066. if (!Context->getLangOpts().MicrosoftExt ||
  6067. IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
  6068. IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
  6069. Result += "extern \"C\" unsigned long int ";
  6070. else
  6071. Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
  6072. if (Ivars[i]->isBitField())
  6073. RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
  6074. else
  6075. WriteInternalIvarName(CDecl, IvarDecl, Result);
  6076. Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
  6077. Result += " = ";
  6078. RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
  6079. Result += ";\n";
  6080. if (Ivars[i]->isBitField()) {
  6081. // skip over rest of the ivar bitfields.
  6082. SKIP_BITFIELDS(i , e, Ivars);
  6083. }
  6084. }
  6085. }
  6086. static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
  6087. ASTContext *Context, std::string &Result,
  6088. ArrayRef<ObjCIvarDecl *> OriginalIvars,
  6089. StringRef VarName,
  6090. ObjCInterfaceDecl *CDecl) {
  6091. if (OriginalIvars.size() > 0) {
  6092. Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
  6093. SmallVector<ObjCIvarDecl *, 8> Ivars;
  6094. // strip off all but the first ivar bitfield from each group of ivars.
  6095. // Such ivars in the ivar list table will be replaced by their grouping struct
  6096. // 'ivar'.
  6097. for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
  6098. if (OriginalIvars[i]->isBitField()) {
  6099. Ivars.push_back(OriginalIvars[i]);
  6100. // skip over rest of the ivar bitfields.
  6101. SKIP_BITFIELDS(i , e, OriginalIvars);
  6102. }
  6103. else
  6104. Ivars.push_back(OriginalIvars[i]);
  6105. }
  6106. Result += "\nstatic ";
  6107. Write__ivar_list_t_TypeDecl(Result, Ivars.size());
  6108. Result += " "; Result += VarName;
  6109. Result += CDecl->getNameAsString();
  6110. Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
  6111. Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
  6112. Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
  6113. for (unsigned i =0, e = Ivars.size(); i < e; i++) {
  6114. ObjCIvarDecl *IvarDecl = Ivars[i];
  6115. if (i == 0)
  6116. Result += "\t{{";
  6117. else
  6118. Result += "\t {";
  6119. Result += "(unsigned long int *)&";
  6120. if (Ivars[i]->isBitField())
  6121. RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
  6122. else
  6123. WriteInternalIvarName(CDecl, IvarDecl, Result);
  6124. Result += ", ";
  6125. Result += "\"";
  6126. if (Ivars[i]->isBitField())
  6127. RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
  6128. else
  6129. Result += IvarDecl->getName();
  6130. Result += "\", ";
  6131. QualType IVQT = IvarDecl->getType();
  6132. if (IvarDecl->isBitField())
  6133. IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
  6134. std::string IvarTypeString, QuoteIvarTypeString;
  6135. Context->getObjCEncodingForType(IVQT, IvarTypeString,
  6136. IvarDecl);
  6137. RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
  6138. Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
  6139. // FIXME. this alignment represents the host alignment and need be changed to
  6140. // represent the target alignment.
  6141. unsigned Align = Context->getTypeAlign(IVQT)/8;
  6142. Align = llvm::Log2_32(Align);
  6143. Result += llvm::utostr(Align); Result += ", ";
  6144. CharUnits Size = Context->getTypeSizeInChars(IVQT);
  6145. Result += llvm::utostr(Size.getQuantity());
  6146. if (i == e-1)
  6147. Result += "}}\n";
  6148. else
  6149. Result += "},\n";
  6150. }
  6151. Result += "};\n";
  6152. }
  6153. }
  6154. /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
  6155. void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
  6156. std::string &Result) {
  6157. // Do not synthesize the protocol more than once.
  6158. if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
  6159. return;
  6160. WriteModernMetadataDeclarations(Context, Result);
  6161. if (ObjCProtocolDecl *Def = PDecl->getDefinition())
  6162. PDecl = Def;
  6163. // Must write out all protocol definitions in current qualifier list,
  6164. // and in their nested qualifiers before writing out current definition.
  6165. for (auto *I : PDecl->protocols())
  6166. RewriteObjCProtocolMetaData(I, Result);
  6167. // Construct method lists.
  6168. std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
  6169. std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
  6170. for (auto *MD : PDecl->instance_methods()) {
  6171. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  6172. OptInstanceMethods.push_back(MD);
  6173. } else {
  6174. InstanceMethods.push_back(MD);
  6175. }
  6176. }
  6177. for (auto *MD : PDecl->class_methods()) {
  6178. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  6179. OptClassMethods.push_back(MD);
  6180. } else {
  6181. ClassMethods.push_back(MD);
  6182. }
  6183. }
  6184. std::vector<ObjCMethodDecl *> AllMethods;
  6185. for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
  6186. AllMethods.push_back(InstanceMethods[i]);
  6187. for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
  6188. AllMethods.push_back(ClassMethods[i]);
  6189. for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
  6190. AllMethods.push_back(OptInstanceMethods[i]);
  6191. for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
  6192. AllMethods.push_back(OptClassMethods[i]);
  6193. Write__extendedMethodTypes_initializer(*this, Context, Result,
  6194. AllMethods,
  6195. "_OBJC_PROTOCOL_METHOD_TYPES_",
  6196. PDecl->getNameAsString());
  6197. // Protocol's super protocol list
  6198. SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
  6199. Write_protocol_list_initializer(Context, Result, SuperProtocols,
  6200. "_OBJC_PROTOCOL_REFS_",
  6201. PDecl->getNameAsString());
  6202. Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
  6203. "_OBJC_PROTOCOL_INSTANCE_METHODS_",
  6204. PDecl->getNameAsString(), false);
  6205. Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
  6206. "_OBJC_PROTOCOL_CLASS_METHODS_",
  6207. PDecl->getNameAsString(), false);
  6208. Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
  6209. "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
  6210. PDecl->getNameAsString(), false);
  6211. Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
  6212. "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
  6213. PDecl->getNameAsString(), false);
  6214. // Protocol's property metadata.
  6215. SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(
  6216. PDecl->instance_properties());
  6217. Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
  6218. /* Container */nullptr,
  6219. "_OBJC_PROTOCOL_PROPERTIES_",
  6220. PDecl->getNameAsString());
  6221. // Writer out root metadata for current protocol: struct _protocol_t
  6222. Result += "\n";
  6223. if (LangOpts.MicrosoftExt)
  6224. Result += "static ";
  6225. Result += "struct _protocol_t _OBJC_PROTOCOL_";
  6226. Result += PDecl->getNameAsString();
  6227. Result += " __attribute__ ((used)) = {\n";
  6228. Result += "\t0,\n"; // id is; is null
  6229. Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
  6230. if (SuperProtocols.size() > 0) {
  6231. Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
  6232. Result += PDecl->getNameAsString(); Result += ",\n";
  6233. }
  6234. else
  6235. Result += "\t0,\n";
  6236. if (InstanceMethods.size() > 0) {
  6237. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
  6238. Result += PDecl->getNameAsString(); Result += ",\n";
  6239. }
  6240. else
  6241. Result += "\t0,\n";
  6242. if (ClassMethods.size() > 0) {
  6243. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
  6244. Result += PDecl->getNameAsString(); Result += ",\n";
  6245. }
  6246. else
  6247. Result += "\t0,\n";
  6248. if (OptInstanceMethods.size() > 0) {
  6249. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
  6250. Result += PDecl->getNameAsString(); Result += ",\n";
  6251. }
  6252. else
  6253. Result += "\t0,\n";
  6254. if (OptClassMethods.size() > 0) {
  6255. Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
  6256. Result += PDecl->getNameAsString(); Result += ",\n";
  6257. }
  6258. else
  6259. Result += "\t0,\n";
  6260. if (ProtocolProperties.size() > 0) {
  6261. Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
  6262. Result += PDecl->getNameAsString(); Result += ",\n";
  6263. }
  6264. else
  6265. Result += "\t0,\n";
  6266. Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
  6267. Result += "\t0,\n";
  6268. if (AllMethods.size() > 0) {
  6269. Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
  6270. Result += PDecl->getNameAsString();
  6271. Result += "\n};\n";
  6272. }
  6273. else
  6274. Result += "\t0\n};\n";
  6275. if (LangOpts.MicrosoftExt)
  6276. Result += "static ";
  6277. Result += "struct _protocol_t *";
  6278. Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
  6279. Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
  6280. Result += ";\n";
  6281. // Mark this protocol as having been generated.
  6282. if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
  6283. llvm_unreachable("protocol already synthesized");
  6284. }
  6285. /// hasObjCExceptionAttribute - Return true if this class or any super
  6286. /// class has the __objc_exception__ attribute.
  6287. /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
  6288. static bool hasObjCExceptionAttribute(ASTContext &Context,
  6289. const ObjCInterfaceDecl *OID) {
  6290. if (OID->hasAttr<ObjCExceptionAttr>())
  6291. return true;
  6292. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  6293. return hasObjCExceptionAttribute(Context, Super);
  6294. return false;
  6295. }
  6296. void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
  6297. std::string &Result) {
  6298. ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
  6299. // Explicitly declared @interface's are already synthesized.
  6300. if (CDecl->isImplicitInterfaceDecl())
  6301. assert(false &&
  6302. "Legacy implicit interface rewriting not supported in moder abi");
  6303. WriteModernMetadataDeclarations(Context, Result);
  6304. SmallVector<ObjCIvarDecl *, 8> IVars;
  6305. for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  6306. IVD; IVD = IVD->getNextIvar()) {
  6307. // Ignore unnamed bit-fields.
  6308. if (!IVD->getDeclName())
  6309. continue;
  6310. IVars.push_back(IVD);
  6311. }
  6312. Write__ivar_list_t_initializer(*this, Context, Result, IVars,
  6313. "_OBJC_$_INSTANCE_VARIABLES_",
  6314. CDecl);
  6315. // Build _objc_method_list for class's instance methods if needed
  6316. SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
  6317. // If any of our property implementations have associated getters or
  6318. // setters, produce metadata for them as well.
  6319. for (const auto *Prop : IDecl->property_impls()) {
  6320. if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  6321. continue;
  6322. if (!Prop->getPropertyIvarDecl())
  6323. continue;
  6324. ObjCPropertyDecl *PD = Prop->getPropertyDecl();
  6325. if (!PD)
  6326. continue;
  6327. if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
  6328. if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
  6329. InstanceMethods.push_back(Getter);
  6330. if (PD->isReadOnly())
  6331. continue;
  6332. if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
  6333. if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
  6334. InstanceMethods.push_back(Setter);
  6335. }
  6336. Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
  6337. "_OBJC_$_INSTANCE_METHODS_",
  6338. IDecl->getNameAsString(), true);
  6339. SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
  6340. Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
  6341. "_OBJC_$_CLASS_METHODS_",
  6342. IDecl->getNameAsString(), true);
  6343. // Protocols referenced in class declaration?
  6344. // Protocol's super protocol list
  6345. std::vector<ObjCProtocolDecl *> RefedProtocols;
  6346. const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
  6347. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  6348. E = Protocols.end();
  6349. I != E; ++I) {
  6350. RefedProtocols.push_back(*I);
  6351. // Must write out all protocol definitions in current qualifier list,
  6352. // and in their nested qualifiers before writing out current definition.
  6353. RewriteObjCProtocolMetaData(*I, Result);
  6354. }
  6355. Write_protocol_list_initializer(Context, Result,
  6356. RefedProtocols,
  6357. "_OBJC_CLASS_PROTOCOLS_$_",
  6358. IDecl->getNameAsString());
  6359. // Protocol's property metadata.
  6360. SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
  6361. CDecl->instance_properties());
  6362. Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
  6363. /* Container */IDecl,
  6364. "_OBJC_$_PROP_LIST_",
  6365. CDecl->getNameAsString());
  6366. // Data for initializing _class_ro_t metaclass meta-data
  6367. uint32_t flags = CLS_META;
  6368. std::string InstanceSize;
  6369. std::string InstanceStart;
  6370. bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
  6371. if (classIsHidden)
  6372. flags |= OBJC2_CLS_HIDDEN;
  6373. if (!CDecl->getSuperClass())
  6374. // class is root
  6375. flags |= CLS_ROOT;
  6376. InstanceSize = "sizeof(struct _class_t)";
  6377. InstanceStart = InstanceSize;
  6378. Write__class_ro_t_initializer(Context, Result, flags,
  6379. InstanceStart, InstanceSize,
  6380. ClassMethods,
  6381. nullptr,
  6382. nullptr,
  6383. nullptr,
  6384. "_OBJC_METACLASS_RO_$_",
  6385. CDecl->getNameAsString());
  6386. // Data for initializing _class_ro_t meta-data
  6387. flags = CLS;
  6388. if (classIsHidden)
  6389. flags |= OBJC2_CLS_HIDDEN;
  6390. if (hasObjCExceptionAttribute(*Context, CDecl))
  6391. flags |= CLS_EXCEPTION;
  6392. if (!CDecl->getSuperClass())
  6393. // class is root
  6394. flags |= CLS_ROOT;
  6395. InstanceSize.clear();
  6396. InstanceStart.clear();
  6397. if (!ObjCSynthesizedStructs.count(CDecl)) {
  6398. InstanceSize = "0";
  6399. InstanceStart = "0";
  6400. }
  6401. else {
  6402. InstanceSize = "sizeof(struct ";
  6403. InstanceSize += CDecl->getNameAsString();
  6404. InstanceSize += "_IMPL)";
  6405. ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
  6406. if (IVD) {
  6407. RewriteIvarOffsetComputation(IVD, InstanceStart);
  6408. }
  6409. else
  6410. InstanceStart = InstanceSize;
  6411. }
  6412. Write__class_ro_t_initializer(Context, Result, flags,
  6413. InstanceStart, InstanceSize,
  6414. InstanceMethods,
  6415. RefedProtocols,
  6416. IVars,
  6417. ClassProperties,
  6418. "_OBJC_CLASS_RO_$_",
  6419. CDecl->getNameAsString());
  6420. Write_class_t(Context, Result,
  6421. "OBJC_METACLASS_$_",
  6422. CDecl, /*metaclass*/true);
  6423. Write_class_t(Context, Result,
  6424. "OBJC_CLASS_$_",
  6425. CDecl, /*metaclass*/false);
  6426. if (ImplementationIsNonLazy(IDecl))
  6427. DefinedNonLazyClasses.push_back(CDecl);
  6428. }
  6429. void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
  6430. int ClsDefCount = ClassImplementation.size();
  6431. if (!ClsDefCount)
  6432. return;
  6433. Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
  6434. Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
  6435. Result += "static void *OBJC_CLASS_SETUP[] = {\n";
  6436. for (int i = 0; i < ClsDefCount; i++) {
  6437. ObjCImplementationDecl *IDecl = ClassImplementation[i];
  6438. ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
  6439. Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
  6440. Result += CDecl->getName(); Result += ",\n";
  6441. }
  6442. Result += "};\n";
  6443. }
  6444. void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
  6445. int ClsDefCount = ClassImplementation.size();
  6446. int CatDefCount = CategoryImplementation.size();
  6447. // For each implemented class, write out all its meta data.
  6448. for (int i = 0; i < ClsDefCount; i++)
  6449. RewriteObjCClassMetaData(ClassImplementation[i], Result);
  6450. RewriteClassSetupInitHook(Result);
  6451. // For each implemented category, write out all its meta data.
  6452. for (int i = 0; i < CatDefCount; i++)
  6453. RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
  6454. RewriteCategorySetupInitHook(Result);
  6455. if (ClsDefCount > 0) {
  6456. if (LangOpts.MicrosoftExt)
  6457. Result += "__declspec(allocate(\".objc_classlist$B\")) ";
  6458. Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
  6459. Result += llvm::utostr(ClsDefCount); Result += "]";
  6460. Result +=
  6461. " __attribute__((used, section (\"__DATA, __objc_classlist,"
  6462. "regular,no_dead_strip\")))= {\n";
  6463. for (int i = 0; i < ClsDefCount; i++) {
  6464. Result += "\t&OBJC_CLASS_$_";
  6465. Result += ClassImplementation[i]->getNameAsString();
  6466. Result += ",\n";
  6467. }
  6468. Result += "};\n";
  6469. if (!DefinedNonLazyClasses.empty()) {
  6470. if (LangOpts.MicrosoftExt)
  6471. Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
  6472. Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
  6473. for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
  6474. Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
  6475. Result += ",\n";
  6476. }
  6477. Result += "};\n";
  6478. }
  6479. }
  6480. if (CatDefCount > 0) {
  6481. if (LangOpts.MicrosoftExt)
  6482. Result += "__declspec(allocate(\".objc_catlist$B\")) ";
  6483. Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
  6484. Result += llvm::utostr(CatDefCount); Result += "]";
  6485. Result +=
  6486. " __attribute__((used, section (\"__DATA, __objc_catlist,"
  6487. "regular,no_dead_strip\")))= {\n";
  6488. for (int i = 0; i < CatDefCount; i++) {
  6489. Result += "\t&_OBJC_$_CATEGORY_";
  6490. Result +=
  6491. CategoryImplementation[i]->getClassInterface()->getNameAsString();
  6492. Result += "_$_";
  6493. Result += CategoryImplementation[i]->getNameAsString();
  6494. Result += ",\n";
  6495. }
  6496. Result += "};\n";
  6497. }
  6498. if (!DefinedNonLazyCategories.empty()) {
  6499. if (LangOpts.MicrosoftExt)
  6500. Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
  6501. Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
  6502. for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
  6503. Result += "\t&_OBJC_$_CATEGORY_";
  6504. Result +=
  6505. DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
  6506. Result += "_$_";
  6507. Result += DefinedNonLazyCategories[i]->getNameAsString();
  6508. Result += ",\n";
  6509. }
  6510. Result += "};\n";
  6511. }
  6512. }
  6513. void RewriteModernObjC::WriteImageInfo(std::string &Result) {
  6514. if (LangOpts.MicrosoftExt)
  6515. Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
  6516. Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
  6517. // version 0, ObjCABI is 2
  6518. Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
  6519. }
  6520. /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
  6521. /// implementation.
  6522. void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
  6523. std::string &Result) {
  6524. WriteModernMetadataDeclarations(Context, Result);
  6525. ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
  6526. // Find category declaration for this implementation.
  6527. ObjCCategoryDecl *CDecl
  6528. = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
  6529. std::string FullCategoryName = ClassDecl->getNameAsString();
  6530. FullCategoryName += "_$_";
  6531. FullCategoryName += CDecl->getNameAsString();
  6532. // Build _objc_method_list for class's instance methods if needed
  6533. SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
  6534. // If any of our property implementations have associated getters or
  6535. // setters, produce metadata for them as well.
  6536. for (const auto *Prop : IDecl->property_impls()) {
  6537. if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  6538. continue;
  6539. if (!Prop->getPropertyIvarDecl())
  6540. continue;
  6541. ObjCPropertyDecl *PD = Prop->getPropertyDecl();
  6542. if (!PD)
  6543. continue;
  6544. if (ObjCMethodDecl *Getter = Prop->getGetterMethodDecl())
  6545. InstanceMethods.push_back(Getter);
  6546. if (PD->isReadOnly())
  6547. continue;
  6548. if (ObjCMethodDecl *Setter = Prop->getSetterMethodDecl())
  6549. InstanceMethods.push_back(Setter);
  6550. }
  6551. Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
  6552. "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
  6553. FullCategoryName, true);
  6554. SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
  6555. Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
  6556. "_OBJC_$_CATEGORY_CLASS_METHODS_",
  6557. FullCategoryName, true);
  6558. // Protocols referenced in class declaration?
  6559. // Protocol's super protocol list
  6560. SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
  6561. for (auto *I : CDecl->protocols())
  6562. // Must write out all protocol definitions in current qualifier list,
  6563. // and in their nested qualifiers before writing out current definition.
  6564. RewriteObjCProtocolMetaData(I, Result);
  6565. Write_protocol_list_initializer(Context, Result,
  6566. RefedProtocols,
  6567. "_OBJC_CATEGORY_PROTOCOLS_$_",
  6568. FullCategoryName);
  6569. // Protocol's property metadata.
  6570. SmallVector<ObjCPropertyDecl *, 8> ClassProperties(
  6571. CDecl->instance_properties());
  6572. Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
  6573. /* Container */IDecl,
  6574. "_OBJC_$_PROP_LIST_",
  6575. FullCategoryName);
  6576. Write_category_t(*this, Context, Result,
  6577. CDecl,
  6578. ClassDecl,
  6579. InstanceMethods,
  6580. ClassMethods,
  6581. RefedProtocols,
  6582. ClassProperties);
  6583. // Determine if this category is also "non-lazy".
  6584. if (ImplementationIsNonLazy(IDecl))
  6585. DefinedNonLazyCategories.push_back(CDecl);
  6586. }
  6587. void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
  6588. int CatDefCount = CategoryImplementation.size();
  6589. if (!CatDefCount)
  6590. return;
  6591. Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
  6592. Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
  6593. Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
  6594. for (int i = 0; i < CatDefCount; i++) {
  6595. ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
  6596. ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
  6597. ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
  6598. Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
  6599. Result += ClassDecl->getName();
  6600. Result += "_$_";
  6601. Result += CatDecl->getName();
  6602. Result += ",\n";
  6603. }
  6604. Result += "};\n";
  6605. }
  6606. // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
  6607. /// class methods.
  6608. template<typename MethodIterator>
  6609. void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
  6610. MethodIterator MethodEnd,
  6611. bool IsInstanceMethod,
  6612. StringRef prefix,
  6613. StringRef ClassName,
  6614. std::string &Result) {
  6615. if (MethodBegin == MethodEnd) return;
  6616. if (!objc_impl_method) {
  6617. /* struct _objc_method {
  6618. SEL _cmd;
  6619. char *method_types;
  6620. void *_imp;
  6621. }
  6622. */
  6623. Result += "\nstruct _objc_method {\n";
  6624. Result += "\tSEL _cmd;\n";
  6625. Result += "\tchar *method_types;\n";
  6626. Result += "\tvoid *_imp;\n";
  6627. Result += "};\n";
  6628. objc_impl_method = true;
  6629. }
  6630. // Build _objc_method_list for class's methods if needed
  6631. /* struct {
  6632. struct _objc_method_list *next_method;
  6633. int method_count;
  6634. struct _objc_method method_list[];
  6635. }
  6636. */
  6637. unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
  6638. Result += "\n";
  6639. if (LangOpts.MicrosoftExt) {
  6640. if (IsInstanceMethod)
  6641. Result += "__declspec(allocate(\".inst_meth$B\")) ";
  6642. else
  6643. Result += "__declspec(allocate(\".cls_meth$B\")) ";
  6644. }
  6645. Result += "static struct {\n";
  6646. Result += "\tstruct _objc_method_list *next_method;\n";
  6647. Result += "\tint method_count;\n";
  6648. Result += "\tstruct _objc_method method_list[";
  6649. Result += utostr(NumMethods);
  6650. Result += "];\n} _OBJC_";
  6651. Result += prefix;
  6652. Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
  6653. Result += "_METHODS_";
  6654. Result += ClassName;
  6655. Result += " __attribute__ ((used, section (\"__OBJC, __";
  6656. Result += IsInstanceMethod ? "inst" : "cls";
  6657. Result += "_meth\")))= ";
  6658. Result += "{\n\t0, " + utostr(NumMethods) + "\n";
  6659. Result += "\t,{{(SEL)\"";
  6660. Result += (*MethodBegin)->getSelector().getAsString().c_str();
  6661. std::string MethodTypeString;
  6662. Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
  6663. Result += "\", \"";
  6664. Result += MethodTypeString;
  6665. Result += "\", (void *)";
  6666. Result += MethodInternalNames[*MethodBegin];
  6667. Result += "}\n";
  6668. for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
  6669. Result += "\t ,{(SEL)\"";
  6670. Result += (*MethodBegin)->getSelector().getAsString().c_str();
  6671. std::string MethodTypeString;
  6672. Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
  6673. Result += "\", \"";
  6674. Result += MethodTypeString;
  6675. Result += "\", (void *)";
  6676. Result += MethodInternalNames[*MethodBegin];
  6677. Result += "}\n";
  6678. }
  6679. Result += "\t }\n};\n";
  6680. }
  6681. Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
  6682. SourceRange OldRange = IV->getSourceRange();
  6683. Expr *BaseExpr = IV->getBase();
  6684. // Rewrite the base, but without actually doing replaces.
  6685. {
  6686. DisableReplaceStmtScope S(*this);
  6687. BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
  6688. IV->setBase(BaseExpr);
  6689. }
  6690. ObjCIvarDecl *D = IV->getDecl();
  6691. Expr *Replacement = IV;
  6692. if (BaseExpr->getType()->isObjCObjectPointerType()) {
  6693. const ObjCInterfaceType *iFaceDecl =
  6694. dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
  6695. assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
  6696. // lookup which class implements the instance variable.
  6697. ObjCInterfaceDecl *clsDeclared = nullptr;
  6698. iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
  6699. clsDeclared);
  6700. assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
  6701. // Build name of symbol holding ivar offset.
  6702. std::string IvarOffsetName;
  6703. if (D->isBitField())
  6704. ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
  6705. else
  6706. WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
  6707. ReferencedIvars[clsDeclared].insert(D);
  6708. // cast offset to "char *".
  6709. CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
  6710. Context->getPointerType(Context->CharTy),
  6711. CK_BitCast,
  6712. BaseExpr);
  6713. VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
  6714. SourceLocation(), &Context->Idents.get(IvarOffsetName),
  6715. Context->UnsignedLongTy, nullptr,
  6716. SC_Extern);
  6717. DeclRefExpr *DRE = new (Context)
  6718. DeclRefExpr(*Context, NewVD, false, Context->UnsignedLongTy,
  6719. VK_LValue, SourceLocation());
  6720. BinaryOperator *addExpr = BinaryOperator::Create(
  6721. *Context, castExpr, DRE, BO_Add,
  6722. Context->getPointerType(Context->CharTy), VK_PRValue, OK_Ordinary,
  6723. SourceLocation(), FPOptionsOverride());
  6724. // Don't forget the parens to enforce the proper binding.
  6725. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
  6726. SourceLocation(),
  6727. addExpr);
  6728. QualType IvarT = D->getType();
  6729. if (D->isBitField())
  6730. IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
  6731. if (!IvarT->getAs<TypedefType>() && IvarT->isRecordType()) {
  6732. RecordDecl *RD = IvarT->castAs<RecordType>()->getDecl();
  6733. RD = RD->getDefinition();
  6734. if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
  6735. // decltype(((Foo_IMPL*)0)->bar) *
  6736. auto *CDecl = cast<ObjCContainerDecl>(D->getDeclContext());
  6737. // ivar in class extensions requires special treatment.
  6738. if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
  6739. CDecl = CatDecl->getClassInterface();
  6740. std::string RecName = std::string(CDecl->getName());
  6741. RecName += "_IMPL";
  6742. RecordDecl *RD = RecordDecl::Create(
  6743. *Context, TTK_Struct, TUDecl, SourceLocation(), SourceLocation(),
  6744. &Context->Idents.get(RecName));
  6745. QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
  6746. unsigned UnsignedIntSize =
  6747. static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
  6748. Expr *Zero = IntegerLiteral::Create(*Context,
  6749. llvm::APInt(UnsignedIntSize, 0),
  6750. Context->UnsignedIntTy, SourceLocation());
  6751. Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
  6752. ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
  6753. Zero);
  6754. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  6755. SourceLocation(),
  6756. &Context->Idents.get(D->getNameAsString()),
  6757. IvarT, nullptr,
  6758. /*BitWidth=*/nullptr,
  6759. /*Mutable=*/true, ICIS_NoInit);
  6760. MemberExpr *ME = MemberExpr::CreateImplicit(
  6761. *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
  6762. IvarT = Context->getDecltypeType(ME, ME->getType());
  6763. }
  6764. }
  6765. convertObjCTypeToCStyleType(IvarT);
  6766. QualType castT = Context->getPointerType(IvarT);
  6767. castExpr = NoTypeInfoCStyleCastExpr(Context,
  6768. castT,
  6769. CK_BitCast,
  6770. PE);
  6771. Expr *Exp = UnaryOperator::Create(
  6772. const_cast<ASTContext &>(*Context), castExpr, UO_Deref, IvarT,
  6773. VK_LValue, OK_Ordinary, SourceLocation(), false, FPOptionsOverride());
  6774. PE = new (Context) ParenExpr(OldRange.getBegin(),
  6775. OldRange.getEnd(),
  6776. Exp);
  6777. if (D->isBitField()) {
  6778. FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
  6779. SourceLocation(),
  6780. &Context->Idents.get(D->getNameAsString()),
  6781. D->getType(), nullptr,
  6782. /*BitWidth=*/D->getBitWidth(),
  6783. /*Mutable=*/true, ICIS_NoInit);
  6784. MemberExpr *ME =
  6785. MemberExpr::CreateImplicit(*Context, PE, /*isArrow*/ false, FD,
  6786. FD->getType(), VK_LValue, OK_Ordinary);
  6787. Replacement = ME;
  6788. }
  6789. else
  6790. Replacement = PE;
  6791. }
  6792. ReplaceStmtWithRange(IV, Replacement, OldRange);
  6793. return Replacement;
  6794. }
  6795. #endif // CLANG_ENABLE_OBJC_REWRITER