RewriteModernObjC.cpp 296 KB

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