CGObjCMac.cpp 304 KB

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