RewriteModernObjC.cpp 296 KB

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