CGObjCMac.cpp 277 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062
  1. //===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This provides Objective-C code generation targeting the Apple runtime.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGObjCRuntime.h"
  14. #include "CGBlocks.h"
  15. #include "CGCleanup.h"
  16. #include "CGRecordLayout.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/StmtObjC.h"
  24. #include "clang/Basic/LangOptions.h"
  25. #include "clang/CodeGen/CGFunctionInfo.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/ADT/DenseSet.h"
  28. #include "llvm/ADT/SetVector.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/IR/CallSite.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/InlineAsm.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <cstdio>
  39. using namespace clang;
  40. using namespace CodeGen;
  41. // HLSL Change Starts
  42. // No ObjC codegen support, so simply skip all of this compilation.
  43. // Here are enough stubs to link the current targets.
  44. #if 0
  45. // HLSL Change Ends
  46. namespace {
  47. // FIXME: We should find a nicer way to make the labels for metadata, string
  48. // concatenation is lame.
  49. class ObjCCommonTypesHelper {
  50. protected:
  51. llvm::LLVMContext &VMContext;
  52. private:
  53. // The types of these functions don't really matter because we
  54. // should always bitcast before calling them.
  55. /// id objc_msgSend (id, SEL, ...)
  56. ///
  57. /// The default messenger, used for sends whose ABI is unchanged from
  58. /// the all-integer/pointer case.
  59. llvm::Constant *getMessageSendFn() const {
  60. // Add the non-lazy-bind attribute, since objc_msgSend is likely to
  61. // be called a lot.
  62. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  63. return
  64. CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  65. params, true),
  66. "objc_msgSend",
  67. llvm::AttributeSet::get(CGM.getLLVMContext(),
  68. llvm::AttributeSet::FunctionIndex,
  69. llvm::Attribute::NonLazyBind));
  70. }
  71. /// void objc_msgSend_stret (id, SEL, ...)
  72. ///
  73. /// The messenger used when the return value is an aggregate returned
  74. /// by indirect reference in the first argument, and therefore the
  75. /// self and selector parameters are shifted over by one.
  76. llvm::Constant *getMessageSendStretFn() const {
  77. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  78. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
  79. params, true),
  80. "objc_msgSend_stret");
  81. }
  82. /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
  83. ///
  84. /// The messenger used when the return value is returned on the x87
  85. /// floating-point stack; without a special entrypoint, the nil case
  86. /// would be unbalanced.
  87. llvm::Constant *getMessageSendFpretFn() const {
  88. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  89. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
  90. params, true),
  91. "objc_msgSend_fpret");
  92. }
  93. /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
  94. ///
  95. /// The messenger used when the return value is returned in two values on the
  96. /// x87 floating point stack; without a special entrypoint, the nil case
  97. /// would be unbalanced. Only used on 64-bit X86.
  98. llvm::Constant *getMessageSendFp2retFn() const {
  99. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  100. llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
  101. llvm::Type *resultType =
  102. llvm::StructType::get(longDoubleType, longDoubleType, nullptr);
  103. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
  104. params, true),
  105. "objc_msgSend_fp2ret");
  106. }
  107. /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
  108. ///
  109. /// The messenger used for super calls, which have different dispatch
  110. /// semantics. The class passed is the superclass of the current
  111. /// class.
  112. llvm::Constant *getMessageSendSuperFn() const {
  113. llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
  114. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  115. params, true),
  116. "objc_msgSendSuper");
  117. }
  118. /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
  119. ///
  120. /// A slightly different messenger used for super calls. The class
  121. /// passed is the current class.
  122. llvm::Constant *getMessageSendSuperFn2() const {
  123. llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
  124. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  125. params, true),
  126. "objc_msgSendSuper2");
  127. }
  128. /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
  129. /// SEL op, ...)
  130. ///
  131. /// The messenger used for super calls which return an aggregate indirectly.
  132. llvm::Constant *getMessageSendSuperStretFn() const {
  133. llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
  134. return CGM.CreateRuntimeFunction(
  135. llvm::FunctionType::get(CGM.VoidTy, params, true),
  136. "objc_msgSendSuper_stret");
  137. }
  138. /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
  139. /// SEL op, ...)
  140. ///
  141. /// objc_msgSendSuper_stret with the super2 semantics.
  142. llvm::Constant *getMessageSendSuperStretFn2() const {
  143. llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
  144. return CGM.CreateRuntimeFunction(
  145. llvm::FunctionType::get(CGM.VoidTy, params, true),
  146. "objc_msgSendSuper2_stret");
  147. }
  148. llvm::Constant *getMessageSendSuperFpretFn() const {
  149. // There is no objc_msgSendSuper_fpret? How can that work?
  150. return getMessageSendSuperFn();
  151. }
  152. llvm::Constant *getMessageSendSuperFpretFn2() const {
  153. // There is no objc_msgSendSuper_fpret? How can that work?
  154. return getMessageSendSuperFn2();
  155. }
  156. protected:
  157. CodeGen::CodeGenModule &CGM;
  158. public:
  159. llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
  160. llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
  161. llvm::Type *IvarOffsetVarTy;
  162. /// ObjectPtrTy - LLVM type for object handles (typeof(id))
  163. llvm::Type *ObjectPtrTy;
  164. /// PtrObjectPtrTy - LLVM type for id *
  165. llvm::Type *PtrObjectPtrTy;
  166. /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
  167. llvm::Type *SelectorPtrTy;
  168. private:
  169. /// ProtocolPtrTy - LLVM type for external protocol handles
  170. /// (typeof(Protocol))
  171. llvm::Type *ExternalProtocolPtrTy;
  172. public:
  173. llvm::Type *getExternalProtocolPtrTy() {
  174. if (!ExternalProtocolPtrTy) {
  175. // FIXME: It would be nice to unify this with the opaque type, so that the
  176. // IR comes out a bit cleaner.
  177. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  178. ASTContext &Ctx = CGM.getContext();
  179. llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
  180. ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
  181. }
  182. return ExternalProtocolPtrTy;
  183. }
  184. // SuperCTy - clang type for struct objc_super.
  185. QualType SuperCTy;
  186. // SuperPtrCTy - clang type for struct objc_super *.
  187. QualType SuperPtrCTy;
  188. /// SuperTy - LLVM type for struct objc_super.
  189. llvm::StructType *SuperTy;
  190. /// SuperPtrTy - LLVM type for struct objc_super *.
  191. llvm::Type *SuperPtrTy;
  192. /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
  193. /// in GCC parlance).
  194. llvm::StructType *PropertyTy;
  195. /// PropertyListTy - LLVM type for struct objc_property_list
  196. /// (_prop_list_t in GCC parlance).
  197. llvm::StructType *PropertyListTy;
  198. /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
  199. llvm::Type *PropertyListPtrTy;
  200. // MethodTy - LLVM type for struct objc_method.
  201. llvm::StructType *MethodTy;
  202. /// CacheTy - LLVM type for struct objc_cache.
  203. llvm::Type *CacheTy;
  204. /// CachePtrTy - LLVM type for struct objc_cache *.
  205. llvm::Type *CachePtrTy;
  206. llvm::Constant *getGetPropertyFn() {
  207. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  208. ASTContext &Ctx = CGM.getContext();
  209. // id objc_getProperty (id, SEL, ptrdiff_t, bool)
  210. SmallVector<CanQualType,4> Params;
  211. CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
  212. CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
  213. Params.push_back(IdType);
  214. Params.push_back(SelType);
  215. Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
  216. Params.push_back(Ctx.BoolTy);
  217. llvm::FunctionType *FTy =
  218. Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
  219. IdType, false, false, Params, FunctionType::ExtInfo(),
  220. RequiredArgs::All));
  221. return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
  222. }
  223. llvm::Constant *getSetPropertyFn() {
  224. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  225. ASTContext &Ctx = CGM.getContext();
  226. // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
  227. SmallVector<CanQualType,6> Params;
  228. CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
  229. CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
  230. Params.push_back(IdType);
  231. Params.push_back(SelType);
  232. Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
  233. Params.push_back(IdType);
  234. Params.push_back(Ctx.BoolTy);
  235. Params.push_back(Ctx.BoolTy);
  236. llvm::FunctionType *FTy =
  237. Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
  238. Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
  239. RequiredArgs::All));
  240. return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
  241. }
  242. llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
  243. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  244. ASTContext &Ctx = CGM.getContext();
  245. // void objc_setProperty_atomic(id self, SEL _cmd,
  246. // id newValue, ptrdiff_t offset);
  247. // void objc_setProperty_nonatomic(id self, SEL _cmd,
  248. // id newValue, ptrdiff_t offset);
  249. // void objc_setProperty_atomic_copy(id self, SEL _cmd,
  250. // id newValue, ptrdiff_t offset);
  251. // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
  252. // id newValue, ptrdiff_t offset);
  253. SmallVector<CanQualType,4> Params;
  254. CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
  255. CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
  256. Params.push_back(IdType);
  257. Params.push_back(SelType);
  258. Params.push_back(IdType);
  259. Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
  260. llvm::FunctionType *FTy =
  261. Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
  262. Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
  263. RequiredArgs::All));
  264. const char *name;
  265. if (atomic && copy)
  266. name = "objc_setProperty_atomic_copy";
  267. else if (atomic && !copy)
  268. name = "objc_setProperty_atomic";
  269. else if (!atomic && copy)
  270. name = "objc_setProperty_nonatomic_copy";
  271. else
  272. name = "objc_setProperty_nonatomic";
  273. return CGM.CreateRuntimeFunction(FTy, name);
  274. }
  275. llvm::Constant *getCopyStructFn() {
  276. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  277. ASTContext &Ctx = CGM.getContext();
  278. // void objc_copyStruct (void *, const void *, size_t, bool, bool)
  279. SmallVector<CanQualType,5> Params;
  280. Params.push_back(Ctx.VoidPtrTy);
  281. Params.push_back(Ctx.VoidPtrTy);
  282. Params.push_back(Ctx.LongTy);
  283. Params.push_back(Ctx.BoolTy);
  284. Params.push_back(Ctx.BoolTy);
  285. llvm::FunctionType *FTy =
  286. Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
  287. Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
  288. RequiredArgs::All));
  289. return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
  290. }
  291. /// This routine declares and returns address of:
  292. /// void objc_copyCppObjectAtomic(
  293. /// void *dest, const void *src,
  294. /// void (*copyHelper) (void *dest, const void *source));
  295. llvm::Constant *getCppAtomicObjectFunction() {
  296. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  297. ASTContext &Ctx = CGM.getContext();
  298. /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
  299. SmallVector<CanQualType,3> Params;
  300. Params.push_back(Ctx.VoidPtrTy);
  301. Params.push_back(Ctx.VoidPtrTy);
  302. Params.push_back(Ctx.VoidPtrTy);
  303. llvm::FunctionType *FTy =
  304. Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false, false,
  305. Params,
  306. FunctionType::ExtInfo(),
  307. RequiredArgs::All));
  308. return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
  309. }
  310. llvm::Constant *getEnumerationMutationFn() {
  311. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  312. ASTContext &Ctx = CGM.getContext();
  313. // void objc_enumerationMutation (id)
  314. SmallVector<CanQualType,1> Params;
  315. Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
  316. llvm::FunctionType *FTy =
  317. Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(
  318. Ctx.VoidTy, false, false, Params, FunctionType::ExtInfo(),
  319. RequiredArgs::All));
  320. return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
  321. }
  322. /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
  323. llvm::Constant *getGcReadWeakFn() {
  324. // id objc_read_weak (id *)
  325. llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
  326. llvm::FunctionType *FTy =
  327. llvm::FunctionType::get(ObjectPtrTy, args, false);
  328. return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
  329. }
  330. /// GcAssignWeakFn -- LLVM objc_assign_weak function.
  331. llvm::Constant *getGcAssignWeakFn() {
  332. // id objc_assign_weak (id, id *)
  333. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  334. llvm::FunctionType *FTy =
  335. llvm::FunctionType::get(ObjectPtrTy, args, false);
  336. return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
  337. }
  338. /// GcAssignGlobalFn -- LLVM objc_assign_global function.
  339. llvm::Constant *getGcAssignGlobalFn() {
  340. // id objc_assign_global(id, id *)
  341. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  342. llvm::FunctionType *FTy =
  343. llvm::FunctionType::get(ObjectPtrTy, args, false);
  344. return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
  345. }
  346. /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
  347. llvm::Constant *getGcAssignThreadLocalFn() {
  348. // id objc_assign_threadlocal(id src, id * dest)
  349. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  350. llvm::FunctionType *FTy =
  351. llvm::FunctionType::get(ObjectPtrTy, args, false);
  352. return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
  353. }
  354. /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
  355. llvm::Constant *getGcAssignIvarFn() {
  356. // id objc_assign_ivar(id, id *, ptrdiff_t)
  357. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
  358. CGM.PtrDiffTy };
  359. llvm::FunctionType *FTy =
  360. llvm::FunctionType::get(ObjectPtrTy, args, false);
  361. return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
  362. }
  363. /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
  364. llvm::Constant *GcMemmoveCollectableFn() {
  365. // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
  366. llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
  367. llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
  368. return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
  369. }
  370. /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
  371. llvm::Constant *getGcAssignStrongCastFn() {
  372. // id objc_assign_strongCast(id, id *)
  373. llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
  374. llvm::FunctionType *FTy =
  375. llvm::FunctionType::get(ObjectPtrTy, args, false);
  376. return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
  377. }
  378. /// ExceptionThrowFn - LLVM objc_exception_throw function.
  379. llvm::Constant *getExceptionThrowFn() {
  380. // void objc_exception_throw(id)
  381. llvm::Type *args[] = { ObjectPtrTy };
  382. llvm::FunctionType *FTy =
  383. llvm::FunctionType::get(CGM.VoidTy, args, false);
  384. return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
  385. }
  386. /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
  387. llvm::Constant *getExceptionRethrowFn() {
  388. // void objc_exception_rethrow(void)
  389. llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
  390. return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
  391. }
  392. /// SyncEnterFn - LLVM object_sync_enter function.
  393. llvm::Constant *getSyncEnterFn() {
  394. // int objc_sync_enter (id)
  395. llvm::Type *args[] = { ObjectPtrTy };
  396. llvm::FunctionType *FTy =
  397. llvm::FunctionType::get(CGM.IntTy, args, false);
  398. return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
  399. }
  400. /// SyncExitFn - LLVM object_sync_exit function.
  401. llvm::Constant *getSyncExitFn() {
  402. // int objc_sync_exit (id)
  403. llvm::Type *args[] = { ObjectPtrTy };
  404. llvm::FunctionType *FTy =
  405. llvm::FunctionType::get(CGM.IntTy, args, false);
  406. return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
  407. }
  408. llvm::Constant *getSendFn(bool IsSuper) const {
  409. return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
  410. }
  411. llvm::Constant *getSendFn2(bool IsSuper) const {
  412. return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
  413. }
  414. llvm::Constant *getSendStretFn(bool IsSuper) const {
  415. return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
  416. }
  417. llvm::Constant *getSendStretFn2(bool IsSuper) const {
  418. return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
  419. }
  420. llvm::Constant *getSendFpretFn(bool IsSuper) const {
  421. return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
  422. }
  423. llvm::Constant *getSendFpretFn2(bool IsSuper) const {
  424. return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
  425. }
  426. llvm::Constant *getSendFp2retFn(bool IsSuper) const {
  427. return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
  428. }
  429. llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
  430. return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
  431. }
  432. ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
  433. };
  434. /// ObjCTypesHelper - Helper class that encapsulates lazy
  435. /// construction of varies types used during ObjC generation.
  436. class ObjCTypesHelper : public ObjCCommonTypesHelper {
  437. public:
  438. /// SymtabTy - LLVM type for struct objc_symtab.
  439. llvm::StructType *SymtabTy;
  440. /// SymtabPtrTy - LLVM type for struct objc_symtab *.
  441. llvm::Type *SymtabPtrTy;
  442. /// ModuleTy - LLVM type for struct objc_module.
  443. llvm::StructType *ModuleTy;
  444. /// ProtocolTy - LLVM type for struct objc_protocol.
  445. llvm::StructType *ProtocolTy;
  446. /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
  447. llvm::Type *ProtocolPtrTy;
  448. /// ProtocolExtensionTy - LLVM type for struct
  449. /// objc_protocol_extension.
  450. llvm::StructType *ProtocolExtensionTy;
  451. /// ProtocolExtensionTy - LLVM type for struct
  452. /// objc_protocol_extension *.
  453. llvm::Type *ProtocolExtensionPtrTy;
  454. /// MethodDescriptionTy - LLVM type for struct
  455. /// objc_method_description.
  456. llvm::StructType *MethodDescriptionTy;
  457. /// MethodDescriptionListTy - LLVM type for struct
  458. /// objc_method_description_list.
  459. llvm::StructType *MethodDescriptionListTy;
  460. /// MethodDescriptionListPtrTy - LLVM type for struct
  461. /// objc_method_description_list *.
  462. llvm::Type *MethodDescriptionListPtrTy;
  463. /// ProtocolListTy - LLVM type for struct objc_property_list.
  464. llvm::StructType *ProtocolListTy;
  465. /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
  466. llvm::Type *ProtocolListPtrTy;
  467. /// CategoryTy - LLVM type for struct objc_category.
  468. llvm::StructType *CategoryTy;
  469. /// ClassTy - LLVM type for struct objc_class.
  470. llvm::StructType *ClassTy;
  471. /// ClassPtrTy - LLVM type for struct objc_class *.
  472. llvm::Type *ClassPtrTy;
  473. /// ClassExtensionTy - LLVM type for struct objc_class_ext.
  474. llvm::StructType *ClassExtensionTy;
  475. /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
  476. llvm::Type *ClassExtensionPtrTy;
  477. // IvarTy - LLVM type for struct objc_ivar.
  478. llvm::StructType *IvarTy;
  479. /// IvarListTy - LLVM type for struct objc_ivar_list.
  480. llvm::Type *IvarListTy;
  481. /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
  482. llvm::Type *IvarListPtrTy;
  483. /// MethodListTy - LLVM type for struct objc_method_list.
  484. llvm::Type *MethodListTy;
  485. /// MethodListPtrTy - LLVM type for struct objc_method_list *.
  486. llvm::Type *MethodListPtrTy;
  487. /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
  488. llvm::Type *ExceptionDataTy;
  489. /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
  490. llvm::Constant *getExceptionTryEnterFn() {
  491. llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
  492. return CGM.CreateRuntimeFunction(
  493. llvm::FunctionType::get(CGM.VoidTy, params, false),
  494. "objc_exception_try_enter");
  495. }
  496. /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
  497. llvm::Constant *getExceptionTryExitFn() {
  498. llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
  499. return CGM.CreateRuntimeFunction(
  500. llvm::FunctionType::get(CGM.VoidTy, params, false),
  501. "objc_exception_try_exit");
  502. }
  503. /// ExceptionExtractFn - LLVM objc_exception_extract function.
  504. llvm::Constant *getExceptionExtractFn() {
  505. llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
  506. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  507. params, false),
  508. "objc_exception_extract");
  509. }
  510. /// ExceptionMatchFn - LLVM objc_exception_match function.
  511. llvm::Constant *getExceptionMatchFn() {
  512. llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
  513. return CGM.CreateRuntimeFunction(
  514. llvm::FunctionType::get(CGM.Int32Ty, params, false),
  515. "objc_exception_match");
  516. }
  517. /// SetJmpFn - LLVM _setjmp function.
  518. llvm::Constant *getSetJmpFn() {
  519. // This is specifically the prototype for x86.
  520. llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
  521. return
  522. CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
  523. params, false),
  524. "_setjmp",
  525. llvm::AttributeSet::get(CGM.getLLVMContext(),
  526. llvm::AttributeSet::FunctionIndex,
  527. llvm::Attribute::NonLazyBind));
  528. }
  529. public:
  530. ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
  531. };
  532. /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
  533. /// modern abi
  534. class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
  535. public:
  536. // MethodListnfABITy - LLVM for struct _method_list_t
  537. llvm::StructType *MethodListnfABITy;
  538. // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
  539. llvm::Type *MethodListnfABIPtrTy;
  540. // ProtocolnfABITy = LLVM for struct _protocol_t
  541. llvm::StructType *ProtocolnfABITy;
  542. // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
  543. llvm::Type *ProtocolnfABIPtrTy;
  544. // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
  545. llvm::StructType *ProtocolListnfABITy;
  546. // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
  547. llvm::Type *ProtocolListnfABIPtrTy;
  548. // ClassnfABITy - LLVM for struct _class_t
  549. llvm::StructType *ClassnfABITy;
  550. // ClassnfABIPtrTy - LLVM for struct _class_t*
  551. llvm::Type *ClassnfABIPtrTy;
  552. // IvarnfABITy - LLVM for struct _ivar_t
  553. llvm::StructType *IvarnfABITy;
  554. // IvarListnfABITy - LLVM for struct _ivar_list_t
  555. llvm::StructType *IvarListnfABITy;
  556. // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
  557. llvm::Type *IvarListnfABIPtrTy;
  558. // ClassRonfABITy - LLVM for struct _class_ro_t
  559. llvm::StructType *ClassRonfABITy;
  560. // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
  561. llvm::Type *ImpnfABITy;
  562. // CategorynfABITy - LLVM for struct _category_t
  563. llvm::StructType *CategorynfABITy;
  564. // New types for nonfragile abi messaging.
  565. // MessageRefTy - LLVM for:
  566. // struct _message_ref_t {
  567. // IMP messenger;
  568. // SEL name;
  569. // };
  570. llvm::StructType *MessageRefTy;
  571. // MessageRefCTy - clang type for struct _message_ref_t
  572. QualType MessageRefCTy;
  573. // MessageRefPtrTy - LLVM for struct _message_ref_t*
  574. llvm::Type *MessageRefPtrTy;
  575. // MessageRefCPtrTy - clang type for struct _message_ref_t*
  576. QualType MessageRefCPtrTy;
  577. // MessengerTy - Type of the messenger (shown as IMP above)
  578. llvm::FunctionType *MessengerTy;
  579. // SuperMessageRefTy - LLVM for:
  580. // struct _super_message_ref_t {
  581. // SUPER_IMP messenger;
  582. // SEL name;
  583. // };
  584. llvm::StructType *SuperMessageRefTy;
  585. // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
  586. llvm::Type *SuperMessageRefPtrTy;
  587. llvm::Constant *getMessageSendFixupFn() {
  588. // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
  589. llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
  590. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  591. params, true),
  592. "objc_msgSend_fixup");
  593. }
  594. llvm::Constant *getMessageSendFpretFixupFn() {
  595. // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
  596. llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
  597. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  598. params, true),
  599. "objc_msgSend_fpret_fixup");
  600. }
  601. llvm::Constant *getMessageSendStretFixupFn() {
  602. // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
  603. llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
  604. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  605. params, true),
  606. "objc_msgSend_stret_fixup");
  607. }
  608. llvm::Constant *getMessageSendSuper2FixupFn() {
  609. // id objc_msgSendSuper2_fixup (struct objc_super *,
  610. // struct _super_message_ref_t*, ...)
  611. llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
  612. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  613. params, true),
  614. "objc_msgSendSuper2_fixup");
  615. }
  616. llvm::Constant *getMessageSendSuper2StretFixupFn() {
  617. // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
  618. // struct _super_message_ref_t*, ...)
  619. llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
  620. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
  621. params, true),
  622. "objc_msgSendSuper2_stret_fixup");
  623. }
  624. llvm::Constant *getObjCEndCatchFn() {
  625. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
  626. "objc_end_catch");
  627. }
  628. llvm::Constant *getObjCBeginCatchFn() {
  629. llvm::Type *params[] = { Int8PtrTy };
  630. return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
  631. params, false),
  632. "objc_begin_catch");
  633. }
  634. llvm::StructType *EHTypeTy;
  635. llvm::Type *EHTypePtrTy;
  636. ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
  637. };
  638. class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
  639. public:
  640. // FIXME - accessibility
  641. class GC_IVAR {
  642. public:
  643. unsigned ivar_bytepos;
  644. unsigned ivar_size;
  645. GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
  646. : ivar_bytepos(bytepos), ivar_size(size) {}
  647. // Allow sorting based on byte pos.
  648. bool operator<(const GC_IVAR &b) const {
  649. return ivar_bytepos < b.ivar_bytepos;
  650. }
  651. };
  652. class SKIP_SCAN {
  653. public:
  654. unsigned skip;
  655. unsigned scan;
  656. SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
  657. : skip(_skip), scan(_scan) {}
  658. };
  659. /// opcode for captured block variables layout 'instructions'.
  660. /// In the following descriptions, 'I' is the value of the immediate field.
  661. /// (field following the opcode).
  662. ///
  663. enum BLOCK_LAYOUT_OPCODE {
  664. /// An operator which affects how the following layout should be
  665. /// interpreted.
  666. /// I == 0: Halt interpretation and treat everything else as
  667. /// a non-pointer. Note that this instruction is equal
  668. /// to '\0'.
  669. /// I != 0: Currently unused.
  670. BLOCK_LAYOUT_OPERATOR = 0,
  671. /// The next I+1 bytes do not contain a value of object pointer type.
  672. /// Note that this can leave the stream unaligned, meaning that
  673. /// subsequent word-size instructions do not begin at a multiple of
  674. /// the pointer size.
  675. BLOCK_LAYOUT_NON_OBJECT_BYTES = 1,
  676. /// The next I+1 words do not contain a value of object pointer type.
  677. /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
  678. /// when the required skip quantity is a multiple of the pointer size.
  679. BLOCK_LAYOUT_NON_OBJECT_WORDS = 2,
  680. /// The next I+1 words are __strong pointers to Objective-C
  681. /// objects or blocks.
  682. BLOCK_LAYOUT_STRONG = 3,
  683. /// The next I+1 words are pointers to __block variables.
  684. BLOCK_LAYOUT_BYREF = 4,
  685. /// The next I+1 words are __weak pointers to Objective-C
  686. /// objects or blocks.
  687. BLOCK_LAYOUT_WEAK = 5,
  688. /// The next I+1 words are __unsafe_unretained pointers to
  689. /// Objective-C objects or blocks.
  690. BLOCK_LAYOUT_UNRETAINED = 6
  691. /// The next I+1 words are block or object pointers with some
  692. /// as-yet-unspecified ownership semantics. If we add more
  693. /// flavors of ownership semantics, values will be taken from
  694. /// this range.
  695. ///
  696. /// This is included so that older tools can at least continue
  697. /// processing the layout past such things.
  698. //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
  699. /// All other opcodes are reserved. Halt interpretation and
  700. /// treat everything else as opaque.
  701. };
  702. class RUN_SKIP {
  703. public:
  704. enum BLOCK_LAYOUT_OPCODE opcode;
  705. CharUnits block_var_bytepos;
  706. CharUnits block_var_size;
  707. RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
  708. CharUnits BytePos = CharUnits::Zero(),
  709. CharUnits Size = CharUnits::Zero())
  710. : opcode(Opcode), block_var_bytepos(BytePos), block_var_size(Size) {}
  711. // Allow sorting based on byte pos.
  712. bool operator<(const RUN_SKIP &b) const {
  713. return block_var_bytepos < b.block_var_bytepos;
  714. }
  715. };
  716. protected:
  717. llvm::LLVMContext &VMContext;
  718. // FIXME! May not be needing this after all.
  719. unsigned ObjCABI;
  720. // gc ivar layout bitmap calculation helper caches.
  721. SmallVector<GC_IVAR, 16> SkipIvars;
  722. SmallVector<GC_IVAR, 16> IvarsInfo;
  723. // arc/mrr layout of captured block literal variables.
  724. SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
  725. /// LazySymbols - Symbols to generate a lazy reference for. See
  726. /// DefinedSymbols and FinishModule().
  727. llvm::SetVector<IdentifierInfo*> LazySymbols;
  728. /// DefinedSymbols - External symbols which are defined by this
  729. /// module. The symbols in this list and LazySymbols are used to add
  730. /// special linker symbols which ensure that Objective-C modules are
  731. /// linked properly.
  732. llvm::SetVector<IdentifierInfo*> DefinedSymbols;
  733. /// ClassNames - uniqued class names.
  734. llvm::StringMap<llvm::GlobalVariable*> ClassNames;
  735. /// MethodVarNames - uniqued method variable names.
  736. llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
  737. /// DefinedCategoryNames - list of category names in form Class_Category.
  738. llvm::SetVector<std::string> DefinedCategoryNames;
  739. /// MethodVarTypes - uniqued method type signatures. We have to use
  740. /// a StringMap here because have no other unique reference.
  741. llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
  742. /// MethodDefinitions - map of methods which have been defined in
  743. /// this translation unit.
  744. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
  745. /// PropertyNames - uniqued method variable names.
  746. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
  747. /// ClassReferences - uniqued class references.
  748. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
  749. /// SelectorReferences - uniqued selector references.
  750. llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
  751. /// Protocols - Protocols for which an objc_protocol structure has
  752. /// been emitted. Forward declarations are handled by creating an
  753. /// empty structure whose initializer is filled in when/if defined.
  754. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
  755. /// DefinedProtocols - Protocols which have actually been
  756. /// defined. We should not need this, see FIXME in GenerateProtocol.
  757. llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
  758. /// DefinedClasses - List of defined classes.
  759. SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
  760. /// ImplementedClasses - List of @implemented classes.
  761. SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
  762. /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
  763. SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
  764. /// DefinedCategories - List of defined categories.
  765. SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
  766. /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
  767. SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
  768. /// GetNameForMethod - Return a name for the given method.
  769. /// \param[out] NameOut - The return value.
  770. void GetNameForMethod(const ObjCMethodDecl *OMD,
  771. const ObjCContainerDecl *CD,
  772. SmallVectorImpl<char> &NameOut);
  773. /// GetMethodVarName - Return a unique constant for the given
  774. /// selector's name. The return value has type char *.
  775. llvm::Constant *GetMethodVarName(Selector Sel);
  776. llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
  777. /// GetMethodVarType - Return a unique constant for the given
  778. /// method's type encoding string. The return value has type char *.
  779. // FIXME: This is a horrible name.
  780. llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
  781. bool Extended = false);
  782. llvm::Constant *GetMethodVarType(const FieldDecl *D);
  783. /// GetPropertyName - Return a unique constant for the given
  784. /// name. The return value has type char *.
  785. llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
  786. // FIXME: This can be dropped once string functions are unified.
  787. llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
  788. const Decl *Container);
  789. /// GetClassName - Return a unique constant for the given selector's
  790. /// runtime name (which may change via use of objc_runtime_name attribute on
  791. /// class or protocol definition. The return value has type char *.
  792. llvm::Constant *GetClassName(StringRef RuntimeName);
  793. llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
  794. /// BuildIvarLayout - Builds ivar layout bitmap for the class
  795. /// implementation for the __strong or __weak case.
  796. ///
  797. llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
  798. bool ForStrongLayout);
  799. llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
  800. void BuildAggrIvarRecordLayout(const RecordType *RT,
  801. unsigned int BytePos, bool ForStrongLayout,
  802. bool &HasUnion);
  803. void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
  804. const llvm::StructLayout *Layout,
  805. const RecordDecl *RD,
  806. ArrayRef<const FieldDecl*> RecFields,
  807. unsigned int BytePos, bool ForStrongLayout,
  808. bool &HasUnion);
  809. Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
  810. void UpdateRunSkipBlockVars(bool IsByref,
  811. Qualifiers::ObjCLifetime LifeTime,
  812. CharUnits FieldOffset,
  813. CharUnits FieldSize);
  814. void BuildRCBlockVarRecordLayout(const RecordType *RT,
  815. CharUnits BytePos, bool &HasUnion,
  816. bool ByrefLayout=false);
  817. void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
  818. const RecordDecl *RD,
  819. ArrayRef<const FieldDecl*> RecFields,
  820. CharUnits BytePos, bool &HasUnion,
  821. bool ByrefLayout);
  822. uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
  823. llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
  824. /// GetIvarLayoutName - Returns a unique constant for the given
  825. /// ivar layout bitmap.
  826. llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
  827. const ObjCCommonTypesHelper &ObjCTypes);
  828. /// EmitPropertyList - Emit the given property list. The return
  829. /// value has type PropertyListPtrTy.
  830. llvm::Constant *EmitPropertyList(Twine Name,
  831. const Decl *Container,
  832. const ObjCContainerDecl *OCD,
  833. const ObjCCommonTypesHelper &ObjCTypes);
  834. /// EmitProtocolMethodTypes - Generate the array of extended method type
  835. /// strings. The return value has type Int8PtrPtrTy.
  836. llvm::Constant *EmitProtocolMethodTypes(Twine Name,
  837. ArrayRef<llvm::Constant*> MethodTypes,
  838. const ObjCCommonTypesHelper &ObjCTypes);
  839. /// PushProtocolProperties - Push protocol's property on the input stack.
  840. void PushProtocolProperties(
  841. llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
  842. SmallVectorImpl<llvm::Constant*> &Properties,
  843. const Decl *Container,
  844. const ObjCProtocolDecl *Proto,
  845. const ObjCCommonTypesHelper &ObjCTypes);
  846. /// GetProtocolRef - Return a reference to the internal protocol
  847. /// description, creating an empty one if it has not been
  848. /// defined. The return value has type ProtocolPtrTy.
  849. llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
  850. /// CreateMetadataVar - Create a global variable with internal
  851. /// linkage for use by the Objective-C runtime.
  852. ///
  853. /// This is a convenience wrapper which not only creates the
  854. /// variable, but also sets the section and alignment and adds the
  855. /// global to the "llvm.used" list.
  856. ///
  857. /// \param Name - The variable name.
  858. /// \param Init - The variable initializer; this is also used to
  859. /// define the type of the variable.
  860. /// \param Section - The section the variable should go into, or empty.
  861. /// \param Align - The alignment for the variable, or 0.
  862. /// \param AddToUsed - Whether the variable should be added to
  863. /// "llvm.used".
  864. llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init,
  865. StringRef Section, unsigned Align,
  866. bool AddToUsed);
  867. CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
  868. ReturnValueSlot Return,
  869. QualType ResultType,
  870. llvm::Value *Sel,
  871. llvm::Value *Arg0,
  872. QualType Arg0Ty,
  873. bool IsSuper,
  874. const CallArgList &CallArgs,
  875. const ObjCMethodDecl *OMD,
  876. const ObjCCommonTypesHelper &ObjCTypes);
  877. /// EmitImageInfo - Emit the image info marker used to encode some module
  878. /// level information.
  879. void EmitImageInfo();
  880. public:
  881. CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
  882. CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
  883. llvm::Constant *GenerateConstantString(const StringLiteral *SL) override;
  884. llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
  885. const ObjCContainerDecl *CD=nullptr) override;
  886. void GenerateProtocol(const ObjCProtocolDecl *PD) override;
  887. /// GetOrEmitProtocol - Get the protocol object for the given
  888. /// declaration, emitting it if necessary. The return value has type
  889. /// ProtocolPtrTy.
  890. virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
  891. /// GetOrEmitProtocolRef - Get a forward reference to the protocol
  892. /// object for the given declaration, emitting it if needed. These
  893. /// forward references will be filled in with empty bodies if no
  894. /// definition is seen. The return value has type ProtocolPtrTy.
  895. virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
  896. llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
  897. const CGBlockInfo &blockInfo) override;
  898. llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
  899. const CGBlockInfo &blockInfo) override;
  900. llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
  901. QualType T) override;
  902. };
  903. class CGObjCMac : public CGObjCCommonMac {
  904. private:
  905. ObjCTypesHelper ObjCTypes;
  906. /// EmitModuleInfo - Another marker encoding module level
  907. /// information.
  908. void EmitModuleInfo();
  909. /// EmitModuleSymols - Emit module symbols, the list of defined
  910. /// classes and categories. The result has type SymtabPtrTy.
  911. llvm::Constant *EmitModuleSymbols();
  912. /// FinishModule - Write out global data structures at the end of
  913. /// processing a translation unit.
  914. void FinishModule();
  915. /// EmitClassExtension - Generate the class extension structure used
  916. /// to store the weak ivar layout and properties. The return value
  917. /// has type ClassExtensionPtrTy.
  918. llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
  919. /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
  920. /// for the given class.
  921. llvm::Value *EmitClassRef(CodeGenFunction &CGF,
  922. const ObjCInterfaceDecl *ID);
  923. llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
  924. IdentifierInfo *II);
  925. llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
  926. /// EmitSuperClassRef - Emits reference to class's main metadata class.
  927. llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
  928. /// EmitIvarList - Emit the ivar list for the given
  929. /// implementation. If ForClass is true the list of class ivars
  930. /// (i.e. metaclass ivars) is emitted, otherwise the list of
  931. /// interface ivars will be emitted. The return value has type
  932. /// IvarListPtrTy.
  933. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
  934. bool ForClass);
  935. /// EmitMetaClass - Emit a forward reference to the class structure
  936. /// for the metaclass of the given interface. The return value has
  937. /// type ClassPtrTy.
  938. llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
  939. /// EmitMetaClass - Emit a class structure for the metaclass of the
  940. /// given implementation. The return value has type ClassPtrTy.
  941. llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
  942. llvm::Constant *Protocols,
  943. ArrayRef<llvm::Constant*> Methods);
  944. llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
  945. llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
  946. /// EmitMethodList - Emit the method list for the given
  947. /// implementation. The return value has type MethodListPtrTy.
  948. llvm::Constant *EmitMethodList(Twine Name,
  949. const char *Section,
  950. ArrayRef<llvm::Constant*> Methods);
  951. /// EmitMethodDescList - Emit a method description list for a list of
  952. /// method declarations.
  953. /// - TypeName: The name for the type containing the methods.
  954. /// - IsProtocol: True iff these methods are for a protocol.
  955. /// - ClassMethds: True iff these are class methods.
  956. /// - Required: When true, only "required" methods are
  957. /// listed. Similarly, when false only "optional" methods are
  958. /// listed. For classes this should always be true.
  959. /// - begin, end: The method list to output.
  960. ///
  961. /// The return value has type MethodDescriptionListPtrTy.
  962. llvm::Constant *EmitMethodDescList(Twine Name,
  963. const char *Section,
  964. ArrayRef<llvm::Constant*> Methods);
  965. /// GetOrEmitProtocol - Get the protocol object for the given
  966. /// declaration, emitting it if necessary. The return value has type
  967. /// ProtocolPtrTy.
  968. llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
  969. /// GetOrEmitProtocolRef - Get a forward reference to the protocol
  970. /// object for the given declaration, emitting it if needed. These
  971. /// forward references will be filled in with empty bodies if no
  972. /// definition is seen. The return value has type ProtocolPtrTy.
  973. llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
  974. /// EmitProtocolExtension - Generate the protocol extension
  975. /// structure used to store optional instance and class methods, and
  976. /// protocol properties. The return value has type
  977. /// ProtocolExtensionPtrTy.
  978. llvm::Constant *
  979. EmitProtocolExtension(const ObjCProtocolDecl *PD,
  980. ArrayRef<llvm::Constant*> OptInstanceMethods,
  981. ArrayRef<llvm::Constant*> OptClassMethods,
  982. ArrayRef<llvm::Constant*> MethodTypesExt);
  983. /// EmitProtocolList - Generate the list of referenced
  984. /// protocols. The return value has type ProtocolListPtrTy.
  985. llvm::Constant *EmitProtocolList(Twine Name,
  986. ObjCProtocolDecl::protocol_iterator begin,
  987. ObjCProtocolDecl::protocol_iterator end);
  988. /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
  989. /// for the given selector.
  990. llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel,
  991. bool lval=false);
  992. public:
  993. CGObjCMac(CodeGen::CodeGenModule &cgm);
  994. llvm::Function *ModuleInitFunction() override;
  995. CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  996. ReturnValueSlot Return,
  997. QualType ResultType,
  998. Selector Sel, llvm::Value *Receiver,
  999. const CallArgList &CallArgs,
  1000. const ObjCInterfaceDecl *Class,
  1001. const ObjCMethodDecl *Method) override;
  1002. CodeGen::RValue
  1003. GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  1004. ReturnValueSlot Return, QualType ResultType,
  1005. Selector Sel, const ObjCInterfaceDecl *Class,
  1006. bool isCategoryImpl, llvm::Value *Receiver,
  1007. bool IsClassMessage, const CallArgList &CallArgs,
  1008. const ObjCMethodDecl *Method) override;
  1009. llvm::Value *GetClass(CodeGenFunction &CGF,
  1010. const ObjCInterfaceDecl *ID) override;
  1011. llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
  1012. bool lval = false) override;
  1013. /// The NeXT/Apple runtimes do not support typed selectors; just emit an
  1014. /// untyped one.
  1015. llvm::Value *GetSelector(CodeGenFunction &CGF,
  1016. const ObjCMethodDecl *Method) override;
  1017. llvm::Constant *GetEHType(QualType T) override;
  1018. void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
  1019. void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
  1020. void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
  1021. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  1022. const ObjCProtocolDecl *PD) override;
  1023. llvm::Constant *GetPropertyGetFunction() override;
  1024. llvm::Constant *GetPropertySetFunction() override;
  1025. llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  1026. bool copy) override;
  1027. llvm::Constant *GetGetStructFunction() override;
  1028. llvm::Constant *GetSetStructFunction() override;
  1029. llvm::Constant *GetCppAtomicObjectGetFunction() override;
  1030. llvm::Constant *GetCppAtomicObjectSetFunction() override;
  1031. llvm::Constant *EnumerationMutationFunction() override;
  1032. void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
  1033. const ObjCAtTryStmt &S) override;
  1034. void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  1035. const ObjCAtSynchronizedStmt &S) override;
  1036. void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
  1037. void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
  1038. bool ClearInsertionPoint=true) override;
  1039. llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
  1040. llvm::Value *AddrWeakObj) override;
  1041. void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  1042. llvm::Value *src, llvm::Value *dst) override;
  1043. void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  1044. llvm::Value *src, llvm::Value *dest,
  1045. bool threadlocal = false) override;
  1046. void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  1047. llvm::Value *src, llvm::Value *dest,
  1048. llvm::Value *ivarOffset) override;
  1049. void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
  1050. llvm::Value *src, llvm::Value *dest) override;
  1051. void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
  1052. llvm::Value *dest, llvm::Value *src,
  1053. llvm::Value *size) override;
  1054. LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
  1055. llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
  1056. unsigned CVRQualifiers) override;
  1057. llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
  1058. const ObjCInterfaceDecl *Interface,
  1059. const ObjCIvarDecl *Ivar) override;
  1060. /// GetClassGlobal - Return the global variable for the Objective-C
  1061. /// class of the given name.
  1062. llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
  1063. bool Weak = false) override {
  1064. llvm_unreachable("CGObjCMac::GetClassGlobal");
  1065. }
  1066. };
  1067. class CGObjCNonFragileABIMac : public CGObjCCommonMac {
  1068. private:
  1069. ObjCNonFragileABITypesHelper ObjCTypes;
  1070. llvm::GlobalVariable* ObjCEmptyCacheVar;
  1071. llvm::GlobalVariable* ObjCEmptyVtableVar;
  1072. /// SuperClassReferences - uniqued super class references.
  1073. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
  1074. /// MetaClassReferences - uniqued meta class references.
  1075. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
  1076. /// EHTypeReferences - uniqued class ehtype references.
  1077. llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
  1078. /// VTableDispatchMethods - List of methods for which we generate
  1079. /// vtable-based message dispatch.
  1080. llvm::DenseSet<Selector> VTableDispatchMethods;
  1081. /// DefinedMetaClasses - List of defined meta-classes.
  1082. std::vector<llvm::GlobalValue*> DefinedMetaClasses;
  1083. /// isVTableDispatchedSelector - Returns true if SEL is a
  1084. /// vtable-based selector.
  1085. bool isVTableDispatchedSelector(Selector Sel);
  1086. /// FinishNonFragileABIModule - Write out global data structures at the end of
  1087. /// processing a translation unit.
  1088. void FinishNonFragileABIModule();
  1089. /// AddModuleClassList - Add the given list of class pointers to the
  1090. /// module with the provided symbol and section names.
  1091. void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
  1092. const char *SymbolName,
  1093. const char *SectionName);
  1094. llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
  1095. unsigned InstanceStart,
  1096. unsigned InstanceSize,
  1097. const ObjCImplementationDecl *ID);
  1098. llvm::GlobalVariable * BuildClassMetaData(const std::string &ClassName,
  1099. llvm::Constant *IsAGV,
  1100. llvm::Constant *SuperClassGV,
  1101. llvm::Constant *ClassRoGV,
  1102. bool HiddenVisibility,
  1103. bool Weak);
  1104. llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
  1105. llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
  1106. /// EmitMethodList - Emit the method list for the given
  1107. /// implementation. The return value has type MethodListnfABITy.
  1108. llvm::Constant *EmitMethodList(Twine Name,
  1109. const char *Section,
  1110. ArrayRef<llvm::Constant*> Methods);
  1111. /// EmitIvarList - Emit the ivar list for the given
  1112. /// implementation. If ForClass is true the list of class ivars
  1113. /// (i.e. metaclass ivars) is emitted, otherwise the list of
  1114. /// interface ivars will be emitted. The return value has type
  1115. /// IvarListnfABIPtrTy.
  1116. llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
  1117. llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
  1118. const ObjCIvarDecl *Ivar,
  1119. unsigned long int offset);
  1120. /// GetOrEmitProtocol - Get the protocol object for the given
  1121. /// declaration, emitting it if necessary. The return value has type
  1122. /// ProtocolPtrTy.
  1123. llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
  1124. /// GetOrEmitProtocolRef - Get a forward reference to the protocol
  1125. /// object for the given declaration, emitting it if needed. These
  1126. /// forward references will be filled in with empty bodies if no
  1127. /// definition is seen. The return value has type ProtocolPtrTy.
  1128. llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
  1129. /// EmitProtocolList - Generate the list of referenced
  1130. /// protocols. The return value has type ProtocolListPtrTy.
  1131. llvm::Constant *EmitProtocolList(Twine Name,
  1132. ObjCProtocolDecl::protocol_iterator begin,
  1133. ObjCProtocolDecl::protocol_iterator end);
  1134. CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
  1135. ReturnValueSlot Return,
  1136. QualType ResultType,
  1137. Selector Sel,
  1138. llvm::Value *Receiver,
  1139. QualType Arg0Ty,
  1140. bool IsSuper,
  1141. const CallArgList &CallArgs,
  1142. const ObjCMethodDecl *Method);
  1143. /// GetClassGlobal - Return the global variable for the Objective-C
  1144. /// class of the given name.
  1145. llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
  1146. bool Weak = false) override;
  1147. /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
  1148. /// for the given class reference.
  1149. llvm::Value *EmitClassRef(CodeGenFunction &CGF,
  1150. const ObjCInterfaceDecl *ID);
  1151. llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
  1152. IdentifierInfo *II, bool Weak,
  1153. const ObjCInterfaceDecl *ID);
  1154. llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
  1155. /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
  1156. /// for the given super class reference.
  1157. llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
  1158. const ObjCInterfaceDecl *ID);
  1159. /// EmitMetaClassRef - Return a Value * of the address of _class_t
  1160. /// meta-data
  1161. llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
  1162. const ObjCInterfaceDecl *ID, bool Weak);
  1163. /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
  1164. /// the given ivar.
  1165. ///
  1166. llvm::GlobalVariable * ObjCIvarOffsetVariable(
  1167. const ObjCInterfaceDecl *ID,
  1168. const ObjCIvarDecl *Ivar);
  1169. /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
  1170. /// for the given selector.
  1171. llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel,
  1172. bool lval=false);
  1173. /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
  1174. /// interface. The return value has type EHTypePtrTy.
  1175. llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
  1176. bool ForDefinition);
  1177. const char *getMetaclassSymbolPrefix() const {
  1178. return "OBJC_METACLASS_$_";
  1179. }
  1180. const char *getClassSymbolPrefix() const {
  1181. return "OBJC_CLASS_$_";
  1182. }
  1183. void GetClassSizeInfo(const ObjCImplementationDecl *OID,
  1184. uint32_t &InstanceStart,
  1185. uint32_t &InstanceSize);
  1186. // Shamelessly stolen from Analysis/CFRefCount.cpp
  1187. Selector GetNullarySelector(const char* name) const {
  1188. IdentifierInfo* II = &CGM.getContext().Idents.get(name);
  1189. return CGM.getContext().Selectors.getSelector(0, &II);
  1190. }
  1191. Selector GetUnarySelector(const char* name) const {
  1192. IdentifierInfo* II = &CGM.getContext().Idents.get(name);
  1193. return CGM.getContext().Selectors.getSelector(1, &II);
  1194. }
  1195. /// ImplementationIsNonLazy - Check whether the given category or
  1196. /// class implementation is "non-lazy".
  1197. bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
  1198. bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
  1199. const ObjCIvarDecl *IV) {
  1200. // Annotate the load as an invariant load iff inside an instance method
  1201. // and ivar belongs to instance method's class and one of its super class.
  1202. // This check is needed because the ivar offset is a lazily
  1203. // initialised value that may depend on objc_msgSend to perform a fixup on
  1204. // the first message dispatch.
  1205. //
  1206. // An additional opportunity to mark the load as invariant arises when the
  1207. // base of the ivar access is a parameter to an Objective C method.
  1208. // However, because the parameters are not available in the current
  1209. // interface, we cannot perform this check.
  1210. if (const ObjCMethodDecl *MD =
  1211. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
  1212. if (MD->isInstanceMethod())
  1213. if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
  1214. return IV->getContainingInterface()->isSuperClassOf(ID);
  1215. return false;
  1216. }
  1217. public:
  1218. CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
  1219. // FIXME. All stubs for now!
  1220. llvm::Function *ModuleInitFunction() override;
  1221. CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  1222. ReturnValueSlot Return,
  1223. QualType ResultType, Selector Sel,
  1224. llvm::Value *Receiver,
  1225. const CallArgList &CallArgs,
  1226. const ObjCInterfaceDecl *Class,
  1227. const ObjCMethodDecl *Method) override;
  1228. CodeGen::RValue
  1229. GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  1230. ReturnValueSlot Return, QualType ResultType,
  1231. Selector Sel, const ObjCInterfaceDecl *Class,
  1232. bool isCategoryImpl, llvm::Value *Receiver,
  1233. bool IsClassMessage, const CallArgList &CallArgs,
  1234. const ObjCMethodDecl *Method) override;
  1235. llvm::Value *GetClass(CodeGenFunction &CGF,
  1236. const ObjCInterfaceDecl *ID) override;
  1237. llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
  1238. bool lvalue = false) override
  1239. { return EmitSelector(CGF, Sel, lvalue); }
  1240. /// The NeXT/Apple runtimes do not support typed selectors; just emit an
  1241. /// untyped one.
  1242. llvm::Value *GetSelector(CodeGenFunction &CGF,
  1243. const ObjCMethodDecl *Method) override
  1244. { return EmitSelector(CGF, Method->getSelector()); }
  1245. void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
  1246. void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
  1247. void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
  1248. llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
  1249. const ObjCProtocolDecl *PD) override;
  1250. llvm::Constant *GetEHType(QualType T) override;
  1251. llvm::Constant *GetPropertyGetFunction() override {
  1252. return ObjCTypes.getGetPropertyFn();
  1253. }
  1254. llvm::Constant *GetPropertySetFunction() override {
  1255. return ObjCTypes.getSetPropertyFn();
  1256. }
  1257. llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
  1258. bool copy) override {
  1259. return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
  1260. }
  1261. llvm::Constant *GetSetStructFunction() override {
  1262. return ObjCTypes.getCopyStructFn();
  1263. }
  1264. llvm::Constant *GetGetStructFunction() override {
  1265. return ObjCTypes.getCopyStructFn();
  1266. }
  1267. llvm::Constant *GetCppAtomicObjectSetFunction() override {
  1268. return ObjCTypes.getCppAtomicObjectFunction();
  1269. }
  1270. llvm::Constant *GetCppAtomicObjectGetFunction() override {
  1271. return ObjCTypes.getCppAtomicObjectFunction();
  1272. }
  1273. llvm::Constant *EnumerationMutationFunction() override {
  1274. return ObjCTypes.getEnumerationMutationFn();
  1275. }
  1276. void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
  1277. const ObjCAtTryStmt &S) override;
  1278. void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  1279. const ObjCAtSynchronizedStmt &S) override;
  1280. void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
  1281. bool ClearInsertionPoint=true) override;
  1282. llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
  1283. llvm::Value *AddrWeakObj) override;
  1284. void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  1285. llvm::Value *src, llvm::Value *dst) override;
  1286. void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  1287. llvm::Value *src, llvm::Value *dest,
  1288. bool threadlocal = false) override;
  1289. void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  1290. llvm::Value *src, llvm::Value *dest,
  1291. llvm::Value *ivarOffset) override;
  1292. void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
  1293. llvm::Value *src, llvm::Value *dest) override;
  1294. void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
  1295. llvm::Value *dest, llvm::Value *src,
  1296. llvm::Value *size) override;
  1297. LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
  1298. llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
  1299. unsigned CVRQualifiers) override;
  1300. llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
  1301. const ObjCInterfaceDecl *Interface,
  1302. const ObjCIvarDecl *Ivar) override;
  1303. };
  1304. /// A helper class for performing the null-initialization of a return
  1305. /// value.
  1306. struct NullReturnState {
  1307. llvm::BasicBlock *NullBB;
  1308. NullReturnState() : NullBB(nullptr) {}
  1309. /// Perform a null-check of the given receiver.
  1310. void init(CodeGenFunction &CGF, llvm::Value *receiver) {
  1311. // Make blocks for the null-receiver and call edges.
  1312. NullBB = CGF.createBasicBlock("msgSend.null-receiver");
  1313. llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
  1314. // Check for a null receiver and, if there is one, jump to the
  1315. // null-receiver block. There's no point in trying to avoid it:
  1316. // we're always going to put *something* there, because otherwise
  1317. // we shouldn't have done this null-check in the first place.
  1318. llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
  1319. CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
  1320. // Otherwise, start performing the call.
  1321. CGF.EmitBlock(callBB);
  1322. }
  1323. /// Complete the null-return operation. It is valid to call this
  1324. /// regardless of whether 'init' has been called.
  1325. RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
  1326. const CallArgList &CallArgs,
  1327. const ObjCMethodDecl *Method) {
  1328. // If we never had to do a null-check, just use the raw result.
  1329. if (!NullBB) return result;
  1330. // The continuation block. This will be left null if we don't have an
  1331. // IP, which can happen if the method we're calling is marked noreturn.
  1332. llvm::BasicBlock *contBB = nullptr;
  1333. // Finish the call path.
  1334. llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
  1335. if (callBB) {
  1336. contBB = CGF.createBasicBlock("msgSend.cont");
  1337. CGF.Builder.CreateBr(contBB);
  1338. }
  1339. // Okay, start emitting the null-receiver block.
  1340. CGF.EmitBlock(NullBB);
  1341. // Release any consumed arguments we've got.
  1342. if (Method) {
  1343. CallArgList::const_iterator I = CallArgs.begin();
  1344. for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
  1345. e = Method->param_end(); i != e; ++i, ++I) {
  1346. const ParmVarDecl *ParamDecl = (*i);
  1347. if (ParamDecl->hasAttr<NSConsumedAttr>()) {
  1348. RValue RV = I->RV;
  1349. assert(RV.isScalar() &&
  1350. "NullReturnState::complete - arg not on object");
  1351. CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
  1352. }
  1353. }
  1354. }
  1355. // The phi code below assumes that we haven't needed any control flow yet.
  1356. assert(CGF.Builder.GetInsertBlock() == NullBB);
  1357. // If we've got a void return, just jump to the continuation block.
  1358. if (result.isScalar() && resultType->isVoidType()) {
  1359. // No jumps required if the message-send was noreturn.
  1360. if (contBB) CGF.EmitBlock(contBB);
  1361. return result;
  1362. }
  1363. // If we've got a scalar return, build a phi.
  1364. if (result.isScalar()) {
  1365. // Derive the null-initialization value.
  1366. llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
  1367. // If no join is necessary, just flow out.
  1368. if (!contBB) return RValue::get(null);
  1369. // Otherwise, build a phi.
  1370. CGF.EmitBlock(contBB);
  1371. llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
  1372. phi->addIncoming(result.getScalarVal(), callBB);
  1373. phi->addIncoming(null, NullBB);
  1374. return RValue::get(phi);
  1375. }
  1376. // If we've got an aggregate return, null the buffer out.
  1377. // FIXME: maybe we should be doing things differently for all the
  1378. // cases where the ABI has us returning (1) non-agg values in
  1379. // memory or (2) agg values in registers.
  1380. if (result.isAggregate()) {
  1381. assert(result.isAggregate() && "null init of non-aggregate result?");
  1382. CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
  1383. if (contBB) CGF.EmitBlock(contBB);
  1384. return result;
  1385. }
  1386. // Complex types.
  1387. CGF.EmitBlock(contBB);
  1388. CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
  1389. // Find the scalar type and its zero value.
  1390. llvm::Type *scalarTy = callResult.first->getType();
  1391. llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
  1392. // Build phis for both coordinates.
  1393. llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
  1394. real->addIncoming(callResult.first, callBB);
  1395. real->addIncoming(scalarZero, NullBB);
  1396. llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
  1397. imag->addIncoming(callResult.second, callBB);
  1398. imag->addIncoming(scalarZero, NullBB);
  1399. return RValue::getComplex(real, imag);
  1400. }
  1401. };
  1402. } // end anonymous namespace
  1403. /* *** Helper Functions *** */
  1404. /// getConstantGEP() - Help routine to construct simple GEPs.
  1405. static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
  1406. llvm::GlobalVariable *C, unsigned idx0,
  1407. unsigned idx1) {
  1408. llvm::Value *Idxs[] = {
  1409. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
  1410. llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
  1411. };
  1412. return llvm::ConstantExpr::getGetElementPtr(C->getValueType(), C, Idxs);
  1413. }
  1414. /// hasObjCExceptionAttribute - Return true if this class or any super
  1415. /// class has the __objc_exception__ attribute.
  1416. static bool hasObjCExceptionAttribute(ASTContext &Context,
  1417. const ObjCInterfaceDecl *OID) {
  1418. if (OID->hasAttr<ObjCExceptionAttr>())
  1419. return true;
  1420. if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
  1421. return hasObjCExceptionAttribute(Context, Super);
  1422. return false;
  1423. }
  1424. /* *** CGObjCMac Public Interface *** */
  1425. CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
  1426. ObjCTypes(cgm) {
  1427. ObjCABI = 1;
  1428. EmitImageInfo();
  1429. }
  1430. /// GetClass - Return a reference to the class for the given interface
  1431. /// decl.
  1432. llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
  1433. const ObjCInterfaceDecl *ID) {
  1434. return EmitClassRef(CGF, ID);
  1435. }
  1436. /// GetSelector - Return the pointer to the unique'd string for this selector.
  1437. llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel,
  1438. bool lval) {
  1439. return EmitSelector(CGF, Sel, lval);
  1440. }
  1441. llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
  1442. *Method) {
  1443. return EmitSelector(CGF, Method->getSelector());
  1444. }
  1445. llvm::Constant *CGObjCMac::GetEHType(QualType T) {
  1446. if (T->isObjCIdType() ||
  1447. T->isObjCQualifiedIdType()) {
  1448. return CGM.GetAddrOfRTTIDescriptor(
  1449. CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
  1450. }
  1451. if (T->isObjCClassType() ||
  1452. T->isObjCQualifiedClassType()) {
  1453. return CGM.GetAddrOfRTTIDescriptor(
  1454. CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
  1455. }
  1456. if (T->isObjCObjectPointerType())
  1457. return CGM.GetAddrOfRTTIDescriptor(T, /*ForEH=*/true);
  1458. llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
  1459. }
  1460. /// Generate a constant CFString object.
  1461. /*
  1462. struct __builtin_CFString {
  1463. const int *isa; // point to __CFConstantStringClassReference
  1464. int flags;
  1465. const char *str;
  1466. long length;
  1467. };
  1468. */
  1469. /// or Generate a constant NSString object.
  1470. /*
  1471. struct __builtin_NSString {
  1472. const int *isa; // point to __NSConstantStringClassReference
  1473. const char *str;
  1474. unsigned int length;
  1475. };
  1476. */
  1477. llvm::Constant *CGObjCCommonMac::GenerateConstantString(
  1478. const StringLiteral *SL) {
  1479. return (CGM.getLangOpts().NoConstantCFStrings == 0 ?
  1480. CGM.GetAddrOfConstantCFString(SL) :
  1481. CGM.GetAddrOfConstantString(SL));
  1482. }
  1483. enum {
  1484. kCFTaggedObjectID_Integer = (1 << 1) + 1
  1485. };
  1486. /// Generates a message send where the super is the receiver. This is
  1487. /// a message send to self with special delivery semantics indicating
  1488. /// which class's method should be called.
  1489. CodeGen::RValue
  1490. CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  1491. ReturnValueSlot Return,
  1492. QualType ResultType,
  1493. Selector Sel,
  1494. const ObjCInterfaceDecl *Class,
  1495. bool isCategoryImpl,
  1496. llvm::Value *Receiver,
  1497. bool IsClassMessage,
  1498. const CodeGen::CallArgList &CallArgs,
  1499. const ObjCMethodDecl *Method) {
  1500. // Create and init a super structure; this is a (receiver, class)
  1501. // pair we will pass to objc_msgSendSuper.
  1502. llvm::Value *ObjCSuper =
  1503. CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
  1504. llvm::Value *ReceiverAsObject =
  1505. CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
  1506. CGF.Builder.CreateStore(
  1507. ReceiverAsObject,
  1508. CGF.Builder.CreateStructGEP(ObjCTypes.SuperTy, ObjCSuper, 0));
  1509. // If this is a class message the metaclass is passed as the target.
  1510. llvm::Value *Target;
  1511. if (IsClassMessage) {
  1512. if (isCategoryImpl) {
  1513. // Message sent to 'super' in a class method defined in a category
  1514. // implementation requires an odd treatment.
  1515. // If we are in a class method, we must retrieve the
  1516. // _metaclass_ for the current class, pointed at by
  1517. // the class's "isa" pointer. The following assumes that
  1518. // isa" is the first ivar in a class (which it must be).
  1519. Target = EmitClassRef(CGF, Class->getSuperClass());
  1520. Target = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, Target, 0);
  1521. Target = CGF.Builder.CreateLoad(Target);
  1522. } else {
  1523. llvm::Constant *MetaClassPtr = EmitMetaClassRef(Class);
  1524. llvm::Value *SuperPtr =
  1525. CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, MetaClassPtr, 1);
  1526. llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
  1527. Target = Super;
  1528. }
  1529. } else if (isCategoryImpl)
  1530. Target = EmitClassRef(CGF, Class->getSuperClass());
  1531. else {
  1532. llvm::Value *ClassPtr = EmitSuperClassRef(Class);
  1533. ClassPtr = CGF.Builder.CreateStructGEP(ObjCTypes.ClassTy, ClassPtr, 1);
  1534. Target = CGF.Builder.CreateLoad(ClassPtr);
  1535. }
  1536. // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
  1537. // ObjCTypes types.
  1538. llvm::Type *ClassTy =
  1539. CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
  1540. Target = CGF.Builder.CreateBitCast(Target, ClassTy);
  1541. CGF.Builder.CreateStore(
  1542. Target, CGF.Builder.CreateStructGEP(ObjCTypes.SuperTy, ObjCSuper, 1));
  1543. return EmitMessageSend(CGF, Return, ResultType,
  1544. EmitSelector(CGF, Sel),
  1545. ObjCSuper, ObjCTypes.SuperPtrCTy,
  1546. true, CallArgs, Method, ObjCTypes);
  1547. }
  1548. /// Generate code for a message send expression.
  1549. CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  1550. ReturnValueSlot Return,
  1551. QualType ResultType,
  1552. Selector Sel,
  1553. llvm::Value *Receiver,
  1554. const CallArgList &CallArgs,
  1555. const ObjCInterfaceDecl *Class,
  1556. const ObjCMethodDecl *Method) {
  1557. return EmitMessageSend(CGF, Return, ResultType,
  1558. EmitSelector(CGF, Sel),
  1559. Receiver, CGF.getContext().getObjCIdType(),
  1560. false, CallArgs, Method, ObjCTypes);
  1561. }
  1562. CodeGen::RValue
  1563. CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
  1564. ReturnValueSlot Return,
  1565. QualType ResultType,
  1566. llvm::Value *Sel,
  1567. llvm::Value *Arg0,
  1568. QualType Arg0Ty,
  1569. bool IsSuper,
  1570. const CallArgList &CallArgs,
  1571. const ObjCMethodDecl *Method,
  1572. const ObjCCommonTypesHelper &ObjCTypes) {
  1573. CallArgList ActualArgs;
  1574. if (!IsSuper)
  1575. Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
  1576. ActualArgs.add(RValue::get(Arg0), Arg0Ty);
  1577. ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
  1578. ActualArgs.addFrom(CallArgs);
  1579. // If we're calling a method, use the formal signature.
  1580. MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
  1581. if (Method)
  1582. assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
  1583. CGM.getContext().getCanonicalType(ResultType) &&
  1584. "Result type mismatch!");
  1585. NullReturnState nullReturn;
  1586. llvm::Constant *Fn = nullptr;
  1587. if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
  1588. if (!IsSuper) nullReturn.init(CGF, Arg0);
  1589. Fn = (ObjCABI == 2) ? ObjCTypes.getSendStretFn2(IsSuper)
  1590. : ObjCTypes.getSendStretFn(IsSuper);
  1591. } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
  1592. Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
  1593. : ObjCTypes.getSendFpretFn(IsSuper);
  1594. } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
  1595. Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
  1596. : ObjCTypes.getSendFp2retFn(IsSuper);
  1597. } else {
  1598. // arm64 uses objc_msgSend for stret methods and yet null receiver check
  1599. // must be made for it.
  1600. if (!IsSuper && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
  1601. nullReturn.init(CGF, Arg0);
  1602. Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
  1603. : ObjCTypes.getSendFn(IsSuper);
  1604. }
  1605. bool requiresnullCheck = false;
  1606. if (CGM.getLangOpts().ObjCAutoRefCount && Method)
  1607. for (const auto *ParamDecl : Method->params()) {
  1608. if (ParamDecl->hasAttr<NSConsumedAttr>()) {
  1609. if (!nullReturn.NullBB)
  1610. nullReturn.init(CGF, Arg0);
  1611. requiresnullCheck = true;
  1612. break;
  1613. }
  1614. }
  1615. Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
  1616. RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs);
  1617. return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
  1618. requiresnullCheck ? Method : nullptr);
  1619. }
  1620. static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
  1621. if (FQT.isObjCGCStrong())
  1622. return Qualifiers::Strong;
  1623. if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() == Qualifiers::OCL_Weak)
  1624. return Qualifiers::Weak;
  1625. // check for __unsafe_unretained
  1626. if (FQT.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
  1627. return Qualifiers::GCNone;
  1628. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
  1629. return Qualifiers::Strong;
  1630. if (const PointerType *PT = FQT->getAs<PointerType>())
  1631. return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
  1632. return Qualifiers::GCNone;
  1633. }
  1634. llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
  1635. const CGBlockInfo &blockInfo) {
  1636. llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  1637. if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
  1638. !CGM.getLangOpts().ObjCAutoRefCount)
  1639. return nullPtr;
  1640. bool hasUnion = false;
  1641. SkipIvars.clear();
  1642. IvarsInfo.clear();
  1643. unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
  1644. unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
  1645. // __isa is the first field in block descriptor and must assume by runtime's
  1646. // convention that it is GC'able.
  1647. IvarsInfo.push_back(GC_IVAR(0, 1));
  1648. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  1649. // Calculate the basic layout of the block structure.
  1650. const llvm::StructLayout *layout =
  1651. CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
  1652. // Ignore the optional 'this' capture: C++ objects are not assumed
  1653. // to be GC'ed.
  1654. // Walk the captured variables.
  1655. for (const auto &CI : blockDecl->captures()) {
  1656. const VarDecl *variable = CI.getVariable();
  1657. QualType type = variable->getType();
  1658. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  1659. // Ignore constant captures.
  1660. if (capture.isConstant()) continue;
  1661. uint64_t fieldOffset = layout->getElementOffset(capture.getIndex());
  1662. // __block variables are passed by their descriptor address.
  1663. if (CI.isByRef()) {
  1664. IvarsInfo.push_back(GC_IVAR(fieldOffset, /*size in words*/ 1));
  1665. continue;
  1666. }
  1667. assert(!type->isArrayType() && "array variable should not be caught");
  1668. if (const RecordType *record = type->getAs<RecordType>()) {
  1669. BuildAggrIvarRecordLayout(record, fieldOffset, true, hasUnion);
  1670. continue;
  1671. }
  1672. Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
  1673. unsigned fieldSize = CGM.getContext().getTypeSize(type);
  1674. if (GCAttr == Qualifiers::Strong)
  1675. IvarsInfo.push_back(GC_IVAR(fieldOffset,
  1676. fieldSize / WordSizeInBits));
  1677. else if (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak)
  1678. SkipIvars.push_back(GC_IVAR(fieldOffset,
  1679. fieldSize / ByteSizeInBits));
  1680. }
  1681. if (IvarsInfo.empty())
  1682. return nullPtr;
  1683. // Sort on byte position; captures might not be allocated in order,
  1684. // and unions can do funny things.
  1685. llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
  1686. llvm::array_pod_sort(SkipIvars.begin(), SkipIvars.end());
  1687. std::string BitMap;
  1688. llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
  1689. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  1690. printf("\n block variable layout for block: ");
  1691. const unsigned char *s = (const unsigned char*)BitMap.c_str();
  1692. for (unsigned i = 0, e = BitMap.size(); i < e; i++)
  1693. if (!(s[i] & 0xf0))
  1694. printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
  1695. else
  1696. printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
  1697. printf("\n");
  1698. }
  1699. return C;
  1700. }
  1701. /// getBlockCaptureLifetime - This routine returns life time of the captured
  1702. /// block variable for the purpose of block layout meta-data generation. FQT is
  1703. /// the type of the variable captured in the block.
  1704. Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
  1705. bool ByrefLayout) {
  1706. if (CGM.getLangOpts().ObjCAutoRefCount)
  1707. return FQT.getObjCLifetime();
  1708. // MRR.
  1709. if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
  1710. return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
  1711. return Qualifiers::OCL_None;
  1712. }
  1713. void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
  1714. Qualifiers::ObjCLifetime LifeTime,
  1715. CharUnits FieldOffset,
  1716. CharUnits FieldSize) {
  1717. // __block variables are passed by their descriptor address.
  1718. if (IsByref)
  1719. RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
  1720. FieldSize));
  1721. else if (LifeTime == Qualifiers::OCL_Strong)
  1722. RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
  1723. FieldSize));
  1724. else if (LifeTime == Qualifiers::OCL_Weak)
  1725. RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
  1726. FieldSize));
  1727. else if (LifeTime == Qualifiers::OCL_ExplicitNone)
  1728. RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
  1729. FieldSize));
  1730. else
  1731. RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
  1732. FieldOffset,
  1733. FieldSize));
  1734. }
  1735. void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
  1736. const RecordDecl *RD,
  1737. ArrayRef<const FieldDecl*> RecFields,
  1738. CharUnits BytePos, bool &HasUnion,
  1739. bool ByrefLayout) {
  1740. bool IsUnion = (RD && RD->isUnion());
  1741. CharUnits MaxUnionSize = CharUnits::Zero();
  1742. const FieldDecl *MaxField = nullptr;
  1743. const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
  1744. CharUnits MaxFieldOffset = CharUnits::Zero();
  1745. CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
  1746. if (RecFields.empty())
  1747. return;
  1748. unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
  1749. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  1750. const FieldDecl *Field = RecFields[i];
  1751. // Note that 'i' here is actually the field index inside RD of Field,
  1752. // although this dependency is hidden.
  1753. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  1754. CharUnits FieldOffset =
  1755. CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
  1756. // Skip over unnamed or bitfields
  1757. if (!Field->getIdentifier() || Field->isBitField()) {
  1758. LastFieldBitfieldOrUnnamed = Field;
  1759. LastBitfieldOrUnnamedOffset = FieldOffset;
  1760. continue;
  1761. }
  1762. LastFieldBitfieldOrUnnamed = nullptr;
  1763. QualType FQT = Field->getType();
  1764. if (FQT->isRecordType() || FQT->isUnionType()) {
  1765. if (FQT->isUnionType())
  1766. HasUnion = true;
  1767. BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
  1768. BytePos + FieldOffset, HasUnion);
  1769. continue;
  1770. }
  1771. if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
  1772. const ConstantArrayType *CArray =
  1773. dyn_cast_or_null<ConstantArrayType>(Array);
  1774. uint64_t ElCount = CArray->getSize().getZExtValue();
  1775. assert(CArray && "only array with known element size is supported");
  1776. FQT = CArray->getElementType();
  1777. while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
  1778. const ConstantArrayType *CArray =
  1779. dyn_cast_or_null<ConstantArrayType>(Array);
  1780. ElCount *= CArray->getSize().getZExtValue();
  1781. FQT = CArray->getElementType();
  1782. }
  1783. if (FQT->isRecordType() && ElCount) {
  1784. int OldIndex = RunSkipBlockVars.size() - 1;
  1785. const RecordType *RT = FQT->getAs<RecordType>();
  1786. BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
  1787. HasUnion);
  1788. // Replicate layout information for each array element. Note that
  1789. // one element is already done.
  1790. uint64_t ElIx = 1;
  1791. for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
  1792. CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
  1793. for (int i = OldIndex+1; i <= FirstIndex; ++i)
  1794. RunSkipBlockVars.push_back(
  1795. RUN_SKIP(RunSkipBlockVars[i].opcode,
  1796. RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
  1797. RunSkipBlockVars[i].block_var_size));
  1798. }
  1799. continue;
  1800. }
  1801. }
  1802. CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
  1803. if (IsUnion) {
  1804. CharUnits UnionIvarSize = FieldSize;
  1805. if (UnionIvarSize > MaxUnionSize) {
  1806. MaxUnionSize = UnionIvarSize;
  1807. MaxField = Field;
  1808. MaxFieldOffset = FieldOffset;
  1809. }
  1810. } else {
  1811. UpdateRunSkipBlockVars(false,
  1812. getBlockCaptureLifetime(FQT, ByrefLayout),
  1813. BytePos + FieldOffset,
  1814. FieldSize);
  1815. }
  1816. }
  1817. if (LastFieldBitfieldOrUnnamed) {
  1818. if (LastFieldBitfieldOrUnnamed->isBitField()) {
  1819. // Last field was a bitfield. Must update the info.
  1820. uint64_t BitFieldSize
  1821. = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
  1822. unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
  1823. ((BitFieldSize % ByteSizeInBits) != 0);
  1824. CharUnits Size = CharUnits::fromQuantity(UnsSize);
  1825. Size += LastBitfieldOrUnnamedOffset;
  1826. UpdateRunSkipBlockVars(false,
  1827. getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
  1828. ByrefLayout),
  1829. BytePos + LastBitfieldOrUnnamedOffset,
  1830. Size);
  1831. } else {
  1832. assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
  1833. // Last field was unnamed. Must update skip info.
  1834. CharUnits FieldSize
  1835. = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
  1836. UpdateRunSkipBlockVars(false,
  1837. getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
  1838. ByrefLayout),
  1839. BytePos + LastBitfieldOrUnnamedOffset,
  1840. FieldSize);
  1841. }
  1842. }
  1843. if (MaxField)
  1844. UpdateRunSkipBlockVars(false,
  1845. getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
  1846. BytePos + MaxFieldOffset,
  1847. MaxUnionSize);
  1848. }
  1849. void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
  1850. CharUnits BytePos,
  1851. bool &HasUnion,
  1852. bool ByrefLayout) {
  1853. const RecordDecl *RD = RT->getDecl();
  1854. SmallVector<const FieldDecl*, 16> Fields(RD->fields());
  1855. llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
  1856. const llvm::StructLayout *RecLayout =
  1857. CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
  1858. BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
  1859. }
  1860. /// InlineLayoutInstruction - This routine produce an inline instruction for the
  1861. /// block variable layout if it can. If not, it returns 0. Rules are as follow:
  1862. /// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
  1863. /// an inline layout of value 0x0000000000000xyz is interpreted as follows:
  1864. /// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
  1865. /// y captured object of BLOCK_LAYOUT_BYREF. Followed by
  1866. /// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
  1867. /// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
  1868. /// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
  1869. uint64_t CGObjCCommonMac::InlineLayoutInstruction(
  1870. SmallVectorImpl<unsigned char> &Layout) {
  1871. uint64_t Result = 0;
  1872. if (Layout.size() <= 3) {
  1873. unsigned size = Layout.size();
  1874. unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
  1875. unsigned char inst;
  1876. enum BLOCK_LAYOUT_OPCODE opcode ;
  1877. switch (size) {
  1878. case 3:
  1879. inst = Layout[0];
  1880. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1881. if (opcode == BLOCK_LAYOUT_STRONG)
  1882. strong_word_count = (inst & 0xF)+1;
  1883. else
  1884. return 0;
  1885. inst = Layout[1];
  1886. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1887. if (opcode == BLOCK_LAYOUT_BYREF)
  1888. byref_word_count = (inst & 0xF)+1;
  1889. else
  1890. return 0;
  1891. inst = Layout[2];
  1892. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1893. if (opcode == BLOCK_LAYOUT_WEAK)
  1894. weak_word_count = (inst & 0xF)+1;
  1895. else
  1896. return 0;
  1897. break;
  1898. case 2:
  1899. inst = Layout[0];
  1900. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1901. if (opcode == BLOCK_LAYOUT_STRONG) {
  1902. strong_word_count = (inst & 0xF)+1;
  1903. inst = Layout[1];
  1904. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1905. if (opcode == BLOCK_LAYOUT_BYREF)
  1906. byref_word_count = (inst & 0xF)+1;
  1907. else if (opcode == BLOCK_LAYOUT_WEAK)
  1908. weak_word_count = (inst & 0xF)+1;
  1909. else
  1910. return 0;
  1911. }
  1912. else if (opcode == BLOCK_LAYOUT_BYREF) {
  1913. byref_word_count = (inst & 0xF)+1;
  1914. inst = Layout[1];
  1915. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1916. if (opcode == BLOCK_LAYOUT_WEAK)
  1917. weak_word_count = (inst & 0xF)+1;
  1918. else
  1919. return 0;
  1920. }
  1921. else
  1922. return 0;
  1923. break;
  1924. case 1:
  1925. inst = Layout[0];
  1926. opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  1927. if (opcode == BLOCK_LAYOUT_STRONG)
  1928. strong_word_count = (inst & 0xF)+1;
  1929. else if (opcode == BLOCK_LAYOUT_BYREF)
  1930. byref_word_count = (inst & 0xF)+1;
  1931. else if (opcode == BLOCK_LAYOUT_WEAK)
  1932. weak_word_count = (inst & 0xF)+1;
  1933. else
  1934. return 0;
  1935. break;
  1936. default:
  1937. return 0;
  1938. }
  1939. // Cannot inline when any of the word counts is 15. Because this is one less
  1940. // than the actual work count (so 15 means 16 actual word counts),
  1941. // and we can only display 0 thru 15 word counts.
  1942. if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
  1943. return 0;
  1944. unsigned count =
  1945. (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
  1946. if (size == count) {
  1947. if (strong_word_count)
  1948. Result = strong_word_count;
  1949. Result <<= 4;
  1950. if (byref_word_count)
  1951. Result += byref_word_count;
  1952. Result <<= 4;
  1953. if (weak_word_count)
  1954. Result += weak_word_count;
  1955. }
  1956. }
  1957. return Result;
  1958. }
  1959. llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
  1960. llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  1961. if (RunSkipBlockVars.empty())
  1962. return nullPtr;
  1963. unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
  1964. unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
  1965. unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
  1966. // Sort on byte position; captures might not be allocated in order,
  1967. // and unions can do funny things.
  1968. llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
  1969. SmallVector<unsigned char, 16> Layout;
  1970. unsigned size = RunSkipBlockVars.size();
  1971. for (unsigned i = 0; i < size; i++) {
  1972. enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
  1973. CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
  1974. CharUnits end_byte_pos = start_byte_pos;
  1975. unsigned j = i+1;
  1976. while (j < size) {
  1977. if (opcode == RunSkipBlockVars[j].opcode) {
  1978. end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
  1979. i++;
  1980. }
  1981. else
  1982. break;
  1983. }
  1984. CharUnits size_in_bytes =
  1985. end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
  1986. if (j < size) {
  1987. CharUnits gap =
  1988. RunSkipBlockVars[j].block_var_bytepos -
  1989. RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
  1990. size_in_bytes += gap;
  1991. }
  1992. CharUnits residue_in_bytes = CharUnits::Zero();
  1993. if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
  1994. residue_in_bytes = size_in_bytes % WordSizeInBytes;
  1995. size_in_bytes -= residue_in_bytes;
  1996. opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
  1997. }
  1998. unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
  1999. while (size_in_words >= 16) {
  2000. // Note that value in imm. is one less that the actual
  2001. // value. So, 0xf means 16 words follow!
  2002. unsigned char inst = (opcode << 4) | 0xf;
  2003. Layout.push_back(inst);
  2004. size_in_words -= 16;
  2005. }
  2006. if (size_in_words > 0) {
  2007. // Note that value in imm. is one less that the actual
  2008. // value. So, we subtract 1 away!
  2009. unsigned char inst = (opcode << 4) | (size_in_words-1);
  2010. Layout.push_back(inst);
  2011. }
  2012. if (residue_in_bytes > CharUnits::Zero()) {
  2013. unsigned char inst =
  2014. (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
  2015. Layout.push_back(inst);
  2016. }
  2017. }
  2018. int e = Layout.size()-1;
  2019. while (e >= 0) {
  2020. unsigned char inst = Layout[e--];
  2021. enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  2022. if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
  2023. Layout.pop_back();
  2024. else
  2025. break;
  2026. }
  2027. uint64_t Result = InlineLayoutInstruction(Layout);
  2028. if (Result != 0) {
  2029. // Block variable layout instruction has been inlined.
  2030. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  2031. if (ComputeByrefLayout)
  2032. printf("\n Inline instruction for BYREF variable layout: ");
  2033. else
  2034. printf("\n Inline instruction for block variable layout: ");
  2035. printf("0x0%" PRIx64 "\n", Result);
  2036. }
  2037. if (WordSizeInBytes == 8) {
  2038. const llvm::APInt Instruction(64, Result);
  2039. return llvm::Constant::getIntegerValue(CGM.Int64Ty, Instruction);
  2040. }
  2041. else {
  2042. const llvm::APInt Instruction(32, Result);
  2043. return llvm::Constant::getIntegerValue(CGM.Int32Ty, Instruction);
  2044. }
  2045. }
  2046. unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
  2047. Layout.push_back(inst);
  2048. std::string BitMap;
  2049. for (unsigned i = 0, e = Layout.size(); i != e; i++)
  2050. BitMap += Layout[i];
  2051. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  2052. if (ComputeByrefLayout)
  2053. printf("\n BYREF variable layout: ");
  2054. else
  2055. printf("\n block variable layout: ");
  2056. for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
  2057. unsigned char inst = BitMap[i];
  2058. enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
  2059. unsigned delta = 1;
  2060. switch (opcode) {
  2061. case BLOCK_LAYOUT_OPERATOR:
  2062. printf("BL_OPERATOR:");
  2063. delta = 0;
  2064. break;
  2065. case BLOCK_LAYOUT_NON_OBJECT_BYTES:
  2066. printf("BL_NON_OBJECT_BYTES:");
  2067. break;
  2068. case BLOCK_LAYOUT_NON_OBJECT_WORDS:
  2069. printf("BL_NON_OBJECT_WORD:");
  2070. break;
  2071. case BLOCK_LAYOUT_STRONG:
  2072. printf("BL_STRONG:");
  2073. break;
  2074. case BLOCK_LAYOUT_BYREF:
  2075. printf("BL_BYREF:");
  2076. break;
  2077. case BLOCK_LAYOUT_WEAK:
  2078. printf("BL_WEAK:");
  2079. break;
  2080. case BLOCK_LAYOUT_UNRETAINED:
  2081. printf("BL_UNRETAINED:");
  2082. break;
  2083. }
  2084. // Actual value of word count is one more that what is in the imm.
  2085. // field of the instruction
  2086. printf("%d", (inst & 0xf) + delta);
  2087. if (i < e-1)
  2088. printf(", ");
  2089. else
  2090. printf("\n");
  2091. }
  2092. }
  2093. llvm::GlobalVariable *Entry = CreateMetadataVar(
  2094. "OBJC_CLASS_NAME_",
  2095. llvm::ConstantDataArray::getString(VMContext, BitMap, false),
  2096. "__TEXT,__objc_classname,cstring_literals", 1, true);
  2097. return getConstantGEP(VMContext, Entry, 0, 0);
  2098. }
  2099. llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
  2100. const CGBlockInfo &blockInfo) {
  2101. assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
  2102. RunSkipBlockVars.clear();
  2103. bool hasUnion = false;
  2104. unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
  2105. unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
  2106. unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
  2107. const BlockDecl *blockDecl = blockInfo.getBlockDecl();
  2108. // Calculate the basic layout of the block structure.
  2109. const llvm::StructLayout *layout =
  2110. CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
  2111. // Ignore the optional 'this' capture: C++ objects are not assumed
  2112. // to be GC'ed.
  2113. if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
  2114. UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
  2115. blockInfo.BlockHeaderForcedGapOffset,
  2116. blockInfo.BlockHeaderForcedGapSize);
  2117. // Walk the captured variables.
  2118. for (const auto &CI : blockDecl->captures()) {
  2119. const VarDecl *variable = CI.getVariable();
  2120. QualType type = variable->getType();
  2121. const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
  2122. // Ignore constant captures.
  2123. if (capture.isConstant()) continue;
  2124. CharUnits fieldOffset =
  2125. CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
  2126. assert(!type->isArrayType() && "array variable should not be caught");
  2127. if (!CI.isByRef())
  2128. if (const RecordType *record = type->getAs<RecordType>()) {
  2129. BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
  2130. continue;
  2131. }
  2132. CharUnits fieldSize;
  2133. if (CI.isByRef())
  2134. fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
  2135. else
  2136. fieldSize = CGM.getContext().getTypeSizeInChars(type);
  2137. UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
  2138. fieldOffset, fieldSize);
  2139. }
  2140. return getBitmapBlockLayout(false);
  2141. }
  2142. llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
  2143. QualType T) {
  2144. assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
  2145. assert(!T->isArrayType() && "__block array variable should not be caught");
  2146. CharUnits fieldOffset;
  2147. RunSkipBlockVars.clear();
  2148. bool hasUnion = false;
  2149. if (const RecordType *record = T->getAs<RecordType>()) {
  2150. BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
  2151. llvm::Constant *Result = getBitmapBlockLayout(true);
  2152. return Result;
  2153. }
  2154. llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
  2155. return nullPtr;
  2156. }
  2157. llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
  2158. const ObjCProtocolDecl *PD) {
  2159. // FIXME: I don't understand why gcc generates this, or where it is
  2160. // resolved. Investigate. Its also wasteful to look this up over and over.
  2161. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
  2162. return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
  2163. ObjCTypes.getExternalProtocolPtrTy());
  2164. }
  2165. void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
  2166. // FIXME: We shouldn't need this, the protocol decl should contain enough
  2167. // information to tell us whether this was a declaration or a definition.
  2168. DefinedProtocols.insert(PD->getIdentifier());
  2169. // If we have generated a forward reference to this protocol, emit
  2170. // it now. Otherwise do nothing, the protocol objects are lazily
  2171. // emitted.
  2172. if (Protocols.count(PD->getIdentifier()))
  2173. GetOrEmitProtocol(PD);
  2174. }
  2175. llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
  2176. if (DefinedProtocols.count(PD->getIdentifier()))
  2177. return GetOrEmitProtocol(PD);
  2178. return GetOrEmitProtocolRef(PD);
  2179. }
  2180. /*
  2181. // Objective-C 1.0 extensions
  2182. struct _objc_protocol {
  2183. struct _objc_protocol_extension *isa;
  2184. char *protocol_name;
  2185. struct _objc_protocol_list *protocol_list;
  2186. struct _objc__method_prototype_list *instance_methods;
  2187. struct _objc__method_prototype_list *class_methods
  2188. };
  2189. See EmitProtocolExtension().
  2190. */
  2191. llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
  2192. llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
  2193. // Early exit if a defining object has already been generated.
  2194. if (Entry && Entry->hasInitializer())
  2195. return Entry;
  2196. // Use the protocol definition, if there is one.
  2197. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  2198. PD = Def;
  2199. // FIXME: I don't understand why gcc generates this, or where it is
  2200. // resolved. Investigate. Its also wasteful to look this up over and over.
  2201. LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
  2202. // Construct method lists.
  2203. std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
  2204. std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
  2205. std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
  2206. for (const auto *MD : PD->instance_methods()) {
  2207. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  2208. if (!C)
  2209. return GetOrEmitProtocolRef(PD);
  2210. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  2211. OptInstanceMethods.push_back(C);
  2212. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  2213. } else {
  2214. InstanceMethods.push_back(C);
  2215. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  2216. }
  2217. }
  2218. for (const auto *MD : PD->class_methods()) {
  2219. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  2220. if (!C)
  2221. return GetOrEmitProtocolRef(PD);
  2222. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  2223. OptClassMethods.push_back(C);
  2224. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  2225. } else {
  2226. ClassMethods.push_back(C);
  2227. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  2228. }
  2229. }
  2230. MethodTypesExt.insert(MethodTypesExt.end(),
  2231. OptMethodTypesExt.begin(), OptMethodTypesExt.end());
  2232. llvm::Constant *Values[] = {
  2233. EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
  2234. MethodTypesExt),
  2235. GetClassName(PD->getObjCRuntimeNameAsString()),
  2236. EmitProtocolList("OBJC_PROTOCOL_REFS_" + PD->getName(),
  2237. PD->protocol_begin(), PD->protocol_end()),
  2238. EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
  2239. "__OBJC,__cat_inst_meth,regular,no_dead_strip",
  2240. InstanceMethods),
  2241. EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
  2242. "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  2243. ClassMethods)};
  2244. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
  2245. Values);
  2246. if (Entry) {
  2247. // Already created, update the initializer.
  2248. assert(Entry->hasPrivateLinkage());
  2249. Entry->setInitializer(Init);
  2250. } else {
  2251. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
  2252. false, llvm::GlobalValue::PrivateLinkage,
  2253. Init, "OBJC_PROTOCOL_" + PD->getName());
  2254. Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
  2255. // FIXME: Is this necessary? Why only for protocol?
  2256. Entry->setAlignment(4);
  2257. Protocols[PD->getIdentifier()] = Entry;
  2258. }
  2259. CGM.addCompilerUsedGlobal(Entry);
  2260. return Entry;
  2261. }
  2262. llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
  2263. llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
  2264. if (!Entry) {
  2265. // We use the initializer as a marker of whether this is a forward
  2266. // reference or not. At module finalization we add the empty
  2267. // contents for protocols which were referenced but never defined.
  2268. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy,
  2269. false, llvm::GlobalValue::PrivateLinkage,
  2270. nullptr, "OBJC_PROTOCOL_" + PD->getName());
  2271. Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
  2272. // FIXME: Is this necessary? Why only for protocol?
  2273. Entry->setAlignment(4);
  2274. }
  2275. return Entry;
  2276. }
  2277. /*
  2278. struct _objc_protocol_extension {
  2279. uint32_t size;
  2280. struct objc_method_description_list *optional_instance_methods;
  2281. struct objc_method_description_list *optional_class_methods;
  2282. struct objc_property_list *instance_properties;
  2283. const char ** extendedMethodTypes;
  2284. };
  2285. */
  2286. llvm::Constant *
  2287. CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
  2288. ArrayRef<llvm::Constant*> OptInstanceMethods,
  2289. ArrayRef<llvm::Constant*> OptClassMethods,
  2290. ArrayRef<llvm::Constant*> MethodTypesExt) {
  2291. uint64_t Size =
  2292. CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
  2293. llvm::Constant *Values[] = {
  2294. llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
  2295. EmitMethodDescList("OBJC_PROTOCOL_INSTANCE_METHODS_OPT_" + PD->getName(),
  2296. "__OBJC,__cat_inst_meth,regular,no_dead_strip",
  2297. OptInstanceMethods),
  2298. EmitMethodDescList("OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
  2299. "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  2300. OptClassMethods),
  2301. EmitPropertyList("OBJC_$_PROP_PROTO_LIST_" + PD->getName(), nullptr, PD,
  2302. ObjCTypes),
  2303. EmitProtocolMethodTypes("OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
  2304. MethodTypesExt, ObjCTypes)};
  2305. // Return null if no extension bits are used.
  2306. if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
  2307. Values[3]->isNullValue() && Values[4]->isNullValue())
  2308. return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
  2309. llvm::Constant *Init =
  2310. llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
  2311. // No special section, but goes in llvm.used
  2312. return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(), Init,
  2313. StringRef(), 0, true);
  2314. }
  2315. /*
  2316. struct objc_protocol_list {
  2317. struct objc_protocol_list *next;
  2318. long count;
  2319. Protocol *list[];
  2320. };
  2321. */
  2322. llvm::Constant *
  2323. CGObjCMac::EmitProtocolList(Twine Name,
  2324. ObjCProtocolDecl::protocol_iterator begin,
  2325. ObjCProtocolDecl::protocol_iterator end) {
  2326. SmallVector<llvm::Constant *, 16> ProtocolRefs;
  2327. for (; begin != end; ++begin)
  2328. ProtocolRefs.push_back(GetProtocolRef(*begin));
  2329. // Just return null for empty protocol lists
  2330. if (ProtocolRefs.empty())
  2331. return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  2332. // This list is null terminated.
  2333. ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
  2334. llvm::Constant *Values[3];
  2335. // This field is only used by the runtime.
  2336. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  2337. Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
  2338. ProtocolRefs.size() - 1);
  2339. Values[2] =
  2340. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
  2341. ProtocolRefs.size()),
  2342. ProtocolRefs);
  2343. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2344. llvm::GlobalVariable *GV =
  2345. CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  2346. 4, false);
  2347. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
  2348. }
  2349. void CGObjCCommonMac::
  2350. PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
  2351. SmallVectorImpl<llvm::Constant *> &Properties,
  2352. const Decl *Container,
  2353. const ObjCProtocolDecl *Proto,
  2354. const ObjCCommonTypesHelper &ObjCTypes) {
  2355. for (const auto *P : Proto->protocols())
  2356. PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
  2357. for (const auto *PD : Proto->properties()) {
  2358. if (!PropertySet.insert(PD->getIdentifier()).second)
  2359. continue;
  2360. llvm::Constant *Prop[] = {
  2361. GetPropertyName(PD->getIdentifier()),
  2362. GetPropertyTypeString(PD, Container)
  2363. };
  2364. Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
  2365. }
  2366. }
  2367. /*
  2368. struct _objc_property {
  2369. const char * const name;
  2370. const char * const attributes;
  2371. };
  2372. struct _objc_property_list {
  2373. uint32_t entsize; // sizeof (struct _objc_property)
  2374. uint32_t prop_count;
  2375. struct _objc_property[prop_count];
  2376. };
  2377. */
  2378. llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
  2379. const Decl *Container,
  2380. const ObjCContainerDecl *OCD,
  2381. const ObjCCommonTypesHelper &ObjCTypes) {
  2382. SmallVector<llvm::Constant *, 16> Properties;
  2383. llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
  2384. for (const auto *PD : OCD->properties()) {
  2385. PropertySet.insert(PD->getIdentifier());
  2386. llvm::Constant *Prop[] = {
  2387. GetPropertyName(PD->getIdentifier()),
  2388. GetPropertyTypeString(PD, Container)
  2389. };
  2390. Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
  2391. Prop));
  2392. }
  2393. if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
  2394. for (const auto *P : OID->all_referenced_protocols())
  2395. PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
  2396. }
  2397. else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
  2398. for (const auto *P : CD->protocols())
  2399. PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
  2400. }
  2401. // Return null for empty list.
  2402. if (Properties.empty())
  2403. return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  2404. unsigned PropertySize =
  2405. CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
  2406. llvm::Constant *Values[3];
  2407. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
  2408. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
  2409. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
  2410. Properties.size());
  2411. Values[2] = llvm::ConstantArray::get(AT, Properties);
  2412. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2413. llvm::GlobalVariable *GV =
  2414. CreateMetadataVar(Name, Init,
  2415. (ObjCABI == 2) ? "__DATA, __objc_const" :
  2416. "__OBJC,__property,regular,no_dead_strip",
  2417. (ObjCABI == 2) ? 8 : 4,
  2418. true);
  2419. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
  2420. }
  2421. llvm::Constant *
  2422. CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
  2423. ArrayRef<llvm::Constant*> MethodTypes,
  2424. const ObjCCommonTypesHelper &ObjCTypes) {
  2425. // Return null for empty list.
  2426. if (MethodTypes.empty())
  2427. return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
  2428. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
  2429. MethodTypes.size());
  2430. llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
  2431. llvm::GlobalVariable *GV = CreateMetadataVar(
  2432. Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(),
  2433. (ObjCABI == 2) ? 8 : 4, true);
  2434. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
  2435. }
  2436. /*
  2437. struct objc_method_description_list {
  2438. int count;
  2439. struct objc_method_description list[];
  2440. };
  2441. */
  2442. llvm::Constant *
  2443. CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
  2444. llvm::Constant *Desc[] = {
  2445. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  2446. ObjCTypes.SelectorPtrTy),
  2447. GetMethodVarType(MD)
  2448. };
  2449. if (!Desc[1])
  2450. return nullptr;
  2451. return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
  2452. Desc);
  2453. }
  2454. llvm::Constant *
  2455. CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
  2456. ArrayRef<llvm::Constant*> Methods) {
  2457. // Return null for empty list.
  2458. if (Methods.empty())
  2459. return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
  2460. llvm::Constant *Values[2];
  2461. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
  2462. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
  2463. Methods.size());
  2464. Values[1] = llvm::ConstantArray::get(AT, Methods);
  2465. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2466. llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
  2467. return llvm::ConstantExpr::getBitCast(GV,
  2468. ObjCTypes.MethodDescriptionListPtrTy);
  2469. }
  2470. /*
  2471. struct _objc_category {
  2472. char *category_name;
  2473. char *class_name;
  2474. struct _objc_method_list *instance_methods;
  2475. struct _objc_method_list *class_methods;
  2476. struct _objc_protocol_list *protocols;
  2477. uint32_t size; // <rdar://4585769>
  2478. struct _objc_property_list *instance_properties;
  2479. };
  2480. */
  2481. void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  2482. unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
  2483. // FIXME: This is poor design, the OCD should have a pointer to the category
  2484. // decl. Additionally, note that Category can be null for the @implementation
  2485. // w/o an @interface case. Sema should just create one for us as it does for
  2486. // @implementation so everyone else can live life under a clear blue sky.
  2487. const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
  2488. const ObjCCategoryDecl *Category =
  2489. Interface->FindCategoryDeclaration(OCD->getIdentifier());
  2490. SmallString<256> ExtName;
  2491. llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
  2492. << OCD->getName();
  2493. SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
  2494. for (const auto *I : OCD->instance_methods())
  2495. // Instance methods should always be defined.
  2496. InstanceMethods.push_back(GetMethodConstant(I));
  2497. for (const auto *I : OCD->class_methods())
  2498. // Class methods should always be defined.
  2499. ClassMethods.push_back(GetMethodConstant(I));
  2500. llvm::Constant *Values[7];
  2501. Values[0] = GetClassName(OCD->getName());
  2502. Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString());
  2503. LazySymbols.insert(Interface->getIdentifier());
  2504. Values[2] = EmitMethodList("OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
  2505. "__OBJC,__cat_inst_meth,regular,no_dead_strip",
  2506. InstanceMethods);
  2507. Values[3] = EmitMethodList("OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
  2508. "__OBJC,__cat_cls_meth,regular,no_dead_strip",
  2509. ClassMethods);
  2510. if (Category) {
  2511. Values[4] =
  2512. EmitProtocolList("OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
  2513. Category->protocol_begin(), Category->protocol_end());
  2514. } else {
  2515. Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  2516. }
  2517. Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  2518. // If there is no category @interface then there can be no properties.
  2519. if (Category) {
  2520. Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
  2521. OCD, Category, ObjCTypes);
  2522. } else {
  2523. Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  2524. }
  2525. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
  2526. Values);
  2527. llvm::GlobalVariable *GV =
  2528. CreateMetadataVar("OBJC_CATEGORY_" + ExtName.str(), Init,
  2529. "__OBJC,__category,regular,no_dead_strip", 4, true);
  2530. DefinedCategories.push_back(GV);
  2531. DefinedCategoryNames.insert(ExtName.str());
  2532. // method definition entries must be clear for next implementation.
  2533. MethodDefinitions.clear();
  2534. }
  2535. enum FragileClassFlags {
  2536. FragileABI_Class_Factory = 0x00001,
  2537. FragileABI_Class_Meta = 0x00002,
  2538. FragileABI_Class_HasCXXStructors = 0x02000,
  2539. FragileABI_Class_Hidden = 0x20000
  2540. };
  2541. enum NonFragileClassFlags {
  2542. /// Is a meta-class.
  2543. NonFragileABI_Class_Meta = 0x00001,
  2544. /// Is a root class.
  2545. NonFragileABI_Class_Root = 0x00002,
  2546. /// Has a C++ constructor and destructor.
  2547. NonFragileABI_Class_HasCXXStructors = 0x00004,
  2548. /// Has hidden visibility.
  2549. NonFragileABI_Class_Hidden = 0x00010,
  2550. /// Has the exception attribute.
  2551. NonFragileABI_Class_Exception = 0x00020,
  2552. /// (Obsolete) ARC-specific: this class has a .release_ivars method
  2553. NonFragileABI_Class_HasIvarReleaser = 0x00040,
  2554. /// Class implementation was compiled under ARC.
  2555. NonFragileABI_Class_CompiledByARC = 0x00080,
  2556. /// Class has non-trivial destructors, but zero-initialization is okay.
  2557. NonFragileABI_Class_HasCXXDestructorOnly = 0x00100
  2558. };
  2559. /*
  2560. struct _objc_class {
  2561. Class isa;
  2562. Class super_class;
  2563. const char *name;
  2564. long version;
  2565. long info;
  2566. long instance_size;
  2567. struct _objc_ivar_list *ivars;
  2568. struct _objc_method_list *methods;
  2569. struct _objc_cache *cache;
  2570. struct _objc_protocol_list *protocols;
  2571. // Objective-C 1.0 extensions (<rdr://4585769>)
  2572. const char *ivar_layout;
  2573. struct _objc_class_ext *ext;
  2574. };
  2575. See EmitClassExtension();
  2576. */
  2577. void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
  2578. DefinedSymbols.insert(ID->getIdentifier());
  2579. std::string ClassName = ID->getNameAsString();
  2580. // FIXME: Gross
  2581. ObjCInterfaceDecl *Interface =
  2582. const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
  2583. llvm::Constant *Protocols =
  2584. EmitProtocolList("OBJC_CLASS_PROTOCOLS_" + ID->getName(),
  2585. Interface->all_referenced_protocol_begin(),
  2586. Interface->all_referenced_protocol_end());
  2587. unsigned Flags = FragileABI_Class_Factory;
  2588. if (ID->hasNonZeroConstructors() || ID->hasDestructors())
  2589. Flags |= FragileABI_Class_HasCXXStructors;
  2590. unsigned Size =
  2591. CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
  2592. // FIXME: Set CXX-structors flag.
  2593. if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
  2594. Flags |= FragileABI_Class_Hidden;
  2595. SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
  2596. for (const auto *I : ID->instance_methods())
  2597. // Instance methods should always be defined.
  2598. InstanceMethods.push_back(GetMethodConstant(I));
  2599. for (const auto *I : ID->class_methods())
  2600. // Class methods should always be defined.
  2601. ClassMethods.push_back(GetMethodConstant(I));
  2602. for (const auto *PID : ID->property_impls()) {
  2603. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2604. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2605. if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
  2606. if (llvm::Constant *C = GetMethodConstant(MD))
  2607. InstanceMethods.push_back(C);
  2608. if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
  2609. if (llvm::Constant *C = GetMethodConstant(MD))
  2610. InstanceMethods.push_back(C);
  2611. }
  2612. }
  2613. llvm::Constant *Values[12];
  2614. Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
  2615. if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
  2616. // Record a reference to the super class.
  2617. LazySymbols.insert(Super->getIdentifier());
  2618. Values[ 1] =
  2619. llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
  2620. ObjCTypes.ClassPtrTy);
  2621. } else {
  2622. Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
  2623. }
  2624. Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
  2625. // Version is always 0.
  2626. Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
  2627. Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
  2628. Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
  2629. Values[ 6] = EmitIvarList(ID, false);
  2630. Values[7] = EmitMethodList("OBJC_INSTANCE_METHODS_" + ID->getName(),
  2631. "__OBJC,__inst_meth,regular,no_dead_strip",
  2632. InstanceMethods);
  2633. // cache is always NULL.
  2634. Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
  2635. Values[ 9] = Protocols;
  2636. Values[10] = BuildIvarLayout(ID, true);
  2637. Values[11] = EmitClassExtension(ID);
  2638. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
  2639. Values);
  2640. std::string Name("OBJC_CLASS_");
  2641. Name += ClassName;
  2642. const char *Section = "__OBJC,__class,regular,no_dead_strip";
  2643. // Check for a forward reference.
  2644. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
  2645. if (GV) {
  2646. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2647. "Forward metaclass reference has incorrect type.");
  2648. GV->setInitializer(Init);
  2649. GV->setSection(Section);
  2650. GV->setAlignment(4);
  2651. CGM.addCompilerUsedGlobal(GV);
  2652. } else
  2653. GV = CreateMetadataVar(Name, Init, Section, 4, true);
  2654. DefinedClasses.push_back(GV);
  2655. ImplementedClasses.push_back(Interface);
  2656. // method definition entries must be clear for next implementation.
  2657. MethodDefinitions.clear();
  2658. }
  2659. llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
  2660. llvm::Constant *Protocols,
  2661. ArrayRef<llvm::Constant*> Methods) {
  2662. unsigned Flags = FragileABI_Class_Meta;
  2663. unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
  2664. if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
  2665. Flags |= FragileABI_Class_Hidden;
  2666. llvm::Constant *Values[12];
  2667. // The isa for the metaclass is the root of the hierarchy.
  2668. const ObjCInterfaceDecl *Root = ID->getClassInterface();
  2669. while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
  2670. Root = Super;
  2671. Values[ 0] =
  2672. llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
  2673. ObjCTypes.ClassPtrTy);
  2674. // The super class for the metaclass is emitted as the name of the
  2675. // super class. The runtime fixes this up to point to the
  2676. // *metaclass* for the super class.
  2677. if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
  2678. Values[ 1] =
  2679. llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
  2680. ObjCTypes.ClassPtrTy);
  2681. } else {
  2682. Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
  2683. }
  2684. Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
  2685. // Version is always 0.
  2686. Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
  2687. Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
  2688. Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
  2689. Values[ 6] = EmitIvarList(ID, true);
  2690. Values[7] =
  2691. EmitMethodList("OBJC_CLASS_METHODS_" + ID->getNameAsString(),
  2692. "__OBJC,__cls_meth,regular,no_dead_strip", Methods);
  2693. // cache is always NULL.
  2694. Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
  2695. Values[ 9] = Protocols;
  2696. // ivar_layout for metaclass is always NULL.
  2697. Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  2698. // The class extension is always unused for metaclasses.
  2699. Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
  2700. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
  2701. Values);
  2702. std::string Name("OBJC_METACLASS_");
  2703. Name += ID->getName();
  2704. // Check for a forward reference.
  2705. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
  2706. if (GV) {
  2707. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2708. "Forward metaclass reference has incorrect type.");
  2709. GV->setInitializer(Init);
  2710. } else {
  2711. GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
  2712. llvm::GlobalValue::PrivateLinkage,
  2713. Init, Name);
  2714. }
  2715. GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
  2716. GV->setAlignment(4);
  2717. CGM.addCompilerUsedGlobal(GV);
  2718. return GV;
  2719. }
  2720. llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
  2721. std::string Name = "OBJC_METACLASS_" + ID->getNameAsString();
  2722. // FIXME: Should we look these up somewhere other than the module. Its a bit
  2723. // silly since we only generate these while processing an implementation, so
  2724. // exactly one pointer would work if know when we entered/exitted an
  2725. // implementation block.
  2726. // Check for an existing forward reference.
  2727. // Previously, metaclass with internal linkage may have been defined.
  2728. // pass 'true' as 2nd argument so it is returned.
  2729. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
  2730. if (!GV)
  2731. GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
  2732. llvm::GlobalValue::PrivateLinkage, nullptr,
  2733. Name);
  2734. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2735. "Forward metaclass reference has incorrect type.");
  2736. return GV;
  2737. }
  2738. llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
  2739. std::string Name = "OBJC_CLASS_" + ID->getNameAsString();
  2740. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
  2741. if (!GV)
  2742. GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
  2743. llvm::GlobalValue::PrivateLinkage, nullptr,
  2744. Name);
  2745. assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
  2746. "Forward class metadata reference has incorrect type.");
  2747. return GV;
  2748. }
  2749. /*
  2750. struct objc_class_ext {
  2751. uint32_t size;
  2752. const char *weak_ivar_layout;
  2753. struct _objc_property_list *properties;
  2754. };
  2755. */
  2756. llvm::Constant *
  2757. CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
  2758. uint64_t Size =
  2759. CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
  2760. llvm::Constant *Values[3];
  2761. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  2762. Values[1] = BuildIvarLayout(ID, false);
  2763. Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
  2764. ID, ID->getClassInterface(), ObjCTypes);
  2765. // Return null if no extension bits are used.
  2766. if (Values[1]->isNullValue() && Values[2]->isNullValue())
  2767. return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
  2768. llvm::Constant *Init =
  2769. llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
  2770. return CreateMetadataVar("OBJC_CLASSEXT_" + ID->getName(), Init,
  2771. "__OBJC,__class_ext,regular,no_dead_strip", 4, true);
  2772. }
  2773. /*
  2774. struct objc_ivar {
  2775. char *ivar_name;
  2776. char *ivar_type;
  2777. int ivar_offset;
  2778. };
  2779. struct objc_ivar_list {
  2780. int ivar_count;
  2781. struct objc_ivar list[count];
  2782. };
  2783. */
  2784. llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
  2785. bool ForClass) {
  2786. std::vector<llvm::Constant*> Ivars;
  2787. // When emitting the root class GCC emits ivar entries for the
  2788. // actual class structure. It is not clear if we need to follow this
  2789. // behavior; for now lets try and get away with not doing it. If so,
  2790. // the cleanest solution would be to make up an ObjCInterfaceDecl
  2791. // for the class.
  2792. if (ForClass)
  2793. return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
  2794. const ObjCInterfaceDecl *OID = ID->getClassInterface();
  2795. for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
  2796. IVD; IVD = IVD->getNextIvar()) {
  2797. // Ignore unnamed bit-fields.
  2798. if (!IVD->getDeclName())
  2799. continue;
  2800. llvm::Constant *Ivar[] = {
  2801. GetMethodVarName(IVD->getIdentifier()),
  2802. GetMethodVarType(IVD),
  2803. llvm::ConstantInt::get(ObjCTypes.IntTy,
  2804. ComputeIvarBaseOffset(CGM, OID, IVD))
  2805. };
  2806. Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
  2807. }
  2808. // Return null for empty list.
  2809. if (Ivars.empty())
  2810. return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
  2811. llvm::Constant *Values[2];
  2812. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
  2813. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
  2814. Ivars.size());
  2815. Values[1] = llvm::ConstantArray::get(AT, Ivars);
  2816. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2817. llvm::GlobalVariable *GV;
  2818. if (ForClass)
  2819. GV =
  2820. CreateMetadataVar("OBJC_CLASS_VARIABLES_" + ID->getName(), Init,
  2821. "__OBJC,__class_vars,regular,no_dead_strip", 4, true);
  2822. else
  2823. GV = CreateMetadataVar("OBJC_INSTANCE_VARIABLES_" + ID->getName(), Init,
  2824. "__OBJC,__instance_vars,regular,no_dead_strip", 4,
  2825. true);
  2826. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
  2827. }
  2828. /*
  2829. struct objc_method {
  2830. SEL method_name;
  2831. char *method_types;
  2832. void *method;
  2833. };
  2834. struct objc_method_list {
  2835. struct objc_method_list *obsolete;
  2836. int count;
  2837. struct objc_method methods_list[count];
  2838. };
  2839. */
  2840. /// GetMethodConstant - Return a struct objc_method constant for the
  2841. /// given method if it has been defined. The result is null if the
  2842. /// method has not been defined. The return value has type MethodPtrTy.
  2843. llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
  2844. llvm::Function *Fn = GetMethodDefinition(MD);
  2845. if (!Fn)
  2846. return nullptr;
  2847. llvm::Constant *Method[] = {
  2848. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  2849. ObjCTypes.SelectorPtrTy),
  2850. GetMethodVarType(MD),
  2851. llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
  2852. };
  2853. return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
  2854. }
  2855. llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
  2856. const char *Section,
  2857. ArrayRef<llvm::Constant*> Methods) {
  2858. // Return null for empty list.
  2859. if (Methods.empty())
  2860. return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
  2861. llvm::Constant *Values[3];
  2862. Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  2863. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
  2864. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
  2865. Methods.size());
  2866. Values[2] = llvm::ConstantArray::get(AT, Methods);
  2867. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  2868. llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
  2869. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
  2870. }
  2871. llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
  2872. const ObjCContainerDecl *CD) {
  2873. SmallString<256> Name;
  2874. GetNameForMethod(OMD, CD, Name);
  2875. CodeGenTypes &Types = CGM.getTypes();
  2876. llvm::FunctionType *MethodTy =
  2877. Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
  2878. llvm::Function *Method =
  2879. llvm::Function::Create(MethodTy,
  2880. llvm::GlobalValue::InternalLinkage,
  2881. Name.str(),
  2882. &CGM.getModule());
  2883. MethodDefinitions.insert(std::make_pair(OMD, Method));
  2884. return Method;
  2885. }
  2886. llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
  2887. llvm::Constant *Init,
  2888. StringRef Section,
  2889. unsigned Align,
  2890. bool AddToUsed) {
  2891. llvm::Type *Ty = Init->getType();
  2892. llvm::GlobalVariable *GV =
  2893. new llvm::GlobalVariable(CGM.getModule(), Ty, false,
  2894. llvm::GlobalValue::PrivateLinkage, Init, Name);
  2895. if (!Section.empty())
  2896. GV->setSection(Section);
  2897. if (Align)
  2898. GV->setAlignment(Align);
  2899. if (AddToUsed)
  2900. CGM.addCompilerUsedGlobal(GV);
  2901. return GV;
  2902. }
  2903. llvm::Function *CGObjCMac::ModuleInitFunction() {
  2904. // Abuse this interface function as a place to finalize.
  2905. FinishModule();
  2906. return nullptr;
  2907. }
  2908. llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
  2909. return ObjCTypes.getGetPropertyFn();
  2910. }
  2911. llvm::Constant *CGObjCMac::GetPropertySetFunction() {
  2912. return ObjCTypes.getSetPropertyFn();
  2913. }
  2914. llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
  2915. bool copy) {
  2916. return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
  2917. }
  2918. llvm::Constant *CGObjCMac::GetGetStructFunction() {
  2919. return ObjCTypes.getCopyStructFn();
  2920. }
  2921. llvm::Constant *CGObjCMac::GetSetStructFunction() {
  2922. return ObjCTypes.getCopyStructFn();
  2923. }
  2924. llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
  2925. return ObjCTypes.getCppAtomicObjectFunction();
  2926. }
  2927. llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
  2928. return ObjCTypes.getCppAtomicObjectFunction();
  2929. }
  2930. llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
  2931. return ObjCTypes.getEnumerationMutationFn();
  2932. }
  2933. void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
  2934. return EmitTryOrSynchronizedStmt(CGF, S);
  2935. }
  2936. void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
  2937. const ObjCAtSynchronizedStmt &S) {
  2938. return EmitTryOrSynchronizedStmt(CGF, S);
  2939. }
  2940. namespace {
  2941. struct PerformFragileFinally : EHScopeStack::Cleanup {
  2942. const Stmt &S;
  2943. llvm::Value *SyncArgSlot;
  2944. llvm::Value *CallTryExitVar;
  2945. llvm::Value *ExceptionData;
  2946. ObjCTypesHelper &ObjCTypes;
  2947. PerformFragileFinally(const Stmt *S,
  2948. llvm::Value *SyncArgSlot,
  2949. llvm::Value *CallTryExitVar,
  2950. llvm::Value *ExceptionData,
  2951. ObjCTypesHelper *ObjCTypes)
  2952. : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
  2953. ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
  2954. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2955. // Check whether we need to call objc_exception_try_exit.
  2956. // In optimized code, this branch will always be folded.
  2957. llvm::BasicBlock *FinallyCallExit =
  2958. CGF.createBasicBlock("finally.call_exit");
  2959. llvm::BasicBlock *FinallyNoCallExit =
  2960. CGF.createBasicBlock("finally.no_call_exit");
  2961. CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
  2962. FinallyCallExit, FinallyNoCallExit);
  2963. CGF.EmitBlock(FinallyCallExit);
  2964. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
  2965. ExceptionData);
  2966. CGF.EmitBlock(FinallyNoCallExit);
  2967. if (isa<ObjCAtTryStmt>(S)) {
  2968. if (const ObjCAtFinallyStmt* FinallyStmt =
  2969. cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
  2970. // Don't try to do the @finally if this is an EH cleanup.
  2971. if (flags.isForEHCleanup()) return;
  2972. // Save the current cleanup destination in case there's
  2973. // control flow inside the finally statement.
  2974. llvm::Value *CurCleanupDest =
  2975. CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
  2976. CGF.EmitStmt(FinallyStmt->getFinallyBody());
  2977. if (CGF.HaveInsertPoint()) {
  2978. CGF.Builder.CreateStore(CurCleanupDest,
  2979. CGF.getNormalCleanupDestSlot());
  2980. } else {
  2981. // Currently, the end of the cleanup must always exist.
  2982. CGF.EnsureInsertPoint();
  2983. }
  2984. }
  2985. } else {
  2986. // Emit objc_sync_exit(expr); as finally's sole statement for
  2987. // @synchronized.
  2988. llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
  2989. CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
  2990. }
  2991. }
  2992. };
  2993. class FragileHazards {
  2994. CodeGenFunction &CGF;
  2995. SmallVector<llvm::Value*, 20> Locals;
  2996. llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
  2997. llvm::InlineAsm *ReadHazard;
  2998. llvm::InlineAsm *WriteHazard;
  2999. llvm::FunctionType *GetAsmFnType();
  3000. void collectLocals();
  3001. void emitReadHazard(CGBuilderTy &Builder);
  3002. public:
  3003. FragileHazards(CodeGenFunction &CGF);
  3004. void emitWriteHazard();
  3005. void emitHazardsInNewBlocks();
  3006. };
  3007. }
  3008. /// Create the fragile-ABI read and write hazards based on the current
  3009. /// state of the function, which is presumed to be immediately prior
  3010. /// to a @try block. These hazards are used to maintain correct
  3011. /// semantics in the face of optimization and the fragile ABI's
  3012. /// cavalier use of setjmp/longjmp.
  3013. FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
  3014. collectLocals();
  3015. if (Locals.empty()) return;
  3016. // Collect all the blocks in the function.
  3017. for (llvm::Function::iterator
  3018. I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
  3019. BlocksBeforeTry.insert(&*I);
  3020. llvm::FunctionType *AsmFnTy = GetAsmFnType();
  3021. // Create a read hazard for the allocas. This inhibits dead-store
  3022. // optimizations and forces the values to memory. This hazard is
  3023. // inserted before any 'throwing' calls in the protected scope to
  3024. // reflect the possibility that the variables might be read from the
  3025. // catch block if the call throws.
  3026. {
  3027. std::string Constraint;
  3028. for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
  3029. if (I) Constraint += ',';
  3030. Constraint += "*m";
  3031. }
  3032. ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
  3033. }
  3034. // Create a write hazard for the allocas. This inhibits folding
  3035. // loads across the hazard. This hazard is inserted at the
  3036. // beginning of the catch path to reflect the possibility that the
  3037. // variables might have been written within the protected scope.
  3038. {
  3039. std::string Constraint;
  3040. for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
  3041. if (I) Constraint += ',';
  3042. Constraint += "=*m";
  3043. }
  3044. WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
  3045. }
  3046. }
  3047. /// Emit a write hazard at the current location.
  3048. void FragileHazards::emitWriteHazard() {
  3049. if (Locals.empty()) return;
  3050. CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
  3051. }
  3052. void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
  3053. assert(!Locals.empty());
  3054. llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
  3055. call->setDoesNotThrow();
  3056. call->setCallingConv(CGF.getRuntimeCC());
  3057. }
  3058. /// Emit read hazards in all the protected blocks, i.e. all the blocks
  3059. /// which have been inserted since the beginning of the try.
  3060. void FragileHazards::emitHazardsInNewBlocks() {
  3061. if (Locals.empty()) return;
  3062. CGBuilderTy Builder(CGF.getLLVMContext());
  3063. // Iterate through all blocks, skipping those prior to the try.
  3064. for (llvm::Function::iterator
  3065. FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
  3066. llvm::BasicBlock &BB = *FI;
  3067. if (BlocksBeforeTry.count(&BB)) continue;
  3068. // Walk through all the calls in the block.
  3069. for (llvm::BasicBlock::iterator
  3070. BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
  3071. llvm::Instruction &I = *BI;
  3072. // Ignore instructions that aren't non-intrinsic calls.
  3073. // These are the only calls that can possibly call longjmp.
  3074. if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
  3075. if (isa<llvm::IntrinsicInst>(I))
  3076. continue;
  3077. // Ignore call sites marked nounwind. This may be questionable,
  3078. // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
  3079. llvm::CallSite CS(&I);
  3080. if (CS.doesNotThrow()) continue;
  3081. // Insert a read hazard before the call. This will ensure that
  3082. // any writes to the locals are performed before making the
  3083. // call. If the call throws, then this is sufficient to
  3084. // guarantee correctness as long as it doesn't also write to any
  3085. // locals.
  3086. Builder.SetInsertPoint(&BB, BI);
  3087. emitReadHazard(Builder);
  3088. }
  3089. }
  3090. }
  3091. static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
  3092. if (V) S.insert(V);
  3093. }
  3094. void FragileHazards::collectLocals() {
  3095. // Compute a set of allocas to ignore.
  3096. llvm::DenseSet<llvm::Value*> AllocasToIgnore;
  3097. addIfPresent(AllocasToIgnore, CGF.ReturnValue);
  3098. addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
  3099. // Collect all the allocas currently in the function. This is
  3100. // probably way too aggressive.
  3101. llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
  3102. for (llvm::BasicBlock::iterator
  3103. I = Entry.begin(), E = Entry.end(); I != E; ++I)
  3104. if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
  3105. Locals.push_back(&*I);
  3106. }
  3107. llvm::FunctionType *FragileHazards::GetAsmFnType() {
  3108. SmallVector<llvm::Type *, 16> tys(Locals.size());
  3109. for (unsigned i = 0, e = Locals.size(); i != e; ++i)
  3110. tys[i] = Locals[i]->getType();
  3111. return llvm::FunctionType::get(CGF.VoidTy, tys, false);
  3112. }
  3113. /*
  3114. Objective-C setjmp-longjmp (sjlj) Exception Handling
  3115. --
  3116. A catch buffer is a setjmp buffer plus:
  3117. - a pointer to the exception that was caught
  3118. - a pointer to the previous exception data buffer
  3119. - two pointers of reserved storage
  3120. Therefore catch buffers form a stack, with a pointer to the top
  3121. of the stack kept in thread-local storage.
  3122. objc_exception_try_enter pushes a catch buffer onto the EH stack.
  3123. objc_exception_try_exit pops the given catch buffer, which is
  3124. required to be the top of the EH stack.
  3125. objc_exception_throw pops the top of the EH stack, writes the
  3126. thrown exception into the appropriate field, and longjmps
  3127. to the setjmp buffer. It crashes the process (with a printf
  3128. and an abort()) if there are no catch buffers on the stack.
  3129. objc_exception_extract just reads the exception pointer out of the
  3130. catch buffer.
  3131. There's no reason an implementation couldn't use a light-weight
  3132. setjmp here --- something like __builtin_setjmp, but API-compatible
  3133. with the heavyweight setjmp. This will be more important if we ever
  3134. want to implement correct ObjC/C++ exception interactions for the
  3135. fragile ABI.
  3136. Note that for this use of setjmp/longjmp to be correct, we may need
  3137. to mark some local variables volatile: if a non-volatile local
  3138. variable is modified between the setjmp and the longjmp, it has
  3139. indeterminate value. For the purposes of LLVM IR, it may be
  3140. sufficient to make loads and stores within the @try (to variables
  3141. declared outside the @try) volatile. This is necessary for
  3142. optimized correctness, but is not currently being done; this is
  3143. being tracked as rdar://problem/8160285
  3144. The basic framework for a @try-catch-finally is as follows:
  3145. {
  3146. objc_exception_data d;
  3147. id _rethrow = null;
  3148. bool _call_try_exit = true;
  3149. objc_exception_try_enter(&d);
  3150. if (!setjmp(d.jmp_buf)) {
  3151. ... try body ...
  3152. } else {
  3153. // exception path
  3154. id _caught = objc_exception_extract(&d);
  3155. // enter new try scope for handlers
  3156. if (!setjmp(d.jmp_buf)) {
  3157. ... match exception and execute catch blocks ...
  3158. // fell off end, rethrow.
  3159. _rethrow = _caught;
  3160. ... jump-through-finally to finally_rethrow ...
  3161. } else {
  3162. // exception in catch block
  3163. _rethrow = objc_exception_extract(&d);
  3164. _call_try_exit = false;
  3165. ... jump-through-finally to finally_rethrow ...
  3166. }
  3167. }
  3168. ... jump-through-finally to finally_end ...
  3169. finally:
  3170. if (_call_try_exit)
  3171. objc_exception_try_exit(&d);
  3172. ... finally block ....
  3173. ... dispatch to finally destination ...
  3174. finally_rethrow:
  3175. objc_exception_throw(_rethrow);
  3176. finally_end:
  3177. }
  3178. This framework differs slightly from the one gcc uses, in that gcc
  3179. uses _rethrow to determine if objc_exception_try_exit should be called
  3180. and if the object should be rethrown. This breaks in the face of
  3181. throwing nil and introduces unnecessary branches.
  3182. We specialize this framework for a few particular circumstances:
  3183. - If there are no catch blocks, then we avoid emitting the second
  3184. exception handling context.
  3185. - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
  3186. e)) we avoid emitting the code to rethrow an uncaught exception.
  3187. - FIXME: If there is no @finally block we can do a few more
  3188. simplifications.
  3189. Rethrows and Jumps-Through-Finally
  3190. --
  3191. '@throw;' is supported by pushing the currently-caught exception
  3192. onto ObjCEHStack while the @catch blocks are emitted.
  3193. Branches through the @finally block are handled with an ordinary
  3194. normal cleanup. We do not register an EH cleanup; fragile-ABI ObjC
  3195. exceptions are not compatible with C++ exceptions, and this is
  3196. hardly the only place where this will go wrong.
  3197. @synchronized(expr) { stmt; } is emitted as if it were:
  3198. id synch_value = expr;
  3199. objc_sync_enter(synch_value);
  3200. @try { stmt; } @finally { objc_sync_exit(synch_value); }
  3201. */
  3202. void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  3203. const Stmt &S) {
  3204. bool isTry = isa<ObjCAtTryStmt>(S);
  3205. // A destination for the fall-through edges of the catch handlers to
  3206. // jump to.
  3207. CodeGenFunction::JumpDest FinallyEnd =
  3208. CGF.getJumpDestInCurrentScope("finally.end");
  3209. // A destination for the rethrow edge of the catch handlers to jump
  3210. // to.
  3211. CodeGenFunction::JumpDest FinallyRethrow =
  3212. CGF.getJumpDestInCurrentScope("finally.rethrow");
  3213. // For @synchronized, call objc_sync_enter(sync.expr). The
  3214. // evaluation of the expression must occur before we enter the
  3215. // @synchronized. We can't avoid a temp here because we need the
  3216. // value to be preserved. If the backend ever does liveness
  3217. // correctly after setjmp, this will be unnecessary.
  3218. llvm::Value *SyncArgSlot = nullptr;
  3219. if (!isTry) {
  3220. llvm::Value *SyncArg =
  3221. CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
  3222. SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
  3223. CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
  3224. SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
  3225. CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
  3226. }
  3227. // Allocate memory for the setjmp buffer. This needs to be kept
  3228. // live throughout the try and catch blocks.
  3229. llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
  3230. "exceptiondata.ptr");
  3231. // Create the fragile hazards. Note that this will not capture any
  3232. // of the allocas required for exception processing, but will
  3233. // capture the current basic block (which extends all the way to the
  3234. // setjmp call) as "before the @try".
  3235. FragileHazards Hazards(CGF);
  3236. // Create a flag indicating whether the cleanup needs to call
  3237. // objc_exception_try_exit. This is true except when
  3238. // - no catches match and we're branching through the cleanup
  3239. // just to rethrow the exception, or
  3240. // - a catch matched and we're falling out of the catch handler.
  3241. // The setjmp-safety rule here is that we should always store to this
  3242. // variable in a place that dominates the branch through the cleanup
  3243. // without passing through any setjmps.
  3244. llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
  3245. "_call_try_exit");
  3246. // A slot containing the exception to rethrow. Only needed when we
  3247. // have both a @catch and a @finally.
  3248. llvm::Value *PropagatingExnVar = nullptr;
  3249. // Push a normal cleanup to leave the try scope.
  3250. CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
  3251. SyncArgSlot,
  3252. CallTryExitVar,
  3253. ExceptionData,
  3254. &ObjCTypes);
  3255. // Enter a try block:
  3256. // - Call objc_exception_try_enter to push ExceptionData on top of
  3257. // the EH stack.
  3258. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
  3259. ExceptionData);
  3260. // - Call setjmp on the exception data buffer.
  3261. llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
  3262. llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
  3263. llvm::Value *SetJmpBuffer = CGF.Builder.CreateGEP(
  3264. ObjCTypes.ExceptionDataTy, ExceptionData, GEPIndexes, "setjmp_buffer");
  3265. llvm::CallInst *SetJmpResult = CGF.EmitNounwindRuntimeCall(
  3266. ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
  3267. SetJmpResult->setCanReturnTwice();
  3268. // If setjmp returned 0, enter the protected block; otherwise,
  3269. // branch to the handler.
  3270. llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
  3271. llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
  3272. llvm::Value *DidCatch =
  3273. CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
  3274. CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
  3275. // Emit the protected block.
  3276. CGF.EmitBlock(TryBlock);
  3277. CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
  3278. CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
  3279. : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
  3280. CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
  3281. // Emit the exception handler block.
  3282. CGF.EmitBlock(TryHandler);
  3283. // Don't optimize loads of the in-scope locals across this point.
  3284. Hazards.emitWriteHazard();
  3285. // For a @synchronized (or a @try with no catches), just branch
  3286. // through the cleanup to the rethrow block.
  3287. if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
  3288. // Tell the cleanup not to re-pop the exit.
  3289. CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
  3290. CGF.EmitBranchThroughCleanup(FinallyRethrow);
  3291. // Otherwise, we have to match against the caught exceptions.
  3292. } else {
  3293. // Retrieve the exception object. We may emit multiple blocks but
  3294. // nothing can cross this so the value is already in SSA form.
  3295. llvm::CallInst *Caught =
  3296. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
  3297. ExceptionData, "caught");
  3298. // Push the exception to rethrow onto the EH value stack for the
  3299. // benefit of any @throws in the handlers.
  3300. CGF.ObjCEHValueStack.push_back(Caught);
  3301. const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
  3302. bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
  3303. llvm::BasicBlock *CatchBlock = nullptr;
  3304. llvm::BasicBlock *CatchHandler = nullptr;
  3305. if (HasFinally) {
  3306. // Save the currently-propagating exception before
  3307. // objc_exception_try_enter clears the exception slot.
  3308. PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
  3309. "propagating_exception");
  3310. CGF.Builder.CreateStore(Caught, PropagatingExnVar);
  3311. // Enter a new exception try block (in case a @catch block
  3312. // throws an exception).
  3313. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
  3314. ExceptionData);
  3315. llvm::CallInst *SetJmpResult =
  3316. CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
  3317. SetJmpBuffer, "setjmp.result");
  3318. SetJmpResult->setCanReturnTwice();
  3319. llvm::Value *Threw =
  3320. CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
  3321. CatchBlock = CGF.createBasicBlock("catch");
  3322. CatchHandler = CGF.createBasicBlock("catch_for_catch");
  3323. CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
  3324. CGF.EmitBlock(CatchBlock);
  3325. }
  3326. CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
  3327. // Handle catch list. As a special case we check if everything is
  3328. // matched and avoid generating code for falling off the end if
  3329. // so.
  3330. bool AllMatched = false;
  3331. for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
  3332. const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
  3333. const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
  3334. const ObjCObjectPointerType *OPT = nullptr;
  3335. // catch(...) always matches.
  3336. if (!CatchParam) {
  3337. AllMatched = true;
  3338. } else {
  3339. OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
  3340. // catch(id e) always matches under this ABI, since only
  3341. // ObjC exceptions end up here in the first place.
  3342. // FIXME: For the time being we also match id<X>; this should
  3343. // be rejected by Sema instead.
  3344. if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
  3345. AllMatched = true;
  3346. }
  3347. // If this is a catch-all, we don't need to test anything.
  3348. if (AllMatched) {
  3349. CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
  3350. if (CatchParam) {
  3351. CGF.EmitAutoVarDecl(*CatchParam);
  3352. assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
  3353. // These types work out because ConvertType(id) == i8*.
  3354. CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
  3355. }
  3356. CGF.EmitStmt(CatchStmt->getCatchBody());
  3357. // The scope of the catch variable ends right here.
  3358. CatchVarCleanups.ForceCleanup();
  3359. CGF.EmitBranchThroughCleanup(FinallyEnd);
  3360. break;
  3361. }
  3362. assert(OPT && "Unexpected non-object pointer type in @catch");
  3363. const ObjCObjectType *ObjTy = OPT->getObjectType();
  3364. // FIXME: @catch (Class c) ?
  3365. ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
  3366. assert(IDecl && "Catch parameter must have Objective-C type!");
  3367. // Check if the @catch block matches the exception object.
  3368. llvm::Value *Class = EmitClassRef(CGF, IDecl);
  3369. llvm::Value *matchArgs[] = { Class, Caught };
  3370. llvm::CallInst *Match =
  3371. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
  3372. matchArgs, "match");
  3373. llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
  3374. llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
  3375. CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
  3376. MatchedBlock, NextCatchBlock);
  3377. // Emit the @catch block.
  3378. CGF.EmitBlock(MatchedBlock);
  3379. // Collect any cleanups for the catch variable. The scope lasts until
  3380. // the end of the catch body.
  3381. CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
  3382. CGF.EmitAutoVarDecl(*CatchParam);
  3383. assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
  3384. // Initialize the catch variable.
  3385. llvm::Value *Tmp =
  3386. CGF.Builder.CreateBitCast(Caught,
  3387. CGF.ConvertType(CatchParam->getType()));
  3388. CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
  3389. CGF.EmitStmt(CatchStmt->getCatchBody());
  3390. // We're done with the catch variable.
  3391. CatchVarCleanups.ForceCleanup();
  3392. CGF.EmitBranchThroughCleanup(FinallyEnd);
  3393. CGF.EmitBlock(NextCatchBlock);
  3394. }
  3395. CGF.ObjCEHValueStack.pop_back();
  3396. // If nothing wanted anything to do with the caught exception,
  3397. // kill the extract call.
  3398. if (Caught->use_empty())
  3399. Caught->eraseFromParent();
  3400. if (!AllMatched)
  3401. CGF.EmitBranchThroughCleanup(FinallyRethrow);
  3402. if (HasFinally) {
  3403. // Emit the exception handler for the @catch blocks.
  3404. CGF.EmitBlock(CatchHandler);
  3405. // In theory we might now need a write hazard, but actually it's
  3406. // unnecessary because there's no local-accessing code between
  3407. // the try's write hazard and here.
  3408. //Hazards.emitWriteHazard();
  3409. // Extract the new exception and save it to the
  3410. // propagating-exception slot.
  3411. assert(PropagatingExnVar);
  3412. llvm::CallInst *NewCaught =
  3413. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
  3414. ExceptionData, "caught");
  3415. CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
  3416. // Don't pop the catch handler; the throw already did.
  3417. CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
  3418. CGF.EmitBranchThroughCleanup(FinallyRethrow);
  3419. }
  3420. }
  3421. // Insert read hazards as required in the new blocks.
  3422. Hazards.emitHazardsInNewBlocks();
  3423. // Pop the cleanup.
  3424. CGF.Builder.restoreIP(TryFallthroughIP);
  3425. if (CGF.HaveInsertPoint())
  3426. CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
  3427. CGF.PopCleanupBlock();
  3428. CGF.EmitBlock(FinallyEnd.getBlock(), true);
  3429. // Emit the rethrow block.
  3430. CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
  3431. CGF.EmitBlock(FinallyRethrow.getBlock(), true);
  3432. if (CGF.HaveInsertPoint()) {
  3433. // If we have a propagating-exception variable, check it.
  3434. llvm::Value *PropagatingExn;
  3435. if (PropagatingExnVar) {
  3436. PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
  3437. // Otherwise, just look in the buffer for the exception to throw.
  3438. } else {
  3439. llvm::CallInst *Caught =
  3440. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
  3441. ExceptionData);
  3442. PropagatingExn = Caught;
  3443. }
  3444. CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
  3445. PropagatingExn);
  3446. CGF.Builder.CreateUnreachable();
  3447. }
  3448. CGF.Builder.restoreIP(SavedIP);
  3449. }
  3450. void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
  3451. const ObjCAtThrowStmt &S,
  3452. bool ClearInsertionPoint) {
  3453. llvm::Value *ExceptionAsObject;
  3454. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  3455. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  3456. ExceptionAsObject =
  3457. CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
  3458. } else {
  3459. assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
  3460. "Unexpected rethrow outside @catch block.");
  3461. ExceptionAsObject = CGF.ObjCEHValueStack.back();
  3462. }
  3463. CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
  3464. ->setDoesNotReturn();
  3465. CGF.Builder.CreateUnreachable();
  3466. // Clear the insertion point to indicate we are in unreachable code.
  3467. if (ClearInsertionPoint)
  3468. CGF.Builder.ClearInsertionPoint();
  3469. }
  3470. /// EmitObjCWeakRead - Code gen for loading value of a __weak
  3471. /// object: objc_read_weak (id *src)
  3472. ///
  3473. llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
  3474. llvm::Value *AddrWeakObj) {
  3475. llvm::Type* DestTy =
  3476. cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
  3477. AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
  3478. ObjCTypes.PtrObjectPtrTy);
  3479. llvm::Value *read_weak =
  3480. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
  3481. AddrWeakObj, "weakread");
  3482. read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
  3483. return read_weak;
  3484. }
  3485. /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
  3486. /// objc_assign_weak (id src, id *dst)
  3487. ///
  3488. void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  3489. llvm::Value *src, llvm::Value *dst) {
  3490. llvm::Type * SrcTy = src->getType();
  3491. if (!isa<llvm::PointerType>(SrcTy)) {
  3492. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3493. assert(Size <= 8 && "does not support size > 8");
  3494. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  3495. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  3496. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  3497. }
  3498. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  3499. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  3500. llvm::Value *args[] = { src, dst };
  3501. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
  3502. args, "weakassign");
  3503. return;
  3504. }
  3505. /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
  3506. /// objc_assign_global (id src, id *dst)
  3507. ///
  3508. void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  3509. llvm::Value *src, llvm::Value *dst,
  3510. bool threadlocal) {
  3511. llvm::Type * SrcTy = src->getType();
  3512. if (!isa<llvm::PointerType>(SrcTy)) {
  3513. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3514. assert(Size <= 8 && "does not support size > 8");
  3515. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  3516. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  3517. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  3518. }
  3519. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  3520. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  3521. llvm::Value *args[] = { src, dst };
  3522. if (!threadlocal)
  3523. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
  3524. args, "globalassign");
  3525. else
  3526. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
  3527. args, "threadlocalassign");
  3528. return;
  3529. }
  3530. /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
  3531. /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
  3532. ///
  3533. void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  3534. llvm::Value *src, llvm::Value *dst,
  3535. llvm::Value *ivarOffset) {
  3536. assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
  3537. llvm::Type * SrcTy = src->getType();
  3538. if (!isa<llvm::PointerType>(SrcTy)) {
  3539. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3540. assert(Size <= 8 && "does not support size > 8");
  3541. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  3542. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  3543. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  3544. }
  3545. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  3546. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  3547. llvm::Value *args[] = { src, dst, ivarOffset };
  3548. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
  3549. return;
  3550. }
  3551. /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
  3552. /// objc_assign_strongCast (id src, id *dst)
  3553. ///
  3554. void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
  3555. llvm::Value *src, llvm::Value *dst) {
  3556. llvm::Type * SrcTy = src->getType();
  3557. if (!isa<llvm::PointerType>(SrcTy)) {
  3558. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  3559. assert(Size <= 8 && "does not support size > 8");
  3560. src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  3561. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
  3562. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  3563. }
  3564. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  3565. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  3566. llvm::Value *args[] = { src, dst };
  3567. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
  3568. args, "weakassign");
  3569. return;
  3570. }
  3571. void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
  3572. llvm::Value *DestPtr,
  3573. llvm::Value *SrcPtr,
  3574. llvm::Value *size) {
  3575. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
  3576. DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
  3577. llvm::Value *args[] = { DestPtr, SrcPtr, size };
  3578. CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
  3579. }
  3580. /// EmitObjCValueForIvar - Code Gen for ivar reference.
  3581. ///
  3582. LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
  3583. QualType ObjectTy,
  3584. llvm::Value *BaseValue,
  3585. const ObjCIvarDecl *Ivar,
  3586. unsigned CVRQualifiers) {
  3587. const ObjCInterfaceDecl *ID =
  3588. ObjectTy->getAs<ObjCObjectType>()->getInterface();
  3589. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  3590. EmitIvarOffset(CGF, ID, Ivar));
  3591. }
  3592. llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
  3593. const ObjCInterfaceDecl *Interface,
  3594. const ObjCIvarDecl *Ivar) {
  3595. uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
  3596. return llvm::ConstantInt::get(
  3597. CGM.getTypes().ConvertType(CGM.getContext().LongTy),
  3598. Offset);
  3599. }
  3600. /* *** Private Interface *** */
  3601. /// EmitImageInfo - Emit the image info marker used to encode some module
  3602. /// level information.
  3603. ///
  3604. /// See: <rdr://4810609&4810587&4810587>
  3605. /// struct IMAGE_INFO {
  3606. /// unsigned version;
  3607. /// unsigned flags;
  3608. /// };
  3609. enum ImageInfoFlags {
  3610. eImageInfo_FixAndContinue = (1 << 0), // This flag is no longer set by clang.
  3611. eImageInfo_GarbageCollected = (1 << 1),
  3612. eImageInfo_GCOnly = (1 << 2),
  3613. eImageInfo_OptimizedByDyld = (1 << 3), // This flag is set by the dyld shared cache.
  3614. // A flag indicating that the module has no instances of a @synthesize of a
  3615. // superclass variable. <rdar://problem/6803242>
  3616. eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
  3617. eImageInfo_ImageIsSimulated = (1 << 5)
  3618. };
  3619. void CGObjCCommonMac::EmitImageInfo() {
  3620. unsigned version = 0; // Version is unused?
  3621. const char *Section = (ObjCABI == 1) ?
  3622. "__OBJC, __image_info,regular" :
  3623. "__DATA, __objc_imageinfo, regular, no_dead_strip";
  3624. // Generate module-level named metadata to convey this information to the
  3625. // linker and code-gen.
  3626. llvm::Module &Mod = CGM.getModule();
  3627. // Add the ObjC ABI version to the module flags.
  3628. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
  3629. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
  3630. version);
  3631. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
  3632. llvm::MDString::get(VMContext,Section));
  3633. if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
  3634. // Non-GC overrides those files which specify GC.
  3635. Mod.addModuleFlag(llvm::Module::Override,
  3636. "Objective-C Garbage Collection", (uint32_t)0);
  3637. } else {
  3638. // Add the ObjC garbage collection value.
  3639. Mod.addModuleFlag(llvm::Module::Error,
  3640. "Objective-C Garbage Collection",
  3641. eImageInfo_GarbageCollected);
  3642. if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
  3643. // Add the ObjC GC Only value.
  3644. Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
  3645. eImageInfo_GCOnly);
  3646. // Require that GC be specified and set to eImageInfo_GarbageCollected.
  3647. llvm::Metadata *Ops[2] = {
  3648. llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
  3649. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  3650. llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
  3651. Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
  3652. llvm::MDNode::get(VMContext, Ops));
  3653. }
  3654. }
  3655. // Indicate whether we're compiling this to run on a simulator.
  3656. const llvm::Triple &Triple = CGM.getTarget().getTriple();
  3657. if (Triple.isiOS() &&
  3658. (Triple.getArch() == llvm::Triple::x86 ||
  3659. Triple.getArch() == llvm::Triple::x86_64))
  3660. Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
  3661. eImageInfo_ImageIsSimulated);
  3662. }
  3663. // struct objc_module {
  3664. // unsigned long version;
  3665. // unsigned long size;
  3666. // const char *name;
  3667. // Symtab symtab;
  3668. // };
  3669. // FIXME: Get from somewhere
  3670. static const int ModuleVersion = 7;
  3671. void CGObjCMac::EmitModuleInfo() {
  3672. uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
  3673. llvm::Constant *Values[] = {
  3674. llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
  3675. llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
  3676. // This used to be the filename, now it is unused. <rdr://4327263>
  3677. GetClassName(StringRef("")),
  3678. EmitModuleSymbols()
  3679. };
  3680. CreateMetadataVar("OBJC_MODULES",
  3681. llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
  3682. "__OBJC,__module_info,regular,no_dead_strip", 4, true);
  3683. }
  3684. llvm::Constant *CGObjCMac::EmitModuleSymbols() {
  3685. unsigned NumClasses = DefinedClasses.size();
  3686. unsigned NumCategories = DefinedCategories.size();
  3687. // Return null if no symbols were defined.
  3688. if (!NumClasses && !NumCategories)
  3689. return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
  3690. llvm::Constant *Values[5];
  3691. Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
  3692. Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
  3693. Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
  3694. Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
  3695. // The runtime expects exactly the list of defined classes followed
  3696. // by the list of defined categories, in a single array.
  3697. SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
  3698. for (unsigned i=0; i<NumClasses; i++) {
  3699. const ObjCInterfaceDecl *ID = ImplementedClasses[i];
  3700. assert(ID);
  3701. if (ObjCImplementationDecl *IMP = ID->getImplementation())
  3702. // We are implementing a weak imported interface. Give it external linkage
  3703. if (ID->isWeakImported() && !IMP->isWeakImported())
  3704. DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
  3705. Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
  3706. ObjCTypes.Int8PtrTy);
  3707. }
  3708. for (unsigned i=0; i<NumCategories; i++)
  3709. Symbols[NumClasses + i] =
  3710. llvm::ConstantExpr::getBitCast(DefinedCategories[i],
  3711. ObjCTypes.Int8PtrTy);
  3712. Values[4] =
  3713. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
  3714. Symbols.size()),
  3715. Symbols);
  3716. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  3717. llvm::GlobalVariable *GV = CreateMetadataVar(
  3718. "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip", 4, true);
  3719. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
  3720. }
  3721. llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
  3722. IdentifierInfo *II) {
  3723. LazySymbols.insert(II);
  3724. llvm::GlobalVariable *&Entry = ClassReferences[II];
  3725. if (!Entry) {
  3726. llvm::Constant *Casted =
  3727. llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
  3728. ObjCTypes.ClassPtrTy);
  3729. Entry = CreateMetadataVar(
  3730. "OBJC_CLASS_REFERENCES_", Casted,
  3731. "__OBJC,__cls_refs,literal_pointers,no_dead_strip", 4, true);
  3732. }
  3733. return CGF.Builder.CreateLoad(Entry);
  3734. }
  3735. llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
  3736. const ObjCInterfaceDecl *ID) {
  3737. return EmitClassRefFromId(CGF, ID->getIdentifier());
  3738. }
  3739. llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
  3740. IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
  3741. return EmitClassRefFromId(CGF, II);
  3742. }
  3743. llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel,
  3744. bool lvalue) {
  3745. llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
  3746. if (!Entry) {
  3747. llvm::Constant *Casted =
  3748. llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
  3749. ObjCTypes.SelectorPtrTy);
  3750. Entry = CreateMetadataVar(
  3751. "OBJC_SELECTOR_REFERENCES_", Casted,
  3752. "__OBJC,__message_refs,literal_pointers,no_dead_strip", 4, true);
  3753. Entry->setExternallyInitialized(true);
  3754. }
  3755. if (lvalue)
  3756. return Entry;
  3757. return CGF.Builder.CreateLoad(Entry);
  3758. }
  3759. llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
  3760. llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
  3761. if (!Entry)
  3762. Entry = CreateMetadataVar(
  3763. "OBJC_CLASS_NAME_",
  3764. llvm::ConstantDataArray::getString(VMContext, RuntimeName),
  3765. ((ObjCABI == 2) ? "__TEXT,__objc_classname,cstring_literals"
  3766. : "__TEXT,__cstring,cstring_literals"),
  3767. 1, true);
  3768. return getConstantGEP(VMContext, Entry, 0, 0);
  3769. }
  3770. llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
  3771. llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
  3772. I = MethodDefinitions.find(MD);
  3773. if (I != MethodDefinitions.end())
  3774. return I->second;
  3775. return nullptr;
  3776. }
  3777. /// GetIvarLayoutName - Returns a unique constant for the given
  3778. /// ivar layout bitmap.
  3779. llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
  3780. const ObjCCommonTypesHelper &ObjCTypes) {
  3781. return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  3782. }
  3783. void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
  3784. unsigned int BytePos,
  3785. bool ForStrongLayout,
  3786. bool &HasUnion) {
  3787. const RecordDecl *RD = RT->getDecl();
  3788. // FIXME - Use iterator.
  3789. SmallVector<const FieldDecl*, 16> Fields(RD->fields());
  3790. llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
  3791. const llvm::StructLayout *RecLayout =
  3792. CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
  3793. BuildAggrIvarLayout(nullptr, RecLayout, RD, Fields, BytePos, ForStrongLayout,
  3794. HasUnion);
  3795. }
  3796. void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
  3797. const llvm::StructLayout *Layout,
  3798. const RecordDecl *RD,
  3799. ArrayRef<const FieldDecl*> RecFields,
  3800. unsigned int BytePos, bool ForStrongLayout,
  3801. bool &HasUnion) {
  3802. bool IsUnion = (RD && RD->isUnion());
  3803. uint64_t MaxUnionIvarSize = 0;
  3804. uint64_t MaxSkippedUnionIvarSize = 0;
  3805. const FieldDecl *MaxField = nullptr;
  3806. const FieldDecl *MaxSkippedField = nullptr;
  3807. const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
  3808. uint64_t MaxFieldOffset = 0;
  3809. uint64_t MaxSkippedFieldOffset = 0;
  3810. uint64_t LastBitfieldOrUnnamedOffset = 0;
  3811. uint64_t FirstFieldDelta = 0;
  3812. if (RecFields.empty())
  3813. return;
  3814. unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
  3815. unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
  3816. if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
  3817. const FieldDecl *FirstField = RecFields[0];
  3818. FirstFieldDelta =
  3819. ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
  3820. }
  3821. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  3822. const FieldDecl *Field = RecFields[i];
  3823. uint64_t FieldOffset;
  3824. if (RD) {
  3825. // Note that 'i' here is actually the field index inside RD of Field,
  3826. // although this dependency is hidden.
  3827. const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
  3828. FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
  3829. } else
  3830. FieldOffset =
  3831. ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
  3832. // Skip over unnamed or bitfields
  3833. if (!Field->getIdentifier() || Field->isBitField()) {
  3834. LastFieldBitfieldOrUnnamed = Field;
  3835. LastBitfieldOrUnnamedOffset = FieldOffset;
  3836. continue;
  3837. }
  3838. LastFieldBitfieldOrUnnamed = nullptr;
  3839. QualType FQT = Field->getType();
  3840. if (FQT->isRecordType() || FQT->isUnionType()) {
  3841. if (FQT->isUnionType())
  3842. HasUnion = true;
  3843. BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
  3844. BytePos + FieldOffset,
  3845. ForStrongLayout, HasUnion);
  3846. continue;
  3847. }
  3848. if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
  3849. const ConstantArrayType *CArray =
  3850. dyn_cast_or_null<ConstantArrayType>(Array);
  3851. uint64_t ElCount = CArray->getSize().getZExtValue();
  3852. assert(CArray && "only array with known element size is supported");
  3853. FQT = CArray->getElementType();
  3854. while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
  3855. const ConstantArrayType *CArray =
  3856. dyn_cast_or_null<ConstantArrayType>(Array);
  3857. ElCount *= CArray->getSize().getZExtValue();
  3858. FQT = CArray->getElementType();
  3859. }
  3860. if (FQT->isRecordType() && ElCount) {
  3861. int OldIndex = IvarsInfo.size() - 1;
  3862. int OldSkIndex = SkipIvars.size() -1;
  3863. const RecordType *RT = FQT->getAs<RecordType>();
  3864. BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
  3865. ForStrongLayout, HasUnion);
  3866. // Replicate layout information for each array element. Note that
  3867. // one element is already done.
  3868. uint64_t ElIx = 1;
  3869. for (int FirstIndex = IvarsInfo.size() - 1,
  3870. FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
  3871. uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
  3872. for (int i = OldIndex+1; i <= FirstIndex; ++i)
  3873. IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
  3874. IvarsInfo[i].ivar_size));
  3875. for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
  3876. SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
  3877. SkipIvars[i].ivar_size));
  3878. }
  3879. continue;
  3880. }
  3881. }
  3882. // At this point, we are done with Record/Union and array there of.
  3883. // For other arrays we are down to its element type.
  3884. Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
  3885. unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
  3886. if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
  3887. || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
  3888. if (IsUnion) {
  3889. uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
  3890. if (UnionIvarSize > MaxUnionIvarSize) {
  3891. MaxUnionIvarSize = UnionIvarSize;
  3892. MaxField = Field;
  3893. MaxFieldOffset = FieldOffset;
  3894. }
  3895. } else {
  3896. IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
  3897. FieldSize / WordSizeInBits));
  3898. }
  3899. } else if ((ForStrongLayout &&
  3900. (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
  3901. || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
  3902. if (IsUnion) {
  3903. // FIXME: Why the asymmetry? We divide by word size in bits on other
  3904. // side.
  3905. uint64_t UnionIvarSize = FieldSize / ByteSizeInBits;
  3906. if (UnionIvarSize > MaxSkippedUnionIvarSize) {
  3907. MaxSkippedUnionIvarSize = UnionIvarSize;
  3908. MaxSkippedField = Field;
  3909. MaxSkippedFieldOffset = FieldOffset;
  3910. }
  3911. } else {
  3912. // FIXME: Why the asymmetry, we divide by byte size in bits here?
  3913. SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
  3914. FieldSize / ByteSizeInBits));
  3915. }
  3916. }
  3917. }
  3918. if (LastFieldBitfieldOrUnnamed) {
  3919. if (LastFieldBitfieldOrUnnamed->isBitField()) {
  3920. // Last field was a bitfield. Must update skip info.
  3921. uint64_t BitFieldSize
  3922. = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
  3923. GC_IVAR skivar;
  3924. skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
  3925. skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
  3926. + ((BitFieldSize % ByteSizeInBits) != 0);
  3927. SkipIvars.push_back(skivar);
  3928. } else {
  3929. assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
  3930. // Last field was unnamed. Must update skip info.
  3931. unsigned FieldSize
  3932. = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
  3933. SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
  3934. FieldSize / ByteSizeInBits));
  3935. }
  3936. }
  3937. if (MaxField)
  3938. IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
  3939. MaxUnionIvarSize));
  3940. if (MaxSkippedField)
  3941. SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
  3942. MaxSkippedUnionIvarSize));
  3943. }
  3944. /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
  3945. /// the computations and returning the layout bitmap (for ivar or blocks) in
  3946. /// the given argument BitMap string container. Routine reads
  3947. /// two containers, IvarsInfo and SkipIvars which are assumed to be
  3948. /// filled already by the caller.
  3949. llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
  3950. unsigned int WordsToScan, WordsToSkip;
  3951. llvm::Type *PtrTy = CGM.Int8PtrTy;
  3952. // Build the string of skip/scan nibbles
  3953. SmallVector<SKIP_SCAN, 32> SkipScanIvars;
  3954. unsigned int WordSize =
  3955. CGM.getTypes().getDataLayout().getTypeAllocSize(PtrTy);
  3956. if (IvarsInfo[0].ivar_bytepos == 0) {
  3957. WordsToSkip = 0;
  3958. WordsToScan = IvarsInfo[0].ivar_size;
  3959. } else {
  3960. WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
  3961. WordsToScan = IvarsInfo[0].ivar_size;
  3962. }
  3963. for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
  3964. unsigned int TailPrevGCObjC =
  3965. IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
  3966. if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
  3967. // consecutive 'scanned' object pointers.
  3968. WordsToScan += IvarsInfo[i].ivar_size;
  3969. } else {
  3970. // Skip over 'gc'able object pointer which lay over each other.
  3971. if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
  3972. continue;
  3973. // Must skip over 1 or more words. We save current skip/scan values
  3974. // and start a new pair.
  3975. SKIP_SCAN SkScan;
  3976. SkScan.skip = WordsToSkip;
  3977. SkScan.scan = WordsToScan;
  3978. SkipScanIvars.push_back(SkScan);
  3979. // Skip the hole.
  3980. SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
  3981. SkScan.scan = 0;
  3982. SkipScanIvars.push_back(SkScan);
  3983. WordsToSkip = 0;
  3984. WordsToScan = IvarsInfo[i].ivar_size;
  3985. }
  3986. }
  3987. if (WordsToScan > 0) {
  3988. SKIP_SCAN SkScan;
  3989. SkScan.skip = WordsToSkip;
  3990. SkScan.scan = WordsToScan;
  3991. SkipScanIvars.push_back(SkScan);
  3992. }
  3993. if (!SkipIvars.empty()) {
  3994. unsigned int LastIndex = SkipIvars.size()-1;
  3995. int LastByteSkipped =
  3996. SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
  3997. LastIndex = IvarsInfo.size()-1;
  3998. int LastByteScanned =
  3999. IvarsInfo[LastIndex].ivar_bytepos +
  4000. IvarsInfo[LastIndex].ivar_size * WordSize;
  4001. // Compute number of bytes to skip at the tail end of the last ivar scanned.
  4002. if (LastByteSkipped > LastByteScanned) {
  4003. unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
  4004. SKIP_SCAN SkScan;
  4005. SkScan.skip = TotalWords - (LastByteScanned/WordSize);
  4006. SkScan.scan = 0;
  4007. SkipScanIvars.push_back(SkScan);
  4008. }
  4009. }
  4010. // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
  4011. // as 0xMN.
  4012. int SkipScan = SkipScanIvars.size()-1;
  4013. for (int i = 0; i <= SkipScan; i++) {
  4014. if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
  4015. && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
  4016. // 0xM0 followed by 0x0N detected.
  4017. SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
  4018. for (int j = i+1; j < SkipScan; j++)
  4019. SkipScanIvars[j] = SkipScanIvars[j+1];
  4020. --SkipScan;
  4021. }
  4022. }
  4023. // Generate the string.
  4024. for (int i = 0; i <= SkipScan; i++) {
  4025. unsigned char byte;
  4026. unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
  4027. unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
  4028. unsigned int skip_big = SkipScanIvars[i].skip / 0xf;
  4029. unsigned int scan_big = SkipScanIvars[i].scan / 0xf;
  4030. // first skip big.
  4031. for (unsigned int ix = 0; ix < skip_big; ix++)
  4032. BitMap += (unsigned char)(0xf0);
  4033. // next (skip small, scan)
  4034. if (skip_small) {
  4035. byte = skip_small << 4;
  4036. if (scan_big > 0) {
  4037. byte |= 0xf;
  4038. --scan_big;
  4039. } else if (scan_small) {
  4040. byte |= scan_small;
  4041. scan_small = 0;
  4042. }
  4043. BitMap += byte;
  4044. }
  4045. // next scan big
  4046. for (unsigned int ix = 0; ix < scan_big; ix++)
  4047. BitMap += (unsigned char)(0x0f);
  4048. // last scan small
  4049. if (scan_small) {
  4050. byte = scan_small;
  4051. BitMap += byte;
  4052. }
  4053. }
  4054. // null terminate string.
  4055. unsigned char zero = 0;
  4056. BitMap += zero;
  4057. llvm::GlobalVariable *Entry = CreateMetadataVar(
  4058. "OBJC_CLASS_NAME_",
  4059. llvm::ConstantDataArray::getString(VMContext, BitMap, false),
  4060. ((ObjCABI == 2) ? "__TEXT,__objc_classname,cstring_literals"
  4061. : "__TEXT,__cstring,cstring_literals"),
  4062. 1, true);
  4063. return getConstantGEP(VMContext, Entry, 0, 0);
  4064. }
  4065. /// BuildIvarLayout - Builds ivar layout bitmap for the class
  4066. /// implementation for the __strong or __weak case.
  4067. /// The layout map displays which words in ivar list must be skipped
  4068. /// and which must be scanned by GC (see below). String is built of bytes.
  4069. /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
  4070. /// of words to skip and right nibble is count of words to scan. So, each
  4071. /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
  4072. /// represented by a 0x00 byte which also ends the string.
  4073. /// 1. when ForStrongLayout is true, following ivars are scanned:
  4074. /// - id, Class
  4075. /// - object *
  4076. /// - __strong anything
  4077. ///
  4078. /// 2. When ForStrongLayout is false, following ivars are scanned:
  4079. /// - __weak anything
  4080. ///
  4081. llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
  4082. const ObjCImplementationDecl *OMD,
  4083. bool ForStrongLayout) {
  4084. bool hasUnion = false;
  4085. llvm::Type *PtrTy = CGM.Int8PtrTy;
  4086. if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
  4087. !CGM.getLangOpts().ObjCAutoRefCount)
  4088. return llvm::Constant::getNullValue(PtrTy);
  4089. const ObjCInterfaceDecl *OI = OMD->getClassInterface();
  4090. SmallVector<const FieldDecl*, 32> RecFields;
  4091. if (CGM.getLangOpts().ObjCAutoRefCount) {
  4092. for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
  4093. IVD; IVD = IVD->getNextIvar())
  4094. RecFields.push_back(cast<FieldDecl>(IVD));
  4095. }
  4096. else {
  4097. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  4098. CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
  4099. // FIXME: This is not ideal; we shouldn't have to do this copy.
  4100. RecFields.append(Ivars.begin(), Ivars.end());
  4101. }
  4102. if (RecFields.empty())
  4103. return llvm::Constant::getNullValue(PtrTy);
  4104. SkipIvars.clear();
  4105. IvarsInfo.clear();
  4106. BuildAggrIvarLayout(OMD, nullptr, nullptr, RecFields, 0, ForStrongLayout,
  4107. hasUnion);
  4108. if (IvarsInfo.empty())
  4109. return llvm::Constant::getNullValue(PtrTy);
  4110. // Sort on byte position in case we encounterred a union nested in
  4111. // the ivar list.
  4112. if (hasUnion && !IvarsInfo.empty())
  4113. std::sort(IvarsInfo.begin(), IvarsInfo.end());
  4114. if (hasUnion && !SkipIvars.empty())
  4115. std::sort(SkipIvars.begin(), SkipIvars.end());
  4116. std::string BitMap;
  4117. llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
  4118. if (CGM.getLangOpts().ObjCGCBitmapPrint) {
  4119. printf("\n%s ivar layout for class '%s': ",
  4120. ForStrongLayout ? "strong" : "weak",
  4121. OMD->getClassInterface()->getName().str().c_str());
  4122. const unsigned char *s = (const unsigned char*)BitMap.c_str();
  4123. for (unsigned i = 0, e = BitMap.size(); i < e; i++)
  4124. if (!(s[i] & 0xf0))
  4125. printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
  4126. else
  4127. printf("0x%x%s", s[i], s[i] != 0 ? ", " : "");
  4128. printf("\n");
  4129. }
  4130. return C;
  4131. }
  4132. llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
  4133. llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
  4134. // FIXME: Avoid std::string in "Sel.getAsString()"
  4135. if (!Entry)
  4136. Entry = CreateMetadataVar(
  4137. "OBJC_METH_VAR_NAME_",
  4138. llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
  4139. ((ObjCABI == 2) ? "__TEXT,__objc_methname,cstring_literals"
  4140. : "__TEXT,__cstring,cstring_literals"),
  4141. 1, true);
  4142. return getConstantGEP(VMContext, Entry, 0, 0);
  4143. }
  4144. // FIXME: Merge into a single cstring creation function.
  4145. llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
  4146. return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
  4147. }
  4148. llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
  4149. std::string TypeStr;
  4150. CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
  4151. llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
  4152. if (!Entry)
  4153. Entry = CreateMetadataVar(
  4154. "OBJC_METH_VAR_TYPE_",
  4155. llvm::ConstantDataArray::getString(VMContext, TypeStr),
  4156. ((ObjCABI == 2) ? "__TEXT,__objc_methtype,cstring_literals"
  4157. : "__TEXT,__cstring,cstring_literals"),
  4158. 1, true);
  4159. return getConstantGEP(VMContext, Entry, 0, 0);
  4160. }
  4161. llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
  4162. bool Extended) {
  4163. std::string TypeStr;
  4164. if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
  4165. return nullptr;
  4166. llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
  4167. if (!Entry)
  4168. Entry = CreateMetadataVar(
  4169. "OBJC_METH_VAR_TYPE_",
  4170. llvm::ConstantDataArray::getString(VMContext, TypeStr),
  4171. ((ObjCABI == 2) ? "__TEXT,__objc_methtype,cstring_literals"
  4172. : "__TEXT,__cstring,cstring_literals"),
  4173. 1, true);
  4174. return getConstantGEP(VMContext, Entry, 0, 0);
  4175. }
  4176. // FIXME: Merge into a single cstring creation function.
  4177. llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
  4178. llvm::GlobalVariable *&Entry = PropertyNames[Ident];
  4179. if (!Entry)
  4180. Entry = CreateMetadataVar(
  4181. "OBJC_PROP_NAME_ATTR_",
  4182. llvm::ConstantDataArray::getString(VMContext, Ident->getName()),
  4183. "__TEXT,__cstring,cstring_literals", 1, true);
  4184. return getConstantGEP(VMContext, Entry, 0, 0);
  4185. }
  4186. // FIXME: Merge into a single cstring creation function.
  4187. // FIXME: This Decl should be more precise.
  4188. llvm::Constant *
  4189. CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
  4190. const Decl *Container) {
  4191. std::string TypeStr;
  4192. CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
  4193. return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
  4194. }
  4195. void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
  4196. const ObjCContainerDecl *CD,
  4197. SmallVectorImpl<char> &Name) {
  4198. llvm::raw_svector_ostream OS(Name);
  4199. assert (CD && "Missing container decl in GetNameForMethod");
  4200. OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
  4201. << '[' << CD->getName();
  4202. if (const ObjCCategoryImplDecl *CID =
  4203. dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
  4204. OS << '(' << *CID << ')';
  4205. OS << ' ' << D->getSelector().getAsString() << ']';
  4206. }
  4207. void CGObjCMac::FinishModule() {
  4208. EmitModuleInfo();
  4209. // Emit the dummy bodies for any protocols which were referenced but
  4210. // never defined.
  4211. for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
  4212. I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
  4213. if (I->second->hasInitializer())
  4214. continue;
  4215. llvm::Constant *Values[5];
  4216. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
  4217. Values[1] = GetClassName(I->first->getName());
  4218. Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
  4219. Values[3] = Values[4] =
  4220. llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
  4221. I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
  4222. Values));
  4223. CGM.addCompilerUsedGlobal(I->second);
  4224. }
  4225. // Add assembler directives to add lazy undefined symbol references
  4226. // for classes which are referenced but not defined. This is
  4227. // important for correct linker interaction.
  4228. //
  4229. // FIXME: It would be nice if we had an LLVM construct for this.
  4230. if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
  4231. SmallString<256> Asm;
  4232. Asm += CGM.getModule().getModuleInlineAsm();
  4233. if (!Asm.empty() && Asm.back() != '\n')
  4234. Asm += '\n';
  4235. llvm::raw_svector_ostream OS(Asm);
  4236. for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
  4237. e = DefinedSymbols.end(); I != e; ++I)
  4238. OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
  4239. << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
  4240. for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
  4241. e = LazySymbols.end(); I != e; ++I) {
  4242. OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
  4243. }
  4244. for (size_t i = 0, e = DefinedCategoryNames.size(); i < e; ++i) {
  4245. OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
  4246. << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
  4247. }
  4248. CGM.getModule().setModuleInlineAsm(OS.str());
  4249. }
  4250. }
  4251. CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
  4252. : CGObjCCommonMac(cgm),
  4253. ObjCTypes(cgm) {
  4254. ObjCEmptyCacheVar = ObjCEmptyVtableVar = nullptr;
  4255. ObjCABI = 2;
  4256. }
  4257. /* *** */
  4258. ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
  4259. : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
  4260. {
  4261. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  4262. ASTContext &Ctx = CGM.getContext();
  4263. ShortTy = Types.ConvertType(Ctx.ShortTy);
  4264. IntTy = Types.ConvertType(Ctx.IntTy);
  4265. LongTy = Types.ConvertType(Ctx.LongTy);
  4266. LongLongTy = Types.ConvertType(Ctx.LongLongTy);
  4267. Int8PtrTy = CGM.Int8PtrTy;
  4268. Int8PtrPtrTy = CGM.Int8PtrPtrTy;
  4269. // arm64 targets use "int" ivar offset variables. All others,
  4270. // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
  4271. if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
  4272. IvarOffsetVarTy = IntTy;
  4273. else
  4274. IvarOffsetVarTy = LongTy;
  4275. ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
  4276. PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
  4277. SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
  4278. // I'm not sure I like this. The implicit coordination is a bit
  4279. // gross. We should solve this in a reasonable fashion because this
  4280. // is a pretty common task (match some runtime data structure with
  4281. // an LLVM data structure).
  4282. // FIXME: This is leaked.
  4283. // FIXME: Merge with rewriter code?
  4284. // struct _objc_super {
  4285. // id self;
  4286. // Class cls;
  4287. // }
  4288. RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
  4289. Ctx.getTranslationUnitDecl(),
  4290. SourceLocation(), SourceLocation(),
  4291. &Ctx.Idents.get("_objc_super"));
  4292. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
  4293. nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
  4294. false, ICIS_NoInit));
  4295. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
  4296. nullptr, Ctx.getObjCClassType(), nullptr,
  4297. nullptr, false, ICIS_NoInit));
  4298. RD->completeDefinition();
  4299. SuperCTy = Ctx.getTagDeclType(RD);
  4300. SuperPtrCTy = Ctx.getPointerType(SuperCTy);
  4301. SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
  4302. SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
  4303. // struct _prop_t {
  4304. // char *name;
  4305. // char *attributes;
  4306. // }
  4307. PropertyTy = llvm::StructType::create("struct._prop_t",
  4308. Int8PtrTy, Int8PtrTy, nullptr);
  4309. // struct _prop_list_t {
  4310. // uint32_t entsize; // sizeof(struct _prop_t)
  4311. // uint32_t count_of_properties;
  4312. // struct _prop_t prop_list[count_of_properties];
  4313. // }
  4314. PropertyListTy =
  4315. llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
  4316. llvm::ArrayType::get(PropertyTy, 0), nullptr);
  4317. // struct _prop_list_t *
  4318. PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
  4319. // struct _objc_method {
  4320. // SEL _cmd;
  4321. // char *method_type;
  4322. // char *_imp;
  4323. // }
  4324. MethodTy = llvm::StructType::create("struct._objc_method",
  4325. SelectorPtrTy, Int8PtrTy, Int8PtrTy,
  4326. nullptr);
  4327. // struct _objc_cache *
  4328. CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
  4329. CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
  4330. }
  4331. ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
  4332. : ObjCCommonTypesHelper(cgm) {
  4333. // struct _objc_method_description {
  4334. // SEL name;
  4335. // char *types;
  4336. // }
  4337. MethodDescriptionTy =
  4338. llvm::StructType::create("struct._objc_method_description",
  4339. SelectorPtrTy, Int8PtrTy, nullptr);
  4340. // struct _objc_method_description_list {
  4341. // int count;
  4342. // struct _objc_method_description[1];
  4343. // }
  4344. MethodDescriptionListTy = llvm::StructType::create(
  4345. "struct._objc_method_description_list", IntTy,
  4346. llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
  4347. // struct _objc_method_description_list *
  4348. MethodDescriptionListPtrTy =
  4349. llvm::PointerType::getUnqual(MethodDescriptionListTy);
  4350. // Protocol description structures
  4351. // struct _objc_protocol_extension {
  4352. // uint32_t size; // sizeof(struct _objc_protocol_extension)
  4353. // struct _objc_method_description_list *optional_instance_methods;
  4354. // struct _objc_method_description_list *optional_class_methods;
  4355. // struct _objc_property_list *instance_properties;
  4356. // const char ** extendedMethodTypes;
  4357. // }
  4358. ProtocolExtensionTy =
  4359. llvm::StructType::create("struct._objc_protocol_extension",
  4360. IntTy, MethodDescriptionListPtrTy,
  4361. MethodDescriptionListPtrTy, PropertyListPtrTy,
  4362. Int8PtrPtrTy, nullptr);
  4363. // struct _objc_protocol_extension *
  4364. ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
  4365. // Handle recursive construction of Protocol and ProtocolList types
  4366. ProtocolTy =
  4367. llvm::StructType::create(VMContext, "struct._objc_protocol");
  4368. ProtocolListTy =
  4369. llvm::StructType::create(VMContext, "struct._objc_protocol_list");
  4370. ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
  4371. LongTy,
  4372. llvm::ArrayType::get(ProtocolTy, 0),
  4373. nullptr);
  4374. // struct _objc_protocol {
  4375. // struct _objc_protocol_extension *isa;
  4376. // char *protocol_name;
  4377. // struct _objc_protocol **_objc_protocol_list;
  4378. // struct _objc_method_description_list *instance_methods;
  4379. // struct _objc_method_description_list *class_methods;
  4380. // }
  4381. ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
  4382. llvm::PointerType::getUnqual(ProtocolListTy),
  4383. MethodDescriptionListPtrTy,
  4384. MethodDescriptionListPtrTy,
  4385. nullptr);
  4386. // struct _objc_protocol_list *
  4387. ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
  4388. ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
  4389. // Class description structures
  4390. // struct _objc_ivar {
  4391. // char *ivar_name;
  4392. // char *ivar_type;
  4393. // int ivar_offset;
  4394. // }
  4395. IvarTy = llvm::StructType::create("struct._objc_ivar",
  4396. Int8PtrTy, Int8PtrTy, IntTy, nullptr);
  4397. // struct _objc_ivar_list *
  4398. IvarListTy =
  4399. llvm::StructType::create(VMContext, "struct._objc_ivar_list");
  4400. IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
  4401. // struct _objc_method_list *
  4402. MethodListTy =
  4403. llvm::StructType::create(VMContext, "struct._objc_method_list");
  4404. MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
  4405. // struct _objc_class_extension *
  4406. ClassExtensionTy =
  4407. llvm::StructType::create("struct._objc_class_extension",
  4408. IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
  4409. ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
  4410. ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
  4411. // struct _objc_class {
  4412. // Class isa;
  4413. // Class super_class;
  4414. // char *name;
  4415. // long version;
  4416. // long info;
  4417. // long instance_size;
  4418. // struct _objc_ivar_list *ivars;
  4419. // struct _objc_method_list *methods;
  4420. // struct _objc_cache *cache;
  4421. // struct _objc_protocol_list *protocols;
  4422. // char *ivar_layout;
  4423. // struct _objc_class_ext *ext;
  4424. // };
  4425. ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
  4426. llvm::PointerType::getUnqual(ClassTy),
  4427. Int8PtrTy,
  4428. LongTy,
  4429. LongTy,
  4430. LongTy,
  4431. IvarListPtrTy,
  4432. MethodListPtrTy,
  4433. CachePtrTy,
  4434. ProtocolListPtrTy,
  4435. Int8PtrTy,
  4436. ClassExtensionPtrTy,
  4437. nullptr);
  4438. ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
  4439. // struct _objc_category {
  4440. // char *category_name;
  4441. // char *class_name;
  4442. // struct _objc_method_list *instance_method;
  4443. // struct _objc_method_list *class_method;
  4444. // uint32_t size; // sizeof(struct _objc_category)
  4445. // struct _objc_property_list *instance_properties;// category's @property
  4446. // }
  4447. CategoryTy =
  4448. llvm::StructType::create("struct._objc_category",
  4449. Int8PtrTy, Int8PtrTy, MethodListPtrTy,
  4450. MethodListPtrTy, ProtocolListPtrTy,
  4451. IntTy, PropertyListPtrTy, nullptr);
  4452. // Global metadata structures
  4453. // struct _objc_symtab {
  4454. // long sel_ref_cnt;
  4455. // SEL *refs;
  4456. // short cls_def_cnt;
  4457. // short cat_def_cnt;
  4458. // char *defs[cls_def_cnt + cat_def_cnt];
  4459. // }
  4460. SymtabTy =
  4461. llvm::StructType::create("struct._objc_symtab",
  4462. LongTy, SelectorPtrTy, ShortTy, ShortTy,
  4463. llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
  4464. SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
  4465. // struct _objc_module {
  4466. // long version;
  4467. // long size; // sizeof(struct _objc_module)
  4468. // char *name;
  4469. // struct _objc_symtab* symtab;
  4470. // }
  4471. ModuleTy =
  4472. llvm::StructType::create("struct._objc_module",
  4473. LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
  4474. // FIXME: This is the size of the setjmp buffer and should be target
  4475. // specific. 18 is what's used on 32-bit X86.
  4476. uint64_t SetJmpBufferSize = 18;
  4477. // Exceptions
  4478. llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
  4479. ExceptionDataTy =
  4480. llvm::StructType::create("struct._objc_exception_data",
  4481. llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
  4482. StackPtrTy, nullptr);
  4483. }
  4484. ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
  4485. : ObjCCommonTypesHelper(cgm) {
  4486. // struct _method_list_t {
  4487. // uint32_t entsize; // sizeof(struct _objc_method)
  4488. // uint32_t method_count;
  4489. // struct _objc_method method_list[method_count];
  4490. // }
  4491. MethodListnfABITy =
  4492. llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
  4493. llvm::ArrayType::get(MethodTy, 0), nullptr);
  4494. // struct method_list_t *
  4495. MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
  4496. // struct _protocol_t {
  4497. // id isa; // NULL
  4498. // const char * const protocol_name;
  4499. // const struct _protocol_list_t * protocol_list; // super protocols
  4500. // const struct method_list_t * const instance_methods;
  4501. // const struct method_list_t * const class_methods;
  4502. // const struct method_list_t *optionalInstanceMethods;
  4503. // const struct method_list_t *optionalClassMethods;
  4504. // const struct _prop_list_t * properties;
  4505. // const uint32_t size; // sizeof(struct _protocol_t)
  4506. // const uint32_t flags; // = 0
  4507. // const char ** extendedMethodTypes;
  4508. // const char *demangledName;
  4509. // }
  4510. // Holder for struct _protocol_list_t *
  4511. ProtocolListnfABITy =
  4512. llvm::StructType::create(VMContext, "struct._objc_protocol_list");
  4513. ProtocolnfABITy =
  4514. llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
  4515. llvm::PointerType::getUnqual(ProtocolListnfABITy),
  4516. MethodListnfABIPtrTy, MethodListnfABIPtrTy,
  4517. MethodListnfABIPtrTy, MethodListnfABIPtrTy,
  4518. PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
  4519. Int8PtrTy,
  4520. nullptr);
  4521. // struct _protocol_t*
  4522. ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
  4523. // struct _protocol_list_t {
  4524. // long protocol_count; // Note, this is 32/64 bit
  4525. // struct _protocol_t *[protocol_count];
  4526. // }
  4527. ProtocolListnfABITy->setBody(LongTy,
  4528. llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
  4529. nullptr);
  4530. // struct _objc_protocol_list*
  4531. ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
  4532. // struct _ivar_t {
  4533. // unsigned [long] int *offset; // pointer to ivar offset location
  4534. // char *name;
  4535. // char *type;
  4536. // uint32_t alignment;
  4537. // uint32_t size;
  4538. // }
  4539. IvarnfABITy = llvm::StructType::create(
  4540. "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
  4541. Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
  4542. // struct _ivar_list_t {
  4543. // uint32 entsize; // sizeof(struct _ivar_t)
  4544. // uint32 count;
  4545. // struct _iver_t list[count];
  4546. // }
  4547. IvarListnfABITy =
  4548. llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
  4549. llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
  4550. IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
  4551. // struct _class_ro_t {
  4552. // uint32_t const flags;
  4553. // uint32_t const instanceStart;
  4554. // uint32_t const instanceSize;
  4555. // uint32_t const reserved; // only when building for 64bit targets
  4556. // const uint8_t * const ivarLayout;
  4557. // const char *const name;
  4558. // const struct _method_list_t * const baseMethods;
  4559. // const struct _objc_protocol_list *const baseProtocols;
  4560. // const struct _ivar_list_t *const ivars;
  4561. // const uint8_t * const weakIvarLayout;
  4562. // const struct _prop_list_t * const properties;
  4563. // }
  4564. // FIXME. Add 'reserved' field in 64bit abi mode!
  4565. ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
  4566. IntTy, IntTy, IntTy, Int8PtrTy,
  4567. Int8PtrTy, MethodListnfABIPtrTy,
  4568. ProtocolListnfABIPtrTy,
  4569. IvarListnfABIPtrTy,
  4570. Int8PtrTy, PropertyListPtrTy,
  4571. nullptr);
  4572. // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
  4573. llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
  4574. ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
  4575. ->getPointerTo();
  4576. // struct _class_t {
  4577. // struct _class_t *isa;
  4578. // struct _class_t * const superclass;
  4579. // void *cache;
  4580. // IMP *vtable;
  4581. // struct class_ro_t *ro;
  4582. // }
  4583. ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
  4584. ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
  4585. llvm::PointerType::getUnqual(ClassnfABITy),
  4586. CachePtrTy,
  4587. llvm::PointerType::getUnqual(ImpnfABITy),
  4588. llvm::PointerType::getUnqual(ClassRonfABITy),
  4589. nullptr);
  4590. // LLVM for struct _class_t *
  4591. ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
  4592. // struct _category_t {
  4593. // const char * const name;
  4594. // struct _class_t *const cls;
  4595. // const struct _method_list_t * const instance_methods;
  4596. // const struct _method_list_t * const class_methods;
  4597. // const struct _protocol_list_t * const protocols;
  4598. // const struct _prop_list_t * const properties;
  4599. // }
  4600. CategorynfABITy = llvm::StructType::create("struct._category_t",
  4601. Int8PtrTy, ClassnfABIPtrTy,
  4602. MethodListnfABIPtrTy,
  4603. MethodListnfABIPtrTy,
  4604. ProtocolListnfABIPtrTy,
  4605. PropertyListPtrTy,
  4606. nullptr);
  4607. // New types for nonfragile abi messaging.
  4608. CodeGen::CodeGenTypes &Types = CGM.getTypes();
  4609. ASTContext &Ctx = CGM.getContext();
  4610. // MessageRefTy - LLVM for:
  4611. // struct _message_ref_t {
  4612. // IMP messenger;
  4613. // SEL name;
  4614. // };
  4615. // First the clang type for struct _message_ref_t
  4616. RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
  4617. Ctx.getTranslationUnitDecl(),
  4618. SourceLocation(), SourceLocation(),
  4619. &Ctx.Idents.get("_message_ref_t"));
  4620. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
  4621. nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
  4622. ICIS_NoInit));
  4623. RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
  4624. nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
  4625. false, ICIS_NoInit));
  4626. RD->completeDefinition();
  4627. MessageRefCTy = Ctx.getTagDeclType(RD);
  4628. MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
  4629. MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
  4630. // MessageRefPtrTy - LLVM for struct _message_ref_t*
  4631. MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
  4632. // SuperMessageRefTy - LLVM for:
  4633. // struct _super_message_ref_t {
  4634. // SUPER_IMP messenger;
  4635. // SEL name;
  4636. // };
  4637. SuperMessageRefTy =
  4638. llvm::StructType::create("struct._super_message_ref_t",
  4639. ImpnfABITy, SelectorPtrTy, nullptr);
  4640. // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
  4641. SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
  4642. // struct objc_typeinfo {
  4643. // const void** vtable; // objc_ehtype_vtable + 2
  4644. // const char* name; // c++ typeinfo string
  4645. // Class cls;
  4646. // };
  4647. EHTypeTy =
  4648. llvm::StructType::create("struct._objc_typeinfo",
  4649. llvm::PointerType::getUnqual(Int8PtrTy),
  4650. Int8PtrTy, ClassnfABIPtrTy, nullptr);
  4651. EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
  4652. }
  4653. llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
  4654. FinishNonFragileABIModule();
  4655. return nullptr;
  4656. }
  4657. void CGObjCNonFragileABIMac::
  4658. AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
  4659. const char *SymbolName,
  4660. const char *SectionName) {
  4661. unsigned NumClasses = Container.size();
  4662. if (!NumClasses)
  4663. return;
  4664. SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
  4665. for (unsigned i=0; i<NumClasses; i++)
  4666. Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
  4667. ObjCTypes.Int8PtrTy);
  4668. llvm::Constant *Init =
  4669. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
  4670. Symbols.size()),
  4671. Symbols);
  4672. llvm::GlobalVariable *GV =
  4673. new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  4674. llvm::GlobalValue::PrivateLinkage,
  4675. Init,
  4676. SymbolName);
  4677. GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
  4678. GV->setSection(SectionName);
  4679. CGM.addCompilerUsedGlobal(GV);
  4680. }
  4681. void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
  4682. // nonfragile abi has no module definition.
  4683. // Build list of all implemented class addresses in array
  4684. // L_OBJC_LABEL_CLASS_$.
  4685. for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
  4686. const ObjCInterfaceDecl *ID = ImplementedClasses[i];
  4687. assert(ID);
  4688. if (ObjCImplementationDecl *IMP = ID->getImplementation())
  4689. // We are implementing a weak imported interface. Give it external linkage
  4690. if (ID->isWeakImported() && !IMP->isWeakImported()) {
  4691. DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
  4692. DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
  4693. }
  4694. }
  4695. AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
  4696. "__DATA, __objc_classlist, regular, no_dead_strip");
  4697. AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
  4698. "__DATA, __objc_nlclslist, regular, no_dead_strip");
  4699. // Build list of all implemented category addresses in array
  4700. // L_OBJC_LABEL_CATEGORY_$.
  4701. AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
  4702. "__DATA, __objc_catlist, regular, no_dead_strip");
  4703. AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
  4704. "__DATA, __objc_nlcatlist, regular, no_dead_strip");
  4705. EmitImageInfo();
  4706. }
  4707. /// isVTableDispatchedSelector - Returns true if SEL is not in the list of
  4708. /// VTableDispatchMethods; false otherwise. What this means is that
  4709. /// except for the 19 selectors in the list, we generate 32bit-style
  4710. /// message dispatch call for all the rest.
  4711. bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
  4712. // At various points we've experimented with using vtable-based
  4713. // dispatch for all methods.
  4714. switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
  4715. case CodeGenOptions::Legacy:
  4716. return false;
  4717. case CodeGenOptions::NonLegacy:
  4718. return true;
  4719. case CodeGenOptions::Mixed:
  4720. break;
  4721. }
  4722. // If so, see whether this selector is in the white-list of things which must
  4723. // use the new dispatch convention. We lazily build a dense set for this.
  4724. if (VTableDispatchMethods.empty()) {
  4725. VTableDispatchMethods.insert(GetNullarySelector("alloc"));
  4726. VTableDispatchMethods.insert(GetNullarySelector("class"));
  4727. VTableDispatchMethods.insert(GetNullarySelector("self"));
  4728. VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
  4729. VTableDispatchMethods.insert(GetNullarySelector("length"));
  4730. VTableDispatchMethods.insert(GetNullarySelector("count"));
  4731. // These are vtable-based if GC is disabled.
  4732. // Optimistically use vtable dispatch for hybrid compiles.
  4733. if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
  4734. VTableDispatchMethods.insert(GetNullarySelector("retain"));
  4735. VTableDispatchMethods.insert(GetNullarySelector("release"));
  4736. VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
  4737. }
  4738. VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
  4739. VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
  4740. VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
  4741. VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
  4742. VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
  4743. VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
  4744. VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
  4745. // These are vtable-based if GC is enabled.
  4746. // Optimistically use vtable dispatch for hybrid compiles.
  4747. if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
  4748. VTableDispatchMethods.insert(GetNullarySelector("hash"));
  4749. VTableDispatchMethods.insert(GetUnarySelector("addObject"));
  4750. // "countByEnumeratingWithState:objects:count"
  4751. IdentifierInfo *KeyIdents[] = {
  4752. &CGM.getContext().Idents.get("countByEnumeratingWithState"),
  4753. &CGM.getContext().Idents.get("objects"),
  4754. &CGM.getContext().Idents.get("count")
  4755. };
  4756. VTableDispatchMethods.insert(
  4757. CGM.getContext().Selectors.getSelector(3, KeyIdents));
  4758. }
  4759. }
  4760. return VTableDispatchMethods.count(Sel);
  4761. }
  4762. /// BuildClassRoTInitializer - generate meta-data for:
  4763. /// struct _class_ro_t {
  4764. /// uint32_t const flags;
  4765. /// uint32_t const instanceStart;
  4766. /// uint32_t const instanceSize;
  4767. /// uint32_t const reserved; // only when building for 64bit targets
  4768. /// const uint8_t * const ivarLayout;
  4769. /// const char *const name;
  4770. /// const struct _method_list_t * const baseMethods;
  4771. /// const struct _protocol_list_t *const baseProtocols;
  4772. /// const struct _ivar_list_t *const ivars;
  4773. /// const uint8_t * const weakIvarLayout;
  4774. /// const struct _prop_list_t * const properties;
  4775. /// }
  4776. ///
  4777. llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
  4778. unsigned flags,
  4779. unsigned InstanceStart,
  4780. unsigned InstanceSize,
  4781. const ObjCImplementationDecl *ID) {
  4782. std::string ClassName = ID->getObjCRuntimeNameAsString();
  4783. llvm::Constant *Values[10]; // 11 for 64bit targets!
  4784. if (CGM.getLangOpts().ObjCAutoRefCount)
  4785. flags |= NonFragileABI_Class_CompiledByARC;
  4786. Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
  4787. Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
  4788. Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
  4789. // FIXME. For 64bit targets add 0 here.
  4790. Values[ 3] = (flags & NonFragileABI_Class_Meta)
  4791. ? GetIvarLayoutName(nullptr, ObjCTypes)
  4792. : BuildIvarLayout(ID, true);
  4793. Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
  4794. // const struct _method_list_t * const baseMethods;
  4795. std::vector<llvm::Constant*> Methods;
  4796. std::string MethodListName("\01l_OBJC_$_");
  4797. if (flags & NonFragileABI_Class_Meta) {
  4798. MethodListName += "CLASS_METHODS_";
  4799. MethodListName += ID->getObjCRuntimeNameAsString();
  4800. for (const auto *I : ID->class_methods())
  4801. // Class methods should always be defined.
  4802. Methods.push_back(GetMethodConstant(I));
  4803. } else {
  4804. MethodListName += "INSTANCE_METHODS_";
  4805. MethodListName += ID->getObjCRuntimeNameAsString();
  4806. for (const auto *I : ID->instance_methods())
  4807. // Instance methods should always be defined.
  4808. Methods.push_back(GetMethodConstant(I));
  4809. for (const auto *PID : ID->property_impls()) {
  4810. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
  4811. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  4812. if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
  4813. if (llvm::Constant *C = GetMethodConstant(MD))
  4814. Methods.push_back(C);
  4815. if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
  4816. if (llvm::Constant *C = GetMethodConstant(MD))
  4817. Methods.push_back(C);
  4818. }
  4819. }
  4820. }
  4821. Values[ 5] = EmitMethodList(MethodListName,
  4822. "__DATA, __objc_const", Methods);
  4823. const ObjCInterfaceDecl *OID = ID->getClassInterface();
  4824. assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
  4825. Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
  4826. + OID->getObjCRuntimeNameAsString(),
  4827. OID->all_referenced_protocol_begin(),
  4828. OID->all_referenced_protocol_end());
  4829. if (flags & NonFragileABI_Class_Meta) {
  4830. Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
  4831. Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
  4832. Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  4833. } else {
  4834. Values[ 7] = EmitIvarList(ID);
  4835. Values[ 8] = BuildIvarLayout(ID, false);
  4836. Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
  4837. ID, ID->getClassInterface(), ObjCTypes);
  4838. }
  4839. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
  4840. Values);
  4841. llvm::GlobalVariable *CLASS_RO_GV =
  4842. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
  4843. llvm::GlobalValue::PrivateLinkage,
  4844. Init,
  4845. (flags & NonFragileABI_Class_Meta) ?
  4846. std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
  4847. std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
  4848. CLASS_RO_GV->setAlignment(
  4849. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
  4850. CLASS_RO_GV->setSection("__DATA, __objc_const");
  4851. return CLASS_RO_GV;
  4852. }
  4853. /// BuildClassMetaData - This routine defines that to-level meta-data
  4854. /// for the given ClassName for:
  4855. /// struct _class_t {
  4856. /// struct _class_t *isa;
  4857. /// struct _class_t * const superclass;
  4858. /// void *cache;
  4859. /// IMP *vtable;
  4860. /// struct class_ro_t *ro;
  4861. /// }
  4862. ///
  4863. llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
  4864. const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
  4865. llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
  4866. llvm::Constant *Values[] = {
  4867. IsAGV,
  4868. SuperClassGV,
  4869. ObjCEmptyCacheVar, // &ObjCEmptyCacheVar
  4870. ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
  4871. ClassRoGV // &CLASS_RO_GV
  4872. };
  4873. if (!Values[1])
  4874. Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
  4875. if (!Values[3])
  4876. Values[3] = llvm::Constant::getNullValue(
  4877. llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
  4878. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
  4879. Values);
  4880. llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
  4881. GV->setInitializer(Init);
  4882. GV->setSection("__DATA, __objc_data");
  4883. GV->setAlignment(
  4884. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
  4885. if (HiddenVisibility)
  4886. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  4887. return GV;
  4888. }
  4889. bool
  4890. CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
  4891. return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
  4892. }
  4893. void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
  4894. uint32_t &InstanceStart,
  4895. uint32_t &InstanceSize) {
  4896. const ASTRecordLayout &RL =
  4897. CGM.getContext().getASTObjCImplementationLayout(OID);
  4898. // InstanceSize is really instance end.
  4899. InstanceSize = RL.getDataSize().getQuantity();
  4900. // If there are no fields, the start is the same as the end.
  4901. if (!RL.getFieldCount())
  4902. InstanceStart = InstanceSize;
  4903. else
  4904. InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
  4905. }
  4906. void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
  4907. std::string ClassName = ID->getObjCRuntimeNameAsString();
  4908. if (!ObjCEmptyCacheVar) {
  4909. ObjCEmptyCacheVar = new llvm::GlobalVariable(
  4910. CGM.getModule(),
  4911. ObjCTypes.CacheTy,
  4912. false,
  4913. llvm::GlobalValue::ExternalLinkage,
  4914. nullptr,
  4915. "_objc_empty_cache");
  4916. // Make this entry NULL for any iOS device target, any iOS simulator target,
  4917. // OS X with deployment target 10.9 or later.
  4918. const llvm::Triple &Triple = CGM.getTarget().getTriple();
  4919. if (Triple.isiOS() || (Triple.isMacOSX() && !Triple.isMacOSXVersionLT(10, 9)))
  4920. // This entry will be null.
  4921. ObjCEmptyVtableVar = nullptr;
  4922. else
  4923. ObjCEmptyVtableVar = new llvm::GlobalVariable(
  4924. CGM.getModule(),
  4925. ObjCTypes.ImpnfABITy,
  4926. false,
  4927. llvm::GlobalValue::ExternalLinkage,
  4928. nullptr,
  4929. "_objc_empty_vtable");
  4930. }
  4931. assert(ID->getClassInterface() &&
  4932. "CGObjCNonFragileABIMac::GenerateClass - class is 0");
  4933. // FIXME: Is this correct (that meta class size is never computed)?
  4934. uint32_t InstanceStart =
  4935. CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
  4936. uint32_t InstanceSize = InstanceStart;
  4937. uint32_t flags = NonFragileABI_Class_Meta;
  4938. llvm::SmallString<64> ObjCMetaClassName(getMetaclassSymbolPrefix());
  4939. llvm::SmallString<64> ObjCClassName(getClassSymbolPrefix());
  4940. llvm::SmallString<64> TClassName;
  4941. llvm::GlobalVariable *SuperClassGV, *IsAGV;
  4942. // Build the flags for the metaclass.
  4943. bool classIsHidden =
  4944. ID->getClassInterface()->getVisibility() == HiddenVisibility;
  4945. if (classIsHidden)
  4946. flags |= NonFragileABI_Class_Hidden;
  4947. // FIXME: why is this flag set on the metaclass?
  4948. // ObjC metaclasses have no fields and don't really get constructed.
  4949. if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
  4950. flags |= NonFragileABI_Class_HasCXXStructors;
  4951. if (!ID->hasNonZeroConstructors())
  4952. flags |= NonFragileABI_Class_HasCXXDestructorOnly;
  4953. }
  4954. if (!ID->getClassInterface()->getSuperClass()) {
  4955. // class is root
  4956. flags |= NonFragileABI_Class_Root;
  4957. TClassName = ObjCClassName;
  4958. TClassName += ClassName;
  4959. SuperClassGV = GetClassGlobal(TClassName.str(),
  4960. ID->getClassInterface()->isWeakImported());
  4961. TClassName = ObjCMetaClassName;
  4962. TClassName += ClassName;
  4963. IsAGV = GetClassGlobal(TClassName.str(),
  4964. ID->getClassInterface()->isWeakImported());
  4965. } else {
  4966. // Has a root. Current class is not a root.
  4967. const ObjCInterfaceDecl *Root = ID->getClassInterface();
  4968. while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
  4969. Root = Super;
  4970. TClassName = ObjCMetaClassName ;
  4971. TClassName += Root->getObjCRuntimeNameAsString();
  4972. IsAGV = GetClassGlobal(TClassName.str(),
  4973. Root->isWeakImported());
  4974. // work on super class metadata symbol.
  4975. TClassName = ObjCMetaClassName;
  4976. TClassName += ID->getClassInterface()->getSuperClass()->getObjCRuntimeNameAsString();
  4977. SuperClassGV = GetClassGlobal(
  4978. TClassName.str(),
  4979. ID->getClassInterface()->getSuperClass()->isWeakImported());
  4980. }
  4981. llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
  4982. InstanceStart,
  4983. InstanceSize,ID);
  4984. TClassName = ObjCMetaClassName;
  4985. TClassName += ClassName;
  4986. llvm::GlobalVariable *MetaTClass = BuildClassMetaData(
  4987. TClassName.str(), IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden,
  4988. ID->getClassInterface()->isWeakImported());
  4989. DefinedMetaClasses.push_back(MetaTClass);
  4990. // Metadata for the class
  4991. flags = 0;
  4992. if (classIsHidden)
  4993. flags |= NonFragileABI_Class_Hidden;
  4994. if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
  4995. flags |= NonFragileABI_Class_HasCXXStructors;
  4996. // Set a flag to enable a runtime optimization when a class has
  4997. // fields that require destruction but which don't require
  4998. // anything except zero-initialization during construction. This
  4999. // is most notably true of __strong and __weak types, but you can
  5000. // also imagine there being C++ types with non-trivial default
  5001. // constructors that merely set all fields to null.
  5002. if (!ID->hasNonZeroConstructors())
  5003. flags |= NonFragileABI_Class_HasCXXDestructorOnly;
  5004. }
  5005. if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
  5006. flags |= NonFragileABI_Class_Exception;
  5007. if (!ID->getClassInterface()->getSuperClass()) {
  5008. flags |= NonFragileABI_Class_Root;
  5009. SuperClassGV = nullptr;
  5010. } else {
  5011. // Has a root. Current class is not a root.
  5012. TClassName = ObjCClassName;
  5013. TClassName += ID->getClassInterface()->getSuperClass()->getObjCRuntimeNameAsString();
  5014. SuperClassGV = GetClassGlobal(
  5015. TClassName.str(),
  5016. ID->getClassInterface()->getSuperClass()->isWeakImported());
  5017. }
  5018. GetClassSizeInfo(ID, InstanceStart, InstanceSize);
  5019. CLASS_RO_GV = BuildClassRoTInitializer(flags,
  5020. InstanceStart,
  5021. InstanceSize,
  5022. ID);
  5023. TClassName = ObjCClassName;
  5024. TClassName += ClassName;
  5025. llvm::GlobalVariable *ClassMD =
  5026. BuildClassMetaData(TClassName.str(), MetaTClass, SuperClassGV, CLASS_RO_GV,
  5027. classIsHidden,
  5028. ID->getClassInterface()->isWeakImported());
  5029. DefinedClasses.push_back(ClassMD);
  5030. ImplementedClasses.push_back(ID->getClassInterface());
  5031. // Determine if this class is also "non-lazy".
  5032. if (ImplementationIsNonLazy(ID))
  5033. DefinedNonLazyClasses.push_back(ClassMD);
  5034. // Force the definition of the EHType if necessary.
  5035. if (flags & NonFragileABI_Class_Exception)
  5036. GetInterfaceEHType(ID->getClassInterface(), true);
  5037. // Make sure method definition entries are all clear for next implementation.
  5038. MethodDefinitions.clear();
  5039. }
  5040. /// GenerateProtocolRef - This routine is called to generate code for
  5041. /// a protocol reference expression; as in:
  5042. /// @code
  5043. /// @protocol(Proto1);
  5044. /// @endcode
  5045. /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
  5046. /// which will hold address of the protocol meta-data.
  5047. ///
  5048. llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
  5049. const ObjCProtocolDecl *PD) {
  5050. // This routine is called for @protocol only. So, we must build definition
  5051. // of protocol's meta-data (not a reference to it!)
  5052. //
  5053. llvm::Constant *Init =
  5054. llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
  5055. ObjCTypes.getExternalProtocolPtrTy());
  5056. std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
  5057. ProtocolName += PD->getObjCRuntimeNameAsString();
  5058. llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
  5059. if (PTGV)
  5060. return CGF.Builder.CreateLoad(PTGV);
  5061. PTGV = new llvm::GlobalVariable(
  5062. CGM.getModule(),
  5063. Init->getType(), false,
  5064. llvm::GlobalValue::WeakAnyLinkage,
  5065. Init,
  5066. ProtocolName);
  5067. PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
  5068. PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5069. CGM.addCompilerUsedGlobal(PTGV);
  5070. return CGF.Builder.CreateLoad(PTGV);
  5071. }
  5072. /// GenerateCategory - Build metadata for a category implementation.
  5073. /// struct _category_t {
  5074. /// const char * const name;
  5075. /// struct _class_t *const cls;
  5076. /// const struct _method_list_t * const instance_methods;
  5077. /// const struct _method_list_t * const class_methods;
  5078. /// const struct _protocol_list_t * const protocols;
  5079. /// const struct _prop_list_t * const properties;
  5080. /// }
  5081. ///
  5082. void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
  5083. const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
  5084. const char *Prefix = "\01l_OBJC_$_CATEGORY_";
  5085. llvm::SmallString<64> ExtCatName(Prefix);
  5086. ExtCatName += Interface->getObjCRuntimeNameAsString();
  5087. ExtCatName += "_$_";
  5088. ExtCatName += OCD->getNameAsString();
  5089. llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
  5090. ExtClassName += Interface->getObjCRuntimeNameAsString();
  5091. llvm::Constant *Values[6];
  5092. Values[0] = GetClassName(OCD->getIdentifier()->getName());
  5093. // meta-class entry symbol
  5094. llvm::GlobalVariable *ClassGV =
  5095. GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
  5096. Values[1] = ClassGV;
  5097. std::vector<llvm::Constant*> Methods;
  5098. llvm::SmallString<64> MethodListName(Prefix);
  5099. MethodListName += "INSTANCE_METHODS_";
  5100. MethodListName += Interface->getObjCRuntimeNameAsString();
  5101. MethodListName += "_$_";
  5102. MethodListName += OCD->getName();
  5103. for (const auto *I : OCD->instance_methods())
  5104. // Instance methods should always be defined.
  5105. Methods.push_back(GetMethodConstant(I));
  5106. Values[2] = EmitMethodList(MethodListName.str(),
  5107. "__DATA, __objc_const",
  5108. Methods);
  5109. MethodListName = Prefix;
  5110. MethodListName += "CLASS_METHODS_";
  5111. MethodListName += Interface->getObjCRuntimeNameAsString();
  5112. MethodListName += "_$_";
  5113. MethodListName += OCD->getNameAsString();
  5114. Methods.clear();
  5115. for (const auto *I : OCD->class_methods())
  5116. // Class methods should always be defined.
  5117. Methods.push_back(GetMethodConstant(I));
  5118. Values[3] = EmitMethodList(MethodListName.str(),
  5119. "__DATA, __objc_const",
  5120. Methods);
  5121. const ObjCCategoryDecl *Category =
  5122. Interface->FindCategoryDeclaration(OCD->getIdentifier());
  5123. if (Category) {
  5124. SmallString<256> ExtName;
  5125. llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
  5126. << OCD->getName();
  5127. Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
  5128. + Interface->getObjCRuntimeNameAsString() + "_$_"
  5129. + Category->getName(),
  5130. Category->protocol_begin(),
  5131. Category->protocol_end());
  5132. Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
  5133. OCD, Category, ObjCTypes);
  5134. } else {
  5135. Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
  5136. Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
  5137. }
  5138. llvm::Constant *Init =
  5139. llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
  5140. Values);
  5141. llvm::GlobalVariable *GCATV
  5142. = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
  5143. false,
  5144. llvm::GlobalValue::PrivateLinkage,
  5145. Init,
  5146. ExtCatName.str());
  5147. GCATV->setAlignment(
  5148. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
  5149. GCATV->setSection("__DATA, __objc_const");
  5150. CGM.addCompilerUsedGlobal(GCATV);
  5151. DefinedCategories.push_back(GCATV);
  5152. // Determine if this category is also "non-lazy".
  5153. if (ImplementationIsNonLazy(OCD))
  5154. DefinedNonLazyCategories.push_back(GCATV);
  5155. // method definition entries must be clear for next implementation.
  5156. MethodDefinitions.clear();
  5157. }
  5158. /// GetMethodConstant - Return a struct objc_method constant for the
  5159. /// given method if it has been defined. The result is null if the
  5160. /// method has not been defined. The return value has type MethodPtrTy.
  5161. llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
  5162. const ObjCMethodDecl *MD) {
  5163. llvm::Function *Fn = GetMethodDefinition(MD);
  5164. if (!Fn)
  5165. return nullptr;
  5166. llvm::Constant *Method[] = {
  5167. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  5168. ObjCTypes.SelectorPtrTy),
  5169. GetMethodVarType(MD),
  5170. llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
  5171. };
  5172. return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
  5173. }
  5174. /// EmitMethodList - Build meta-data for method declarations
  5175. /// struct _method_list_t {
  5176. /// uint32_t entsize; // sizeof(struct _objc_method)
  5177. /// uint32_t method_count;
  5178. /// struct _objc_method method_list[method_count];
  5179. /// }
  5180. ///
  5181. llvm::Constant *
  5182. CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
  5183. const char *Section,
  5184. ArrayRef<llvm::Constant*> Methods) {
  5185. // Return null for empty list.
  5186. if (Methods.empty())
  5187. return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
  5188. llvm::Constant *Values[3];
  5189. // sizeof(struct _objc_method)
  5190. unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
  5191. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  5192. // method_count
  5193. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
  5194. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
  5195. Methods.size());
  5196. Values[2] = llvm::ConstantArray::get(AT, Methods);
  5197. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  5198. llvm::GlobalVariable *GV =
  5199. new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  5200. llvm::GlobalValue::PrivateLinkage, Init, Name);
  5201. GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
  5202. GV->setSection(Section);
  5203. CGM.addCompilerUsedGlobal(GV);
  5204. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
  5205. }
  5206. /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
  5207. /// the given ivar.
  5208. llvm::GlobalVariable *
  5209. CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
  5210. const ObjCIvarDecl *Ivar) {
  5211. const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
  5212. llvm::SmallString<64> Name("OBJC_IVAR_$_");
  5213. Name += Container->getObjCRuntimeNameAsString();
  5214. Name += ".";
  5215. Name += Ivar->getName();
  5216. llvm::GlobalVariable *IvarOffsetGV =
  5217. CGM.getModule().getGlobalVariable(Name);
  5218. if (!IvarOffsetGV)
  5219. IvarOffsetGV = new llvm::GlobalVariable(
  5220. CGM.getModule(), ObjCTypes.IvarOffsetVarTy, false,
  5221. llvm::GlobalValue::ExternalLinkage, nullptr, Name.str());
  5222. return IvarOffsetGV;
  5223. }
  5224. llvm::Constant *
  5225. CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
  5226. const ObjCIvarDecl *Ivar,
  5227. unsigned long int Offset) {
  5228. llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
  5229. IvarOffsetGV->setInitializer(
  5230. llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
  5231. IvarOffsetGV->setAlignment(
  5232. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
  5233. // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
  5234. // well (i.e., in ObjCIvarOffsetVariable).
  5235. if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
  5236. Ivar->getAccessControl() == ObjCIvarDecl::Package ||
  5237. ID->getVisibility() == HiddenVisibility)
  5238. IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5239. else
  5240. IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  5241. IvarOffsetGV->setSection("__DATA, __objc_ivar");
  5242. return IvarOffsetGV;
  5243. }
  5244. /// EmitIvarList - Emit the ivar list for the given
  5245. /// implementation. The return value has type
  5246. /// IvarListnfABIPtrTy.
  5247. /// struct _ivar_t {
  5248. /// unsigned [long] int *offset; // pointer to ivar offset location
  5249. /// char *name;
  5250. /// char *type;
  5251. /// uint32_t alignment;
  5252. /// uint32_t size;
  5253. /// }
  5254. /// struct _ivar_list_t {
  5255. /// uint32 entsize; // sizeof(struct _ivar_t)
  5256. /// uint32 count;
  5257. /// struct _iver_t list[count];
  5258. /// }
  5259. ///
  5260. llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
  5261. const ObjCImplementationDecl *ID) {
  5262. std::vector<llvm::Constant*> Ivars;
  5263. const ObjCInterfaceDecl *OID = ID->getClassInterface();
  5264. assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
  5265. // FIXME. Consolidate this with similar code in GenerateClass.
  5266. for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
  5267. IVD; IVD = IVD->getNextIvar()) {
  5268. // Ignore unnamed bit-fields.
  5269. if (!IVD->getDeclName())
  5270. continue;
  5271. llvm::Constant *Ivar[5];
  5272. Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
  5273. ComputeIvarBaseOffset(CGM, ID, IVD));
  5274. Ivar[1] = GetMethodVarName(IVD->getIdentifier());
  5275. Ivar[2] = GetMethodVarType(IVD);
  5276. llvm::Type *FieldTy =
  5277. CGM.getTypes().ConvertTypeForMem(IVD->getType());
  5278. unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
  5279. unsigned Align = CGM.getContext().getPreferredTypeAlign(
  5280. IVD->getType().getTypePtr()) >> 3;
  5281. Align = llvm::Log2_32(Align);
  5282. Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
  5283. // NOTE. Size of a bitfield does not match gcc's, because of the
  5284. // way bitfields are treated special in each. But I am told that
  5285. // 'size' for bitfield ivars is ignored by the runtime so it does
  5286. // not matter. If it matters, there is enough info to get the
  5287. // bitfield right!
  5288. Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  5289. Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
  5290. }
  5291. // Return null for empty list.
  5292. if (Ivars.empty())
  5293. return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
  5294. llvm::Constant *Values[3];
  5295. unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
  5296. Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  5297. Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
  5298. llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
  5299. Ivars.size());
  5300. Values[2] = llvm::ConstantArray::get(AT, Ivars);
  5301. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  5302. const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
  5303. llvm::GlobalVariable *GV =
  5304. new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  5305. llvm::GlobalValue::PrivateLinkage,
  5306. Init,
  5307. Prefix + OID->getObjCRuntimeNameAsString());
  5308. GV->setAlignment(
  5309. CGM.getDataLayout().getABITypeAlignment(Init->getType()));
  5310. GV->setSection("__DATA, __objc_const");
  5311. CGM.addCompilerUsedGlobal(GV);
  5312. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
  5313. }
  5314. llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
  5315. const ObjCProtocolDecl *PD) {
  5316. llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
  5317. if (!Entry) {
  5318. // We use the initializer as a marker of whether this is a forward
  5319. // reference or not. At module finalization we add the empty
  5320. // contents for protocols which were referenced but never defined.
  5321. Entry =
  5322. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
  5323. false, llvm::GlobalValue::ExternalLinkage,
  5324. nullptr,
  5325. "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
  5326. Entry->setSection("__DATA,__datacoal_nt,coalesced");
  5327. }
  5328. return Entry;
  5329. }
  5330. /// GetOrEmitProtocol - Generate the protocol meta-data:
  5331. /// @code
  5332. /// struct _protocol_t {
  5333. /// id isa; // NULL
  5334. /// const char * const protocol_name;
  5335. /// const struct _protocol_list_t * protocol_list; // super protocols
  5336. /// const struct method_list_t * const instance_methods;
  5337. /// const struct method_list_t * const class_methods;
  5338. /// const struct method_list_t *optionalInstanceMethods;
  5339. /// const struct method_list_t *optionalClassMethods;
  5340. /// const struct _prop_list_t * properties;
  5341. /// const uint32_t size; // sizeof(struct _protocol_t)
  5342. /// const uint32_t flags; // = 0
  5343. /// const char ** extendedMethodTypes;
  5344. /// const char *demangledName;
  5345. /// }
  5346. /// @endcode
  5347. ///
  5348. llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
  5349. const ObjCProtocolDecl *PD) {
  5350. llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
  5351. // Early exit if a defining object has already been generated.
  5352. if (Entry && Entry->hasInitializer())
  5353. return Entry;
  5354. // Use the protocol definition, if there is one.
  5355. if (const ObjCProtocolDecl *Def = PD->getDefinition())
  5356. PD = Def;
  5357. // Construct method lists.
  5358. std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
  5359. std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
  5360. std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
  5361. for (const auto *MD : PD->instance_methods()) {
  5362. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  5363. if (!C)
  5364. return GetOrEmitProtocolRef(PD);
  5365. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  5366. OptInstanceMethods.push_back(C);
  5367. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  5368. } else {
  5369. InstanceMethods.push_back(C);
  5370. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  5371. }
  5372. }
  5373. for (const auto *MD : PD->class_methods()) {
  5374. llvm::Constant *C = GetMethodDescriptionConstant(MD);
  5375. if (!C)
  5376. return GetOrEmitProtocolRef(PD);
  5377. if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
  5378. OptClassMethods.push_back(C);
  5379. OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
  5380. } else {
  5381. ClassMethods.push_back(C);
  5382. MethodTypesExt.push_back(GetMethodVarType(MD, true));
  5383. }
  5384. }
  5385. MethodTypesExt.insert(MethodTypesExt.end(),
  5386. OptMethodTypesExt.begin(), OptMethodTypesExt.end());
  5387. llvm::Constant *Values[12];
  5388. // isa is NULL
  5389. Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
  5390. Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
  5391. Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
  5392. PD->protocol_begin(),
  5393. PD->protocol_end());
  5394. Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
  5395. + PD->getObjCRuntimeNameAsString(),
  5396. "__DATA, __objc_const",
  5397. InstanceMethods);
  5398. Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
  5399. + PD->getObjCRuntimeNameAsString(),
  5400. "__DATA, __objc_const",
  5401. ClassMethods);
  5402. Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
  5403. + PD->getObjCRuntimeNameAsString(),
  5404. "__DATA, __objc_const",
  5405. OptInstanceMethods);
  5406. Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
  5407. + PD->getObjCRuntimeNameAsString(),
  5408. "__DATA, __objc_const",
  5409. OptClassMethods);
  5410. Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
  5411. nullptr, PD, ObjCTypes);
  5412. uint32_t Size =
  5413. CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
  5414. Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
  5415. Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
  5416. Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
  5417. + PD->getObjCRuntimeNameAsString(),
  5418. MethodTypesExt, ObjCTypes);
  5419. // const char *demangledName;
  5420. Values[11] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  5421. llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
  5422. Values);
  5423. if (Entry) {
  5424. // Already created, fix the linkage and update the initializer.
  5425. Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
  5426. Entry->setInitializer(Init);
  5427. } else {
  5428. Entry =
  5429. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
  5430. false, llvm::GlobalValue::WeakAnyLinkage, Init,
  5431. "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
  5432. Entry->setAlignment(
  5433. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
  5434. Entry->setSection("__DATA,__datacoal_nt,coalesced");
  5435. Protocols[PD->getIdentifier()] = Entry;
  5436. }
  5437. Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5438. CGM.addCompilerUsedGlobal(Entry);
  5439. // Use this protocol meta-data to build protocol list table in section
  5440. // __DATA, __objc_protolist
  5441. llvm::GlobalVariable *PTGV =
  5442. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
  5443. false, llvm::GlobalValue::WeakAnyLinkage, Entry,
  5444. "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
  5445. PTGV->setAlignment(
  5446. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
  5447. PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
  5448. PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5449. CGM.addCompilerUsedGlobal(PTGV);
  5450. return Entry;
  5451. }
  5452. /// EmitProtocolList - Generate protocol list meta-data:
  5453. /// @code
  5454. /// struct _protocol_list_t {
  5455. /// long protocol_count; // Note, this is 32/64 bit
  5456. /// struct _protocol_t[protocol_count];
  5457. /// }
  5458. /// @endcode
  5459. ///
  5460. llvm::Constant *
  5461. CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
  5462. ObjCProtocolDecl::protocol_iterator begin,
  5463. ObjCProtocolDecl::protocol_iterator end) {
  5464. SmallVector<llvm::Constant *, 16> ProtocolRefs;
  5465. // Just return null for empty protocol lists
  5466. if (begin == end)
  5467. return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
  5468. // FIXME: We shouldn't need to do this lookup here, should we?
  5469. SmallString<256> TmpName;
  5470. Name.toVector(TmpName);
  5471. llvm::GlobalVariable *GV =
  5472. CGM.getModule().getGlobalVariable(TmpName.str(), true);
  5473. if (GV)
  5474. return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
  5475. for (; begin != end; ++begin)
  5476. ProtocolRefs.push_back(GetProtocolRef(*begin)); // Implemented???
  5477. // This list is null terminated.
  5478. ProtocolRefs.push_back(llvm::Constant::getNullValue(
  5479. ObjCTypes.ProtocolnfABIPtrTy));
  5480. llvm::Constant *Values[2];
  5481. Values[0] =
  5482. llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
  5483. Values[1] =
  5484. llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
  5485. ProtocolRefs.size()),
  5486. ProtocolRefs);
  5487. llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
  5488. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
  5489. llvm::GlobalValue::PrivateLinkage,
  5490. Init, Name);
  5491. GV->setSection("__DATA, __objc_const");
  5492. GV->setAlignment(
  5493. CGM.getDataLayout().getABITypeAlignment(Init->getType()));
  5494. CGM.addCompilerUsedGlobal(GV);
  5495. return llvm::ConstantExpr::getBitCast(GV,
  5496. ObjCTypes.ProtocolListnfABIPtrTy);
  5497. }
  5498. /// GetMethodDescriptionConstant - This routine build following meta-data:
  5499. /// struct _objc_method {
  5500. /// SEL _cmd;
  5501. /// char *method_type;
  5502. /// char *_imp;
  5503. /// }
  5504. llvm::Constant *
  5505. CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
  5506. llvm::Constant *Desc[3];
  5507. Desc[0] =
  5508. llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
  5509. ObjCTypes.SelectorPtrTy);
  5510. Desc[1] = GetMethodVarType(MD);
  5511. if (!Desc[1])
  5512. return nullptr;
  5513. // Protocol methods have no implementation. So, this entry is always NULL.
  5514. Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
  5515. return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
  5516. }
  5517. /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
  5518. /// This code gen. amounts to generating code for:
  5519. /// @code
  5520. /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
  5521. /// @encode
  5522. ///
  5523. LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
  5524. CodeGen::CodeGenFunction &CGF,
  5525. QualType ObjectTy,
  5526. llvm::Value *BaseValue,
  5527. const ObjCIvarDecl *Ivar,
  5528. unsigned CVRQualifiers) {
  5529. ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
  5530. llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
  5531. return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
  5532. Offset);
  5533. }
  5534. llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
  5535. CodeGen::CodeGenFunction &CGF,
  5536. const ObjCInterfaceDecl *Interface,
  5537. const ObjCIvarDecl *Ivar) {
  5538. llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
  5539. IvarOffsetValue = CGF.Builder.CreateLoad(IvarOffsetValue, "ivar");
  5540. if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
  5541. cast<llvm::LoadInst>(IvarOffsetValue)
  5542. ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
  5543. llvm::MDNode::get(VMContext, None));
  5544. // This could be 32bit int or 64bit integer depending on the architecture.
  5545. // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
  5546. // as this is what caller always expectes.
  5547. if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
  5548. IvarOffsetValue = CGF.Builder.CreateIntCast(
  5549. IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
  5550. return IvarOffsetValue;
  5551. }
  5552. static void appendSelectorForMessageRefTable(std::string &buffer,
  5553. Selector selector) {
  5554. if (selector.isUnarySelector()) {
  5555. buffer += selector.getNameForSlot(0);
  5556. return;
  5557. }
  5558. for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
  5559. buffer += selector.getNameForSlot(i);
  5560. buffer += '_';
  5561. }
  5562. }
  5563. /// Emit a "v-table" message send. We emit a weak hidden-visibility
  5564. /// struct, initially containing the selector pointer and a pointer to
  5565. /// a "fixup" variant of the appropriate objc_msgSend. To call, we
  5566. /// load and call the function pointer, passing the address of the
  5567. /// struct as the second parameter. The runtime determines whether
  5568. /// the selector is currently emitted using vtable dispatch; if so, it
  5569. /// substitutes a stub function which simply tail-calls through the
  5570. /// appropriate vtable slot, and if not, it substitues a stub function
  5571. /// which tail-calls objc_msgSend. Both stubs adjust the selector
  5572. /// argument to correctly point to the selector.
  5573. RValue
  5574. CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
  5575. ReturnValueSlot returnSlot,
  5576. QualType resultType,
  5577. Selector selector,
  5578. llvm::Value *arg0,
  5579. QualType arg0Type,
  5580. bool isSuper,
  5581. const CallArgList &formalArgs,
  5582. const ObjCMethodDecl *method) {
  5583. // Compute the actual arguments.
  5584. CallArgList args;
  5585. // First argument: the receiver / super-call structure.
  5586. if (!isSuper)
  5587. arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
  5588. args.add(RValue::get(arg0), arg0Type);
  5589. // Second argument: a pointer to the message ref structure. Leave
  5590. // the actual argument value blank for now.
  5591. args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
  5592. args.insert(args.end(), formalArgs.begin(), formalArgs.end());
  5593. MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
  5594. NullReturnState nullReturn;
  5595. // Find the function to call and the mangled name for the message
  5596. // ref structure. Using a different mangled name wouldn't actually
  5597. // be a problem; it would just be a waste.
  5598. //
  5599. // The runtime currently never uses vtable dispatch for anything
  5600. // except normal, non-super message-sends.
  5601. // FIXME: don't use this for that.
  5602. llvm::Constant *fn = nullptr;
  5603. std::string messageRefName("\01l_");
  5604. if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
  5605. if (isSuper) {
  5606. fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
  5607. messageRefName += "objc_msgSendSuper2_stret_fixup";
  5608. } else {
  5609. nullReturn.init(CGF, arg0);
  5610. fn = ObjCTypes.getMessageSendStretFixupFn();
  5611. messageRefName += "objc_msgSend_stret_fixup";
  5612. }
  5613. } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
  5614. fn = ObjCTypes.getMessageSendFpretFixupFn();
  5615. messageRefName += "objc_msgSend_fpret_fixup";
  5616. } else {
  5617. if (isSuper) {
  5618. fn = ObjCTypes.getMessageSendSuper2FixupFn();
  5619. messageRefName += "objc_msgSendSuper2_fixup";
  5620. } else {
  5621. fn = ObjCTypes.getMessageSendFixupFn();
  5622. messageRefName += "objc_msgSend_fixup";
  5623. }
  5624. }
  5625. assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
  5626. messageRefName += '_';
  5627. // Append the selector name, except use underscores anywhere we
  5628. // would have used colons.
  5629. appendSelectorForMessageRefTable(messageRefName, selector);
  5630. llvm::GlobalVariable *messageRef
  5631. = CGM.getModule().getGlobalVariable(messageRefName);
  5632. if (!messageRef) {
  5633. // Build the message ref structure.
  5634. llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
  5635. llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
  5636. messageRef = new llvm::GlobalVariable(CGM.getModule(),
  5637. init->getType(),
  5638. /*constant*/ false,
  5639. llvm::GlobalValue::WeakAnyLinkage,
  5640. init,
  5641. messageRefName);
  5642. messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
  5643. messageRef->setAlignment(16);
  5644. messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
  5645. }
  5646. bool requiresnullCheck = false;
  5647. if (CGM.getLangOpts().ObjCAutoRefCount && method)
  5648. for (const auto *ParamDecl : method->params()) {
  5649. if (ParamDecl->hasAttr<NSConsumedAttr>()) {
  5650. if (!nullReturn.NullBB)
  5651. nullReturn.init(CGF, arg0);
  5652. requiresnullCheck = true;
  5653. break;
  5654. }
  5655. }
  5656. llvm::Value *mref =
  5657. CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
  5658. // Update the message ref argument.
  5659. args[1].RV = RValue::get(mref);
  5660. // Load the function to call from the message ref table.
  5661. llvm::Value *callee =
  5662. CGF.Builder.CreateStructGEP(ObjCTypes.MessageRefTy, mref, 0);
  5663. callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
  5664. callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
  5665. RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
  5666. return nullReturn.complete(CGF, result, resultType, formalArgs,
  5667. requiresnullCheck ? method : nullptr);
  5668. }
  5669. /// Generate code for a message send expression in the nonfragile abi.
  5670. CodeGen::RValue
  5671. CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
  5672. ReturnValueSlot Return,
  5673. QualType ResultType,
  5674. Selector Sel,
  5675. llvm::Value *Receiver,
  5676. const CallArgList &CallArgs,
  5677. const ObjCInterfaceDecl *Class,
  5678. const ObjCMethodDecl *Method) {
  5679. return isVTableDispatchedSelector(Sel)
  5680. ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
  5681. Receiver, CGF.getContext().getObjCIdType(),
  5682. false, CallArgs, Method)
  5683. : EmitMessageSend(CGF, Return, ResultType,
  5684. EmitSelector(CGF, Sel),
  5685. Receiver, CGF.getContext().getObjCIdType(),
  5686. false, CallArgs, Method, ObjCTypes);
  5687. }
  5688. llvm::GlobalVariable *
  5689. CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name, bool Weak) {
  5690. llvm::GlobalValue::LinkageTypes L =
  5691. Weak ? llvm::GlobalValue::ExternalWeakLinkage
  5692. : llvm::GlobalValue::ExternalLinkage;
  5693. llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
  5694. if (!GV)
  5695. GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
  5696. false, L, nullptr, Name);
  5697. assert(GV->getLinkage() == L);
  5698. return GV;
  5699. }
  5700. llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
  5701. IdentifierInfo *II,
  5702. bool Weak,
  5703. const ObjCInterfaceDecl *ID) {
  5704. llvm::GlobalVariable *&Entry = ClassReferences[II];
  5705. if (!Entry) {
  5706. std::string ClassName(
  5707. getClassSymbolPrefix() +
  5708. (ID ? ID->getObjCRuntimeNameAsString() : II->getName()).str());
  5709. llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
  5710. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
  5711. false, llvm::GlobalValue::PrivateLinkage,
  5712. ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
  5713. Entry->setAlignment(
  5714. CGM.getDataLayout().getABITypeAlignment(
  5715. ObjCTypes.ClassnfABIPtrTy));
  5716. Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
  5717. CGM.addCompilerUsedGlobal(Entry);
  5718. }
  5719. return CGF.Builder.CreateLoad(Entry);
  5720. }
  5721. llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
  5722. const ObjCInterfaceDecl *ID) {
  5723. return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
  5724. }
  5725. llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
  5726. CodeGenFunction &CGF) {
  5727. IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
  5728. return EmitClassRefFromId(CGF, II, false, 0);
  5729. }
  5730. llvm::Value *
  5731. CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
  5732. const ObjCInterfaceDecl *ID) {
  5733. llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
  5734. if (!Entry) {
  5735. llvm::SmallString<64> ClassName(getClassSymbolPrefix());
  5736. ClassName += ID->getObjCRuntimeNameAsString();
  5737. llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
  5738. ID->isWeakImported());
  5739. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
  5740. false, llvm::GlobalValue::PrivateLinkage,
  5741. ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
  5742. Entry->setAlignment(
  5743. CGM.getDataLayout().getABITypeAlignment(
  5744. ObjCTypes.ClassnfABIPtrTy));
  5745. Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
  5746. CGM.addCompilerUsedGlobal(Entry);
  5747. }
  5748. return CGF.Builder.CreateLoad(Entry);
  5749. }
  5750. /// EmitMetaClassRef - Return a Value * of the address of _class_t
  5751. /// meta-data
  5752. ///
  5753. llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
  5754. const ObjCInterfaceDecl *ID,
  5755. bool Weak) {
  5756. llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
  5757. if (!Entry) {
  5758. llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
  5759. MetaClassName += ID->getObjCRuntimeNameAsString();
  5760. llvm::GlobalVariable *MetaClassGV =
  5761. GetClassGlobal(MetaClassName.str(), Weak);
  5762. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
  5763. false, llvm::GlobalValue::PrivateLinkage,
  5764. MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
  5765. Entry->setAlignment(
  5766. CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABIPtrTy));
  5767. Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
  5768. CGM.addCompilerUsedGlobal(Entry);
  5769. }
  5770. return CGF.Builder.CreateLoad(Entry);
  5771. }
  5772. /// GetClass - Return a reference to the class for the given interface
  5773. /// decl.
  5774. llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
  5775. const ObjCInterfaceDecl *ID) {
  5776. if (ID->isWeakImported()) {
  5777. llvm::SmallString<64> ClassName(getClassSymbolPrefix());
  5778. ClassName += ID->getObjCRuntimeNameAsString();
  5779. llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
  5780. (void)ClassGV;
  5781. assert(ClassGV->hasExternalWeakLinkage());
  5782. }
  5783. return EmitClassRef(CGF, ID);
  5784. }
  5785. /// Generates a message send where the super is the receiver. This is
  5786. /// a message send to self with special delivery semantics indicating
  5787. /// which class's method should be called.
  5788. CodeGen::RValue
  5789. CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
  5790. ReturnValueSlot Return,
  5791. QualType ResultType,
  5792. Selector Sel,
  5793. const ObjCInterfaceDecl *Class,
  5794. bool isCategoryImpl,
  5795. llvm::Value *Receiver,
  5796. bool IsClassMessage,
  5797. const CodeGen::CallArgList &CallArgs,
  5798. const ObjCMethodDecl *Method) {
  5799. // ...
  5800. // Create and init a super structure; this is a (receiver, class)
  5801. // pair we will pass to objc_msgSendSuper.
  5802. llvm::Value *ObjCSuper =
  5803. CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
  5804. llvm::Value *ReceiverAsObject =
  5805. CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
  5806. CGF.Builder.CreateStore(
  5807. ReceiverAsObject,
  5808. CGF.Builder.CreateStructGEP(ObjCTypes.SuperTy, ObjCSuper, 0));
  5809. // If this is a class message the metaclass is passed as the target.
  5810. llvm::Value *Target;
  5811. if (IsClassMessage)
  5812. Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
  5813. else
  5814. Target = EmitSuperClassRef(CGF, Class);
  5815. // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
  5816. // ObjCTypes types.
  5817. llvm::Type *ClassTy =
  5818. CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
  5819. Target = CGF.Builder.CreateBitCast(Target, ClassTy);
  5820. CGF.Builder.CreateStore(
  5821. Target, CGF.Builder.CreateStructGEP(ObjCTypes.SuperTy, ObjCSuper, 1));
  5822. return (isVTableDispatchedSelector(Sel))
  5823. ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
  5824. ObjCSuper, ObjCTypes.SuperPtrCTy,
  5825. true, CallArgs, Method)
  5826. : EmitMessageSend(CGF, Return, ResultType,
  5827. EmitSelector(CGF, Sel),
  5828. ObjCSuper, ObjCTypes.SuperPtrCTy,
  5829. true, CallArgs, Method, ObjCTypes);
  5830. }
  5831. llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
  5832. Selector Sel, bool lval) {
  5833. llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
  5834. if (!Entry) {
  5835. llvm::Constant *Casted =
  5836. llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
  5837. ObjCTypes.SelectorPtrTy);
  5838. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
  5839. false, llvm::GlobalValue::PrivateLinkage,
  5840. Casted, "OBJC_SELECTOR_REFERENCES_");
  5841. Entry->setExternallyInitialized(true);
  5842. Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
  5843. CGM.addCompilerUsedGlobal(Entry);
  5844. }
  5845. if (lval)
  5846. return Entry;
  5847. llvm::LoadInst* LI = CGF.Builder.CreateLoad(Entry);
  5848. LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
  5849. llvm::MDNode::get(VMContext, None));
  5850. return LI;
  5851. }
  5852. /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
  5853. /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
  5854. ///
  5855. void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
  5856. llvm::Value *src,
  5857. llvm::Value *dst,
  5858. llvm::Value *ivarOffset) {
  5859. llvm::Type * SrcTy = src->getType();
  5860. if (!isa<llvm::PointerType>(SrcTy)) {
  5861. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  5862. assert(Size <= 8 && "does not support size > 8");
  5863. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5864. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5865. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5866. }
  5867. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5868. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5869. llvm::Value *args[] = { src, dst, ivarOffset };
  5870. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
  5871. }
  5872. /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
  5873. /// objc_assign_strongCast (id src, id *dst)
  5874. ///
  5875. void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
  5876. CodeGen::CodeGenFunction &CGF,
  5877. llvm::Value *src, llvm::Value *dst) {
  5878. llvm::Type * SrcTy = src->getType();
  5879. if (!isa<llvm::PointerType>(SrcTy)) {
  5880. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  5881. assert(Size <= 8 && "does not support size > 8");
  5882. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5883. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5884. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5885. }
  5886. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5887. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5888. llvm::Value *args[] = { src, dst };
  5889. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
  5890. args, "weakassign");
  5891. }
  5892. void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
  5893. CodeGen::CodeGenFunction &CGF,
  5894. llvm::Value *DestPtr,
  5895. llvm::Value *SrcPtr,
  5896. llvm::Value *Size) {
  5897. SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
  5898. DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
  5899. llvm::Value *args[] = { DestPtr, SrcPtr, Size };
  5900. CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
  5901. }
  5902. /// EmitObjCWeakRead - Code gen for loading value of a __weak
  5903. /// object: objc_read_weak (id *src)
  5904. ///
  5905. llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
  5906. CodeGen::CodeGenFunction &CGF,
  5907. llvm::Value *AddrWeakObj) {
  5908. llvm::Type* DestTy =
  5909. cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
  5910. AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
  5911. llvm::Value *read_weak =
  5912. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
  5913. AddrWeakObj, "weakread");
  5914. read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
  5915. return read_weak;
  5916. }
  5917. /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
  5918. /// objc_assign_weak (id src, id *dst)
  5919. ///
  5920. void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
  5921. llvm::Value *src, llvm::Value *dst) {
  5922. llvm::Type * SrcTy = src->getType();
  5923. if (!isa<llvm::PointerType>(SrcTy)) {
  5924. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  5925. assert(Size <= 8 && "does not support size > 8");
  5926. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5927. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5928. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5929. }
  5930. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5931. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5932. llvm::Value *args[] = { src, dst };
  5933. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
  5934. args, "weakassign");
  5935. }
  5936. /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
  5937. /// objc_assign_global (id src, id *dst)
  5938. ///
  5939. void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
  5940. llvm::Value *src, llvm::Value *dst,
  5941. bool threadlocal) {
  5942. llvm::Type * SrcTy = src->getType();
  5943. if (!isa<llvm::PointerType>(SrcTy)) {
  5944. unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  5945. assert(Size <= 8 && "does not support size > 8");
  5946. src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
  5947. : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
  5948. src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
  5949. }
  5950. src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
  5951. dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
  5952. llvm::Value *args[] = { src, dst };
  5953. if (!threadlocal)
  5954. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
  5955. args, "globalassign");
  5956. else
  5957. CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
  5958. args, "threadlocalassign");
  5959. }
  5960. void
  5961. CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
  5962. const ObjCAtSynchronizedStmt &S) {
  5963. EmitAtSynchronizedStmt(CGF, S,
  5964. cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
  5965. cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
  5966. }
  5967. llvm::Constant *
  5968. CGObjCNonFragileABIMac::GetEHType(QualType T) {
  5969. // There's a particular fixed type info for 'id'.
  5970. if (T->isObjCIdType() ||
  5971. T->isObjCQualifiedIdType()) {
  5972. llvm::Constant *IDEHType =
  5973. CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
  5974. if (!IDEHType)
  5975. IDEHType =
  5976. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
  5977. false,
  5978. llvm::GlobalValue::ExternalLinkage,
  5979. nullptr, "OBJC_EHTYPE_id");
  5980. return IDEHType;
  5981. }
  5982. // All other types should be Objective-C interface pointer types.
  5983. const ObjCObjectPointerType *PT =
  5984. T->getAs<ObjCObjectPointerType>();
  5985. assert(PT && "Invalid @catch type.");
  5986. const ObjCInterfaceType *IT = PT->getInterfaceType();
  5987. assert(IT && "Invalid @catch type.");
  5988. return GetInterfaceEHType(IT->getDecl(), false);
  5989. }
  5990. void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
  5991. const ObjCAtTryStmt &S) {
  5992. EmitTryCatchStmt(CGF, S,
  5993. cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
  5994. cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
  5995. cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
  5996. }
  5997. /// EmitThrowStmt - Generate code for a throw statement.
  5998. void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
  5999. const ObjCAtThrowStmt &S,
  6000. bool ClearInsertionPoint) {
  6001. if (const Expr *ThrowExpr = S.getThrowExpr()) {
  6002. llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
  6003. Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
  6004. CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
  6005. .setDoesNotReturn();
  6006. } else {
  6007. CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
  6008. .setDoesNotReturn();
  6009. }
  6010. CGF.Builder.CreateUnreachable();
  6011. if (ClearInsertionPoint)
  6012. CGF.Builder.ClearInsertionPoint();
  6013. }
  6014. llvm::Constant *
  6015. CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
  6016. bool ForDefinition) {
  6017. llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
  6018. // If we don't need a definition, return the entry if found or check
  6019. // if we use an external reference.
  6020. if (!ForDefinition) {
  6021. if (Entry)
  6022. return Entry;
  6023. // If this type (or a super class) has the __objc_exception__
  6024. // attribute, emit an external reference.
  6025. if (hasObjCExceptionAttribute(CGM.getContext(), ID))
  6026. return Entry =
  6027. new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
  6028. llvm::GlobalValue::ExternalLinkage,
  6029. nullptr,
  6030. ("OBJC_EHTYPE_$_" +
  6031. ID->getObjCRuntimeNameAsString()));
  6032. }
  6033. // Otherwise we need to either make a new entry or fill in the
  6034. // initializer.
  6035. assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
  6036. llvm::SmallString<64> ClassName(getClassSymbolPrefix());
  6037. ClassName += ID->getObjCRuntimeNameAsString();
  6038. std::string VTableName = "objc_ehtype_vtable";
  6039. llvm::GlobalVariable *VTableGV =
  6040. CGM.getModule().getGlobalVariable(VTableName);
  6041. if (!VTableGV)
  6042. VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
  6043. false,
  6044. llvm::GlobalValue::ExternalLinkage,
  6045. nullptr, VTableName);
  6046. llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
  6047. llvm::Constant *Values[] = {
  6048. llvm::ConstantExpr::getGetElementPtr(VTableGV->getValueType(), VTableGV,
  6049. VTableIdx),
  6050. GetClassName(ID->getObjCRuntimeNameAsString()),
  6051. GetClassGlobal(ClassName.str())};
  6052. llvm::Constant *Init =
  6053. llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
  6054. llvm::GlobalValue::LinkageTypes L = ForDefinition
  6055. ? llvm::GlobalValue::ExternalLinkage
  6056. : llvm::GlobalValue::WeakAnyLinkage;
  6057. if (Entry) {
  6058. Entry->setInitializer(Init);
  6059. } else {
  6060. llvm::SmallString<64> EHTYPEName("OBJC_EHTYPE_$_");
  6061. EHTYPEName += ID->getObjCRuntimeNameAsString();
  6062. Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
  6063. L,
  6064. Init,
  6065. EHTYPEName.str());
  6066. }
  6067. assert(Entry->getLinkage() == L);
  6068. if (ID->getVisibility() == HiddenVisibility)
  6069. Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
  6070. Entry->setAlignment(CGM.getDataLayout().getABITypeAlignment(
  6071. ObjCTypes.EHTypeTy));
  6072. if (ForDefinition)
  6073. Entry->setSection("__DATA,__objc_const");
  6074. else
  6075. Entry->setSection("__DATA,__datacoal_nt,coalesced");
  6076. return Entry;
  6077. }
  6078. /* *** */
  6079. CodeGen::CGObjCRuntime *
  6080. CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
  6081. switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
  6082. case ObjCRuntime::FragileMacOSX:
  6083. return new CGObjCMac(CGM);
  6084. case ObjCRuntime::MacOSX:
  6085. case ObjCRuntime::iOS:
  6086. return new CGObjCNonFragileABIMac(CGM);
  6087. case ObjCRuntime::GNUstep:
  6088. case ObjCRuntime::GCC:
  6089. case ObjCRuntime::ObjFW:
  6090. llvm_unreachable("these runtimes are not Mac runtimes");
  6091. }
  6092. llvm_unreachable("bad runtime");
  6093. }
  6094. #endif // HLSL Change