RewriteModernObjC.cpp 288 KB

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