RewriteModernObjC.cpp 289 KB

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