ASTWriter.cpp 246 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936
  1. //===- ASTWriter.cpp - AST File Writer ------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the ASTWriter class, which writes AST files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ASTWriter.h"
  14. #include "ASTCommon.h"
  15. #include "ASTReaderInternals.h"
  16. #include "MultiOnDiskHashTable.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/ASTUnresolvedSet.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclBase.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclContextInternals.h"
  24. #include "clang/AST/DeclFriend.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/DeclarationName.h"
  28. #include "clang/AST/Expr.h"
  29. #include "clang/AST/ExprCXX.h"
  30. #include "clang/AST/LambdaCapture.h"
  31. #include "clang/AST/NestedNameSpecifier.h"
  32. #include "clang/AST/RawCommentList.h"
  33. #include "clang/AST/TemplateName.h"
  34. #include "clang/AST/Type.h"
  35. #include "clang/AST/TypeLocVisitor.h"
  36. #include "clang/Basic/Diagnostic.h"
  37. #include "clang/Basic/DiagnosticOptions.h"
  38. #include "clang/Basic/FileManager.h"
  39. #include "clang/Basic/FileSystemOptions.h"
  40. #include "clang/Basic/IdentifierTable.h"
  41. #include "clang/Basic/LLVM.h"
  42. #include "clang/Basic/Lambda.h"
  43. #include "clang/Basic/LangOptions.h"
  44. #include "clang/Basic/MemoryBufferCache.h"
  45. #include "clang/Basic/Module.h"
  46. #include "clang/Basic/ObjCRuntime.h"
  47. #include "clang/Basic/OpenCLOptions.h"
  48. #include "clang/Basic/SourceLocation.h"
  49. #include "clang/Basic/SourceManager.h"
  50. #include "clang/Basic/SourceManagerInternals.h"
  51. #include "clang/Basic/Specifiers.h"
  52. #include "clang/Basic/TargetInfo.h"
  53. #include "clang/Basic/TargetOptions.h"
  54. #include "clang/Basic/Version.h"
  55. #include "clang/Lex/HeaderSearch.h"
  56. #include "clang/Lex/HeaderSearchOptions.h"
  57. #include "clang/Lex/MacroInfo.h"
  58. #include "clang/Lex/ModuleMap.h"
  59. #include "clang/Lex/PreprocessingRecord.h"
  60. #include "clang/Lex/Preprocessor.h"
  61. #include "clang/Lex/PreprocessorOptions.h"
  62. #include "clang/Lex/Token.h"
  63. #include "clang/Sema/IdentifierResolver.h"
  64. #include "clang/Sema/ObjCMethodList.h"
  65. #include "clang/Sema/Sema.h"
  66. #include "clang/Sema/Weak.h"
  67. #include "clang/Serialization/ASTReader.h"
  68. #include "clang/Serialization/Module.h"
  69. #include "clang/Serialization/ModuleFileExtension.h"
  70. #include "clang/Serialization/SerializationDiagnostic.h"
  71. #include "llvm/ADT/APFloat.h"
  72. #include "llvm/ADT/APInt.h"
  73. #include "llvm/ADT/APSInt.h"
  74. #include "llvm/ADT/ArrayRef.h"
  75. #include "llvm/ADT/DenseMap.h"
  76. #include "llvm/ADT/Hashing.h"
  77. #include "llvm/ADT/Optional.h"
  78. #include "llvm/ADT/PointerIntPair.h"
  79. #include "llvm/ADT/STLExtras.h"
  80. #include "llvm/ADT/ScopeExit.h"
  81. #include "llvm/ADT/SmallSet.h"
  82. #include "llvm/ADT/SmallString.h"
  83. #include "llvm/ADT/SmallVector.h"
  84. #include "llvm/ADT/StringMap.h"
  85. #include "llvm/ADT/StringRef.h"
  86. #include "llvm/Bitcode/BitCodes.h"
  87. #include "llvm/Bitcode/BitstreamWriter.h"
  88. #include "llvm/Support/Casting.h"
  89. #include "llvm/Support/Compression.h"
  90. #include "llvm/Support/DJB.h"
  91. #include "llvm/Support/Endian.h"
  92. #include "llvm/Support/EndianStream.h"
  93. #include "llvm/Support/Error.h"
  94. #include "llvm/Support/ErrorHandling.h"
  95. #include "llvm/Support/MemoryBuffer.h"
  96. #include "llvm/Support/OnDiskHashTable.h"
  97. #include "llvm/Support/Path.h"
  98. #include "llvm/Support/SHA1.h"
  99. #include "llvm/Support/VersionTuple.h"
  100. #include "llvm/Support/raw_ostream.h"
  101. #include <algorithm>
  102. #include <cassert>
  103. #include <cstdint>
  104. #include <cstdlib>
  105. #include <cstring>
  106. #include <ctime>
  107. #include <deque>
  108. #include <limits>
  109. #include <memory>
  110. #include <queue>
  111. #include <tuple>
  112. #include <utility>
  113. #include <vector>
  114. using namespace clang;
  115. using namespace clang::serialization;
  116. template <typename T, typename Allocator>
  117. static StringRef bytes(const std::vector<T, Allocator> &v) {
  118. if (v.empty()) return StringRef();
  119. return StringRef(reinterpret_cast<const char*>(&v[0]),
  120. sizeof(T) * v.size());
  121. }
  122. template <typename T>
  123. static StringRef bytes(const SmallVectorImpl<T> &v) {
  124. return StringRef(reinterpret_cast<const char*>(v.data()),
  125. sizeof(T) * v.size());
  126. }
  127. //===----------------------------------------------------------------------===//
  128. // Type serialization
  129. //===----------------------------------------------------------------------===//
  130. namespace clang {
  131. class ASTTypeWriter {
  132. ASTWriter &Writer;
  133. ASTRecordWriter Record;
  134. /// Type code that corresponds to the record generated.
  135. TypeCode Code = static_cast<TypeCode>(0);
  136. /// Abbreviation to use for the record, if any.
  137. unsigned AbbrevToUse = 0;
  138. public:
  139. ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
  140. : Writer(Writer), Record(Writer, Record) {}
  141. uint64_t Emit() {
  142. return Record.Emit(Code, AbbrevToUse);
  143. }
  144. void Visit(QualType T) {
  145. if (T.hasLocalNonFastQualifiers()) {
  146. Qualifiers Qs = T.getLocalQualifiers();
  147. Record.AddTypeRef(T.getLocalUnqualifiedType());
  148. Record.push_back(Qs.getAsOpaqueValue());
  149. Code = TYPE_EXT_QUAL;
  150. AbbrevToUse = Writer.TypeExtQualAbbrev;
  151. } else {
  152. switch (T->getTypeClass()) {
  153. // For all of the concrete, non-dependent types, call the
  154. // appropriate visitor function.
  155. #define TYPE(Class, Base) \
  156. case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
  157. #define ABSTRACT_TYPE(Class, Base)
  158. #include "clang/AST/TypeNodes.def"
  159. }
  160. }
  161. }
  162. void VisitArrayType(const ArrayType *T);
  163. void VisitFunctionType(const FunctionType *T);
  164. void VisitTagType(const TagType *T);
  165. #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
  166. #define ABSTRACT_TYPE(Class, Base)
  167. #include "clang/AST/TypeNodes.def"
  168. };
  169. } // namespace clang
  170. void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
  171. llvm_unreachable("Built-in types are never serialized");
  172. }
  173. void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
  174. Record.AddTypeRef(T->getElementType());
  175. Code = TYPE_COMPLEX;
  176. }
  177. void ASTTypeWriter::VisitPointerType(const PointerType *T) {
  178. Record.AddTypeRef(T->getPointeeType());
  179. Code = TYPE_POINTER;
  180. }
  181. void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
  182. Record.AddTypeRef(T->getOriginalType());
  183. Code = TYPE_DECAYED;
  184. }
  185. void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
  186. Record.AddTypeRef(T->getOriginalType());
  187. Record.AddTypeRef(T->getAdjustedType());
  188. Code = TYPE_ADJUSTED;
  189. }
  190. void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
  191. Record.AddTypeRef(T->getPointeeType());
  192. Code = TYPE_BLOCK_POINTER;
  193. }
  194. void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
  195. Record.AddTypeRef(T->getPointeeTypeAsWritten());
  196. Record.push_back(T->isSpelledAsLValue());
  197. Code = TYPE_LVALUE_REFERENCE;
  198. }
  199. void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
  200. Record.AddTypeRef(T->getPointeeTypeAsWritten());
  201. Code = TYPE_RVALUE_REFERENCE;
  202. }
  203. void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
  204. Record.AddTypeRef(T->getPointeeType());
  205. Record.AddTypeRef(QualType(T->getClass(), 0));
  206. Code = TYPE_MEMBER_POINTER;
  207. }
  208. void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
  209. Record.AddTypeRef(T->getElementType());
  210. Record.push_back(T->getSizeModifier()); // FIXME: stable values
  211. Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
  212. }
  213. void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
  214. VisitArrayType(T);
  215. Record.AddAPInt(T->getSize());
  216. Code = TYPE_CONSTANT_ARRAY;
  217. }
  218. void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
  219. VisitArrayType(T);
  220. Code = TYPE_INCOMPLETE_ARRAY;
  221. }
  222. void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
  223. VisitArrayType(T);
  224. Record.AddSourceLocation(T->getLBracketLoc());
  225. Record.AddSourceLocation(T->getRBracketLoc());
  226. Record.AddStmt(T->getSizeExpr());
  227. Code = TYPE_VARIABLE_ARRAY;
  228. }
  229. void ASTTypeWriter::VisitVectorType(const VectorType *T) {
  230. Record.AddTypeRef(T->getElementType());
  231. Record.push_back(T->getNumElements());
  232. Record.push_back(T->getVectorKind());
  233. Code = TYPE_VECTOR;
  234. }
  235. void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
  236. VisitVectorType(T);
  237. Code = TYPE_EXT_VECTOR;
  238. }
  239. void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
  240. Record.AddTypeRef(T->getReturnType());
  241. FunctionType::ExtInfo C = T->getExtInfo();
  242. Record.push_back(C.getNoReturn());
  243. Record.push_back(C.getHasRegParm());
  244. Record.push_back(C.getRegParm());
  245. // FIXME: need to stabilize encoding of calling convention...
  246. Record.push_back(C.getCC());
  247. Record.push_back(C.getProducesResult());
  248. Record.push_back(C.getNoCallerSavedRegs());
  249. Record.push_back(C.getNoCfCheck());
  250. if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
  251. AbbrevToUse = 0;
  252. }
  253. void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  254. VisitFunctionType(T);
  255. Code = TYPE_FUNCTION_NO_PROTO;
  256. }
  257. static void addExceptionSpec(const FunctionProtoType *T,
  258. ASTRecordWriter &Record) {
  259. Record.push_back(T->getExceptionSpecType());
  260. if (T->getExceptionSpecType() == EST_Dynamic) {
  261. Record.push_back(T->getNumExceptions());
  262. for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
  263. Record.AddTypeRef(T->getExceptionType(I));
  264. } else if (isComputedNoexcept(T->getExceptionSpecType())) {
  265. Record.AddStmt(T->getNoexceptExpr());
  266. } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
  267. Record.AddDeclRef(T->getExceptionSpecDecl());
  268. Record.AddDeclRef(T->getExceptionSpecTemplate());
  269. } else if (T->getExceptionSpecType() == EST_Unevaluated) {
  270. Record.AddDeclRef(T->getExceptionSpecDecl());
  271. }
  272. }
  273. void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
  274. VisitFunctionType(T);
  275. Record.push_back(T->isVariadic());
  276. Record.push_back(T->hasTrailingReturn());
  277. Record.push_back(T->getTypeQuals());
  278. Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
  279. addExceptionSpec(T, Record);
  280. Record.push_back(T->getNumParams());
  281. for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
  282. Record.AddTypeRef(T->getParamType(I));
  283. if (T->hasExtParameterInfos()) {
  284. for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
  285. Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
  286. }
  287. if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
  288. T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
  289. T->hasExtParameterInfos())
  290. AbbrevToUse = 0;
  291. Code = TYPE_FUNCTION_PROTO;
  292. }
  293. void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
  294. Record.AddDeclRef(T->getDecl());
  295. Code = TYPE_UNRESOLVED_USING;
  296. }
  297. void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
  298. Record.AddDeclRef(T->getDecl());
  299. assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
  300. Record.AddTypeRef(T->getCanonicalTypeInternal());
  301. Code = TYPE_TYPEDEF;
  302. }
  303. void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
  304. Record.AddStmt(T->getUnderlyingExpr());
  305. Code = TYPE_TYPEOF_EXPR;
  306. }
  307. void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
  308. Record.AddTypeRef(T->getUnderlyingType());
  309. Code = TYPE_TYPEOF;
  310. }
  311. void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
  312. Record.AddTypeRef(T->getUnderlyingType());
  313. Record.AddStmt(T->getUnderlyingExpr());
  314. Code = TYPE_DECLTYPE;
  315. }
  316. void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
  317. Record.AddTypeRef(T->getBaseType());
  318. Record.AddTypeRef(T->getUnderlyingType());
  319. Record.push_back(T->getUTTKind());
  320. Code = TYPE_UNARY_TRANSFORM;
  321. }
  322. void ASTTypeWriter::VisitAutoType(const AutoType *T) {
  323. Record.AddTypeRef(T->getDeducedType());
  324. Record.push_back((unsigned)T->getKeyword());
  325. if (T->getDeducedType().isNull())
  326. Record.push_back(T->isDependentType());
  327. Code = TYPE_AUTO;
  328. }
  329. void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
  330. const DeducedTemplateSpecializationType *T) {
  331. Record.AddTemplateName(T->getTemplateName());
  332. Record.AddTypeRef(T->getDeducedType());
  333. if (T->getDeducedType().isNull())
  334. Record.push_back(T->isDependentType());
  335. Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
  336. }
  337. void ASTTypeWriter::VisitTagType(const TagType *T) {
  338. Record.push_back(T->isDependentType());
  339. Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
  340. assert(!T->isBeingDefined() &&
  341. "Cannot serialize in the middle of a type definition");
  342. }
  343. void ASTTypeWriter::VisitRecordType(const RecordType *T) {
  344. VisitTagType(T);
  345. Code = TYPE_RECORD;
  346. }
  347. void ASTTypeWriter::VisitEnumType(const EnumType *T) {
  348. VisitTagType(T);
  349. Code = TYPE_ENUM;
  350. }
  351. void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
  352. Record.AddTypeRef(T->getModifiedType());
  353. Record.AddTypeRef(T->getEquivalentType());
  354. Record.push_back(T->getAttrKind());
  355. Code = TYPE_ATTRIBUTED;
  356. }
  357. void
  358. ASTTypeWriter::VisitSubstTemplateTypeParmType(
  359. const SubstTemplateTypeParmType *T) {
  360. Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
  361. Record.AddTypeRef(T->getReplacementType());
  362. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
  363. }
  364. void
  365. ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
  366. const SubstTemplateTypeParmPackType *T) {
  367. Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
  368. Record.AddTemplateArgument(T->getArgumentPack());
  369. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
  370. }
  371. void
  372. ASTTypeWriter::VisitTemplateSpecializationType(
  373. const TemplateSpecializationType *T) {
  374. Record.push_back(T->isDependentType());
  375. Record.AddTemplateName(T->getTemplateName());
  376. Record.push_back(T->getNumArgs());
  377. for (const auto &ArgI : *T)
  378. Record.AddTemplateArgument(ArgI);
  379. Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
  380. : T->isCanonicalUnqualified()
  381. ? QualType()
  382. : T->getCanonicalTypeInternal());
  383. Code = TYPE_TEMPLATE_SPECIALIZATION;
  384. }
  385. void
  386. ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
  387. VisitArrayType(T);
  388. Record.AddStmt(T->getSizeExpr());
  389. Record.AddSourceRange(T->getBracketsRange());
  390. Code = TYPE_DEPENDENT_SIZED_ARRAY;
  391. }
  392. void
  393. ASTTypeWriter::VisitDependentSizedExtVectorType(
  394. const DependentSizedExtVectorType *T) {
  395. Record.AddTypeRef(T->getElementType());
  396. Record.AddStmt(T->getSizeExpr());
  397. Record.AddSourceLocation(T->getAttributeLoc());
  398. Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
  399. }
  400. void ASTTypeWriter::VisitDependentVectorType(const DependentVectorType *T) {
  401. Record.AddTypeRef(T->getElementType());
  402. Record.AddStmt(const_cast<Expr*>(T->getSizeExpr()));
  403. Record.AddSourceLocation(T->getAttributeLoc());
  404. Record.push_back(T->getVectorKind());
  405. Code = TYPE_DEPENDENT_SIZED_VECTOR;
  406. }
  407. void
  408. ASTTypeWriter::VisitDependentAddressSpaceType(
  409. const DependentAddressSpaceType *T) {
  410. Record.AddTypeRef(T->getPointeeType());
  411. Record.AddStmt(T->getAddrSpaceExpr());
  412. Record.AddSourceLocation(T->getAttributeLoc());
  413. Code = TYPE_DEPENDENT_ADDRESS_SPACE;
  414. }
  415. void
  416. ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  417. Record.push_back(T->getDepth());
  418. Record.push_back(T->getIndex());
  419. Record.push_back(T->isParameterPack());
  420. Record.AddDeclRef(T->getDecl());
  421. Code = TYPE_TEMPLATE_TYPE_PARM;
  422. }
  423. void
  424. ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
  425. Record.push_back(T->getKeyword());
  426. Record.AddNestedNameSpecifier(T->getQualifier());
  427. Record.AddIdentifierRef(T->getIdentifier());
  428. Record.AddTypeRef(
  429. T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
  430. Code = TYPE_DEPENDENT_NAME;
  431. }
  432. void
  433. ASTTypeWriter::VisitDependentTemplateSpecializationType(
  434. const DependentTemplateSpecializationType *T) {
  435. Record.push_back(T->getKeyword());
  436. Record.AddNestedNameSpecifier(T->getQualifier());
  437. Record.AddIdentifierRef(T->getIdentifier());
  438. Record.push_back(T->getNumArgs());
  439. for (const auto &I : *T)
  440. Record.AddTemplateArgument(I);
  441. Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
  442. }
  443. void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
  444. Record.AddTypeRef(T->getPattern());
  445. if (Optional<unsigned> NumExpansions = T->getNumExpansions())
  446. Record.push_back(*NumExpansions + 1);
  447. else
  448. Record.push_back(0);
  449. Code = TYPE_PACK_EXPANSION;
  450. }
  451. void ASTTypeWriter::VisitParenType(const ParenType *T) {
  452. Record.AddTypeRef(T->getInnerType());
  453. Code = TYPE_PAREN;
  454. }
  455. void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
  456. Record.push_back(T->getKeyword());
  457. Record.AddNestedNameSpecifier(T->getQualifier());
  458. Record.AddTypeRef(T->getNamedType());
  459. Record.AddDeclRef(T->getOwnedTagDecl());
  460. Code = TYPE_ELABORATED;
  461. }
  462. void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
  463. Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
  464. Record.AddTypeRef(T->getInjectedSpecializationType());
  465. Code = TYPE_INJECTED_CLASS_NAME;
  466. }
  467. void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
  468. Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
  469. Code = TYPE_OBJC_INTERFACE;
  470. }
  471. void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
  472. Record.AddDeclRef(T->getDecl());
  473. Record.push_back(T->getNumProtocols());
  474. for (const auto *I : T->quals())
  475. Record.AddDeclRef(I);
  476. Code = TYPE_OBJC_TYPE_PARAM;
  477. }
  478. void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
  479. Record.AddTypeRef(T->getBaseType());
  480. Record.push_back(T->getTypeArgsAsWritten().size());
  481. for (auto TypeArg : T->getTypeArgsAsWritten())
  482. Record.AddTypeRef(TypeArg);
  483. Record.push_back(T->getNumProtocols());
  484. for (const auto *I : T->quals())
  485. Record.AddDeclRef(I);
  486. Record.push_back(T->isKindOfTypeAsWritten());
  487. Code = TYPE_OBJC_OBJECT;
  488. }
  489. void
  490. ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  491. Record.AddTypeRef(T->getPointeeType());
  492. Code = TYPE_OBJC_OBJECT_POINTER;
  493. }
  494. void
  495. ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
  496. Record.AddTypeRef(T->getValueType());
  497. Code = TYPE_ATOMIC;
  498. }
  499. void
  500. ASTTypeWriter::VisitPipeType(const PipeType *T) {
  501. Record.AddTypeRef(T->getElementType());
  502. Record.push_back(T->isReadOnly());
  503. Code = TYPE_PIPE;
  504. }
  505. namespace {
  506. class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
  507. ASTRecordWriter &Record;
  508. public:
  509. TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
  510. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  511. #define TYPELOC(CLASS, PARENT) \
  512. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  513. #include "clang/AST/TypeLocNodes.def"
  514. void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
  515. void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
  516. };
  517. } // namespace
  518. void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  519. // nothing to do
  520. }
  521. void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  522. Record.AddSourceLocation(TL.getBuiltinLoc());
  523. if (TL.needsExtraLocalData()) {
  524. Record.push_back(TL.getWrittenTypeSpec());
  525. Record.push_back(TL.getWrittenSignSpec());
  526. Record.push_back(TL.getWrittenWidthSpec());
  527. Record.push_back(TL.hasModeAttr());
  528. }
  529. }
  530. void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  531. Record.AddSourceLocation(TL.getNameLoc());
  532. }
  533. void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
  534. Record.AddSourceLocation(TL.getStarLoc());
  535. }
  536. void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  537. // nothing to do
  538. }
  539. void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  540. // nothing to do
  541. }
  542. void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  543. Record.AddSourceLocation(TL.getCaretLoc());
  544. }
  545. void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  546. Record.AddSourceLocation(TL.getAmpLoc());
  547. }
  548. void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  549. Record.AddSourceLocation(TL.getAmpAmpLoc());
  550. }
  551. void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  552. Record.AddSourceLocation(TL.getStarLoc());
  553. Record.AddTypeSourceInfo(TL.getClassTInfo());
  554. }
  555. void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  556. Record.AddSourceLocation(TL.getLBracketLoc());
  557. Record.AddSourceLocation(TL.getRBracketLoc());
  558. Record.push_back(TL.getSizeExpr() ? 1 : 0);
  559. if (TL.getSizeExpr())
  560. Record.AddStmt(TL.getSizeExpr());
  561. }
  562. void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  563. VisitArrayTypeLoc(TL);
  564. }
  565. void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  566. VisitArrayTypeLoc(TL);
  567. }
  568. void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  569. VisitArrayTypeLoc(TL);
  570. }
  571. void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
  572. DependentSizedArrayTypeLoc TL) {
  573. VisitArrayTypeLoc(TL);
  574. }
  575. void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
  576. DependentAddressSpaceTypeLoc TL) {
  577. Record.AddSourceLocation(TL.getAttrNameLoc());
  578. SourceRange range = TL.getAttrOperandParensRange();
  579. Record.AddSourceLocation(range.getBegin());
  580. Record.AddSourceLocation(range.getEnd());
  581. Record.AddStmt(TL.getAttrExprOperand());
  582. }
  583. void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
  584. DependentSizedExtVectorTypeLoc TL) {
  585. Record.AddSourceLocation(TL.getNameLoc());
  586. }
  587. void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
  588. Record.AddSourceLocation(TL.getNameLoc());
  589. }
  590. void TypeLocWriter::VisitDependentVectorTypeLoc(
  591. DependentVectorTypeLoc TL) {
  592. Record.AddSourceLocation(TL.getNameLoc());
  593. }
  594. void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  595. Record.AddSourceLocation(TL.getNameLoc());
  596. }
  597. void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  598. Record.AddSourceLocation(TL.getLocalRangeBegin());
  599. Record.AddSourceLocation(TL.getLParenLoc());
  600. Record.AddSourceLocation(TL.getRParenLoc());
  601. Record.AddSourceRange(TL.getExceptionSpecRange());
  602. Record.AddSourceLocation(TL.getLocalRangeEnd());
  603. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
  604. Record.AddDeclRef(TL.getParam(i));
  605. }
  606. void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  607. VisitFunctionTypeLoc(TL);
  608. }
  609. void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  610. VisitFunctionTypeLoc(TL);
  611. }
  612. void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  613. Record.AddSourceLocation(TL.getNameLoc());
  614. }
  615. void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  616. Record.AddSourceLocation(TL.getNameLoc());
  617. }
  618. void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  619. if (TL.getNumProtocols()) {
  620. Record.AddSourceLocation(TL.getProtocolLAngleLoc());
  621. Record.AddSourceLocation(TL.getProtocolRAngleLoc());
  622. }
  623. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  624. Record.AddSourceLocation(TL.getProtocolLoc(i));
  625. }
  626. void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  627. Record.AddSourceLocation(TL.getTypeofLoc());
  628. Record.AddSourceLocation(TL.getLParenLoc());
  629. Record.AddSourceLocation(TL.getRParenLoc());
  630. }
  631. void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  632. Record.AddSourceLocation(TL.getTypeofLoc());
  633. Record.AddSourceLocation(TL.getLParenLoc());
  634. Record.AddSourceLocation(TL.getRParenLoc());
  635. Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
  636. }
  637. void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  638. Record.AddSourceLocation(TL.getNameLoc());
  639. }
  640. void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  641. Record.AddSourceLocation(TL.getKWLoc());
  642. Record.AddSourceLocation(TL.getLParenLoc());
  643. Record.AddSourceLocation(TL.getRParenLoc());
  644. Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
  645. }
  646. void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
  647. Record.AddSourceLocation(TL.getNameLoc());
  648. }
  649. void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
  650. DeducedTemplateSpecializationTypeLoc TL) {
  651. Record.AddSourceLocation(TL.getTemplateNameLoc());
  652. }
  653. void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
  654. Record.AddSourceLocation(TL.getNameLoc());
  655. }
  656. void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
  657. Record.AddSourceLocation(TL.getNameLoc());
  658. }
  659. void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  660. Record.AddAttr(TL.getAttr());
  661. }
  662. void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  663. Record.AddSourceLocation(TL.getNameLoc());
  664. }
  665. void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
  666. SubstTemplateTypeParmTypeLoc TL) {
  667. Record.AddSourceLocation(TL.getNameLoc());
  668. }
  669. void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
  670. SubstTemplateTypeParmPackTypeLoc TL) {
  671. Record.AddSourceLocation(TL.getNameLoc());
  672. }
  673. void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
  674. TemplateSpecializationTypeLoc TL) {
  675. Record.AddSourceLocation(TL.getTemplateKeywordLoc());
  676. Record.AddSourceLocation(TL.getTemplateNameLoc());
  677. Record.AddSourceLocation(TL.getLAngleLoc());
  678. Record.AddSourceLocation(TL.getRAngleLoc());
  679. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  680. Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
  681. TL.getArgLoc(i).getLocInfo());
  682. }
  683. void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
  684. Record.AddSourceLocation(TL.getLParenLoc());
  685. Record.AddSourceLocation(TL.getRParenLoc());
  686. }
  687. void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  688. Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
  689. Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
  690. }
  691. void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  692. Record.AddSourceLocation(TL.getNameLoc());
  693. }
  694. void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  695. Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
  696. Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
  697. Record.AddSourceLocation(TL.getNameLoc());
  698. }
  699. void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
  700. DependentTemplateSpecializationTypeLoc TL) {
  701. Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
  702. Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
  703. Record.AddSourceLocation(TL.getTemplateKeywordLoc());
  704. Record.AddSourceLocation(TL.getTemplateNameLoc());
  705. Record.AddSourceLocation(TL.getLAngleLoc());
  706. Record.AddSourceLocation(TL.getRAngleLoc());
  707. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  708. Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
  709. TL.getArgLoc(I).getLocInfo());
  710. }
  711. void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  712. Record.AddSourceLocation(TL.getEllipsisLoc());
  713. }
  714. void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  715. Record.AddSourceLocation(TL.getNameLoc());
  716. }
  717. void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  718. Record.push_back(TL.hasBaseTypeAsWritten());
  719. Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
  720. Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
  721. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  722. Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
  723. Record.AddSourceLocation(TL.getProtocolLAngleLoc());
  724. Record.AddSourceLocation(TL.getProtocolRAngleLoc());
  725. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  726. Record.AddSourceLocation(TL.getProtocolLoc(i));
  727. }
  728. void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  729. Record.AddSourceLocation(TL.getStarLoc());
  730. }
  731. void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  732. Record.AddSourceLocation(TL.getKWLoc());
  733. Record.AddSourceLocation(TL.getLParenLoc());
  734. Record.AddSourceLocation(TL.getRParenLoc());
  735. }
  736. void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
  737. Record.AddSourceLocation(TL.getKWLoc());
  738. }
  739. void ASTWriter::WriteTypeAbbrevs() {
  740. using namespace llvm;
  741. std::shared_ptr<BitCodeAbbrev> Abv;
  742. // Abbreviation for TYPE_EXT_QUAL
  743. Abv = std::make_shared<BitCodeAbbrev>();
  744. Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
  745. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
  746. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
  747. TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
  748. // Abbreviation for TYPE_FUNCTION_PROTO
  749. Abv = std::make_shared<BitCodeAbbrev>();
  750. Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
  751. // FunctionType
  752. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
  753. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
  754. Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
  755. Abv->Add(BitCodeAbbrevOp(0)); // RegParm
  756. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
  757. Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
  758. Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
  759. Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
  760. // FunctionProtoType
  761. Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
  762. Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
  763. Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
  764. Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
  765. Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
  766. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
  767. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  768. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
  769. TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
  770. }
  771. //===----------------------------------------------------------------------===//
  772. // ASTWriter Implementation
  773. //===----------------------------------------------------------------------===//
  774. static void EmitBlockID(unsigned ID, const char *Name,
  775. llvm::BitstreamWriter &Stream,
  776. ASTWriter::RecordDataImpl &Record) {
  777. Record.clear();
  778. Record.push_back(ID);
  779. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  780. // Emit the block name if present.
  781. if (!Name || Name[0] == 0)
  782. return;
  783. Record.clear();
  784. while (*Name)
  785. Record.push_back(*Name++);
  786. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  787. }
  788. static void EmitRecordID(unsigned ID, const char *Name,
  789. llvm::BitstreamWriter &Stream,
  790. ASTWriter::RecordDataImpl &Record) {
  791. Record.clear();
  792. Record.push_back(ID);
  793. while (*Name)
  794. Record.push_back(*Name++);
  795. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  796. }
  797. static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
  798. ASTWriter::RecordDataImpl &Record) {
  799. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  800. RECORD(STMT_STOP);
  801. RECORD(STMT_NULL_PTR);
  802. RECORD(STMT_REF_PTR);
  803. RECORD(STMT_NULL);
  804. RECORD(STMT_COMPOUND);
  805. RECORD(STMT_CASE);
  806. RECORD(STMT_DEFAULT);
  807. RECORD(STMT_LABEL);
  808. RECORD(STMT_ATTRIBUTED);
  809. RECORD(STMT_IF);
  810. RECORD(STMT_SWITCH);
  811. RECORD(STMT_WHILE);
  812. RECORD(STMT_DO);
  813. RECORD(STMT_FOR);
  814. RECORD(STMT_GOTO);
  815. RECORD(STMT_INDIRECT_GOTO);
  816. RECORD(STMT_CONTINUE);
  817. RECORD(STMT_BREAK);
  818. RECORD(STMT_RETURN);
  819. RECORD(STMT_DECL);
  820. RECORD(STMT_GCCASM);
  821. RECORD(STMT_MSASM);
  822. RECORD(EXPR_PREDEFINED);
  823. RECORD(EXPR_DECL_REF);
  824. RECORD(EXPR_INTEGER_LITERAL);
  825. RECORD(EXPR_FLOATING_LITERAL);
  826. RECORD(EXPR_IMAGINARY_LITERAL);
  827. RECORD(EXPR_STRING_LITERAL);
  828. RECORD(EXPR_CHARACTER_LITERAL);
  829. RECORD(EXPR_PAREN);
  830. RECORD(EXPR_PAREN_LIST);
  831. RECORD(EXPR_UNARY_OPERATOR);
  832. RECORD(EXPR_SIZEOF_ALIGN_OF);
  833. RECORD(EXPR_ARRAY_SUBSCRIPT);
  834. RECORD(EXPR_CALL);
  835. RECORD(EXPR_MEMBER);
  836. RECORD(EXPR_BINARY_OPERATOR);
  837. RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
  838. RECORD(EXPR_CONDITIONAL_OPERATOR);
  839. RECORD(EXPR_IMPLICIT_CAST);
  840. RECORD(EXPR_CSTYLE_CAST);
  841. RECORD(EXPR_COMPOUND_LITERAL);
  842. RECORD(EXPR_EXT_VECTOR_ELEMENT);
  843. RECORD(EXPR_INIT_LIST);
  844. RECORD(EXPR_DESIGNATED_INIT);
  845. RECORD(EXPR_DESIGNATED_INIT_UPDATE);
  846. RECORD(EXPR_IMPLICIT_VALUE_INIT);
  847. RECORD(EXPR_NO_INIT);
  848. RECORD(EXPR_VA_ARG);
  849. RECORD(EXPR_ADDR_LABEL);
  850. RECORD(EXPR_STMT);
  851. RECORD(EXPR_CHOOSE);
  852. RECORD(EXPR_GNU_NULL);
  853. RECORD(EXPR_SHUFFLE_VECTOR);
  854. RECORD(EXPR_BLOCK);
  855. RECORD(EXPR_GENERIC_SELECTION);
  856. RECORD(EXPR_OBJC_STRING_LITERAL);
  857. RECORD(EXPR_OBJC_BOXED_EXPRESSION);
  858. RECORD(EXPR_OBJC_ARRAY_LITERAL);
  859. RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
  860. RECORD(EXPR_OBJC_ENCODE);
  861. RECORD(EXPR_OBJC_SELECTOR_EXPR);
  862. RECORD(EXPR_OBJC_PROTOCOL_EXPR);
  863. RECORD(EXPR_OBJC_IVAR_REF_EXPR);
  864. RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
  865. RECORD(EXPR_OBJC_KVC_REF_EXPR);
  866. RECORD(EXPR_OBJC_MESSAGE_EXPR);
  867. RECORD(STMT_OBJC_FOR_COLLECTION);
  868. RECORD(STMT_OBJC_CATCH);
  869. RECORD(STMT_OBJC_FINALLY);
  870. RECORD(STMT_OBJC_AT_TRY);
  871. RECORD(STMT_OBJC_AT_SYNCHRONIZED);
  872. RECORD(STMT_OBJC_AT_THROW);
  873. RECORD(EXPR_OBJC_BOOL_LITERAL);
  874. RECORD(STMT_CXX_CATCH);
  875. RECORD(STMT_CXX_TRY);
  876. RECORD(STMT_CXX_FOR_RANGE);
  877. RECORD(EXPR_CXX_OPERATOR_CALL);
  878. RECORD(EXPR_CXX_MEMBER_CALL);
  879. RECORD(EXPR_CXX_CONSTRUCT);
  880. RECORD(EXPR_CXX_TEMPORARY_OBJECT);
  881. RECORD(EXPR_CXX_STATIC_CAST);
  882. RECORD(EXPR_CXX_DYNAMIC_CAST);
  883. RECORD(EXPR_CXX_REINTERPRET_CAST);
  884. RECORD(EXPR_CXX_CONST_CAST);
  885. RECORD(EXPR_CXX_FUNCTIONAL_CAST);
  886. RECORD(EXPR_USER_DEFINED_LITERAL);
  887. RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
  888. RECORD(EXPR_CXX_BOOL_LITERAL);
  889. RECORD(EXPR_CXX_NULL_PTR_LITERAL);
  890. RECORD(EXPR_CXX_TYPEID_EXPR);
  891. RECORD(EXPR_CXX_TYPEID_TYPE);
  892. RECORD(EXPR_CXX_THIS);
  893. RECORD(EXPR_CXX_THROW);
  894. RECORD(EXPR_CXX_DEFAULT_ARG);
  895. RECORD(EXPR_CXX_DEFAULT_INIT);
  896. RECORD(EXPR_CXX_BIND_TEMPORARY);
  897. RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
  898. RECORD(EXPR_CXX_NEW);
  899. RECORD(EXPR_CXX_DELETE);
  900. RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
  901. RECORD(EXPR_EXPR_WITH_CLEANUPS);
  902. RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
  903. RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
  904. RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
  905. RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
  906. RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
  907. RECORD(EXPR_CXX_EXPRESSION_TRAIT);
  908. RECORD(EXPR_CXX_NOEXCEPT);
  909. RECORD(EXPR_OPAQUE_VALUE);
  910. RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
  911. RECORD(EXPR_TYPE_TRAIT);
  912. RECORD(EXPR_ARRAY_TYPE_TRAIT);
  913. RECORD(EXPR_PACK_EXPANSION);
  914. RECORD(EXPR_SIZEOF_PACK);
  915. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
  916. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
  917. RECORD(EXPR_FUNCTION_PARM_PACK);
  918. RECORD(EXPR_MATERIALIZE_TEMPORARY);
  919. RECORD(EXPR_CUDA_KERNEL_CALL);
  920. RECORD(EXPR_CXX_UUIDOF_EXPR);
  921. RECORD(EXPR_CXX_UUIDOF_TYPE);
  922. RECORD(EXPR_LAMBDA);
  923. #undef RECORD
  924. }
  925. void ASTWriter::WriteBlockInfoBlock() {
  926. RecordData Record;
  927. Stream.EnterBlockInfoBlock();
  928. #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
  929. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  930. // Control Block.
  931. BLOCK(CONTROL_BLOCK);
  932. RECORD(METADATA);
  933. RECORD(MODULE_NAME);
  934. RECORD(MODULE_DIRECTORY);
  935. RECORD(MODULE_MAP_FILE);
  936. RECORD(IMPORTS);
  937. RECORD(ORIGINAL_FILE);
  938. RECORD(ORIGINAL_PCH_DIR);
  939. RECORD(ORIGINAL_FILE_ID);
  940. RECORD(INPUT_FILE_OFFSETS);
  941. BLOCK(OPTIONS_BLOCK);
  942. RECORD(LANGUAGE_OPTIONS);
  943. RECORD(TARGET_OPTIONS);
  944. RECORD(FILE_SYSTEM_OPTIONS);
  945. RECORD(HEADER_SEARCH_OPTIONS);
  946. RECORD(PREPROCESSOR_OPTIONS);
  947. BLOCK(INPUT_FILES_BLOCK);
  948. RECORD(INPUT_FILE);
  949. // AST Top-Level Block.
  950. BLOCK(AST_BLOCK);
  951. RECORD(TYPE_OFFSET);
  952. RECORD(DECL_OFFSET);
  953. RECORD(IDENTIFIER_OFFSET);
  954. RECORD(IDENTIFIER_TABLE);
  955. RECORD(EAGERLY_DESERIALIZED_DECLS);
  956. RECORD(MODULAR_CODEGEN_DECLS);
  957. RECORD(SPECIAL_TYPES);
  958. RECORD(STATISTICS);
  959. RECORD(TENTATIVE_DEFINITIONS);
  960. RECORD(SELECTOR_OFFSETS);
  961. RECORD(METHOD_POOL);
  962. RECORD(PP_COUNTER_VALUE);
  963. RECORD(SOURCE_LOCATION_OFFSETS);
  964. RECORD(SOURCE_LOCATION_PRELOADS);
  965. RECORD(EXT_VECTOR_DECLS);
  966. RECORD(UNUSED_FILESCOPED_DECLS);
  967. RECORD(PPD_ENTITIES_OFFSETS);
  968. RECORD(VTABLE_USES);
  969. RECORD(PPD_SKIPPED_RANGES);
  970. RECORD(REFERENCED_SELECTOR_POOL);
  971. RECORD(TU_UPDATE_LEXICAL);
  972. RECORD(SEMA_DECL_REFS);
  973. RECORD(WEAK_UNDECLARED_IDENTIFIERS);
  974. RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
  975. RECORD(UPDATE_VISIBLE);
  976. RECORD(DECL_UPDATE_OFFSETS);
  977. RECORD(DECL_UPDATES);
  978. RECORD(CUDA_SPECIAL_DECL_REFS);
  979. RECORD(HEADER_SEARCH_TABLE);
  980. RECORD(FP_PRAGMA_OPTIONS);
  981. RECORD(OPENCL_EXTENSIONS);
  982. RECORD(OPENCL_EXTENSION_TYPES);
  983. RECORD(OPENCL_EXTENSION_DECLS);
  984. RECORD(DELEGATING_CTORS);
  985. RECORD(KNOWN_NAMESPACES);
  986. RECORD(MODULE_OFFSET_MAP);
  987. RECORD(SOURCE_MANAGER_LINE_TABLE);
  988. RECORD(OBJC_CATEGORIES_MAP);
  989. RECORD(FILE_SORTED_DECLS);
  990. RECORD(IMPORTED_MODULES);
  991. RECORD(OBJC_CATEGORIES);
  992. RECORD(MACRO_OFFSET);
  993. RECORD(INTERESTING_IDENTIFIERS);
  994. RECORD(UNDEFINED_BUT_USED);
  995. RECORD(LATE_PARSED_TEMPLATE);
  996. RECORD(OPTIMIZE_PRAGMA_OPTIONS);
  997. RECORD(MSSTRUCT_PRAGMA_OPTIONS);
  998. RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
  999. RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
  1000. RECORD(DELETE_EXPRS_TO_ANALYZE);
  1001. RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
  1002. RECORD(PP_CONDITIONAL_STACK);
  1003. // SourceManager Block.
  1004. BLOCK(SOURCE_MANAGER_BLOCK);
  1005. RECORD(SM_SLOC_FILE_ENTRY);
  1006. RECORD(SM_SLOC_BUFFER_ENTRY);
  1007. RECORD(SM_SLOC_BUFFER_BLOB);
  1008. RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
  1009. RECORD(SM_SLOC_EXPANSION_ENTRY);
  1010. // Preprocessor Block.
  1011. BLOCK(PREPROCESSOR_BLOCK);
  1012. RECORD(PP_MACRO_DIRECTIVE_HISTORY);
  1013. RECORD(PP_MACRO_FUNCTION_LIKE);
  1014. RECORD(PP_MACRO_OBJECT_LIKE);
  1015. RECORD(PP_MODULE_MACRO);
  1016. RECORD(PP_TOKEN);
  1017. // Submodule Block.
  1018. BLOCK(SUBMODULE_BLOCK);
  1019. RECORD(SUBMODULE_METADATA);
  1020. RECORD(SUBMODULE_DEFINITION);
  1021. RECORD(SUBMODULE_UMBRELLA_HEADER);
  1022. RECORD(SUBMODULE_HEADER);
  1023. RECORD(SUBMODULE_TOPHEADER);
  1024. RECORD(SUBMODULE_UMBRELLA_DIR);
  1025. RECORD(SUBMODULE_IMPORTS);
  1026. RECORD(SUBMODULE_EXPORTS);
  1027. RECORD(SUBMODULE_REQUIRES);
  1028. RECORD(SUBMODULE_EXCLUDED_HEADER);
  1029. RECORD(SUBMODULE_LINK_LIBRARY);
  1030. RECORD(SUBMODULE_CONFIG_MACRO);
  1031. RECORD(SUBMODULE_CONFLICT);
  1032. RECORD(SUBMODULE_PRIVATE_HEADER);
  1033. RECORD(SUBMODULE_TEXTUAL_HEADER);
  1034. RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
  1035. RECORD(SUBMODULE_INITIALIZERS);
  1036. RECORD(SUBMODULE_EXPORT_AS);
  1037. // Comments Block.
  1038. BLOCK(COMMENTS_BLOCK);
  1039. RECORD(COMMENTS_RAW_COMMENT);
  1040. // Decls and Types block.
  1041. BLOCK(DECLTYPES_BLOCK);
  1042. RECORD(TYPE_EXT_QUAL);
  1043. RECORD(TYPE_COMPLEX);
  1044. RECORD(TYPE_POINTER);
  1045. RECORD(TYPE_BLOCK_POINTER);
  1046. RECORD(TYPE_LVALUE_REFERENCE);
  1047. RECORD(TYPE_RVALUE_REFERENCE);
  1048. RECORD(TYPE_MEMBER_POINTER);
  1049. RECORD(TYPE_CONSTANT_ARRAY);
  1050. RECORD(TYPE_INCOMPLETE_ARRAY);
  1051. RECORD(TYPE_VARIABLE_ARRAY);
  1052. RECORD(TYPE_VECTOR);
  1053. RECORD(TYPE_EXT_VECTOR);
  1054. RECORD(TYPE_FUNCTION_NO_PROTO);
  1055. RECORD(TYPE_FUNCTION_PROTO);
  1056. RECORD(TYPE_TYPEDEF);
  1057. RECORD(TYPE_TYPEOF_EXPR);
  1058. RECORD(TYPE_TYPEOF);
  1059. RECORD(TYPE_RECORD);
  1060. RECORD(TYPE_ENUM);
  1061. RECORD(TYPE_OBJC_INTERFACE);
  1062. RECORD(TYPE_OBJC_OBJECT_POINTER);
  1063. RECORD(TYPE_DECLTYPE);
  1064. RECORD(TYPE_ELABORATED);
  1065. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
  1066. RECORD(TYPE_UNRESOLVED_USING);
  1067. RECORD(TYPE_INJECTED_CLASS_NAME);
  1068. RECORD(TYPE_OBJC_OBJECT);
  1069. RECORD(TYPE_TEMPLATE_TYPE_PARM);
  1070. RECORD(TYPE_TEMPLATE_SPECIALIZATION);
  1071. RECORD(TYPE_DEPENDENT_NAME);
  1072. RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
  1073. RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
  1074. RECORD(TYPE_PAREN);
  1075. RECORD(TYPE_PACK_EXPANSION);
  1076. RECORD(TYPE_ATTRIBUTED);
  1077. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
  1078. RECORD(TYPE_AUTO);
  1079. RECORD(TYPE_UNARY_TRANSFORM);
  1080. RECORD(TYPE_ATOMIC);
  1081. RECORD(TYPE_DECAYED);
  1082. RECORD(TYPE_ADJUSTED);
  1083. RECORD(TYPE_OBJC_TYPE_PARAM);
  1084. RECORD(LOCAL_REDECLARATIONS);
  1085. RECORD(DECL_TYPEDEF);
  1086. RECORD(DECL_TYPEALIAS);
  1087. RECORD(DECL_ENUM);
  1088. RECORD(DECL_RECORD);
  1089. RECORD(DECL_ENUM_CONSTANT);
  1090. RECORD(DECL_FUNCTION);
  1091. RECORD(DECL_OBJC_METHOD);
  1092. RECORD(DECL_OBJC_INTERFACE);
  1093. RECORD(DECL_OBJC_PROTOCOL);
  1094. RECORD(DECL_OBJC_IVAR);
  1095. RECORD(DECL_OBJC_AT_DEFS_FIELD);
  1096. RECORD(DECL_OBJC_CATEGORY);
  1097. RECORD(DECL_OBJC_CATEGORY_IMPL);
  1098. RECORD(DECL_OBJC_IMPLEMENTATION);
  1099. RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
  1100. RECORD(DECL_OBJC_PROPERTY);
  1101. RECORD(DECL_OBJC_PROPERTY_IMPL);
  1102. RECORD(DECL_FIELD);
  1103. RECORD(DECL_MS_PROPERTY);
  1104. RECORD(DECL_VAR);
  1105. RECORD(DECL_IMPLICIT_PARAM);
  1106. RECORD(DECL_PARM_VAR);
  1107. RECORD(DECL_FILE_SCOPE_ASM);
  1108. RECORD(DECL_BLOCK);
  1109. RECORD(DECL_CONTEXT_LEXICAL);
  1110. RECORD(DECL_CONTEXT_VISIBLE);
  1111. RECORD(DECL_NAMESPACE);
  1112. RECORD(DECL_NAMESPACE_ALIAS);
  1113. RECORD(DECL_USING);
  1114. RECORD(DECL_USING_SHADOW);
  1115. RECORD(DECL_USING_DIRECTIVE);
  1116. RECORD(DECL_UNRESOLVED_USING_VALUE);
  1117. RECORD(DECL_UNRESOLVED_USING_TYPENAME);
  1118. RECORD(DECL_LINKAGE_SPEC);
  1119. RECORD(DECL_CXX_RECORD);
  1120. RECORD(DECL_CXX_METHOD);
  1121. RECORD(DECL_CXX_CONSTRUCTOR);
  1122. RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
  1123. RECORD(DECL_CXX_DESTRUCTOR);
  1124. RECORD(DECL_CXX_CONVERSION);
  1125. RECORD(DECL_ACCESS_SPEC);
  1126. RECORD(DECL_FRIEND);
  1127. RECORD(DECL_FRIEND_TEMPLATE);
  1128. RECORD(DECL_CLASS_TEMPLATE);
  1129. RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
  1130. RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
  1131. RECORD(DECL_VAR_TEMPLATE);
  1132. RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
  1133. RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
  1134. RECORD(DECL_FUNCTION_TEMPLATE);
  1135. RECORD(DECL_TEMPLATE_TYPE_PARM);
  1136. RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
  1137. RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
  1138. RECORD(DECL_TYPE_ALIAS_TEMPLATE);
  1139. RECORD(DECL_STATIC_ASSERT);
  1140. RECORD(DECL_CXX_BASE_SPECIFIERS);
  1141. RECORD(DECL_CXX_CTOR_INITIALIZERS);
  1142. RECORD(DECL_INDIRECTFIELD);
  1143. RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
  1144. RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
  1145. RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
  1146. RECORD(DECL_IMPORT);
  1147. RECORD(DECL_OMP_THREADPRIVATE);
  1148. RECORD(DECL_EMPTY);
  1149. RECORD(DECL_OBJC_TYPE_PARAM);
  1150. RECORD(DECL_OMP_CAPTUREDEXPR);
  1151. RECORD(DECL_PRAGMA_COMMENT);
  1152. RECORD(DECL_PRAGMA_DETECT_MISMATCH);
  1153. RECORD(DECL_OMP_DECLARE_REDUCTION);
  1154. // Statements and Exprs can occur in the Decls and Types block.
  1155. AddStmtsExprs(Stream, Record);
  1156. BLOCK(PREPROCESSOR_DETAIL_BLOCK);
  1157. RECORD(PPD_MACRO_EXPANSION);
  1158. RECORD(PPD_MACRO_DEFINITION);
  1159. RECORD(PPD_INCLUSION_DIRECTIVE);
  1160. // Decls and Types block.
  1161. BLOCK(EXTENSION_BLOCK);
  1162. RECORD(EXTENSION_METADATA);
  1163. BLOCK(UNHASHED_CONTROL_BLOCK);
  1164. RECORD(SIGNATURE);
  1165. RECORD(DIAGNOSTIC_OPTIONS);
  1166. RECORD(DIAG_PRAGMA_MAPPINGS);
  1167. #undef RECORD
  1168. #undef BLOCK
  1169. Stream.ExitBlock();
  1170. }
  1171. /// Prepares a path for being written to an AST file by converting it
  1172. /// to an absolute path and removing nested './'s.
  1173. ///
  1174. /// \return \c true if the path was changed.
  1175. static bool cleanPathForOutput(FileManager &FileMgr,
  1176. SmallVectorImpl<char> &Path) {
  1177. bool Changed = FileMgr.makeAbsolutePath(Path);
  1178. return Changed | llvm::sys::path::remove_dots(Path);
  1179. }
  1180. /// Adjusts the given filename to only write out the portion of the
  1181. /// filename that is not part of the system root directory.
  1182. ///
  1183. /// \param Filename the file name to adjust.
  1184. ///
  1185. /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
  1186. /// the returned filename will be adjusted by this root directory.
  1187. ///
  1188. /// \returns either the original filename (if it needs no adjustment) or the
  1189. /// adjusted filename (which points into the @p Filename parameter).
  1190. static const char *
  1191. adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
  1192. assert(Filename && "No file name to adjust?");
  1193. if (BaseDir.empty())
  1194. return Filename;
  1195. // Verify that the filename and the system root have the same prefix.
  1196. unsigned Pos = 0;
  1197. for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
  1198. if (Filename[Pos] != BaseDir[Pos])
  1199. return Filename; // Prefixes don't match.
  1200. // We hit the end of the filename before we hit the end of the system root.
  1201. if (!Filename[Pos])
  1202. return Filename;
  1203. // If there's not a path separator at the end of the base directory nor
  1204. // immediately after it, then this isn't within the base directory.
  1205. if (!llvm::sys::path::is_separator(Filename[Pos])) {
  1206. if (!llvm::sys::path::is_separator(BaseDir.back()))
  1207. return Filename;
  1208. } else {
  1209. // If the file name has a '/' at the current position, skip over the '/'.
  1210. // We distinguish relative paths from absolute paths by the
  1211. // absence of '/' at the beginning of relative paths.
  1212. //
  1213. // FIXME: This is wrong. We distinguish them by asking if the path is
  1214. // absolute, which isn't the same thing. And there might be multiple '/'s
  1215. // in a row. Use a better mechanism to indicate whether we have emitted an
  1216. // absolute or relative path.
  1217. ++Pos;
  1218. }
  1219. return Filename + Pos;
  1220. }
  1221. ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
  1222. // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
  1223. llvm::SHA1 Hasher;
  1224. Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
  1225. auto Hash = Hasher.result();
  1226. // Convert to an array [5*i32].
  1227. ASTFileSignature Signature;
  1228. auto LShift = [&](unsigned char Val, unsigned Shift) {
  1229. return (uint32_t)Val << Shift;
  1230. };
  1231. for (int I = 0; I != 5; ++I)
  1232. Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
  1233. LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
  1234. return Signature;
  1235. }
  1236. ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
  1237. ASTContext &Context) {
  1238. // Flush first to prepare the PCM hash (signature).
  1239. Stream.FlushToWord();
  1240. auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
  1241. // Enter the block and prepare to write records.
  1242. RecordData Record;
  1243. Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
  1244. // For implicit modules, write the hash of the PCM as its signature.
  1245. ASTFileSignature Signature;
  1246. if (WritingModule &&
  1247. PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
  1248. Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
  1249. Record.append(Signature.begin(), Signature.end());
  1250. Stream.EmitRecord(SIGNATURE, Record);
  1251. Record.clear();
  1252. }
  1253. // Diagnostic options.
  1254. const auto &Diags = Context.getDiagnostics();
  1255. const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
  1256. #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
  1257. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  1258. Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
  1259. #include "clang/Basic/DiagnosticOptions.def"
  1260. Record.push_back(DiagOpts.Warnings.size());
  1261. for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
  1262. AddString(DiagOpts.Warnings[I], Record);
  1263. Record.push_back(DiagOpts.Remarks.size());
  1264. for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
  1265. AddString(DiagOpts.Remarks[I], Record);
  1266. // Note: we don't serialize the log or serialization file names, because they
  1267. // are generally transient files and will almost always be overridden.
  1268. Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
  1269. // Write out the diagnostic/pragma mappings.
  1270. WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
  1271. // Leave the options block.
  1272. Stream.ExitBlock();
  1273. return Signature;
  1274. }
  1275. /// Write the control block.
  1276. void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
  1277. StringRef isysroot,
  1278. const std::string &OutputFile) {
  1279. using namespace llvm;
  1280. Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
  1281. RecordData Record;
  1282. // Metadata
  1283. auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
  1284. MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
  1285. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
  1286. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
  1287. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
  1288. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
  1289. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
  1290. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
  1291. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
  1292. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
  1293. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
  1294. unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
  1295. assert((!WritingModule || isysroot.empty()) &&
  1296. "writing module as a relocatable PCH?");
  1297. {
  1298. RecordData::value_type Record[] = {
  1299. METADATA,
  1300. VERSION_MAJOR,
  1301. VERSION_MINOR,
  1302. CLANG_VERSION_MAJOR,
  1303. CLANG_VERSION_MINOR,
  1304. !isysroot.empty(),
  1305. IncludeTimestamps,
  1306. Context.getLangOpts().BuildingPCHWithObjectFile,
  1307. ASTHasCompilerErrors};
  1308. Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
  1309. getClangFullRepositoryVersion());
  1310. }
  1311. if (WritingModule) {
  1312. // Module name
  1313. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1314. Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
  1315. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1316. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  1317. RecordData::value_type Record[] = {MODULE_NAME};
  1318. Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
  1319. }
  1320. if (WritingModule && WritingModule->Directory) {
  1321. SmallString<128> BaseDir(WritingModule->Directory->getName());
  1322. cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
  1323. // If the home of the module is the current working directory, then we
  1324. // want to pick up the cwd of the build process loading the module, not
  1325. // our cwd, when we load this module.
  1326. if (!PP.getHeaderSearchInfo()
  1327. .getHeaderSearchOpts()
  1328. .ModuleMapFileHomeIsCwd ||
  1329. WritingModule->Directory->getName() != StringRef(".")) {
  1330. // Module directory.
  1331. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1332. Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
  1333. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
  1334. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  1335. RecordData::value_type Record[] = {MODULE_DIRECTORY};
  1336. Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
  1337. }
  1338. // Write out all other paths relative to the base directory if possible.
  1339. BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
  1340. } else if (!isysroot.empty()) {
  1341. // Write out paths relative to the sysroot if possible.
  1342. BaseDirectory = isysroot;
  1343. }
  1344. // Module map file
  1345. if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
  1346. Record.clear();
  1347. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  1348. AddPath(WritingModule->PresumedModuleMapFile.empty()
  1349. ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
  1350. : StringRef(WritingModule->PresumedModuleMapFile),
  1351. Record);
  1352. // Additional module map files.
  1353. if (auto *AdditionalModMaps =
  1354. Map.getAdditionalModuleMapFiles(WritingModule)) {
  1355. Record.push_back(AdditionalModMaps->size());
  1356. for (const FileEntry *F : *AdditionalModMaps)
  1357. AddPath(F->getName(), Record);
  1358. } else {
  1359. Record.push_back(0);
  1360. }
  1361. Stream.EmitRecord(MODULE_MAP_FILE, Record);
  1362. }
  1363. // Imports
  1364. if (Chain) {
  1365. serialization::ModuleManager &Mgr = Chain->getModuleManager();
  1366. Record.clear();
  1367. for (ModuleFile &M : Mgr) {
  1368. // Skip modules that weren't directly imported.
  1369. if (!M.isDirectlyImported())
  1370. continue;
  1371. Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
  1372. AddSourceLocation(M.ImportLoc, Record);
  1373. // If we have calculated signature, there is no need to store
  1374. // the size or timestamp.
  1375. Record.push_back(M.Signature ? 0 : M.File->getSize());
  1376. Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
  1377. for (auto I : M.Signature)
  1378. Record.push_back(I);
  1379. AddString(M.ModuleName, Record);
  1380. AddPath(M.FileName, Record);
  1381. }
  1382. Stream.EmitRecord(IMPORTS, Record);
  1383. }
  1384. // Write the options block.
  1385. Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
  1386. // Language options.
  1387. Record.clear();
  1388. const LangOptions &LangOpts = Context.getLangOpts();
  1389. #define LANGOPT(Name, Bits, Default, Description) \
  1390. Record.push_back(LangOpts.Name);
  1391. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  1392. Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
  1393. #include "clang/Basic/LangOptions.def"
  1394. #define SANITIZER(NAME, ID) \
  1395. Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
  1396. #include "clang/Basic/Sanitizers.def"
  1397. Record.push_back(LangOpts.ModuleFeatures.size());
  1398. for (StringRef Feature : LangOpts.ModuleFeatures)
  1399. AddString(Feature, Record);
  1400. Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
  1401. AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
  1402. AddString(LangOpts.CurrentModule, Record);
  1403. // Comment options.
  1404. Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
  1405. for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
  1406. AddString(I, Record);
  1407. }
  1408. Record.push_back(LangOpts.CommentOpts.ParseAllComments);
  1409. // OpenMP offloading options.
  1410. Record.push_back(LangOpts.OMPTargetTriples.size());
  1411. for (auto &T : LangOpts.OMPTargetTriples)
  1412. AddString(T.getTriple(), Record);
  1413. AddString(LangOpts.OMPHostIRFile, Record);
  1414. Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
  1415. // Target options.
  1416. Record.clear();
  1417. const TargetInfo &Target = Context.getTargetInfo();
  1418. const TargetOptions &TargetOpts = Target.getTargetOpts();
  1419. AddString(TargetOpts.Triple, Record);
  1420. AddString(TargetOpts.CPU, Record);
  1421. AddString(TargetOpts.ABI, Record);
  1422. Record.push_back(TargetOpts.FeaturesAsWritten.size());
  1423. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
  1424. AddString(TargetOpts.FeaturesAsWritten[I], Record);
  1425. }
  1426. Record.push_back(TargetOpts.Features.size());
  1427. for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
  1428. AddString(TargetOpts.Features[I], Record);
  1429. }
  1430. Stream.EmitRecord(TARGET_OPTIONS, Record);
  1431. // File system options.
  1432. Record.clear();
  1433. const FileSystemOptions &FSOpts =
  1434. Context.getSourceManager().getFileManager().getFileSystemOpts();
  1435. AddString(FSOpts.WorkingDir, Record);
  1436. Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
  1437. // Header search options.
  1438. Record.clear();
  1439. const HeaderSearchOptions &HSOpts
  1440. = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  1441. AddString(HSOpts.Sysroot, Record);
  1442. // Include entries.
  1443. Record.push_back(HSOpts.UserEntries.size());
  1444. for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
  1445. const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
  1446. AddString(Entry.Path, Record);
  1447. Record.push_back(static_cast<unsigned>(Entry.Group));
  1448. Record.push_back(Entry.IsFramework);
  1449. Record.push_back(Entry.IgnoreSysRoot);
  1450. }
  1451. // System header prefixes.
  1452. Record.push_back(HSOpts.SystemHeaderPrefixes.size());
  1453. for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
  1454. AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
  1455. Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
  1456. }
  1457. AddString(HSOpts.ResourceDir, Record);
  1458. AddString(HSOpts.ModuleCachePath, Record);
  1459. AddString(HSOpts.ModuleUserBuildPath, Record);
  1460. Record.push_back(HSOpts.DisableModuleHash);
  1461. Record.push_back(HSOpts.ImplicitModuleMaps);
  1462. Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
  1463. Record.push_back(HSOpts.UseBuiltinIncludes);
  1464. Record.push_back(HSOpts.UseStandardSystemIncludes);
  1465. Record.push_back(HSOpts.UseStandardCXXIncludes);
  1466. Record.push_back(HSOpts.UseLibcxx);
  1467. // Write out the specific module cache path that contains the module files.
  1468. AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
  1469. Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
  1470. // Preprocessor options.
  1471. Record.clear();
  1472. const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
  1473. // Macro definitions.
  1474. Record.push_back(PPOpts.Macros.size());
  1475. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  1476. AddString(PPOpts.Macros[I].first, Record);
  1477. Record.push_back(PPOpts.Macros[I].second);
  1478. }
  1479. // Includes
  1480. Record.push_back(PPOpts.Includes.size());
  1481. for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
  1482. AddString(PPOpts.Includes[I], Record);
  1483. // Macro includes
  1484. Record.push_back(PPOpts.MacroIncludes.size());
  1485. for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
  1486. AddString(PPOpts.MacroIncludes[I], Record);
  1487. Record.push_back(PPOpts.UsePredefines);
  1488. // Detailed record is important since it is used for the module cache hash.
  1489. Record.push_back(PPOpts.DetailedRecord);
  1490. AddString(PPOpts.ImplicitPCHInclude, Record);
  1491. AddString(PPOpts.ImplicitPTHInclude, Record);
  1492. Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
  1493. Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
  1494. // Leave the options block.
  1495. Stream.ExitBlock();
  1496. // Original file name and file ID
  1497. SourceManager &SM = Context.getSourceManager();
  1498. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1499. auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
  1500. FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
  1501. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
  1502. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1503. unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
  1504. Record.clear();
  1505. Record.push_back(ORIGINAL_FILE);
  1506. Record.push_back(SM.getMainFileID().getOpaqueValue());
  1507. EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
  1508. }
  1509. Record.clear();
  1510. Record.push_back(SM.getMainFileID().getOpaqueValue());
  1511. Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
  1512. // Original PCH directory
  1513. if (!OutputFile.empty() && OutputFile != "-") {
  1514. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1515. Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
  1516. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1517. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  1518. SmallString<128> OutputPath(OutputFile);
  1519. SM.getFileManager().makeAbsolutePath(OutputPath);
  1520. StringRef origDir = llvm::sys::path::parent_path(OutputPath);
  1521. RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
  1522. Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
  1523. }
  1524. WriteInputFiles(Context.SourceMgr,
  1525. PP.getHeaderSearchInfo().getHeaderSearchOpts(),
  1526. PP.getLangOpts().Modules);
  1527. Stream.ExitBlock();
  1528. }
  1529. namespace {
  1530. /// An input file.
  1531. struct InputFileEntry {
  1532. const FileEntry *File;
  1533. bool IsSystemFile;
  1534. bool IsTransient;
  1535. bool BufferOverridden;
  1536. bool IsTopLevelModuleMap;
  1537. };
  1538. } // namespace
  1539. void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
  1540. HeaderSearchOptions &HSOpts,
  1541. bool Modules) {
  1542. using namespace llvm;
  1543. Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
  1544. // Create input-file abbreviation.
  1545. auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
  1546. IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
  1547. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  1548. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
  1549. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
  1550. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
  1551. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
  1552. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
  1553. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1554. unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
  1555. // Get all ContentCache objects for files, sorted by whether the file is a
  1556. // system one or not. System files go at the back, users files at the front.
  1557. std::deque<InputFileEntry> SortedFiles;
  1558. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
  1559. // Get this source location entry.
  1560. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1561. assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
  1562. // We only care about file entries that were not overridden.
  1563. if (!SLoc->isFile())
  1564. continue;
  1565. const SrcMgr::FileInfo &File = SLoc->getFile();
  1566. const SrcMgr::ContentCache *Cache = File.getContentCache();
  1567. if (!Cache->OrigEntry)
  1568. continue;
  1569. InputFileEntry Entry;
  1570. Entry.File = Cache->OrigEntry;
  1571. Entry.IsSystemFile = Cache->IsSystemFile;
  1572. Entry.IsTransient = Cache->IsTransient;
  1573. Entry.BufferOverridden = Cache->BufferOverridden;
  1574. Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
  1575. File.getIncludeLoc().isInvalid();
  1576. if (Cache->IsSystemFile)
  1577. SortedFiles.push_back(Entry);
  1578. else
  1579. SortedFiles.push_front(Entry);
  1580. }
  1581. unsigned UserFilesNum = 0;
  1582. // Write out all of the input files.
  1583. std::vector<uint64_t> InputFileOffsets;
  1584. for (const auto &Entry : SortedFiles) {
  1585. uint32_t &InputFileID = InputFileIDs[Entry.File];
  1586. if (InputFileID != 0)
  1587. continue; // already recorded this file.
  1588. // Record this entry's offset.
  1589. InputFileOffsets.push_back(Stream.GetCurrentBitNo());
  1590. InputFileID = InputFileOffsets.size();
  1591. if (!Entry.IsSystemFile)
  1592. ++UserFilesNum;
  1593. // Emit size/modification time for this file.
  1594. // And whether this file was overridden.
  1595. RecordData::value_type Record[] = {
  1596. INPUT_FILE,
  1597. InputFileOffsets.size(),
  1598. (uint64_t)Entry.File->getSize(),
  1599. (uint64_t)getTimestampForOutput(Entry.File),
  1600. Entry.BufferOverridden,
  1601. Entry.IsTransient,
  1602. Entry.IsTopLevelModuleMap};
  1603. EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
  1604. }
  1605. Stream.ExitBlock();
  1606. // Create input file offsets abbreviation.
  1607. auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
  1608. OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
  1609. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
  1610. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
  1611. // input files
  1612. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
  1613. unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
  1614. // Write input file offsets.
  1615. RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
  1616. InputFileOffsets.size(), UserFilesNum};
  1617. Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
  1618. }
  1619. //===----------------------------------------------------------------------===//
  1620. // Source Manager Serialization
  1621. //===----------------------------------------------------------------------===//
  1622. /// Create an abbreviation for the SLocEntry that refers to a
  1623. /// file.
  1624. static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
  1625. using namespace llvm;
  1626. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1627. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
  1628. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1629. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1630. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
  1631. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1632. // FileEntry fields.
  1633. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
  1634. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
  1635. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
  1636. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
  1637. return Stream.EmitAbbrev(std::move(Abbrev));
  1638. }
  1639. /// Create an abbreviation for the SLocEntry that refers to a
  1640. /// buffer.
  1641. static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
  1642. using namespace llvm;
  1643. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1644. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
  1645. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1646. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1647. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
  1648. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1649. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
  1650. return Stream.EmitAbbrev(std::move(Abbrev));
  1651. }
  1652. /// Create an abbreviation for the SLocEntry that refers to a
  1653. /// buffer's blob.
  1654. static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
  1655. bool Compressed) {
  1656. using namespace llvm;
  1657. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1658. Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
  1659. : SM_SLOC_BUFFER_BLOB));
  1660. if (Compressed)
  1661. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
  1662. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
  1663. return Stream.EmitAbbrev(std::move(Abbrev));
  1664. }
  1665. /// Create an abbreviation for the SLocEntry that refers to a macro
  1666. /// expansion.
  1667. static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
  1668. using namespace llvm;
  1669. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1670. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
  1671. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1672. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
  1673. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
  1674. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
  1675. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
  1676. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
  1677. return Stream.EmitAbbrev(std::move(Abbrev));
  1678. }
  1679. namespace {
  1680. // Trait used for the on-disk hash table of header search information.
  1681. class HeaderFileInfoTrait {
  1682. ASTWriter &Writer;
  1683. // Keep track of the framework names we've used during serialization.
  1684. SmallVector<char, 128> FrameworkStringData;
  1685. llvm::StringMap<unsigned> FrameworkNameOffset;
  1686. public:
  1687. HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
  1688. struct key_type {
  1689. StringRef Filename;
  1690. off_t Size;
  1691. time_t ModTime;
  1692. };
  1693. using key_type_ref = const key_type &;
  1694. using UnresolvedModule =
  1695. llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
  1696. struct data_type {
  1697. const HeaderFileInfo &HFI;
  1698. ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
  1699. UnresolvedModule Unresolved;
  1700. };
  1701. using data_type_ref = const data_type &;
  1702. using hash_value_type = unsigned;
  1703. using offset_type = unsigned;
  1704. hash_value_type ComputeHash(key_type_ref key) {
  1705. // The hash is based only on size/time of the file, so that the reader can
  1706. // match even when symlinking or excess path elements ("foo/../", "../")
  1707. // change the form of the name. However, complete path is still the key.
  1708. return llvm::hash_combine(key.Size, key.ModTime);
  1709. }
  1710. std::pair<unsigned, unsigned>
  1711. EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
  1712. using namespace llvm::support;
  1713. endian::Writer LE(Out, little);
  1714. unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
  1715. LE.write<uint16_t>(KeyLen);
  1716. unsigned DataLen = 1 + 2 + 4 + 4;
  1717. for (auto ModInfo : Data.KnownHeaders)
  1718. if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
  1719. DataLen += 4;
  1720. if (Data.Unresolved.getPointer())
  1721. DataLen += 4;
  1722. LE.write<uint8_t>(DataLen);
  1723. return std::make_pair(KeyLen, DataLen);
  1724. }
  1725. void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
  1726. using namespace llvm::support;
  1727. endian::Writer LE(Out, little);
  1728. LE.write<uint64_t>(key.Size);
  1729. KeyLen -= 8;
  1730. LE.write<uint64_t>(key.ModTime);
  1731. KeyLen -= 8;
  1732. Out.write(key.Filename.data(), KeyLen);
  1733. }
  1734. void EmitData(raw_ostream &Out, key_type_ref key,
  1735. data_type_ref Data, unsigned DataLen) {
  1736. using namespace llvm::support;
  1737. endian::Writer LE(Out, little);
  1738. uint64_t Start = Out.tell(); (void)Start;
  1739. unsigned char Flags = (Data.HFI.isImport << 5)
  1740. | (Data.HFI.isPragmaOnce << 4)
  1741. | (Data.HFI.DirInfo << 1)
  1742. | Data.HFI.IndexHeaderMapHeader;
  1743. LE.write<uint8_t>(Flags);
  1744. LE.write<uint16_t>(Data.HFI.NumIncludes);
  1745. if (!Data.HFI.ControllingMacro)
  1746. LE.write<uint32_t>(Data.HFI.ControllingMacroID);
  1747. else
  1748. LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
  1749. unsigned Offset = 0;
  1750. if (!Data.HFI.Framework.empty()) {
  1751. // If this header refers into a framework, save the framework name.
  1752. llvm::StringMap<unsigned>::iterator Pos
  1753. = FrameworkNameOffset.find(Data.HFI.Framework);
  1754. if (Pos == FrameworkNameOffset.end()) {
  1755. Offset = FrameworkStringData.size() + 1;
  1756. FrameworkStringData.append(Data.HFI.Framework.begin(),
  1757. Data.HFI.Framework.end());
  1758. FrameworkStringData.push_back(0);
  1759. FrameworkNameOffset[Data.HFI.Framework] = Offset;
  1760. } else
  1761. Offset = Pos->second;
  1762. }
  1763. LE.write<uint32_t>(Offset);
  1764. auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
  1765. if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
  1766. uint32_t Value = (ModID << 2) | (unsigned)Role;
  1767. assert((Value >> 2) == ModID && "overflow in header module info");
  1768. LE.write<uint32_t>(Value);
  1769. }
  1770. };
  1771. // FIXME: If the header is excluded, we should write out some
  1772. // record of that fact.
  1773. for (auto ModInfo : Data.KnownHeaders)
  1774. EmitModule(ModInfo.getModule(), ModInfo.getRole());
  1775. if (Data.Unresolved.getPointer())
  1776. EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
  1777. assert(Out.tell() - Start == DataLen && "Wrong data length");
  1778. }
  1779. const char *strings_begin() const { return FrameworkStringData.begin(); }
  1780. const char *strings_end() const { return FrameworkStringData.end(); }
  1781. };
  1782. } // namespace
  1783. /// Write the header search block for the list of files that
  1784. ///
  1785. /// \param HS The header search structure to save.
  1786. void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
  1787. HeaderFileInfoTrait GeneratorTrait(*this);
  1788. llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
  1789. SmallVector<const char *, 4> SavedStrings;
  1790. unsigned NumHeaderSearchEntries = 0;
  1791. // Find all unresolved headers for the current module. We generally will
  1792. // have resolved them before we get here, but not necessarily: we might be
  1793. // compiling a preprocessed module, where there is no requirement for the
  1794. // original files to exist any more.
  1795. const HeaderFileInfo Empty; // So we can take a reference.
  1796. if (WritingModule) {
  1797. llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
  1798. while (!Worklist.empty()) {
  1799. Module *M = Worklist.pop_back_val();
  1800. if (!M->isAvailable())
  1801. continue;
  1802. // Map to disk files where possible, to pick up any missing stat
  1803. // information. This also means we don't need to check the unresolved
  1804. // headers list when emitting resolved headers in the first loop below.
  1805. // FIXME: It'd be preferable to avoid doing this if we were given
  1806. // sufficient stat information in the module map.
  1807. HS.getModuleMap().resolveHeaderDirectives(M);
  1808. // If the file didn't exist, we can still create a module if we were given
  1809. // enough information in the module map.
  1810. for (auto U : M->MissingHeaders) {
  1811. // Check that we were given enough information to build a module
  1812. // without this file existing on disk.
  1813. if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
  1814. PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
  1815. << WritingModule->getFullModuleName() << U.Size.hasValue()
  1816. << U.FileName;
  1817. continue;
  1818. }
  1819. // Form the effective relative pathname for the file.
  1820. SmallString<128> Filename(M->Directory->getName());
  1821. llvm::sys::path::append(Filename, U.FileName);
  1822. PreparePathForOutput(Filename);
  1823. StringRef FilenameDup = strdup(Filename.c_str());
  1824. SavedStrings.push_back(FilenameDup.data());
  1825. HeaderFileInfoTrait::key_type Key = {
  1826. FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
  1827. };
  1828. HeaderFileInfoTrait::data_type Data = {
  1829. Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
  1830. };
  1831. // FIXME: Deal with cases where there are multiple unresolved header
  1832. // directives in different submodules for the same header.
  1833. Generator.insert(Key, Data, GeneratorTrait);
  1834. ++NumHeaderSearchEntries;
  1835. }
  1836. Worklist.append(M->submodule_begin(), M->submodule_end());
  1837. }
  1838. }
  1839. SmallVector<const FileEntry *, 16> FilesByUID;
  1840. HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
  1841. if (FilesByUID.size() > HS.header_file_size())
  1842. FilesByUID.resize(HS.header_file_size());
  1843. for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
  1844. const FileEntry *File = FilesByUID[UID];
  1845. if (!File)
  1846. continue;
  1847. // Get the file info. This will load info from the external source if
  1848. // necessary. Skip emitting this file if we have no information on it
  1849. // as a header file (in which case HFI will be null) or if it hasn't
  1850. // changed since it was loaded. Also skip it if it's for a modular header
  1851. // from a different module; in that case, we rely on the module(s)
  1852. // containing the header to provide this information.
  1853. const HeaderFileInfo *HFI =
  1854. HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
  1855. if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
  1856. continue;
  1857. // Massage the file path into an appropriate form.
  1858. StringRef Filename = File->getName();
  1859. SmallString<128> FilenameTmp(Filename);
  1860. if (PreparePathForOutput(FilenameTmp)) {
  1861. // If we performed any translation on the file name at all, we need to
  1862. // save this string, since the generator will refer to it later.
  1863. Filename = StringRef(strdup(FilenameTmp.c_str()));
  1864. SavedStrings.push_back(Filename.data());
  1865. }
  1866. HeaderFileInfoTrait::key_type Key = {
  1867. Filename, File->getSize(), getTimestampForOutput(File)
  1868. };
  1869. HeaderFileInfoTrait::data_type Data = {
  1870. *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
  1871. };
  1872. Generator.insert(Key, Data, GeneratorTrait);
  1873. ++NumHeaderSearchEntries;
  1874. }
  1875. // Create the on-disk hash table in a buffer.
  1876. SmallString<4096> TableData;
  1877. uint32_t BucketOffset;
  1878. {
  1879. using namespace llvm::support;
  1880. llvm::raw_svector_ostream Out(TableData);
  1881. // Make sure that no bucket is at offset 0
  1882. endian::write<uint32_t>(Out, 0, little);
  1883. BucketOffset = Generator.Emit(Out, GeneratorTrait);
  1884. }
  1885. // Create a blob abbreviation
  1886. using namespace llvm;
  1887. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1888. Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
  1889. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1890. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1891. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1892. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1893. unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  1894. // Write the header search table
  1895. RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
  1896. NumHeaderSearchEntries, TableData.size()};
  1897. TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
  1898. Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
  1899. // Free all of the strings we had to duplicate.
  1900. for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
  1901. free(const_cast<char *>(SavedStrings[I]));
  1902. }
  1903. static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
  1904. unsigned SLocBufferBlobCompressedAbbrv,
  1905. unsigned SLocBufferBlobAbbrv) {
  1906. using RecordDataType = ASTWriter::RecordData::value_type;
  1907. // Compress the buffer if possible. We expect that almost all PCM
  1908. // consumers will not want its contents.
  1909. SmallString<0> CompressedBuffer;
  1910. if (llvm::zlib::isAvailable()) {
  1911. llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
  1912. if (!E) {
  1913. RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
  1914. Blob.size() - 1};
  1915. Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
  1916. CompressedBuffer);
  1917. return;
  1918. }
  1919. llvm::consumeError(std::move(E));
  1920. }
  1921. RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
  1922. Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
  1923. }
  1924. /// Writes the block containing the serialized form of the
  1925. /// source manager.
  1926. ///
  1927. /// TODO: We should probably use an on-disk hash table (stored in a
  1928. /// blob), indexed based on the file name, so that we only create
  1929. /// entries for files that we actually need. In the common case (no
  1930. /// errors), we probably won't have to create file entries for any of
  1931. /// the files in the AST.
  1932. void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
  1933. const Preprocessor &PP) {
  1934. RecordData Record;
  1935. // Enter the source manager block.
  1936. Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
  1937. // Abbreviations for the various kinds of source-location entries.
  1938. unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
  1939. unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
  1940. unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
  1941. unsigned SLocBufferBlobCompressedAbbrv =
  1942. CreateSLocBufferBlobAbbrev(Stream, true);
  1943. unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
  1944. // Write out the source location entry table. We skip the first
  1945. // entry, which is always the same dummy entry.
  1946. std::vector<uint32_t> SLocEntryOffsets;
  1947. RecordData PreloadSLocs;
  1948. SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
  1949. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
  1950. I != N; ++I) {
  1951. // Get this source location entry.
  1952. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1953. FileID FID = FileID::get(I);
  1954. assert(&SourceMgr.getSLocEntry(FID) == SLoc);
  1955. // Record the offset of this source-location entry.
  1956. SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
  1957. // Figure out which record code to use.
  1958. unsigned Code;
  1959. if (SLoc->isFile()) {
  1960. const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
  1961. if (Cache->OrigEntry) {
  1962. Code = SM_SLOC_FILE_ENTRY;
  1963. } else
  1964. Code = SM_SLOC_BUFFER_ENTRY;
  1965. } else
  1966. Code = SM_SLOC_EXPANSION_ENTRY;
  1967. Record.clear();
  1968. Record.push_back(Code);
  1969. // Starting offset of this entry within this module, so skip the dummy.
  1970. Record.push_back(SLoc->getOffset() - 2);
  1971. if (SLoc->isFile()) {
  1972. const SrcMgr::FileInfo &File = SLoc->getFile();
  1973. AddSourceLocation(File.getIncludeLoc(), Record);
  1974. Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
  1975. Record.push_back(File.hasLineDirectives());
  1976. const SrcMgr::ContentCache *Content = File.getContentCache();
  1977. bool EmitBlob = false;
  1978. if (Content->OrigEntry) {
  1979. assert(Content->OrigEntry == Content->ContentsEntry &&
  1980. "Writing to AST an overridden file is not supported");
  1981. // The source location entry is a file. Emit input file ID.
  1982. assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
  1983. Record.push_back(InputFileIDs[Content->OrigEntry]);
  1984. Record.push_back(File.NumCreatedFIDs);
  1985. FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
  1986. if (FDI != FileDeclIDs.end()) {
  1987. Record.push_back(FDI->second->FirstDeclIndex);
  1988. Record.push_back(FDI->second->DeclIDs.size());
  1989. } else {
  1990. Record.push_back(0);
  1991. Record.push_back(0);
  1992. }
  1993. Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
  1994. if (Content->BufferOverridden || Content->IsTransient)
  1995. EmitBlob = true;
  1996. } else {
  1997. // The source location entry is a buffer. The blob associated
  1998. // with this entry contains the contents of the buffer.
  1999. // We add one to the size so that we capture the trailing NULL
  2000. // that is required by llvm::MemoryBuffer::getMemBuffer (on
  2001. // the reader side).
  2002. const llvm::MemoryBuffer *Buffer
  2003. = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
  2004. StringRef Name = Buffer->getBufferIdentifier();
  2005. Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
  2006. StringRef(Name.data(), Name.size() + 1));
  2007. EmitBlob = true;
  2008. if (Name == "<built-in>")
  2009. PreloadSLocs.push_back(SLocEntryOffsets.size());
  2010. }
  2011. if (EmitBlob) {
  2012. // Include the implicit terminating null character in the on-disk buffer
  2013. // if we're writing it uncompressed.
  2014. const llvm::MemoryBuffer *Buffer =
  2015. Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
  2016. StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
  2017. emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
  2018. SLocBufferBlobAbbrv);
  2019. }
  2020. } else {
  2021. // The source location entry is a macro expansion.
  2022. const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
  2023. AddSourceLocation(Expansion.getSpellingLoc(), Record);
  2024. AddSourceLocation(Expansion.getExpansionLocStart(), Record);
  2025. AddSourceLocation(Expansion.isMacroArgExpansion()
  2026. ? SourceLocation()
  2027. : Expansion.getExpansionLocEnd(),
  2028. Record);
  2029. Record.push_back(Expansion.isExpansionTokenRange());
  2030. // Compute the token length for this macro expansion.
  2031. unsigned NextOffset = SourceMgr.getNextLocalOffset();
  2032. if (I + 1 != N)
  2033. NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
  2034. Record.push_back(NextOffset - SLoc->getOffset() - 1);
  2035. Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
  2036. }
  2037. }
  2038. Stream.ExitBlock();
  2039. if (SLocEntryOffsets.empty())
  2040. return;
  2041. // Write the source-location offsets table into the AST block. This
  2042. // table is used for lazily loading source-location information.
  2043. using namespace llvm;
  2044. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2045. Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
  2046. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
  2047. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
  2048. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
  2049. unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2050. {
  2051. RecordData::value_type Record[] = {
  2052. SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
  2053. SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
  2054. Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
  2055. bytes(SLocEntryOffsets));
  2056. }
  2057. // Write the source location entry preloads array, telling the AST
  2058. // reader which source locations entries it should load eagerly.
  2059. Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
  2060. // Write the line table. It depends on remapping working, so it must come
  2061. // after the source location offsets.
  2062. if (SourceMgr.hasLineTable()) {
  2063. LineTableInfo &LineTable = SourceMgr.getLineTable();
  2064. Record.clear();
  2065. // Emit the needed file names.
  2066. llvm::DenseMap<int, int> FilenameMap;
  2067. FilenameMap[-1] = -1; // For unspecified filenames.
  2068. for (const auto &L : LineTable) {
  2069. if (L.first.ID < 0)
  2070. continue;
  2071. for (auto &LE : L.second) {
  2072. if (FilenameMap.insert(std::make_pair(LE.FilenameID,
  2073. FilenameMap.size() - 1)).second)
  2074. AddPath(LineTable.getFilename(LE.FilenameID), Record);
  2075. }
  2076. }
  2077. Record.push_back(0);
  2078. // Emit the line entries
  2079. for (const auto &L : LineTable) {
  2080. // Only emit entries for local files.
  2081. if (L.first.ID < 0)
  2082. continue;
  2083. // Emit the file ID
  2084. Record.push_back(L.first.ID);
  2085. // Emit the line entries
  2086. Record.push_back(L.second.size());
  2087. for (const auto &LE : L.second) {
  2088. Record.push_back(LE.FileOffset);
  2089. Record.push_back(LE.LineNo);
  2090. Record.push_back(FilenameMap[LE.FilenameID]);
  2091. Record.push_back((unsigned)LE.FileKind);
  2092. Record.push_back(LE.IncludeOffset);
  2093. }
  2094. }
  2095. Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
  2096. }
  2097. }
  2098. //===----------------------------------------------------------------------===//
  2099. // Preprocessor Serialization
  2100. //===----------------------------------------------------------------------===//
  2101. static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
  2102. const Preprocessor &PP) {
  2103. if (MacroInfo *MI = MD->getMacroInfo())
  2104. if (MI->isBuiltinMacro())
  2105. return true;
  2106. if (IsModule) {
  2107. SourceLocation Loc = MD->getLocation();
  2108. if (Loc.isInvalid())
  2109. return true;
  2110. if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
  2111. return true;
  2112. }
  2113. return false;
  2114. }
  2115. /// Writes the block containing the serialized form of the
  2116. /// preprocessor.
  2117. void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
  2118. PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
  2119. if (PPRec)
  2120. WritePreprocessorDetail(*PPRec);
  2121. RecordData Record;
  2122. RecordData ModuleMacroRecord;
  2123. // If the preprocessor __COUNTER__ value has been bumped, remember it.
  2124. if (PP.getCounterValue() != 0) {
  2125. RecordData::value_type Record[] = {PP.getCounterValue()};
  2126. Stream.EmitRecord(PP_COUNTER_VALUE, Record);
  2127. }
  2128. if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
  2129. assert(!IsModule);
  2130. auto SkipInfo = PP.getPreambleSkipInfo();
  2131. if (SkipInfo.hasValue()) {
  2132. Record.push_back(true);
  2133. AddSourceLocation(SkipInfo->HashTokenLoc, Record);
  2134. AddSourceLocation(SkipInfo->IfTokenLoc, Record);
  2135. Record.push_back(SkipInfo->FoundNonSkipPortion);
  2136. Record.push_back(SkipInfo->FoundElse);
  2137. AddSourceLocation(SkipInfo->ElseLoc, Record);
  2138. } else {
  2139. Record.push_back(false);
  2140. }
  2141. for (const auto &Cond : PP.getPreambleConditionalStack()) {
  2142. AddSourceLocation(Cond.IfLoc, Record);
  2143. Record.push_back(Cond.WasSkipping);
  2144. Record.push_back(Cond.FoundNonSkip);
  2145. Record.push_back(Cond.FoundElse);
  2146. }
  2147. Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
  2148. Record.clear();
  2149. }
  2150. // Enter the preprocessor block.
  2151. Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
  2152. // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
  2153. // FIXME: Include a location for the use, and say which one was used.
  2154. if (PP.SawDateOrTime())
  2155. PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
  2156. // Loop over all the macro directives that are live at the end of the file,
  2157. // emitting each to the PP section.
  2158. // Construct the list of identifiers with macro directives that need to be
  2159. // serialized.
  2160. SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
  2161. for (auto &Id : PP.getIdentifierTable())
  2162. if (Id.second->hadMacroDefinition() &&
  2163. (!Id.second->isFromAST() ||
  2164. Id.second->hasChangedSinceDeserialization()))
  2165. MacroIdentifiers.push_back(Id.second);
  2166. // Sort the set of macro definitions that need to be serialized by the
  2167. // name of the macro, to provide a stable ordering.
  2168. llvm::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
  2169. llvm::less_ptr<IdentifierInfo>());
  2170. // Emit the macro directives as a list and associate the offset with the
  2171. // identifier they belong to.
  2172. for (const IdentifierInfo *Name : MacroIdentifiers) {
  2173. MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
  2174. auto StartOffset = Stream.GetCurrentBitNo();
  2175. // Emit the macro directives in reverse source order.
  2176. for (; MD; MD = MD->getPrevious()) {
  2177. // Once we hit an ignored macro, we're done: the rest of the chain
  2178. // will all be ignored macros.
  2179. if (shouldIgnoreMacro(MD, IsModule, PP))
  2180. break;
  2181. AddSourceLocation(MD->getLocation(), Record);
  2182. Record.push_back(MD->getKind());
  2183. if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
  2184. Record.push_back(getMacroRef(DefMD->getInfo(), Name));
  2185. } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
  2186. Record.push_back(VisMD->isPublic());
  2187. }
  2188. }
  2189. // Write out any exported module macros.
  2190. bool EmittedModuleMacros = false;
  2191. // We write out exported module macros for PCH as well.
  2192. auto Leafs = PP.getLeafModuleMacros(Name);
  2193. SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
  2194. llvm::DenseMap<ModuleMacro*, unsigned> Visits;
  2195. while (!Worklist.empty()) {
  2196. auto *Macro = Worklist.pop_back_val();
  2197. // Emit a record indicating this submodule exports this macro.
  2198. ModuleMacroRecord.push_back(
  2199. getSubmoduleID(Macro->getOwningModule()));
  2200. ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
  2201. for (auto *M : Macro->overrides())
  2202. ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
  2203. Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
  2204. ModuleMacroRecord.clear();
  2205. // Enqueue overridden macros once we've visited all their ancestors.
  2206. for (auto *M : Macro->overrides())
  2207. if (++Visits[M] == M->getNumOverridingMacros())
  2208. Worklist.push_back(M);
  2209. EmittedModuleMacros = true;
  2210. }
  2211. if (Record.empty() && !EmittedModuleMacros)
  2212. continue;
  2213. IdentMacroDirectivesOffsetMap[Name] = StartOffset;
  2214. Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
  2215. Record.clear();
  2216. }
  2217. /// Offsets of each of the macros into the bitstream, indexed by
  2218. /// the local macro ID
  2219. ///
  2220. /// For each identifier that is associated with a macro, this map
  2221. /// provides the offset into the bitstream where that macro is
  2222. /// defined.
  2223. std::vector<uint32_t> MacroOffsets;
  2224. for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
  2225. const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
  2226. MacroInfo *MI = MacroInfosToEmit[I].MI;
  2227. MacroID ID = MacroInfosToEmit[I].ID;
  2228. if (ID < FirstMacroID) {
  2229. assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
  2230. continue;
  2231. }
  2232. // Record the local offset of this macro.
  2233. unsigned Index = ID - FirstMacroID;
  2234. if (Index == MacroOffsets.size())
  2235. MacroOffsets.push_back(Stream.GetCurrentBitNo());
  2236. else {
  2237. if (Index > MacroOffsets.size())
  2238. MacroOffsets.resize(Index + 1);
  2239. MacroOffsets[Index] = Stream.GetCurrentBitNo();
  2240. }
  2241. AddIdentifierRef(Name, Record);
  2242. AddSourceLocation(MI->getDefinitionLoc(), Record);
  2243. AddSourceLocation(MI->getDefinitionEndLoc(), Record);
  2244. Record.push_back(MI->isUsed());
  2245. Record.push_back(MI->isUsedForHeaderGuard());
  2246. unsigned Code;
  2247. if (MI->isObjectLike()) {
  2248. Code = PP_MACRO_OBJECT_LIKE;
  2249. } else {
  2250. Code = PP_MACRO_FUNCTION_LIKE;
  2251. Record.push_back(MI->isC99Varargs());
  2252. Record.push_back(MI->isGNUVarargs());
  2253. Record.push_back(MI->hasCommaPasting());
  2254. Record.push_back(MI->getNumParams());
  2255. for (const IdentifierInfo *Param : MI->params())
  2256. AddIdentifierRef(Param, Record);
  2257. }
  2258. // If we have a detailed preprocessing record, record the macro definition
  2259. // ID that corresponds to this macro.
  2260. if (PPRec)
  2261. Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
  2262. Stream.EmitRecord(Code, Record);
  2263. Record.clear();
  2264. // Emit the tokens array.
  2265. for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
  2266. // Note that we know that the preprocessor does not have any annotation
  2267. // tokens in it because they are created by the parser, and thus can't
  2268. // be in a macro definition.
  2269. const Token &Tok = MI->getReplacementToken(TokNo);
  2270. AddToken(Tok, Record);
  2271. Stream.EmitRecord(PP_TOKEN, Record);
  2272. Record.clear();
  2273. }
  2274. ++NumMacros;
  2275. }
  2276. Stream.ExitBlock();
  2277. // Write the offsets table for macro IDs.
  2278. using namespace llvm;
  2279. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2280. Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
  2281. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
  2282. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  2283. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2284. unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2285. {
  2286. RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
  2287. FirstMacroID - NUM_PREDEF_MACRO_IDS};
  2288. Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
  2289. }
  2290. }
  2291. void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
  2292. if (PPRec.local_begin() == PPRec.local_end())
  2293. return;
  2294. SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
  2295. // Enter the preprocessor block.
  2296. Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
  2297. // If the preprocessor has a preprocessing record, emit it.
  2298. unsigned NumPreprocessingRecords = 0;
  2299. using namespace llvm;
  2300. // Set up the abbreviation for
  2301. unsigned InclusionAbbrev = 0;
  2302. {
  2303. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2304. Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
  2305. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
  2306. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
  2307. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
  2308. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
  2309. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2310. InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2311. }
  2312. unsigned FirstPreprocessorEntityID
  2313. = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
  2314. + NUM_PREDEF_PP_ENTITY_IDS;
  2315. unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
  2316. RecordData Record;
  2317. for (PreprocessingRecord::iterator E = PPRec.local_begin(),
  2318. EEnd = PPRec.local_end();
  2319. E != EEnd;
  2320. (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
  2321. Record.clear();
  2322. PreprocessedEntityOffsets.push_back(
  2323. PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
  2324. if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
  2325. // Record this macro definition's ID.
  2326. MacroDefinitions[MD] = NextPreprocessorEntityID;
  2327. AddIdentifierRef(MD->getName(), Record);
  2328. Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
  2329. continue;
  2330. }
  2331. if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
  2332. Record.push_back(ME->isBuiltinMacro());
  2333. if (ME->isBuiltinMacro())
  2334. AddIdentifierRef(ME->getName(), Record);
  2335. else
  2336. Record.push_back(MacroDefinitions[ME->getDefinition()]);
  2337. Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
  2338. continue;
  2339. }
  2340. if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
  2341. Record.push_back(PPD_INCLUSION_DIRECTIVE);
  2342. Record.push_back(ID->getFileName().size());
  2343. Record.push_back(ID->wasInQuotes());
  2344. Record.push_back(static_cast<unsigned>(ID->getKind()));
  2345. Record.push_back(ID->importedModule());
  2346. SmallString<64> Buffer;
  2347. Buffer += ID->getFileName();
  2348. // Check that the FileEntry is not null because it was not resolved and
  2349. // we create a PCH even with compiler errors.
  2350. if (ID->getFile())
  2351. Buffer += ID->getFile()->getName();
  2352. Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
  2353. continue;
  2354. }
  2355. llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
  2356. }
  2357. Stream.ExitBlock();
  2358. // Write the offsets table for the preprocessing record.
  2359. if (NumPreprocessingRecords > 0) {
  2360. assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
  2361. // Write the offsets table for identifier IDs.
  2362. using namespace llvm;
  2363. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2364. Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
  2365. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
  2366. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2367. unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2368. RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
  2369. FirstPreprocessorEntityID -
  2370. NUM_PREDEF_PP_ENTITY_IDS};
  2371. Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
  2372. bytes(PreprocessedEntityOffsets));
  2373. }
  2374. // Write the skipped region table for the preprocessing record.
  2375. ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
  2376. if (SkippedRanges.size() > 0) {
  2377. std::vector<PPSkippedRange> SerializedSkippedRanges;
  2378. SerializedSkippedRanges.reserve(SkippedRanges.size());
  2379. for (auto const& Range : SkippedRanges)
  2380. SerializedSkippedRanges.emplace_back(Range);
  2381. using namespace llvm;
  2382. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2383. Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
  2384. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2385. unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2386. Record.clear();
  2387. Record.push_back(PPD_SKIPPED_RANGES);
  2388. Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
  2389. bytes(SerializedSkippedRanges));
  2390. }
  2391. }
  2392. unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
  2393. if (!Mod)
  2394. return 0;
  2395. llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
  2396. if (Known != SubmoduleIDs.end())
  2397. return Known->second;
  2398. auto *Top = Mod->getTopLevelModule();
  2399. if (Top != WritingModule &&
  2400. (getLangOpts().CompilingPCH ||
  2401. !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
  2402. return 0;
  2403. return SubmoduleIDs[Mod] = NextSubmoduleID++;
  2404. }
  2405. unsigned ASTWriter::getSubmoduleID(Module *Mod) {
  2406. // FIXME: This can easily happen, if we have a reference to a submodule that
  2407. // did not result in us loading a module file for that submodule. For
  2408. // instance, a cross-top-level-module 'conflict' declaration will hit this.
  2409. unsigned ID = getLocalOrImportedSubmoduleID(Mod);
  2410. assert((ID || !Mod) &&
  2411. "asked for module ID for non-local, non-imported module");
  2412. return ID;
  2413. }
  2414. /// Compute the number of modules within the given tree (including the
  2415. /// given module).
  2416. static unsigned getNumberOfModules(Module *Mod) {
  2417. unsigned ChildModules = 0;
  2418. for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
  2419. Sub != SubEnd; ++Sub)
  2420. ChildModules += getNumberOfModules(*Sub);
  2421. return ChildModules + 1;
  2422. }
  2423. void ASTWriter::WriteSubmodules(Module *WritingModule) {
  2424. // Enter the submodule description block.
  2425. Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
  2426. // Write the abbreviations needed for the submodules block.
  2427. using namespace llvm;
  2428. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2429. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
  2430. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  2431. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
  2432. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
  2433. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  2434. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
  2435. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
  2436. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
  2437. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
  2438. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
  2439. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
  2440. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
  2441. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
  2442. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2443. unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2444. Abbrev = std::make_shared<BitCodeAbbrev>();
  2445. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
  2446. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2447. unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2448. Abbrev = std::make_shared<BitCodeAbbrev>();
  2449. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
  2450. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2451. unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2452. Abbrev = std::make_shared<BitCodeAbbrev>();
  2453. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
  2454. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2455. unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2456. Abbrev = std::make_shared<BitCodeAbbrev>();
  2457. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
  2458. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2459. unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2460. Abbrev = std::make_shared<BitCodeAbbrev>();
  2461. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
  2462. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
  2463. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
  2464. unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2465. Abbrev = std::make_shared<BitCodeAbbrev>();
  2466. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
  2467. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2468. unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2469. Abbrev = std::make_shared<BitCodeAbbrev>();
  2470. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
  2471. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2472. unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2473. Abbrev = std::make_shared<BitCodeAbbrev>();
  2474. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
  2475. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2476. unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2477. Abbrev = std::make_shared<BitCodeAbbrev>();
  2478. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
  2479. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2480. unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2481. Abbrev = std::make_shared<BitCodeAbbrev>();
  2482. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
  2483. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  2484. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2485. unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2486. Abbrev = std::make_shared<BitCodeAbbrev>();
  2487. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
  2488. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
  2489. unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2490. Abbrev = std::make_shared<BitCodeAbbrev>();
  2491. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
  2492. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
  2493. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
  2494. unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2495. Abbrev = std::make_shared<BitCodeAbbrev>();
  2496. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
  2497. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
  2498. unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2499. // Write the submodule metadata block.
  2500. RecordData::value_type Record[] = {
  2501. getNumberOfModules(WritingModule),
  2502. FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
  2503. Stream.EmitRecord(SUBMODULE_METADATA, Record);
  2504. // Write all of the submodules.
  2505. std::queue<Module *> Q;
  2506. Q.push(WritingModule);
  2507. while (!Q.empty()) {
  2508. Module *Mod = Q.front();
  2509. Q.pop();
  2510. unsigned ID = getSubmoduleID(Mod);
  2511. uint64_t ParentID = 0;
  2512. if (Mod->Parent) {
  2513. assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
  2514. ParentID = SubmoduleIDs[Mod->Parent];
  2515. }
  2516. // Emit the definition of the block.
  2517. {
  2518. RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
  2519. ID,
  2520. ParentID,
  2521. (RecordData::value_type)Mod->Kind,
  2522. Mod->IsFramework,
  2523. Mod->IsExplicit,
  2524. Mod->IsSystem,
  2525. Mod->IsExternC,
  2526. Mod->InferSubmodules,
  2527. Mod->InferExplicitSubmodules,
  2528. Mod->InferExportWildcard,
  2529. Mod->ConfigMacrosExhaustive,
  2530. Mod->ModuleMapIsPrivate};
  2531. Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
  2532. }
  2533. // Emit the requirements.
  2534. for (const auto &R : Mod->Requirements) {
  2535. RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
  2536. Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
  2537. }
  2538. // Emit the umbrella header, if there is one.
  2539. if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
  2540. RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
  2541. Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
  2542. UmbrellaHeader.NameAsWritten);
  2543. } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
  2544. RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
  2545. Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
  2546. UmbrellaDir.NameAsWritten);
  2547. }
  2548. // Emit the headers.
  2549. struct {
  2550. unsigned RecordKind;
  2551. unsigned Abbrev;
  2552. Module::HeaderKind HeaderKind;
  2553. } HeaderLists[] = {
  2554. {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
  2555. {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
  2556. {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
  2557. {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
  2558. Module::HK_PrivateTextual},
  2559. {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
  2560. };
  2561. for (auto &HL : HeaderLists) {
  2562. RecordData::value_type Record[] = {HL.RecordKind};
  2563. for (auto &H : Mod->Headers[HL.HeaderKind])
  2564. Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
  2565. }
  2566. // Emit the top headers.
  2567. {
  2568. auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
  2569. RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
  2570. for (auto *H : TopHeaders)
  2571. Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
  2572. }
  2573. // Emit the imports.
  2574. if (!Mod->Imports.empty()) {
  2575. RecordData Record;
  2576. for (auto *I : Mod->Imports)
  2577. Record.push_back(getSubmoduleID(I));
  2578. Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
  2579. }
  2580. // Emit the exports.
  2581. if (!Mod->Exports.empty()) {
  2582. RecordData Record;
  2583. for (const auto &E : Mod->Exports) {
  2584. // FIXME: This may fail; we don't require that all exported modules
  2585. // are local or imported.
  2586. Record.push_back(getSubmoduleID(E.getPointer()));
  2587. Record.push_back(E.getInt());
  2588. }
  2589. Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
  2590. }
  2591. //FIXME: How do we emit the 'use'd modules? They may not be submodules.
  2592. // Might be unnecessary as use declarations are only used to build the
  2593. // module itself.
  2594. // Emit the link libraries.
  2595. for (const auto &LL : Mod->LinkLibraries) {
  2596. RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
  2597. LL.IsFramework};
  2598. Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
  2599. }
  2600. // Emit the conflicts.
  2601. for (const auto &C : Mod->Conflicts) {
  2602. // FIXME: This may fail; we don't require that all conflicting modules
  2603. // are local or imported.
  2604. RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
  2605. getSubmoduleID(C.Other)};
  2606. Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
  2607. }
  2608. // Emit the configuration macros.
  2609. for (const auto &CM : Mod->ConfigMacros) {
  2610. RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
  2611. Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
  2612. }
  2613. // Emit the initializers, if any.
  2614. RecordData Inits;
  2615. for (Decl *D : Context->getModuleInitializers(Mod))
  2616. Inits.push_back(GetDeclRef(D));
  2617. if (!Inits.empty())
  2618. Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
  2619. // Emit the name of the re-exported module, if any.
  2620. if (!Mod->ExportAsModule.empty()) {
  2621. RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
  2622. Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
  2623. }
  2624. // Queue up the submodules of this module.
  2625. for (auto *M : Mod->submodules())
  2626. Q.push(M);
  2627. }
  2628. Stream.ExitBlock();
  2629. assert((NextSubmoduleID - FirstSubmoduleID ==
  2630. getNumberOfModules(WritingModule)) &&
  2631. "Wrong # of submodules; found a reference to a non-local, "
  2632. "non-imported submodule?");
  2633. }
  2634. void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
  2635. bool isModule) {
  2636. llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
  2637. DiagStateIDMap;
  2638. unsigned CurrID = 0;
  2639. RecordData Record;
  2640. auto EncodeDiagStateFlags =
  2641. [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
  2642. unsigned Result = (unsigned)DS->ExtBehavior;
  2643. for (unsigned Val :
  2644. {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
  2645. (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
  2646. (unsigned)DS->SuppressSystemWarnings})
  2647. Result = (Result << 1) | Val;
  2648. return Result;
  2649. };
  2650. unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
  2651. Record.push_back(Flags);
  2652. auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
  2653. bool IncludeNonPragmaStates) {
  2654. // Ensure that the diagnostic state wasn't modified since it was created.
  2655. // We will not correctly round-trip this information otherwise.
  2656. assert(Flags == EncodeDiagStateFlags(State) &&
  2657. "diag state flags vary in single AST file");
  2658. unsigned &DiagStateID = DiagStateIDMap[State];
  2659. Record.push_back(DiagStateID);
  2660. if (DiagStateID == 0) {
  2661. DiagStateID = ++CurrID;
  2662. // Add a placeholder for the number of mappings.
  2663. auto SizeIdx = Record.size();
  2664. Record.emplace_back();
  2665. for (const auto &I : *State) {
  2666. if (I.second.isPragma() || IncludeNonPragmaStates) {
  2667. Record.push_back(I.first);
  2668. Record.push_back(I.second.serialize());
  2669. }
  2670. }
  2671. // Update the placeholder.
  2672. Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
  2673. }
  2674. };
  2675. AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
  2676. // Reserve a spot for the number of locations with state transitions.
  2677. auto NumLocationsIdx = Record.size();
  2678. Record.emplace_back();
  2679. // Emit the state transitions.
  2680. unsigned NumLocations = 0;
  2681. for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
  2682. if (!FileIDAndFile.first.isValid() ||
  2683. !FileIDAndFile.second.HasLocalTransitions)
  2684. continue;
  2685. ++NumLocations;
  2686. SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
  2687. assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
  2688. AddSourceLocation(Loc, Record);
  2689. Record.push_back(FileIDAndFile.second.StateTransitions.size());
  2690. for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
  2691. Record.push_back(StatePoint.Offset);
  2692. AddDiagState(StatePoint.State, false);
  2693. }
  2694. }
  2695. // Backpatch the number of locations.
  2696. Record[NumLocationsIdx] = NumLocations;
  2697. // Emit CurDiagStateLoc. Do it last in order to match source order.
  2698. //
  2699. // This also protects against a hypothetical corner case with simulating
  2700. // -Werror settings for implicit modules in the ASTReader, where reading
  2701. // CurDiagState out of context could change whether warning pragmas are
  2702. // treated as errors.
  2703. AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
  2704. AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
  2705. Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
  2706. }
  2707. //===----------------------------------------------------------------------===//
  2708. // Type Serialization
  2709. //===----------------------------------------------------------------------===//
  2710. /// Write the representation of a type to the AST stream.
  2711. void ASTWriter::WriteType(QualType T) {
  2712. TypeIdx &IdxRef = TypeIdxs[T];
  2713. if (IdxRef.getIndex() == 0) // we haven't seen this type before.
  2714. IdxRef = TypeIdx(NextTypeID++);
  2715. TypeIdx Idx = IdxRef;
  2716. assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
  2717. RecordData Record;
  2718. // Emit the type's representation.
  2719. ASTTypeWriter W(*this, Record);
  2720. W.Visit(T);
  2721. uint64_t Offset = W.Emit();
  2722. // Record the offset for this type.
  2723. unsigned Index = Idx.getIndex() - FirstTypeID;
  2724. if (TypeOffsets.size() == Index)
  2725. TypeOffsets.push_back(Offset);
  2726. else if (TypeOffsets.size() < Index) {
  2727. TypeOffsets.resize(Index + 1);
  2728. TypeOffsets[Index] = Offset;
  2729. } else {
  2730. llvm_unreachable("Types emitted in wrong order");
  2731. }
  2732. }
  2733. //===----------------------------------------------------------------------===//
  2734. // Declaration Serialization
  2735. //===----------------------------------------------------------------------===//
  2736. /// Write the block containing all of the declaration IDs
  2737. /// lexically declared within the given DeclContext.
  2738. ///
  2739. /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
  2740. /// bitstream, or 0 if no block was written.
  2741. uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
  2742. DeclContext *DC) {
  2743. if (DC->decls_empty())
  2744. return 0;
  2745. uint64_t Offset = Stream.GetCurrentBitNo();
  2746. SmallVector<uint32_t, 128> KindDeclPairs;
  2747. for (const auto *D : DC->decls()) {
  2748. KindDeclPairs.push_back(D->getKind());
  2749. KindDeclPairs.push_back(GetDeclRef(D));
  2750. }
  2751. ++NumLexicalDeclContexts;
  2752. RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
  2753. Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
  2754. bytes(KindDeclPairs));
  2755. return Offset;
  2756. }
  2757. void ASTWriter::WriteTypeDeclOffsets() {
  2758. using namespace llvm;
  2759. // Write the type offsets array
  2760. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2761. Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
  2762. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
  2763. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
  2764. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
  2765. unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2766. {
  2767. RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
  2768. FirstTypeID - NUM_PREDEF_TYPE_IDS};
  2769. Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
  2770. }
  2771. // Write the declaration offsets array
  2772. Abbrev = std::make_shared<BitCodeAbbrev>();
  2773. Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
  2774. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
  2775. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
  2776. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
  2777. unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2778. {
  2779. RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
  2780. FirstDeclID - NUM_PREDEF_DECL_IDS};
  2781. Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
  2782. }
  2783. }
  2784. void ASTWriter::WriteFileDeclIDsMap() {
  2785. using namespace llvm;
  2786. SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
  2787. FileDeclIDs.begin(), FileDeclIDs.end());
  2788. llvm::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
  2789. llvm::less_first());
  2790. // Join the vectors of DeclIDs from all files.
  2791. SmallVector<DeclID, 256> FileGroupedDeclIDs;
  2792. for (auto &FileDeclEntry : SortedFileDeclIDs) {
  2793. DeclIDInFileInfo &Info = *FileDeclEntry.second;
  2794. Info.FirstDeclIndex = FileGroupedDeclIDs.size();
  2795. for (auto &LocDeclEntry : Info.DeclIDs)
  2796. FileGroupedDeclIDs.push_back(LocDeclEntry.second);
  2797. }
  2798. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2799. Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
  2800. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2801. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2802. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  2803. RecordData::value_type Record[] = {FILE_SORTED_DECLS,
  2804. FileGroupedDeclIDs.size()};
  2805. Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
  2806. }
  2807. void ASTWriter::WriteComments() {
  2808. Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
  2809. auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
  2810. if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
  2811. return;
  2812. ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
  2813. RecordData Record;
  2814. for (const auto *I : RawComments) {
  2815. Record.clear();
  2816. AddSourceRange(I->getSourceRange(), Record);
  2817. Record.push_back(I->getKind());
  2818. Record.push_back(I->isTrailingComment());
  2819. Record.push_back(I->isAlmostTrailingComment());
  2820. Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
  2821. }
  2822. }
  2823. //===----------------------------------------------------------------------===//
  2824. // Global Method Pool and Selector Serialization
  2825. //===----------------------------------------------------------------------===//
  2826. namespace {
  2827. // Trait used for the on-disk hash table used in the method pool.
  2828. class ASTMethodPoolTrait {
  2829. ASTWriter &Writer;
  2830. public:
  2831. using key_type = Selector;
  2832. using key_type_ref = key_type;
  2833. struct data_type {
  2834. SelectorID ID;
  2835. ObjCMethodList Instance, Factory;
  2836. };
  2837. using data_type_ref = const data_type &;
  2838. using hash_value_type = unsigned;
  2839. using offset_type = unsigned;
  2840. explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
  2841. static hash_value_type ComputeHash(Selector Sel) {
  2842. return serialization::ComputeHash(Sel);
  2843. }
  2844. std::pair<unsigned, unsigned>
  2845. EmitKeyDataLength(raw_ostream& Out, Selector Sel,
  2846. data_type_ref Methods) {
  2847. using namespace llvm::support;
  2848. endian::Writer LE(Out, little);
  2849. unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
  2850. LE.write<uint16_t>(KeyLen);
  2851. unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
  2852. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2853. Method = Method->getNext())
  2854. if (Method->getMethod())
  2855. DataLen += 4;
  2856. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2857. Method = Method->getNext())
  2858. if (Method->getMethod())
  2859. DataLen += 4;
  2860. LE.write<uint16_t>(DataLen);
  2861. return std::make_pair(KeyLen, DataLen);
  2862. }
  2863. void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
  2864. using namespace llvm::support;
  2865. endian::Writer LE(Out, little);
  2866. uint64_t Start = Out.tell();
  2867. assert((Start >> 32) == 0 && "Selector key offset too large");
  2868. Writer.SetSelectorOffset(Sel, Start);
  2869. unsigned N = Sel.getNumArgs();
  2870. LE.write<uint16_t>(N);
  2871. if (N == 0)
  2872. N = 1;
  2873. for (unsigned I = 0; I != N; ++I)
  2874. LE.write<uint32_t>(
  2875. Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
  2876. }
  2877. void EmitData(raw_ostream& Out, key_type_ref,
  2878. data_type_ref Methods, unsigned DataLen) {
  2879. using namespace llvm::support;
  2880. endian::Writer LE(Out, little);
  2881. uint64_t Start = Out.tell(); (void)Start;
  2882. LE.write<uint32_t>(Methods.ID);
  2883. unsigned NumInstanceMethods = 0;
  2884. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2885. Method = Method->getNext())
  2886. if (Method->getMethod())
  2887. ++NumInstanceMethods;
  2888. unsigned NumFactoryMethods = 0;
  2889. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2890. Method = Method->getNext())
  2891. if (Method->getMethod())
  2892. ++NumFactoryMethods;
  2893. unsigned InstanceBits = Methods.Instance.getBits();
  2894. assert(InstanceBits < 4);
  2895. unsigned InstanceHasMoreThanOneDeclBit =
  2896. Methods.Instance.hasMoreThanOneDecl();
  2897. unsigned FullInstanceBits = (NumInstanceMethods << 3) |
  2898. (InstanceHasMoreThanOneDeclBit << 2) |
  2899. InstanceBits;
  2900. unsigned FactoryBits = Methods.Factory.getBits();
  2901. assert(FactoryBits < 4);
  2902. unsigned FactoryHasMoreThanOneDeclBit =
  2903. Methods.Factory.hasMoreThanOneDecl();
  2904. unsigned FullFactoryBits = (NumFactoryMethods << 3) |
  2905. (FactoryHasMoreThanOneDeclBit << 2) |
  2906. FactoryBits;
  2907. LE.write<uint16_t>(FullInstanceBits);
  2908. LE.write<uint16_t>(FullFactoryBits);
  2909. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2910. Method = Method->getNext())
  2911. if (Method->getMethod())
  2912. LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
  2913. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2914. Method = Method->getNext())
  2915. if (Method->getMethod())
  2916. LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
  2917. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  2918. }
  2919. };
  2920. } // namespace
  2921. /// Write ObjC data: selectors and the method pool.
  2922. ///
  2923. /// The method pool contains both instance and factory methods, stored
  2924. /// in an on-disk hash table indexed by the selector. The hash table also
  2925. /// contains an empty entry for every other selector known to Sema.
  2926. void ASTWriter::WriteSelectors(Sema &SemaRef) {
  2927. using namespace llvm;
  2928. // Do we have to do anything at all?
  2929. if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
  2930. return;
  2931. unsigned NumTableEntries = 0;
  2932. // Create and write out the blob that contains selectors and the method pool.
  2933. {
  2934. llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
  2935. ASTMethodPoolTrait Trait(*this);
  2936. // Create the on-disk hash table representation. We walk through every
  2937. // selector we've seen and look it up in the method pool.
  2938. SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
  2939. for (auto &SelectorAndID : SelectorIDs) {
  2940. Selector S = SelectorAndID.first;
  2941. SelectorID ID = SelectorAndID.second;
  2942. Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
  2943. ASTMethodPoolTrait::data_type Data = {
  2944. ID,
  2945. ObjCMethodList(),
  2946. ObjCMethodList()
  2947. };
  2948. if (F != SemaRef.MethodPool.end()) {
  2949. Data.Instance = F->second.first;
  2950. Data.Factory = F->second.second;
  2951. }
  2952. // Only write this selector if it's not in an existing AST or something
  2953. // changed.
  2954. if (Chain && ID < FirstSelectorID) {
  2955. // Selector already exists. Did it change?
  2956. bool changed = false;
  2957. for (ObjCMethodList *M = &Data.Instance;
  2958. !changed && M && M->getMethod(); M = M->getNext()) {
  2959. if (!M->getMethod()->isFromASTFile())
  2960. changed = true;
  2961. }
  2962. for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
  2963. M = M->getNext()) {
  2964. if (!M->getMethod()->isFromASTFile())
  2965. changed = true;
  2966. }
  2967. if (!changed)
  2968. continue;
  2969. } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
  2970. // A new method pool entry.
  2971. ++NumTableEntries;
  2972. }
  2973. Generator.insert(S, Data, Trait);
  2974. }
  2975. // Create the on-disk hash table in a buffer.
  2976. SmallString<4096> MethodPool;
  2977. uint32_t BucketOffset;
  2978. {
  2979. using namespace llvm::support;
  2980. ASTMethodPoolTrait Trait(*this);
  2981. llvm::raw_svector_ostream Out(MethodPool);
  2982. // Make sure that no bucket is at offset 0
  2983. endian::write<uint32_t>(Out, 0, little);
  2984. BucketOffset = Generator.Emit(Out, Trait);
  2985. }
  2986. // Create a blob abbreviation
  2987. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2988. Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
  2989. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2990. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2991. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2992. unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2993. // Write the method pool
  2994. {
  2995. RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
  2996. NumTableEntries};
  2997. Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
  2998. }
  2999. // Create a blob abbreviation for the selector table offsets.
  3000. Abbrev = std::make_shared<BitCodeAbbrev>();
  3001. Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
  3002. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  3003. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  3004. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3005. unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3006. // Write the selector offsets table.
  3007. {
  3008. RecordData::value_type Record[] = {
  3009. SELECTOR_OFFSETS, SelectorOffsets.size(),
  3010. FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
  3011. Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
  3012. bytes(SelectorOffsets));
  3013. }
  3014. }
  3015. }
  3016. /// Write the selectors referenced in @selector expression into AST file.
  3017. void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
  3018. using namespace llvm;
  3019. if (SemaRef.ReferencedSelectors.empty())
  3020. return;
  3021. RecordData Record;
  3022. ASTRecordWriter Writer(*this, Record);
  3023. // Note: this writes out all references even for a dependent AST. But it is
  3024. // very tricky to fix, and given that @selector shouldn't really appear in
  3025. // headers, probably not worth it. It's not a correctness issue.
  3026. for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
  3027. Selector Sel = SelectorAndLocation.first;
  3028. SourceLocation Loc = SelectorAndLocation.second;
  3029. Writer.AddSelectorRef(Sel);
  3030. Writer.AddSourceLocation(Loc);
  3031. }
  3032. Writer.Emit(REFERENCED_SELECTOR_POOL);
  3033. }
  3034. //===----------------------------------------------------------------------===//
  3035. // Identifier Table Serialization
  3036. //===----------------------------------------------------------------------===//
  3037. /// Determine the declaration that should be put into the name lookup table to
  3038. /// represent the given declaration in this module. This is usually D itself,
  3039. /// but if D was imported and merged into a local declaration, we want the most
  3040. /// recent local declaration instead. The chosen declaration will be the most
  3041. /// recent declaration in any module that imports this one.
  3042. static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
  3043. NamedDecl *D) {
  3044. if (!LangOpts.Modules || !D->isFromASTFile())
  3045. return D;
  3046. if (Decl *Redecl = D->getPreviousDecl()) {
  3047. // For Redeclarable decls, a prior declaration might be local.
  3048. for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
  3049. // If we find a local decl, we're done.
  3050. if (!Redecl->isFromASTFile()) {
  3051. // Exception: in very rare cases (for injected-class-names), not all
  3052. // redeclarations are in the same semantic context. Skip ones in a
  3053. // different context. They don't go in this lookup table at all.
  3054. if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
  3055. D->getDeclContext()->getRedeclContext()))
  3056. continue;
  3057. return cast<NamedDecl>(Redecl);
  3058. }
  3059. // If we find a decl from a (chained-)PCH stop since we won't find a
  3060. // local one.
  3061. if (Redecl->getOwningModuleID() == 0)
  3062. break;
  3063. }
  3064. } else if (Decl *First = D->getCanonicalDecl()) {
  3065. // For Mergeable decls, the first decl might be local.
  3066. if (!First->isFromASTFile())
  3067. return cast<NamedDecl>(First);
  3068. }
  3069. // All declarations are imported. Our most recent declaration will also be
  3070. // the most recent one in anyone who imports us.
  3071. return D;
  3072. }
  3073. namespace {
  3074. class ASTIdentifierTableTrait {
  3075. ASTWriter &Writer;
  3076. Preprocessor &PP;
  3077. IdentifierResolver &IdResolver;
  3078. bool IsModule;
  3079. bool NeedDecls;
  3080. ASTWriter::RecordData *InterestingIdentifierOffsets;
  3081. /// Determines whether this is an "interesting" identifier that needs a
  3082. /// full IdentifierInfo structure written into the hash table. Notably, this
  3083. /// doesn't check whether the name has macros defined; use PublicMacroIterator
  3084. /// to check that.
  3085. bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
  3086. if (MacroOffset ||
  3087. II->isPoisoned() ||
  3088. (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
  3089. II->hasRevertedTokenIDToIdentifier() ||
  3090. (NeedDecls && II->getFETokenInfo()))
  3091. return true;
  3092. return false;
  3093. }
  3094. public:
  3095. using key_type = IdentifierInfo *;
  3096. using key_type_ref = key_type;
  3097. using data_type = IdentID;
  3098. using data_type_ref = data_type;
  3099. using hash_value_type = unsigned;
  3100. using offset_type = unsigned;
  3101. ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
  3102. IdentifierResolver &IdResolver, bool IsModule,
  3103. ASTWriter::RecordData *InterestingIdentifierOffsets)
  3104. : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
  3105. NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
  3106. InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
  3107. bool needDecls() const { return NeedDecls; }
  3108. static hash_value_type ComputeHash(const IdentifierInfo* II) {
  3109. return llvm::djbHash(II->getName());
  3110. }
  3111. bool isInterestingIdentifier(const IdentifierInfo *II) {
  3112. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  3113. return isInterestingIdentifier(II, MacroOffset);
  3114. }
  3115. bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
  3116. return isInterestingIdentifier(II, 0);
  3117. }
  3118. std::pair<unsigned, unsigned>
  3119. EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
  3120. unsigned KeyLen = II->getLength() + 1;
  3121. unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
  3122. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  3123. if (isInterestingIdentifier(II, MacroOffset)) {
  3124. DataLen += 2; // 2 bytes for builtin ID
  3125. DataLen += 2; // 2 bytes for flags
  3126. if (MacroOffset)
  3127. DataLen += 4; // MacroDirectives offset.
  3128. if (NeedDecls) {
  3129. for (IdentifierResolver::iterator D = IdResolver.begin(II),
  3130. DEnd = IdResolver.end();
  3131. D != DEnd; ++D)
  3132. DataLen += 4;
  3133. }
  3134. }
  3135. using namespace llvm::support;
  3136. endian::Writer LE(Out, little);
  3137. assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
  3138. LE.write<uint16_t>(DataLen);
  3139. // We emit the key length after the data length so that every
  3140. // string is preceded by a 16-bit length. This matches the PTH
  3141. // format for storing identifiers.
  3142. LE.write<uint16_t>(KeyLen);
  3143. return std::make_pair(KeyLen, DataLen);
  3144. }
  3145. void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
  3146. unsigned KeyLen) {
  3147. // Record the location of the key data. This is used when generating
  3148. // the mapping from persistent IDs to strings.
  3149. Writer.SetIdentifierOffset(II, Out.tell());
  3150. // Emit the offset of the key/data length information to the interesting
  3151. // identifiers table if necessary.
  3152. if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
  3153. InterestingIdentifierOffsets->push_back(Out.tell() - 4);
  3154. Out.write(II->getNameStart(), KeyLen);
  3155. }
  3156. void EmitData(raw_ostream& Out, IdentifierInfo* II,
  3157. IdentID ID, unsigned) {
  3158. using namespace llvm::support;
  3159. endian::Writer LE(Out, little);
  3160. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  3161. if (!isInterestingIdentifier(II, MacroOffset)) {
  3162. LE.write<uint32_t>(ID << 1);
  3163. return;
  3164. }
  3165. LE.write<uint32_t>((ID << 1) | 0x01);
  3166. uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
  3167. assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
  3168. LE.write<uint16_t>(Bits);
  3169. Bits = 0;
  3170. bool HadMacroDefinition = MacroOffset != 0;
  3171. Bits = (Bits << 1) | unsigned(HadMacroDefinition);
  3172. Bits = (Bits << 1) | unsigned(II->isExtensionToken());
  3173. Bits = (Bits << 1) | unsigned(II->isPoisoned());
  3174. Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
  3175. Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
  3176. Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
  3177. LE.write<uint16_t>(Bits);
  3178. if (HadMacroDefinition)
  3179. LE.write<uint32_t>(MacroOffset);
  3180. if (NeedDecls) {
  3181. // Emit the declaration IDs in reverse order, because the
  3182. // IdentifierResolver provides the declarations as they would be
  3183. // visible (e.g., the function "stat" would come before the struct
  3184. // "stat"), but the ASTReader adds declarations to the end of the list
  3185. // (so we need to see the struct "stat" before the function "stat").
  3186. // Only emit declarations that aren't from a chained PCH, though.
  3187. SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
  3188. IdResolver.end());
  3189. for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
  3190. DEnd = Decls.rend();
  3191. D != DEnd; ++D)
  3192. LE.write<uint32_t>(
  3193. Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
  3194. }
  3195. }
  3196. };
  3197. } // namespace
  3198. /// Write the identifier table into the AST file.
  3199. ///
  3200. /// The identifier table consists of a blob containing string data
  3201. /// (the actual identifiers themselves) and a separate "offsets" index
  3202. /// that maps identifier IDs to locations within the blob.
  3203. void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
  3204. IdentifierResolver &IdResolver,
  3205. bool IsModule) {
  3206. using namespace llvm;
  3207. RecordData InterestingIdents;
  3208. // Create and write out the blob that contains the identifier
  3209. // strings.
  3210. {
  3211. llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
  3212. ASTIdentifierTableTrait Trait(
  3213. *this, PP, IdResolver, IsModule,
  3214. (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
  3215. // Look for any identifiers that were named while processing the
  3216. // headers, but are otherwise not needed. We add these to the hash
  3217. // table to enable checking of the predefines buffer in the case
  3218. // where the user adds new macro definitions when building the AST
  3219. // file.
  3220. SmallVector<const IdentifierInfo *, 128> IIs;
  3221. for (const auto &ID : PP.getIdentifierTable())
  3222. IIs.push_back(ID.second);
  3223. // Sort the identifiers lexicographically before getting them references so
  3224. // that their order is stable.
  3225. llvm::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
  3226. for (const IdentifierInfo *II : IIs)
  3227. if (Trait.isInterestingNonMacroIdentifier(II))
  3228. getIdentifierRef(II);
  3229. // Create the on-disk hash table representation. We only store offsets
  3230. // for identifiers that appear here for the first time.
  3231. IdentifierOffsets.resize(NextIdentID - FirstIdentID);
  3232. for (auto IdentIDPair : IdentifierIDs) {
  3233. auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
  3234. IdentID ID = IdentIDPair.second;
  3235. assert(II && "NULL identifier in identifier table");
  3236. // Write out identifiers if either the ID is local or the identifier has
  3237. // changed since it was loaded.
  3238. if (ID >= FirstIdentID || !Chain || !II->isFromAST()
  3239. || II->hasChangedSinceDeserialization() ||
  3240. (Trait.needDecls() &&
  3241. II->hasFETokenInfoChangedSinceDeserialization()))
  3242. Generator.insert(II, ID, Trait);
  3243. }
  3244. // Create the on-disk hash table in a buffer.
  3245. SmallString<4096> IdentifierTable;
  3246. uint32_t BucketOffset;
  3247. {
  3248. using namespace llvm::support;
  3249. llvm::raw_svector_ostream Out(IdentifierTable);
  3250. // Make sure that no bucket is at offset 0
  3251. endian::write<uint32_t>(Out, 0, little);
  3252. BucketOffset = Generator.Emit(Out, Trait);
  3253. }
  3254. // Create a blob abbreviation
  3255. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  3256. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
  3257. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3258. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3259. unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3260. // Write the identifier table
  3261. RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
  3262. Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
  3263. }
  3264. // Write the offsets table for identifier IDs.
  3265. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  3266. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
  3267. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
  3268. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  3269. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3270. unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3271. #ifndef NDEBUG
  3272. for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
  3273. assert(IdentifierOffsets[I] && "Missing identifier offset?");
  3274. #endif
  3275. RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
  3276. IdentifierOffsets.size(),
  3277. FirstIdentID - NUM_PREDEF_IDENT_IDS};
  3278. Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
  3279. bytes(IdentifierOffsets));
  3280. // In C++, write the list of interesting identifiers (those that are
  3281. // defined as macros, poisoned, or similar unusual things).
  3282. if (!InterestingIdents.empty())
  3283. Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
  3284. }
  3285. //===----------------------------------------------------------------------===//
  3286. // DeclContext's Name Lookup Table Serialization
  3287. //===----------------------------------------------------------------------===//
  3288. namespace {
  3289. // Trait used for the on-disk hash table used in the method pool.
  3290. class ASTDeclContextNameLookupTrait {
  3291. ASTWriter &Writer;
  3292. llvm::SmallVector<DeclID, 64> DeclIDs;
  3293. public:
  3294. using key_type = DeclarationNameKey;
  3295. using key_type_ref = key_type;
  3296. /// A start and end index into DeclIDs, representing a sequence of decls.
  3297. using data_type = std::pair<unsigned, unsigned>;
  3298. using data_type_ref = const data_type &;
  3299. using hash_value_type = unsigned;
  3300. using offset_type = unsigned;
  3301. explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
  3302. template<typename Coll>
  3303. data_type getData(const Coll &Decls) {
  3304. unsigned Start = DeclIDs.size();
  3305. for (NamedDecl *D : Decls) {
  3306. DeclIDs.push_back(
  3307. Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
  3308. }
  3309. return std::make_pair(Start, DeclIDs.size());
  3310. }
  3311. data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
  3312. unsigned Start = DeclIDs.size();
  3313. for (auto ID : FromReader)
  3314. DeclIDs.push_back(ID);
  3315. return std::make_pair(Start, DeclIDs.size());
  3316. }
  3317. static bool EqualKey(key_type_ref a, key_type_ref b) {
  3318. return a == b;
  3319. }
  3320. hash_value_type ComputeHash(DeclarationNameKey Name) {
  3321. return Name.getHash();
  3322. }
  3323. void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
  3324. assert(Writer.hasChain() &&
  3325. "have reference to loaded module file but no chain?");
  3326. using namespace llvm::support;
  3327. endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
  3328. }
  3329. std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
  3330. DeclarationNameKey Name,
  3331. data_type_ref Lookup) {
  3332. using namespace llvm::support;
  3333. endian::Writer LE(Out, little);
  3334. unsigned KeyLen = 1;
  3335. switch (Name.getKind()) {
  3336. case DeclarationName::Identifier:
  3337. case DeclarationName::ObjCZeroArgSelector:
  3338. case DeclarationName::ObjCOneArgSelector:
  3339. case DeclarationName::ObjCMultiArgSelector:
  3340. case DeclarationName::CXXLiteralOperatorName:
  3341. case DeclarationName::CXXDeductionGuideName:
  3342. KeyLen += 4;
  3343. break;
  3344. case DeclarationName::CXXOperatorName:
  3345. KeyLen += 1;
  3346. break;
  3347. case DeclarationName::CXXConstructorName:
  3348. case DeclarationName::CXXDestructorName:
  3349. case DeclarationName::CXXConversionFunctionName:
  3350. case DeclarationName::CXXUsingDirective:
  3351. break;
  3352. }
  3353. LE.write<uint16_t>(KeyLen);
  3354. // 4 bytes for each DeclID.
  3355. unsigned DataLen = 4 * (Lookup.second - Lookup.first);
  3356. assert(uint16_t(DataLen) == DataLen &&
  3357. "too many decls for serialized lookup result");
  3358. LE.write<uint16_t>(DataLen);
  3359. return std::make_pair(KeyLen, DataLen);
  3360. }
  3361. void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
  3362. using namespace llvm::support;
  3363. endian::Writer LE(Out, little);
  3364. LE.write<uint8_t>(Name.getKind());
  3365. switch (Name.getKind()) {
  3366. case DeclarationName::Identifier:
  3367. case DeclarationName::CXXLiteralOperatorName:
  3368. case DeclarationName::CXXDeductionGuideName:
  3369. LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
  3370. return;
  3371. case DeclarationName::ObjCZeroArgSelector:
  3372. case DeclarationName::ObjCOneArgSelector:
  3373. case DeclarationName::ObjCMultiArgSelector:
  3374. LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
  3375. return;
  3376. case DeclarationName::CXXOperatorName:
  3377. assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
  3378. "Invalid operator?");
  3379. LE.write<uint8_t>(Name.getOperatorKind());
  3380. return;
  3381. case DeclarationName::CXXConstructorName:
  3382. case DeclarationName::CXXDestructorName:
  3383. case DeclarationName::CXXConversionFunctionName:
  3384. case DeclarationName::CXXUsingDirective:
  3385. return;
  3386. }
  3387. llvm_unreachable("Invalid name kind?");
  3388. }
  3389. void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
  3390. unsigned DataLen) {
  3391. using namespace llvm::support;
  3392. endian::Writer LE(Out, little);
  3393. uint64_t Start = Out.tell(); (void)Start;
  3394. for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
  3395. LE.write<uint32_t>(DeclIDs[I]);
  3396. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  3397. }
  3398. };
  3399. } // namespace
  3400. bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
  3401. DeclContext *DC) {
  3402. return Result.hasExternalDecls() &&
  3403. DC->hasNeedToReconcileExternalVisibleStorage();
  3404. }
  3405. bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
  3406. DeclContext *DC) {
  3407. for (auto *D : Result.getLookupResult())
  3408. if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
  3409. return false;
  3410. return true;
  3411. }
  3412. void
  3413. ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
  3414. llvm::SmallVectorImpl<char> &LookupTable) {
  3415. assert(!ConstDC->hasLazyLocalLexicalLookups() &&
  3416. !ConstDC->hasLazyExternalLexicalLookups() &&
  3417. "must call buildLookups first");
  3418. // FIXME: We need to build the lookups table, which is logically const.
  3419. auto *DC = const_cast<DeclContext*>(ConstDC);
  3420. assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
  3421. // Create the on-disk hash table representation.
  3422. MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
  3423. ASTDeclContextNameLookupTrait> Generator;
  3424. ASTDeclContextNameLookupTrait Trait(*this);
  3425. // The first step is to collect the declaration names which we need to
  3426. // serialize into the name lookup table, and to collect them in a stable
  3427. // order.
  3428. SmallVector<DeclarationName, 16> Names;
  3429. // We also build up small sets of the constructor and conversion function
  3430. // names which are visible.
  3431. llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
  3432. for (auto &Lookup : *DC->buildLookup()) {
  3433. auto &Name = Lookup.first;
  3434. auto &Result = Lookup.second;
  3435. // If there are no local declarations in our lookup result, we
  3436. // don't need to write an entry for the name at all. If we can't
  3437. // write out a lookup set without performing more deserialization,
  3438. // just skip this entry.
  3439. if (isLookupResultExternal(Result, DC) &&
  3440. isLookupResultEntirelyExternal(Result, DC))
  3441. continue;
  3442. // We also skip empty results. If any of the results could be external and
  3443. // the currently available results are empty, then all of the results are
  3444. // external and we skip it above. So the only way we get here with an empty
  3445. // results is when no results could have been external *and* we have
  3446. // external results.
  3447. //
  3448. // FIXME: While we might want to start emitting on-disk entries for negative
  3449. // lookups into a decl context as an optimization, today we *have* to skip
  3450. // them because there are names with empty lookup results in decl contexts
  3451. // which we can't emit in any stable ordering: we lookup constructors and
  3452. // conversion functions in the enclosing namespace scope creating empty
  3453. // results for them. This in almost certainly a bug in Clang's name lookup,
  3454. // but that is likely to be hard or impossible to fix and so we tolerate it
  3455. // here by omitting lookups with empty results.
  3456. if (Lookup.second.getLookupResult().empty())
  3457. continue;
  3458. switch (Lookup.first.getNameKind()) {
  3459. default:
  3460. Names.push_back(Lookup.first);
  3461. break;
  3462. case DeclarationName::CXXConstructorName:
  3463. assert(isa<CXXRecordDecl>(DC) &&
  3464. "Cannot have a constructor name outside of a class!");
  3465. ConstructorNameSet.insert(Name);
  3466. break;
  3467. case DeclarationName::CXXConversionFunctionName:
  3468. assert(isa<CXXRecordDecl>(DC) &&
  3469. "Cannot have a conversion function name outside of a class!");
  3470. ConversionNameSet.insert(Name);
  3471. break;
  3472. }
  3473. }
  3474. // Sort the names into a stable order.
  3475. llvm::sort(Names.begin(), Names.end());
  3476. if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
  3477. // We need to establish an ordering of constructor and conversion function
  3478. // names, and they don't have an intrinsic ordering.
  3479. // First we try the easy case by forming the current context's constructor
  3480. // name and adding that name first. This is a very useful optimization to
  3481. // avoid walking the lexical declarations in many cases, and it also
  3482. // handles the only case where a constructor name can come from some other
  3483. // lexical context -- when that name is an implicit constructor merged from
  3484. // another declaration in the redecl chain. Any non-implicit constructor or
  3485. // conversion function which doesn't occur in all the lexical contexts
  3486. // would be an ODR violation.
  3487. auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
  3488. Context->getCanonicalType(Context->getRecordType(D)));
  3489. if (ConstructorNameSet.erase(ImplicitCtorName))
  3490. Names.push_back(ImplicitCtorName);
  3491. // If we still have constructors or conversion functions, we walk all the
  3492. // names in the decl and add the constructors and conversion functions
  3493. // which are visible in the order they lexically occur within the context.
  3494. if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
  3495. for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
  3496. if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
  3497. auto Name = ChildND->getDeclName();
  3498. switch (Name.getNameKind()) {
  3499. default:
  3500. continue;
  3501. case DeclarationName::CXXConstructorName:
  3502. if (ConstructorNameSet.erase(Name))
  3503. Names.push_back(Name);
  3504. break;
  3505. case DeclarationName::CXXConversionFunctionName:
  3506. if (ConversionNameSet.erase(Name))
  3507. Names.push_back(Name);
  3508. break;
  3509. }
  3510. if (ConstructorNameSet.empty() && ConversionNameSet.empty())
  3511. break;
  3512. }
  3513. assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
  3514. "constructors by walking all the "
  3515. "lexical members of the context.");
  3516. assert(ConversionNameSet.empty() && "Failed to find all of the visible "
  3517. "conversion functions by walking all "
  3518. "the lexical members of the context.");
  3519. }
  3520. // Next we need to do a lookup with each name into this decl context to fully
  3521. // populate any results from external sources. We don't actually use the
  3522. // results of these lookups because we only want to use the results after all
  3523. // results have been loaded and the pointers into them will be stable.
  3524. for (auto &Name : Names)
  3525. DC->lookup(Name);
  3526. // Now we need to insert the results for each name into the hash table. For
  3527. // constructor names and conversion function names, we actually need to merge
  3528. // all of the results for them into one list of results each and insert
  3529. // those.
  3530. SmallVector<NamedDecl *, 8> ConstructorDecls;
  3531. SmallVector<NamedDecl *, 8> ConversionDecls;
  3532. // Now loop over the names, either inserting them or appending for the two
  3533. // special cases.
  3534. for (auto &Name : Names) {
  3535. DeclContext::lookup_result Result = DC->noload_lookup(Name);
  3536. switch (Name.getNameKind()) {
  3537. default:
  3538. Generator.insert(Name, Trait.getData(Result), Trait);
  3539. break;
  3540. case DeclarationName::CXXConstructorName:
  3541. ConstructorDecls.append(Result.begin(), Result.end());
  3542. break;
  3543. case DeclarationName::CXXConversionFunctionName:
  3544. ConversionDecls.append(Result.begin(), Result.end());
  3545. break;
  3546. }
  3547. }
  3548. // Handle our two special cases if we ended up having any. We arbitrarily use
  3549. // the first declaration's name here because the name itself isn't part of
  3550. // the key, only the kind of name is used.
  3551. if (!ConstructorDecls.empty())
  3552. Generator.insert(ConstructorDecls.front()->getDeclName(),
  3553. Trait.getData(ConstructorDecls), Trait);
  3554. if (!ConversionDecls.empty())
  3555. Generator.insert(ConversionDecls.front()->getDeclName(),
  3556. Trait.getData(ConversionDecls), Trait);
  3557. // Create the on-disk hash table. Also emit the existing imported and
  3558. // merged table if there is one.
  3559. auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
  3560. Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
  3561. }
  3562. /// Write the block containing all of the declaration IDs
  3563. /// visible from the given DeclContext.
  3564. ///
  3565. /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
  3566. /// bitstream, or 0 if no block was written.
  3567. uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
  3568. DeclContext *DC) {
  3569. // If we imported a key declaration of this namespace, write the visible
  3570. // lookup results as an update record for it rather than including them
  3571. // on this declaration. We will only look at key declarations on reload.
  3572. if (isa<NamespaceDecl>(DC) && Chain &&
  3573. Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
  3574. // Only do this once, for the first local declaration of the namespace.
  3575. for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
  3576. Prev = Prev->getPreviousDecl())
  3577. if (!Prev->isFromASTFile())
  3578. return 0;
  3579. // Note that we need to emit an update record for the primary context.
  3580. UpdatedDeclContexts.insert(DC->getPrimaryContext());
  3581. // Make sure all visible decls are written. They will be recorded later. We
  3582. // do this using a side data structure so we can sort the names into
  3583. // a deterministic order.
  3584. StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
  3585. SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
  3586. LookupResults;
  3587. if (Map) {
  3588. LookupResults.reserve(Map->size());
  3589. for (auto &Entry : *Map)
  3590. LookupResults.push_back(
  3591. std::make_pair(Entry.first, Entry.second.getLookupResult()));
  3592. }
  3593. llvm::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
  3594. for (auto &NameAndResult : LookupResults) {
  3595. DeclarationName Name = NameAndResult.first;
  3596. DeclContext::lookup_result Result = NameAndResult.second;
  3597. if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3598. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  3599. // We have to work around a name lookup bug here where negative lookup
  3600. // results for these names get cached in namespace lookup tables (these
  3601. // names should never be looked up in a namespace).
  3602. assert(Result.empty() && "Cannot have a constructor or conversion "
  3603. "function name in a namespace!");
  3604. continue;
  3605. }
  3606. for (NamedDecl *ND : Result)
  3607. if (!ND->isFromASTFile())
  3608. GetDeclRef(ND);
  3609. }
  3610. return 0;
  3611. }
  3612. if (DC->getPrimaryContext() != DC)
  3613. return 0;
  3614. // Skip contexts which don't support name lookup.
  3615. if (!DC->isLookupContext())
  3616. return 0;
  3617. // If not in C++, we perform name lookup for the translation unit via the
  3618. // IdentifierInfo chains, don't bother to build a visible-declarations table.
  3619. if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
  3620. return 0;
  3621. // Serialize the contents of the mapping used for lookup. Note that,
  3622. // although we have two very different code paths, the serialized
  3623. // representation is the same for both cases: a declaration name,
  3624. // followed by a size, followed by references to the visible
  3625. // declarations that have that name.
  3626. uint64_t Offset = Stream.GetCurrentBitNo();
  3627. StoredDeclsMap *Map = DC->buildLookup();
  3628. if (!Map || Map->empty())
  3629. return 0;
  3630. // Create the on-disk hash table in a buffer.
  3631. SmallString<4096> LookupTable;
  3632. GenerateNameLookupTable(DC, LookupTable);
  3633. // Write the lookup table
  3634. RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
  3635. Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
  3636. LookupTable);
  3637. ++NumVisibleDeclContexts;
  3638. return Offset;
  3639. }
  3640. /// Write an UPDATE_VISIBLE block for the given context.
  3641. ///
  3642. /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
  3643. /// DeclContext in a dependent AST file. As such, they only exist for the TU
  3644. /// (in C++), for namespaces, and for classes with forward-declared unscoped
  3645. /// enumeration members (in C++11).
  3646. void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
  3647. StoredDeclsMap *Map = DC->getLookupPtr();
  3648. if (!Map || Map->empty())
  3649. return;
  3650. // Create the on-disk hash table in a buffer.
  3651. SmallString<4096> LookupTable;
  3652. GenerateNameLookupTable(DC, LookupTable);
  3653. // If we're updating a namespace, select a key declaration as the key for the
  3654. // update record; those are the only ones that will be checked on reload.
  3655. if (isa<NamespaceDecl>(DC))
  3656. DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
  3657. // Write the lookup table
  3658. RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
  3659. Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
  3660. }
  3661. /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
  3662. void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
  3663. RecordData::value_type Record[] = {Opts.getInt()};
  3664. Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
  3665. }
  3666. /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
  3667. void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
  3668. if (!SemaRef.Context.getLangOpts().OpenCL)
  3669. return;
  3670. const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
  3671. RecordData Record;
  3672. for (const auto &I:Opts.OptMap) {
  3673. AddString(I.getKey(), Record);
  3674. auto V = I.getValue();
  3675. Record.push_back(V.Supported ? 1 : 0);
  3676. Record.push_back(V.Enabled ? 1 : 0);
  3677. Record.push_back(V.Avail);
  3678. Record.push_back(V.Core);
  3679. }
  3680. Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
  3681. }
  3682. void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
  3683. if (!SemaRef.Context.getLangOpts().OpenCL)
  3684. return;
  3685. RecordData Record;
  3686. for (const auto &I : SemaRef.OpenCLTypeExtMap) {
  3687. Record.push_back(
  3688. static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
  3689. Record.push_back(I.second.size());
  3690. for (auto Ext : I.second)
  3691. AddString(Ext, Record);
  3692. }
  3693. Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
  3694. }
  3695. void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
  3696. if (!SemaRef.Context.getLangOpts().OpenCL)
  3697. return;
  3698. RecordData Record;
  3699. for (const auto &I : SemaRef.OpenCLDeclExtMap) {
  3700. Record.push_back(getDeclID(I.first));
  3701. Record.push_back(static_cast<unsigned>(I.second.size()));
  3702. for (auto Ext : I.second)
  3703. AddString(Ext, Record);
  3704. }
  3705. Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
  3706. }
  3707. void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
  3708. if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
  3709. RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
  3710. Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
  3711. }
  3712. }
  3713. void ASTWriter::WriteObjCCategories() {
  3714. SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
  3715. RecordData Categories;
  3716. for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
  3717. unsigned Size = 0;
  3718. unsigned StartIndex = Categories.size();
  3719. ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
  3720. // Allocate space for the size.
  3721. Categories.push_back(0);
  3722. // Add the categories.
  3723. for (ObjCInterfaceDecl::known_categories_iterator
  3724. Cat = Class->known_categories_begin(),
  3725. CatEnd = Class->known_categories_end();
  3726. Cat != CatEnd; ++Cat, ++Size) {
  3727. assert(getDeclID(*Cat) != 0 && "Bogus category");
  3728. AddDeclRef(*Cat, Categories);
  3729. }
  3730. // Update the size.
  3731. Categories[StartIndex] = Size;
  3732. // Record this interface -> category map.
  3733. ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
  3734. CategoriesMap.push_back(CatInfo);
  3735. }
  3736. // Sort the categories map by the definition ID, since the reader will be
  3737. // performing binary searches on this information.
  3738. llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
  3739. // Emit the categories map.
  3740. using namespace llvm;
  3741. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  3742. Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
  3743. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
  3744. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3745. unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
  3746. RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
  3747. Stream.EmitRecordWithBlob(AbbrevID, Record,
  3748. reinterpret_cast<char *>(CategoriesMap.data()),
  3749. CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
  3750. // Emit the category lists.
  3751. Stream.EmitRecord(OBJC_CATEGORIES, Categories);
  3752. }
  3753. void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
  3754. Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
  3755. if (LPTMap.empty())
  3756. return;
  3757. RecordData Record;
  3758. for (auto &LPTMapEntry : LPTMap) {
  3759. const FunctionDecl *FD = LPTMapEntry.first;
  3760. LateParsedTemplate &LPT = *LPTMapEntry.second;
  3761. AddDeclRef(FD, Record);
  3762. AddDeclRef(LPT.D, Record);
  3763. Record.push_back(LPT.Toks.size());
  3764. for (const auto &Tok : LPT.Toks) {
  3765. AddToken(Tok, Record);
  3766. }
  3767. }
  3768. Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
  3769. }
  3770. /// Write the state of 'pragma clang optimize' at the end of the module.
  3771. void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
  3772. RecordData Record;
  3773. SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
  3774. AddSourceLocation(PragmaLoc, Record);
  3775. Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
  3776. }
  3777. /// Write the state of 'pragma ms_struct' at the end of the module.
  3778. void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
  3779. RecordData Record;
  3780. Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
  3781. Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
  3782. }
  3783. /// Write the state of 'pragma pointers_to_members' at the end of the
  3784. //module.
  3785. void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
  3786. RecordData Record;
  3787. Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
  3788. AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
  3789. Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
  3790. }
  3791. /// Write the state of 'pragma pack' at the end of the module.
  3792. void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
  3793. // Don't serialize pragma pack state for modules, since it should only take
  3794. // effect on a per-submodule basis.
  3795. if (WritingModule)
  3796. return;
  3797. RecordData Record;
  3798. Record.push_back(SemaRef.PackStack.CurrentValue);
  3799. AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
  3800. Record.push_back(SemaRef.PackStack.Stack.size());
  3801. for (const auto &StackEntry : SemaRef.PackStack.Stack) {
  3802. Record.push_back(StackEntry.Value);
  3803. AddSourceLocation(StackEntry.PragmaLocation, Record);
  3804. AddSourceLocation(StackEntry.PragmaPushLocation, Record);
  3805. AddString(StackEntry.StackSlotLabel, Record);
  3806. }
  3807. Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
  3808. }
  3809. void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
  3810. ModuleFileExtensionWriter &Writer) {
  3811. // Enter the extension block.
  3812. Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
  3813. // Emit the metadata record abbreviation.
  3814. auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
  3815. Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
  3816. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3817. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3818. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3819. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3820. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  3821. unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
  3822. // Emit the metadata record.
  3823. RecordData Record;
  3824. auto Metadata = Writer.getExtension()->getExtensionMetadata();
  3825. Record.push_back(EXTENSION_METADATA);
  3826. Record.push_back(Metadata.MajorVersion);
  3827. Record.push_back(Metadata.MinorVersion);
  3828. Record.push_back(Metadata.BlockName.size());
  3829. Record.push_back(Metadata.UserInfo.size());
  3830. SmallString<64> Buffer;
  3831. Buffer += Metadata.BlockName;
  3832. Buffer += Metadata.UserInfo;
  3833. Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
  3834. // Emit the contents of the extension block.
  3835. Writer.writeExtensionContents(SemaRef, Stream);
  3836. // Exit the extension block.
  3837. Stream.ExitBlock();
  3838. }
  3839. //===----------------------------------------------------------------------===//
  3840. // General Serialization Routines
  3841. //===----------------------------------------------------------------------===//
  3842. void ASTRecordWriter::AddAttr(const Attr *A) {
  3843. auto &Record = *this;
  3844. if (!A)
  3845. return Record.push_back(0);
  3846. Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
  3847. Record.AddSourceRange(A->getRange());
  3848. #include "clang/Serialization/AttrPCHWrite.inc"
  3849. }
  3850. /// Emit the list of attributes to the specified record.
  3851. void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
  3852. push_back(Attrs.size());
  3853. for (const auto *A : Attrs)
  3854. AddAttr(A);
  3855. }
  3856. void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
  3857. AddSourceLocation(Tok.getLocation(), Record);
  3858. Record.push_back(Tok.getLength());
  3859. // FIXME: When reading literal tokens, reconstruct the literal pointer
  3860. // if it is needed.
  3861. AddIdentifierRef(Tok.getIdentifierInfo(), Record);
  3862. // FIXME: Should translate token kind to a stable encoding.
  3863. Record.push_back(Tok.getKind());
  3864. // FIXME: Should translate token flags to a stable encoding.
  3865. Record.push_back(Tok.getFlags());
  3866. }
  3867. void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
  3868. Record.push_back(Str.size());
  3869. Record.insert(Record.end(), Str.begin(), Str.end());
  3870. }
  3871. bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
  3872. assert(Context && "should have context when outputting path");
  3873. bool Changed =
  3874. cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
  3875. // Remove a prefix to make the path relative, if relevant.
  3876. const char *PathBegin = Path.data();
  3877. const char *PathPtr =
  3878. adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
  3879. if (PathPtr != PathBegin) {
  3880. Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
  3881. Changed = true;
  3882. }
  3883. return Changed;
  3884. }
  3885. void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
  3886. SmallString<128> FilePath(Path);
  3887. PreparePathForOutput(FilePath);
  3888. AddString(FilePath, Record);
  3889. }
  3890. void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
  3891. StringRef Path) {
  3892. SmallString<128> FilePath(Path);
  3893. PreparePathForOutput(FilePath);
  3894. Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
  3895. }
  3896. void ASTWriter::AddVersionTuple(const VersionTuple &Version,
  3897. RecordDataImpl &Record) {
  3898. Record.push_back(Version.getMajor());
  3899. if (Optional<unsigned> Minor = Version.getMinor())
  3900. Record.push_back(*Minor + 1);
  3901. else
  3902. Record.push_back(0);
  3903. if (Optional<unsigned> Subminor = Version.getSubminor())
  3904. Record.push_back(*Subminor + 1);
  3905. else
  3906. Record.push_back(0);
  3907. }
  3908. /// Note that the identifier II occurs at the given offset
  3909. /// within the identifier table.
  3910. void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
  3911. IdentID ID = IdentifierIDs[II];
  3912. // Only store offsets new to this AST file. Other identifier names are looked
  3913. // up earlier in the chain and thus don't need an offset.
  3914. if (ID >= FirstIdentID)
  3915. IdentifierOffsets[ID - FirstIdentID] = Offset;
  3916. }
  3917. /// Note that the selector Sel occurs at the given offset
  3918. /// within the method pool/selector table.
  3919. void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
  3920. unsigned ID = SelectorIDs[Sel];
  3921. assert(ID && "Unknown selector");
  3922. // Don't record offsets for selectors that are also available in a different
  3923. // file.
  3924. if (ID < FirstSelectorID)
  3925. return;
  3926. SelectorOffsets[ID - FirstSelectorID] = Offset;
  3927. }
  3928. ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
  3929. SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
  3930. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  3931. bool IncludeTimestamps)
  3932. : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
  3933. IncludeTimestamps(IncludeTimestamps) {
  3934. for (const auto &Ext : Extensions) {
  3935. if (auto Writer = Ext->createExtensionWriter(*this))
  3936. ModuleFileExtensionWriters.push_back(std::move(Writer));
  3937. }
  3938. }
  3939. ASTWriter::~ASTWriter() {
  3940. llvm::DeleteContainerSeconds(FileDeclIDs);
  3941. }
  3942. const LangOptions &ASTWriter::getLangOpts() const {
  3943. assert(WritingAST && "can't determine lang opts when not writing AST");
  3944. return Context->getLangOpts();
  3945. }
  3946. time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
  3947. return IncludeTimestamps ? E->getModificationTime() : 0;
  3948. }
  3949. ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
  3950. const std::string &OutputFile,
  3951. Module *WritingModule, StringRef isysroot,
  3952. bool hasErrors) {
  3953. WritingAST = true;
  3954. ASTHasCompilerErrors = hasErrors;
  3955. // Emit the file header.
  3956. Stream.Emit((unsigned)'C', 8);
  3957. Stream.Emit((unsigned)'P', 8);
  3958. Stream.Emit((unsigned)'C', 8);
  3959. Stream.Emit((unsigned)'H', 8);
  3960. WriteBlockInfoBlock();
  3961. Context = &SemaRef.Context;
  3962. PP = &SemaRef.PP;
  3963. this->WritingModule = WritingModule;
  3964. ASTFileSignature Signature =
  3965. WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
  3966. Context = nullptr;
  3967. PP = nullptr;
  3968. this->WritingModule = nullptr;
  3969. this->BaseDirectory.clear();
  3970. WritingAST = false;
  3971. if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
  3972. // Construct MemoryBuffer and update buffer manager.
  3973. PCMCache.addBuffer(OutputFile,
  3974. llvm::MemoryBuffer::getMemBufferCopy(
  3975. StringRef(Buffer.begin(), Buffer.size())));
  3976. }
  3977. return Signature;
  3978. }
  3979. template<typename Vector>
  3980. static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
  3981. ASTWriter::RecordData &Record) {
  3982. for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
  3983. I != E; ++I) {
  3984. Writer.AddDeclRef(*I, Record);
  3985. }
  3986. }
  3987. ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
  3988. const std::string &OutputFile,
  3989. Module *WritingModule) {
  3990. using namespace llvm;
  3991. bool isModule = WritingModule != nullptr;
  3992. // Make sure that the AST reader knows to finalize itself.
  3993. if (Chain)
  3994. Chain->finalizeForWriting();
  3995. ASTContext &Context = SemaRef.Context;
  3996. Preprocessor &PP = SemaRef.PP;
  3997. // Set up predefined declaration IDs.
  3998. auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
  3999. if (D) {
  4000. assert(D->isCanonicalDecl() && "predefined decl is not canonical");
  4001. DeclIDs[D] = ID;
  4002. }
  4003. };
  4004. RegisterPredefDecl(Context.getTranslationUnitDecl(),
  4005. PREDEF_DECL_TRANSLATION_UNIT_ID);
  4006. RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
  4007. RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
  4008. RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
  4009. RegisterPredefDecl(Context.ObjCProtocolClassDecl,
  4010. PREDEF_DECL_OBJC_PROTOCOL_ID);
  4011. RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
  4012. RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
  4013. RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
  4014. PREDEF_DECL_OBJC_INSTANCETYPE_ID);
  4015. RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
  4016. RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
  4017. RegisterPredefDecl(Context.BuiltinMSVaListDecl,
  4018. PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
  4019. RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
  4020. RegisterPredefDecl(Context.MakeIntegerSeqDecl,
  4021. PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
  4022. RegisterPredefDecl(Context.CFConstantStringTypeDecl,
  4023. PREDEF_DECL_CF_CONSTANT_STRING_ID);
  4024. RegisterPredefDecl(Context.CFConstantStringTagDecl,
  4025. PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
  4026. RegisterPredefDecl(Context.TypePackElementDecl,
  4027. PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
  4028. // Build a record containing all of the tentative definitions in this file, in
  4029. // TentativeDefinitions order. Generally, this record will be empty for
  4030. // headers.
  4031. RecordData TentativeDefinitions;
  4032. AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
  4033. // Build a record containing all of the file scoped decls in this file.
  4034. RecordData UnusedFileScopedDecls;
  4035. if (!isModule)
  4036. AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
  4037. UnusedFileScopedDecls);
  4038. // Build a record containing all of the delegating constructors we still need
  4039. // to resolve.
  4040. RecordData DelegatingCtorDecls;
  4041. if (!isModule)
  4042. AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
  4043. // Write the set of weak, undeclared identifiers. We always write the
  4044. // entire table, since later PCH files in a PCH chain are only interested in
  4045. // the results at the end of the chain.
  4046. RecordData WeakUndeclaredIdentifiers;
  4047. for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
  4048. IdentifierInfo *II = WeakUndeclaredIdentifier.first;
  4049. WeakInfo &WI = WeakUndeclaredIdentifier.second;
  4050. AddIdentifierRef(II, WeakUndeclaredIdentifiers);
  4051. AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
  4052. AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
  4053. WeakUndeclaredIdentifiers.push_back(WI.getUsed());
  4054. }
  4055. // Build a record containing all of the ext_vector declarations.
  4056. RecordData ExtVectorDecls;
  4057. AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
  4058. // Build a record containing all of the VTable uses information.
  4059. RecordData VTableUses;
  4060. if (!SemaRef.VTableUses.empty()) {
  4061. for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
  4062. AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
  4063. AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
  4064. VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
  4065. }
  4066. }
  4067. // Build a record containing all of the UnusedLocalTypedefNameCandidates.
  4068. RecordData UnusedLocalTypedefNameCandidates;
  4069. for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
  4070. AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
  4071. // Build a record containing all of pending implicit instantiations.
  4072. RecordData PendingInstantiations;
  4073. for (const auto &I : SemaRef.PendingInstantiations) {
  4074. AddDeclRef(I.first, PendingInstantiations);
  4075. AddSourceLocation(I.second, PendingInstantiations);
  4076. }
  4077. assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
  4078. "There are local ones at end of translation unit!");
  4079. // Build a record containing some declaration references.
  4080. RecordData SemaDeclRefs;
  4081. if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
  4082. AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
  4083. AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
  4084. AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
  4085. }
  4086. RecordData CUDASpecialDeclRefs;
  4087. if (Context.getcudaConfigureCallDecl()) {
  4088. AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
  4089. }
  4090. // Build a record containing all of the known namespaces.
  4091. RecordData KnownNamespaces;
  4092. for (const auto &I : SemaRef.KnownNamespaces) {
  4093. if (!I.second)
  4094. AddDeclRef(I.first, KnownNamespaces);
  4095. }
  4096. // Build a record of all used, undefined objects that require definitions.
  4097. RecordData UndefinedButUsed;
  4098. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  4099. SemaRef.getUndefinedButUsed(Undefined);
  4100. for (const auto &I : Undefined) {
  4101. AddDeclRef(I.first, UndefinedButUsed);
  4102. AddSourceLocation(I.second, UndefinedButUsed);
  4103. }
  4104. // Build a record containing all delete-expressions that we would like to
  4105. // analyze later in AST.
  4106. RecordData DeleteExprsToAnalyze;
  4107. if (!isModule) {
  4108. for (const auto &DeleteExprsInfo :
  4109. SemaRef.getMismatchingDeleteExpressions()) {
  4110. AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
  4111. DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
  4112. for (const auto &DeleteLoc : DeleteExprsInfo.second) {
  4113. AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
  4114. DeleteExprsToAnalyze.push_back(DeleteLoc.second);
  4115. }
  4116. }
  4117. }
  4118. // Write the control block
  4119. WriteControlBlock(PP, Context, isysroot, OutputFile);
  4120. // Write the remaining AST contents.
  4121. Stream.EnterSubblock(AST_BLOCK_ID, 5);
  4122. // This is so that older clang versions, before the introduction
  4123. // of the control block, can read and reject the newer PCH format.
  4124. {
  4125. RecordData Record = {VERSION_MAJOR};
  4126. Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
  4127. }
  4128. // Create a lexical update block containing all of the declarations in the
  4129. // translation unit that do not come from other AST files.
  4130. const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  4131. SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
  4132. for (const auto *D : TU->noload_decls()) {
  4133. if (!D->isFromASTFile()) {
  4134. NewGlobalKindDeclPairs.push_back(D->getKind());
  4135. NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
  4136. }
  4137. }
  4138. auto Abv = std::make_shared<BitCodeAbbrev>();
  4139. Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
  4140. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  4141. unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
  4142. {
  4143. RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
  4144. Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
  4145. bytes(NewGlobalKindDeclPairs));
  4146. }
  4147. // And a visible updates block for the translation unit.
  4148. Abv = std::make_shared<BitCodeAbbrev>();
  4149. Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
  4150. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  4151. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  4152. UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
  4153. WriteDeclContextVisibleUpdate(TU);
  4154. // If we have any extern "C" names, write out a visible update for them.
  4155. if (Context.ExternCContext)
  4156. WriteDeclContextVisibleUpdate(Context.ExternCContext);
  4157. // If the translation unit has an anonymous namespace, and we don't already
  4158. // have an update block for it, write it as an update block.
  4159. // FIXME: Why do we not do this if there's already an update block?
  4160. if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
  4161. ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
  4162. if (Record.empty())
  4163. Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
  4164. }
  4165. // Add update records for all mangling numbers and static local numbers.
  4166. // These aren't really update records, but this is a convenient way of
  4167. // tagging this rare extra data onto the declarations.
  4168. for (const auto &Number : Context.MangleNumbers)
  4169. if (!Number.first->isFromASTFile())
  4170. DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
  4171. Number.second));
  4172. for (const auto &Number : Context.StaticLocalNumbers)
  4173. if (!Number.first->isFromASTFile())
  4174. DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
  4175. Number.second));
  4176. // Make sure visible decls, added to DeclContexts previously loaded from
  4177. // an AST file, are registered for serialization. Likewise for template
  4178. // specializations added to imported templates.
  4179. for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
  4180. GetDeclRef(I);
  4181. }
  4182. // Make sure all decls associated with an identifier are registered for
  4183. // serialization, if we're storing decls with identifiers.
  4184. if (!WritingModule || !getLangOpts().CPlusPlus) {
  4185. llvm::SmallVector<const IdentifierInfo*, 256> IIs;
  4186. for (const auto &ID : PP.getIdentifierTable()) {
  4187. const IdentifierInfo *II = ID.second;
  4188. if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
  4189. IIs.push_back(II);
  4190. }
  4191. // Sort the identifiers to visit based on their name.
  4192. llvm::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
  4193. for (const IdentifierInfo *II : IIs) {
  4194. for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
  4195. DEnd = SemaRef.IdResolver.end();
  4196. D != DEnd; ++D) {
  4197. GetDeclRef(*D);
  4198. }
  4199. }
  4200. }
  4201. // For method pool in the module, if it contains an entry for a selector,
  4202. // the entry should be complete, containing everything introduced by that
  4203. // module and all modules it imports. It's possible that the entry is out of
  4204. // date, so we need to pull in the new content here.
  4205. // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
  4206. // safe, we copy all selectors out.
  4207. llvm::SmallVector<Selector, 256> AllSelectors;
  4208. for (auto &SelectorAndID : SelectorIDs)
  4209. AllSelectors.push_back(SelectorAndID.first);
  4210. for (auto &Selector : AllSelectors)
  4211. SemaRef.updateOutOfDateSelector(Selector);
  4212. // Form the record of special types.
  4213. RecordData SpecialTypes;
  4214. AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
  4215. AddTypeRef(Context.getFILEType(), SpecialTypes);
  4216. AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
  4217. AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
  4218. AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
  4219. AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
  4220. AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
  4221. AddTypeRef(Context.getucontext_tType(), SpecialTypes);
  4222. if (Chain) {
  4223. // Write the mapping information describing our module dependencies and how
  4224. // each of those modules were mapped into our own offset/ID space, so that
  4225. // the reader can build the appropriate mapping to its own offset/ID space.
  4226. // The map consists solely of a blob with the following format:
  4227. // *(module-kind:i8
  4228. // module-name-len:i16 module-name:len*i8
  4229. // source-location-offset:i32
  4230. // identifier-id:i32
  4231. // preprocessed-entity-id:i32
  4232. // macro-definition-id:i32
  4233. // submodule-id:i32
  4234. // selector-id:i32
  4235. // declaration-id:i32
  4236. // c++-base-specifiers-id:i32
  4237. // type-id:i32)
  4238. //
  4239. // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
  4240. // MK_ExplicitModule, then the module-name is the module name. Otherwise,
  4241. // it is the module file name.
  4242. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  4243. Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
  4244. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  4245. unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  4246. SmallString<2048> Buffer;
  4247. {
  4248. llvm::raw_svector_ostream Out(Buffer);
  4249. for (ModuleFile &M : Chain->ModuleMgr) {
  4250. using namespace llvm::support;
  4251. endian::Writer LE(Out, little);
  4252. LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
  4253. StringRef Name =
  4254. M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
  4255. ? M.ModuleName
  4256. : M.FileName;
  4257. LE.write<uint16_t>(Name.size());
  4258. Out.write(Name.data(), Name.size());
  4259. // Note: if a base ID was uint max, it would not be possible to load
  4260. // another module after it or have more than one entity inside it.
  4261. uint32_t None = std::numeric_limits<uint32_t>::max();
  4262. auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
  4263. assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
  4264. if (ShouldWrite)
  4265. LE.write<uint32_t>(BaseID);
  4266. else
  4267. LE.write<uint32_t>(None);
  4268. };
  4269. // These values should be unique within a chain, since they will be read
  4270. // as keys into ContinuousRangeMaps.
  4271. writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
  4272. writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
  4273. writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
  4274. writeBaseIDOrNone(M.BasePreprocessedEntityID,
  4275. M.NumPreprocessedEntities);
  4276. writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
  4277. writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
  4278. writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
  4279. writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
  4280. }
  4281. }
  4282. RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
  4283. Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
  4284. Buffer.data(), Buffer.size());
  4285. }
  4286. RecordData DeclUpdatesOffsetsRecord;
  4287. // Keep writing types, declarations, and declaration update records
  4288. // until we've emitted all of them.
  4289. Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
  4290. WriteTypeAbbrevs();
  4291. WriteDeclAbbrevs();
  4292. do {
  4293. WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
  4294. while (!DeclTypesToEmit.empty()) {
  4295. DeclOrType DOT = DeclTypesToEmit.front();
  4296. DeclTypesToEmit.pop();
  4297. if (DOT.isType())
  4298. WriteType(DOT.getType());
  4299. else
  4300. WriteDecl(Context, DOT.getDecl());
  4301. }
  4302. } while (!DeclUpdates.empty());
  4303. Stream.ExitBlock();
  4304. DoneWritingDeclsAndTypes = true;
  4305. // These things can only be done once we've written out decls and types.
  4306. WriteTypeDeclOffsets();
  4307. if (!DeclUpdatesOffsetsRecord.empty())
  4308. Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
  4309. WriteFileDeclIDsMap();
  4310. WriteSourceManagerBlock(Context.getSourceManager(), PP);
  4311. WriteComments();
  4312. WritePreprocessor(PP, isModule);
  4313. WriteHeaderSearch(PP.getHeaderSearchInfo());
  4314. WriteSelectors(SemaRef);
  4315. WriteReferencedSelectorsPool(SemaRef);
  4316. WriteLateParsedTemplates(SemaRef);
  4317. WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
  4318. WriteFPPragmaOptions(SemaRef.getFPOptions());
  4319. WriteOpenCLExtensions(SemaRef);
  4320. WriteOpenCLExtensionTypes(SemaRef);
  4321. WriteOpenCLExtensionDecls(SemaRef);
  4322. WriteCUDAPragmas(SemaRef);
  4323. // If we're emitting a module, write out the submodule information.
  4324. if (WritingModule)
  4325. WriteSubmodules(WritingModule);
  4326. Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
  4327. // Write the record containing external, unnamed definitions.
  4328. if (!EagerlyDeserializedDecls.empty())
  4329. Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
  4330. if (!ModularCodegenDecls.empty())
  4331. Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
  4332. // Write the record containing tentative definitions.
  4333. if (!TentativeDefinitions.empty())
  4334. Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
  4335. // Write the record containing unused file scoped decls.
  4336. if (!UnusedFileScopedDecls.empty())
  4337. Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
  4338. // Write the record containing weak undeclared identifiers.
  4339. if (!WeakUndeclaredIdentifiers.empty())
  4340. Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
  4341. WeakUndeclaredIdentifiers);
  4342. // Write the record containing ext_vector type names.
  4343. if (!ExtVectorDecls.empty())
  4344. Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
  4345. // Write the record containing VTable uses information.
  4346. if (!VTableUses.empty())
  4347. Stream.EmitRecord(VTABLE_USES, VTableUses);
  4348. // Write the record containing potentially unused local typedefs.
  4349. if (!UnusedLocalTypedefNameCandidates.empty())
  4350. Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
  4351. UnusedLocalTypedefNameCandidates);
  4352. // Write the record containing pending implicit instantiations.
  4353. if (!PendingInstantiations.empty())
  4354. Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
  4355. // Write the record containing declaration references of Sema.
  4356. if (!SemaDeclRefs.empty())
  4357. Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
  4358. // Write the record containing CUDA-specific declaration references.
  4359. if (!CUDASpecialDeclRefs.empty())
  4360. Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
  4361. // Write the delegating constructors.
  4362. if (!DelegatingCtorDecls.empty())
  4363. Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
  4364. // Write the known namespaces.
  4365. if (!KnownNamespaces.empty())
  4366. Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
  4367. // Write the undefined internal functions and variables, and inline functions.
  4368. if (!UndefinedButUsed.empty())
  4369. Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
  4370. if (!DeleteExprsToAnalyze.empty())
  4371. Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
  4372. // Write the visible updates to DeclContexts.
  4373. for (auto *DC : UpdatedDeclContexts)
  4374. WriteDeclContextVisibleUpdate(DC);
  4375. if (!WritingModule) {
  4376. // Write the submodules that were imported, if any.
  4377. struct ModuleInfo {
  4378. uint64_t ID;
  4379. Module *M;
  4380. ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
  4381. };
  4382. llvm::SmallVector<ModuleInfo, 64> Imports;
  4383. for (const auto *I : Context.local_imports()) {
  4384. assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
  4385. Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
  4386. I->getImportedModule()));
  4387. }
  4388. if (!Imports.empty()) {
  4389. auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
  4390. return A.ID < B.ID;
  4391. };
  4392. auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
  4393. return A.ID == B.ID;
  4394. };
  4395. // Sort and deduplicate module IDs.
  4396. llvm::sort(Imports.begin(), Imports.end(), Cmp);
  4397. Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
  4398. Imports.end());
  4399. RecordData ImportedModules;
  4400. for (const auto &Import : Imports) {
  4401. ImportedModules.push_back(Import.ID);
  4402. // FIXME: If the module has macros imported then later has declarations
  4403. // imported, this location won't be the right one as a location for the
  4404. // declaration imports.
  4405. AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
  4406. }
  4407. Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
  4408. }
  4409. }
  4410. WriteObjCCategories();
  4411. if(!WritingModule) {
  4412. WriteOptimizePragmaOptions(SemaRef);
  4413. WriteMSStructPragmaOptions(SemaRef);
  4414. WriteMSPointersToMembersPragmaOptions(SemaRef);
  4415. }
  4416. WritePackPragmaOptions(SemaRef);
  4417. // Some simple statistics
  4418. RecordData::value_type Record[] = {
  4419. NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
  4420. Stream.EmitRecord(STATISTICS, Record);
  4421. Stream.ExitBlock();
  4422. // Write the module file extension blocks.
  4423. for (const auto &ExtWriter : ModuleFileExtensionWriters)
  4424. WriteModuleFileExtension(SemaRef, *ExtWriter);
  4425. return writeUnhashedControlBlock(PP, Context);
  4426. }
  4427. void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
  4428. if (DeclUpdates.empty())
  4429. return;
  4430. DeclUpdateMap LocalUpdates;
  4431. LocalUpdates.swap(DeclUpdates);
  4432. for (auto &DeclUpdate : LocalUpdates) {
  4433. const Decl *D = DeclUpdate.first;
  4434. bool HasUpdatedBody = false;
  4435. RecordData RecordData;
  4436. ASTRecordWriter Record(*this, RecordData);
  4437. for (auto &Update : DeclUpdate.second) {
  4438. DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
  4439. // An updated body is emitted last, so that the reader doesn't need
  4440. // to skip over the lazy body to reach statements for other records.
  4441. if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
  4442. HasUpdatedBody = true;
  4443. else
  4444. Record.push_back(Kind);
  4445. switch (Kind) {
  4446. case UPD_CXX_ADDED_IMPLICIT_MEMBER:
  4447. case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
  4448. case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
  4449. assert(Update.getDecl() && "no decl to add?");
  4450. Record.push_back(GetDeclRef(Update.getDecl()));
  4451. break;
  4452. case UPD_CXX_ADDED_FUNCTION_DEFINITION:
  4453. break;
  4454. case UPD_CXX_POINT_OF_INSTANTIATION:
  4455. // FIXME: Do we need to also save the template specialization kind here?
  4456. Record.AddSourceLocation(Update.getLoc());
  4457. break;
  4458. case UPD_CXX_ADDED_VAR_DEFINITION: {
  4459. const VarDecl *VD = cast<VarDecl>(D);
  4460. Record.push_back(VD->isInline());
  4461. Record.push_back(VD->isInlineSpecified());
  4462. if (VD->getInit()) {
  4463. Record.push_back(!VD->isInitKnownICE() ? 1
  4464. : (VD->isInitICE() ? 3 : 2));
  4465. Record.AddStmt(const_cast<Expr*>(VD->getInit()));
  4466. } else {
  4467. Record.push_back(0);
  4468. }
  4469. break;
  4470. }
  4471. case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
  4472. Record.AddStmt(const_cast<Expr *>(
  4473. cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
  4474. break;
  4475. case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
  4476. Record.AddStmt(
  4477. cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
  4478. break;
  4479. case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
  4480. auto *RD = cast<CXXRecordDecl>(D);
  4481. UpdatedDeclContexts.insert(RD->getPrimaryContext());
  4482. Record.push_back(RD->isParamDestroyedInCallee());
  4483. Record.push_back(RD->getArgPassingRestrictions());
  4484. Record.AddCXXDefinitionData(RD);
  4485. Record.AddOffset(WriteDeclContextLexicalBlock(
  4486. *Context, const_cast<CXXRecordDecl *>(RD)));
  4487. // This state is sometimes updated by template instantiation, when we
  4488. // switch from the specialization referring to the template declaration
  4489. // to it referring to the template definition.
  4490. if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
  4491. Record.push_back(MSInfo->getTemplateSpecializationKind());
  4492. Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
  4493. } else {
  4494. auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
  4495. Record.push_back(Spec->getTemplateSpecializationKind());
  4496. Record.AddSourceLocation(Spec->getPointOfInstantiation());
  4497. // The instantiation might have been resolved to a partial
  4498. // specialization. If so, record which one.
  4499. auto From = Spec->getInstantiatedFrom();
  4500. if (auto PartialSpec =
  4501. From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
  4502. Record.push_back(true);
  4503. Record.AddDeclRef(PartialSpec);
  4504. Record.AddTemplateArgumentList(
  4505. &Spec->getTemplateInstantiationArgs());
  4506. } else {
  4507. Record.push_back(false);
  4508. }
  4509. }
  4510. Record.push_back(RD->getTagKind());
  4511. Record.AddSourceLocation(RD->getLocation());
  4512. Record.AddSourceLocation(RD->getBeginLoc());
  4513. Record.AddSourceRange(RD->getBraceRange());
  4514. // Instantiation may change attributes; write them all out afresh.
  4515. Record.push_back(D->hasAttrs());
  4516. if (D->hasAttrs())
  4517. Record.AddAttributes(D->getAttrs());
  4518. // FIXME: Ensure we don't get here for explicit instantiations.
  4519. break;
  4520. }
  4521. case UPD_CXX_RESOLVED_DTOR_DELETE:
  4522. Record.AddDeclRef(Update.getDecl());
  4523. Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
  4524. break;
  4525. case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
  4526. addExceptionSpec(
  4527. cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
  4528. Record);
  4529. break;
  4530. case UPD_CXX_DEDUCED_RETURN_TYPE:
  4531. Record.push_back(GetOrCreateTypeID(Update.getType()));
  4532. break;
  4533. case UPD_DECL_MARKED_USED:
  4534. break;
  4535. case UPD_MANGLING_NUMBER:
  4536. case UPD_STATIC_LOCAL_NUMBER:
  4537. Record.push_back(Update.getNumber());
  4538. break;
  4539. case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
  4540. Record.AddSourceRange(
  4541. D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
  4542. break;
  4543. case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
  4544. Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
  4545. Record.AddSourceRange(
  4546. D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
  4547. break;
  4548. case UPD_DECL_EXPORTED:
  4549. Record.push_back(getSubmoduleID(Update.getModule()));
  4550. break;
  4551. case UPD_ADDED_ATTR_TO_RECORD:
  4552. Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
  4553. break;
  4554. }
  4555. }
  4556. if (HasUpdatedBody) {
  4557. const auto *Def = cast<FunctionDecl>(D);
  4558. Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
  4559. Record.push_back(Def->isInlined());
  4560. Record.AddSourceLocation(Def->getInnerLocStart());
  4561. Record.AddFunctionDefinition(Def);
  4562. }
  4563. OffsetsRecord.push_back(GetDeclRef(D));
  4564. OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
  4565. }
  4566. }
  4567. void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
  4568. uint32_t Raw = Loc.getRawEncoding();
  4569. Record.push_back((Raw << 1) | (Raw >> 31));
  4570. }
  4571. void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
  4572. AddSourceLocation(Range.getBegin(), Record);
  4573. AddSourceLocation(Range.getEnd(), Record);
  4574. }
  4575. void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
  4576. Record->push_back(Value.getBitWidth());
  4577. const uint64_t *Words = Value.getRawData();
  4578. Record->append(Words, Words + Value.getNumWords());
  4579. }
  4580. void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
  4581. Record->push_back(Value.isUnsigned());
  4582. AddAPInt(Value);
  4583. }
  4584. void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
  4585. AddAPInt(Value.bitcastToAPInt());
  4586. }
  4587. void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
  4588. Record.push_back(getIdentifierRef(II));
  4589. }
  4590. IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
  4591. if (!II)
  4592. return 0;
  4593. IdentID &ID = IdentifierIDs[II];
  4594. if (ID == 0)
  4595. ID = NextIdentID++;
  4596. return ID;
  4597. }
  4598. MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
  4599. // Don't emit builtin macros like __LINE__ to the AST file unless they
  4600. // have been redefined by the header (in which case they are not
  4601. // isBuiltinMacro).
  4602. if (!MI || MI->isBuiltinMacro())
  4603. return 0;
  4604. MacroID &ID = MacroIDs[MI];
  4605. if (ID == 0) {
  4606. ID = NextMacroID++;
  4607. MacroInfoToEmitData Info = { Name, MI, ID };
  4608. MacroInfosToEmit.push_back(Info);
  4609. }
  4610. return ID;
  4611. }
  4612. MacroID ASTWriter::getMacroID(MacroInfo *MI) {
  4613. if (!MI || MI->isBuiltinMacro())
  4614. return 0;
  4615. assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
  4616. return MacroIDs[MI];
  4617. }
  4618. uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
  4619. return IdentMacroDirectivesOffsetMap.lookup(Name);
  4620. }
  4621. void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
  4622. Record->push_back(Writer->getSelectorRef(SelRef));
  4623. }
  4624. SelectorID ASTWriter::getSelectorRef(Selector Sel) {
  4625. if (Sel.getAsOpaquePtr() == nullptr) {
  4626. return 0;
  4627. }
  4628. SelectorID SID = SelectorIDs[Sel];
  4629. if (SID == 0 && Chain) {
  4630. // This might trigger a ReadSelector callback, which will set the ID for
  4631. // this selector.
  4632. Chain->LoadSelector(Sel);
  4633. SID = SelectorIDs[Sel];
  4634. }
  4635. if (SID == 0) {
  4636. SID = NextSelectorID++;
  4637. SelectorIDs[Sel] = SID;
  4638. }
  4639. return SID;
  4640. }
  4641. void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
  4642. AddDeclRef(Temp->getDestructor());
  4643. }
  4644. void ASTRecordWriter::AddTemplateArgumentLocInfo(
  4645. TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
  4646. switch (Kind) {
  4647. case TemplateArgument::Expression:
  4648. AddStmt(Arg.getAsExpr());
  4649. break;
  4650. case TemplateArgument::Type:
  4651. AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
  4652. break;
  4653. case TemplateArgument::Template:
  4654. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
  4655. AddSourceLocation(Arg.getTemplateNameLoc());
  4656. break;
  4657. case TemplateArgument::TemplateExpansion:
  4658. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
  4659. AddSourceLocation(Arg.getTemplateNameLoc());
  4660. AddSourceLocation(Arg.getTemplateEllipsisLoc());
  4661. break;
  4662. case TemplateArgument::Null:
  4663. case TemplateArgument::Integral:
  4664. case TemplateArgument::Declaration:
  4665. case TemplateArgument::NullPtr:
  4666. case TemplateArgument::Pack:
  4667. // FIXME: Is this right?
  4668. break;
  4669. }
  4670. }
  4671. void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
  4672. AddTemplateArgument(Arg.getArgument());
  4673. if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
  4674. bool InfoHasSameExpr
  4675. = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
  4676. Record->push_back(InfoHasSameExpr);
  4677. if (InfoHasSameExpr)
  4678. return; // Avoid storing the same expr twice.
  4679. }
  4680. AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
  4681. }
  4682. void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
  4683. if (!TInfo) {
  4684. AddTypeRef(QualType());
  4685. return;
  4686. }
  4687. AddTypeRef(TInfo->getType());
  4688. AddTypeLoc(TInfo->getTypeLoc());
  4689. }
  4690. void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
  4691. TypeLocWriter TLW(*this);
  4692. for (; !TL.isNull(); TL = TL.getNextTypeLoc())
  4693. TLW.Visit(TL);
  4694. }
  4695. void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
  4696. Record.push_back(GetOrCreateTypeID(T));
  4697. }
  4698. TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
  4699. assert(Context);
  4700. return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
  4701. if (T.isNull())
  4702. return TypeIdx();
  4703. assert(!T.getLocalFastQualifiers());
  4704. TypeIdx &Idx = TypeIdxs[T];
  4705. if (Idx.getIndex() == 0) {
  4706. if (DoneWritingDeclsAndTypes) {
  4707. assert(0 && "New type seen after serializing all the types to emit!");
  4708. return TypeIdx();
  4709. }
  4710. // We haven't seen this type before. Assign it a new ID and put it
  4711. // into the queue of types to emit.
  4712. Idx = TypeIdx(NextTypeID++);
  4713. DeclTypesToEmit.push(T);
  4714. }
  4715. return Idx;
  4716. });
  4717. }
  4718. TypeID ASTWriter::getTypeID(QualType T) const {
  4719. assert(Context);
  4720. return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
  4721. if (T.isNull())
  4722. return TypeIdx();
  4723. assert(!T.getLocalFastQualifiers());
  4724. TypeIdxMap::const_iterator I = TypeIdxs.find(T);
  4725. assert(I != TypeIdxs.end() && "Type not emitted!");
  4726. return I->second;
  4727. });
  4728. }
  4729. void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
  4730. Record.push_back(GetDeclRef(D));
  4731. }
  4732. DeclID ASTWriter::GetDeclRef(const Decl *D) {
  4733. assert(WritingAST && "Cannot request a declaration ID before AST writing");
  4734. if (!D) {
  4735. return 0;
  4736. }
  4737. // If D comes from an AST file, its declaration ID is already known and
  4738. // fixed.
  4739. if (D->isFromASTFile())
  4740. return D->getGlobalID();
  4741. assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
  4742. DeclID &ID = DeclIDs[D];
  4743. if (ID == 0) {
  4744. if (DoneWritingDeclsAndTypes) {
  4745. assert(0 && "New decl seen after serializing all the decls to emit!");
  4746. return 0;
  4747. }
  4748. // We haven't seen this declaration before. Give it a new ID and
  4749. // enqueue it in the list of declarations to emit.
  4750. ID = NextDeclID++;
  4751. DeclTypesToEmit.push(const_cast<Decl *>(D));
  4752. }
  4753. return ID;
  4754. }
  4755. DeclID ASTWriter::getDeclID(const Decl *D) {
  4756. if (!D)
  4757. return 0;
  4758. // If D comes from an AST file, its declaration ID is already known and
  4759. // fixed.
  4760. if (D->isFromASTFile())
  4761. return D->getGlobalID();
  4762. assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
  4763. return DeclIDs[D];
  4764. }
  4765. void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
  4766. assert(ID);
  4767. assert(D);
  4768. SourceLocation Loc = D->getLocation();
  4769. if (Loc.isInvalid())
  4770. return;
  4771. // We only keep track of the file-level declarations of each file.
  4772. if (!D->getLexicalDeclContext()->isFileContext())
  4773. return;
  4774. // FIXME: ParmVarDecls that are part of a function type of a parameter of
  4775. // a function/objc method, should not have TU as lexical context.
  4776. // TemplateTemplateParmDecls that are part of an alias template, should not
  4777. // have TU as lexical context.
  4778. if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
  4779. return;
  4780. SourceManager &SM = Context->getSourceManager();
  4781. SourceLocation FileLoc = SM.getFileLoc(Loc);
  4782. assert(SM.isLocalSourceLocation(FileLoc));
  4783. FileID FID;
  4784. unsigned Offset;
  4785. std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  4786. if (FID.isInvalid())
  4787. return;
  4788. assert(SM.getSLocEntry(FID).isFile());
  4789. DeclIDInFileInfo *&Info = FileDeclIDs[FID];
  4790. if (!Info)
  4791. Info = new DeclIDInFileInfo();
  4792. std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
  4793. LocDeclIDsTy &Decls = Info->DeclIDs;
  4794. if (Decls.empty() || Decls.back().first <= Offset) {
  4795. Decls.push_back(LocDecl);
  4796. return;
  4797. }
  4798. LocDeclIDsTy::iterator I =
  4799. std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
  4800. Decls.insert(I, LocDecl);
  4801. }
  4802. void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
  4803. // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
  4804. Record->push_back(Name.getNameKind());
  4805. switch (Name.getNameKind()) {
  4806. case DeclarationName::Identifier:
  4807. AddIdentifierRef(Name.getAsIdentifierInfo());
  4808. break;
  4809. case DeclarationName::ObjCZeroArgSelector:
  4810. case DeclarationName::ObjCOneArgSelector:
  4811. case DeclarationName::ObjCMultiArgSelector:
  4812. AddSelectorRef(Name.getObjCSelector());
  4813. break;
  4814. case DeclarationName::CXXConstructorName:
  4815. case DeclarationName::CXXDestructorName:
  4816. case DeclarationName::CXXConversionFunctionName:
  4817. AddTypeRef(Name.getCXXNameType());
  4818. break;
  4819. case DeclarationName::CXXDeductionGuideName:
  4820. AddDeclRef(Name.getCXXDeductionGuideTemplate());
  4821. break;
  4822. case DeclarationName::CXXOperatorName:
  4823. Record->push_back(Name.getCXXOverloadedOperator());
  4824. break;
  4825. case DeclarationName::CXXLiteralOperatorName:
  4826. AddIdentifierRef(Name.getCXXLiteralIdentifier());
  4827. break;
  4828. case DeclarationName::CXXUsingDirective:
  4829. // No extra data to emit
  4830. break;
  4831. }
  4832. }
  4833. unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
  4834. assert(needsAnonymousDeclarationNumber(D) &&
  4835. "expected an anonymous declaration");
  4836. // Number the anonymous declarations within this context, if we've not
  4837. // already done so.
  4838. auto It = AnonymousDeclarationNumbers.find(D);
  4839. if (It == AnonymousDeclarationNumbers.end()) {
  4840. auto *DC = D->getLexicalDeclContext();
  4841. numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
  4842. AnonymousDeclarationNumbers[ND] = Number;
  4843. });
  4844. It = AnonymousDeclarationNumbers.find(D);
  4845. assert(It != AnonymousDeclarationNumbers.end() &&
  4846. "declaration not found within its lexical context");
  4847. }
  4848. return It->second;
  4849. }
  4850. void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
  4851. DeclarationName Name) {
  4852. switch (Name.getNameKind()) {
  4853. case DeclarationName::CXXConstructorName:
  4854. case DeclarationName::CXXDestructorName:
  4855. case DeclarationName::CXXConversionFunctionName:
  4856. AddTypeSourceInfo(DNLoc.NamedType.TInfo);
  4857. break;
  4858. case DeclarationName::CXXOperatorName:
  4859. AddSourceLocation(SourceLocation::getFromRawEncoding(
  4860. DNLoc.CXXOperatorName.BeginOpNameLoc));
  4861. AddSourceLocation(
  4862. SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
  4863. break;
  4864. case DeclarationName::CXXLiteralOperatorName:
  4865. AddSourceLocation(SourceLocation::getFromRawEncoding(
  4866. DNLoc.CXXLiteralOperatorName.OpNameLoc));
  4867. break;
  4868. case DeclarationName::Identifier:
  4869. case DeclarationName::ObjCZeroArgSelector:
  4870. case DeclarationName::ObjCOneArgSelector:
  4871. case DeclarationName::ObjCMultiArgSelector:
  4872. case DeclarationName::CXXUsingDirective:
  4873. case DeclarationName::CXXDeductionGuideName:
  4874. break;
  4875. }
  4876. }
  4877. void ASTRecordWriter::AddDeclarationNameInfo(
  4878. const DeclarationNameInfo &NameInfo) {
  4879. AddDeclarationName(NameInfo.getName());
  4880. AddSourceLocation(NameInfo.getLoc());
  4881. AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
  4882. }
  4883. void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
  4884. AddNestedNameSpecifierLoc(Info.QualifierLoc);
  4885. Record->push_back(Info.NumTemplParamLists);
  4886. for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
  4887. AddTemplateParameterList(Info.TemplParamLists[i]);
  4888. }
  4889. void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
  4890. // Nested name specifiers usually aren't too long. I think that 8 would
  4891. // typically accommodate the vast majority.
  4892. SmallVector<NestedNameSpecifier *, 8> NestedNames;
  4893. // Push each of the NNS's onto a stack for serialization in reverse order.
  4894. while (NNS) {
  4895. NestedNames.push_back(NNS);
  4896. NNS = NNS->getPrefix();
  4897. }
  4898. Record->push_back(NestedNames.size());
  4899. while(!NestedNames.empty()) {
  4900. NNS = NestedNames.pop_back_val();
  4901. NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
  4902. Record->push_back(Kind);
  4903. switch (Kind) {
  4904. case NestedNameSpecifier::Identifier:
  4905. AddIdentifierRef(NNS->getAsIdentifier());
  4906. break;
  4907. case NestedNameSpecifier::Namespace:
  4908. AddDeclRef(NNS->getAsNamespace());
  4909. break;
  4910. case NestedNameSpecifier::NamespaceAlias:
  4911. AddDeclRef(NNS->getAsNamespaceAlias());
  4912. break;
  4913. case NestedNameSpecifier::TypeSpec:
  4914. case NestedNameSpecifier::TypeSpecWithTemplate:
  4915. AddTypeRef(QualType(NNS->getAsType(), 0));
  4916. Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  4917. break;
  4918. case NestedNameSpecifier::Global:
  4919. // Don't need to write an associated value.
  4920. break;
  4921. case NestedNameSpecifier::Super:
  4922. AddDeclRef(NNS->getAsRecordDecl());
  4923. break;
  4924. }
  4925. }
  4926. }
  4927. void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
  4928. // Nested name specifiers usually aren't too long. I think that 8 would
  4929. // typically accommodate the vast majority.
  4930. SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
  4931. // Push each of the nested-name-specifiers's onto a stack for
  4932. // serialization in reverse order.
  4933. while (NNS) {
  4934. NestedNames.push_back(NNS);
  4935. NNS = NNS.getPrefix();
  4936. }
  4937. Record->push_back(NestedNames.size());
  4938. while(!NestedNames.empty()) {
  4939. NNS = NestedNames.pop_back_val();
  4940. NestedNameSpecifier::SpecifierKind Kind
  4941. = NNS.getNestedNameSpecifier()->getKind();
  4942. Record->push_back(Kind);
  4943. switch (Kind) {
  4944. case NestedNameSpecifier::Identifier:
  4945. AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
  4946. AddSourceRange(NNS.getLocalSourceRange());
  4947. break;
  4948. case NestedNameSpecifier::Namespace:
  4949. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
  4950. AddSourceRange(NNS.getLocalSourceRange());
  4951. break;
  4952. case NestedNameSpecifier::NamespaceAlias:
  4953. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
  4954. AddSourceRange(NNS.getLocalSourceRange());
  4955. break;
  4956. case NestedNameSpecifier::TypeSpec:
  4957. case NestedNameSpecifier::TypeSpecWithTemplate:
  4958. Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  4959. AddTypeRef(NNS.getTypeLoc().getType());
  4960. AddTypeLoc(NNS.getTypeLoc());
  4961. AddSourceLocation(NNS.getLocalSourceRange().getEnd());
  4962. break;
  4963. case NestedNameSpecifier::Global:
  4964. AddSourceLocation(NNS.getLocalSourceRange().getEnd());
  4965. break;
  4966. case NestedNameSpecifier::Super:
  4967. AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
  4968. AddSourceRange(NNS.getLocalSourceRange());
  4969. break;
  4970. }
  4971. }
  4972. }
  4973. void ASTRecordWriter::AddTemplateName(TemplateName Name) {
  4974. TemplateName::NameKind Kind = Name.getKind();
  4975. Record->push_back(Kind);
  4976. switch (Kind) {
  4977. case TemplateName::Template:
  4978. AddDeclRef(Name.getAsTemplateDecl());
  4979. break;
  4980. case TemplateName::OverloadedTemplate: {
  4981. OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
  4982. Record->push_back(OvT->size());
  4983. for (const auto &I : *OvT)
  4984. AddDeclRef(I);
  4985. break;
  4986. }
  4987. case TemplateName::QualifiedTemplate: {
  4988. QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
  4989. AddNestedNameSpecifier(QualT->getQualifier());
  4990. Record->push_back(QualT->hasTemplateKeyword());
  4991. AddDeclRef(QualT->getTemplateDecl());
  4992. break;
  4993. }
  4994. case TemplateName::DependentTemplate: {
  4995. DependentTemplateName *DepT = Name.getAsDependentTemplateName();
  4996. AddNestedNameSpecifier(DepT->getQualifier());
  4997. Record->push_back(DepT->isIdentifier());
  4998. if (DepT->isIdentifier())
  4999. AddIdentifierRef(DepT->getIdentifier());
  5000. else
  5001. Record->push_back(DepT->getOperator());
  5002. break;
  5003. }
  5004. case TemplateName::SubstTemplateTemplateParm: {
  5005. SubstTemplateTemplateParmStorage *subst
  5006. = Name.getAsSubstTemplateTemplateParm();
  5007. AddDeclRef(subst->getParameter());
  5008. AddTemplateName(subst->getReplacement());
  5009. break;
  5010. }
  5011. case TemplateName::SubstTemplateTemplateParmPack: {
  5012. SubstTemplateTemplateParmPackStorage *SubstPack
  5013. = Name.getAsSubstTemplateTemplateParmPack();
  5014. AddDeclRef(SubstPack->getParameterPack());
  5015. AddTemplateArgument(SubstPack->getArgumentPack());
  5016. break;
  5017. }
  5018. }
  5019. }
  5020. void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
  5021. Record->push_back(Arg.getKind());
  5022. switch (Arg.getKind()) {
  5023. case TemplateArgument::Null:
  5024. break;
  5025. case TemplateArgument::Type:
  5026. AddTypeRef(Arg.getAsType());
  5027. break;
  5028. case TemplateArgument::Declaration:
  5029. AddDeclRef(Arg.getAsDecl());
  5030. AddTypeRef(Arg.getParamTypeForDecl());
  5031. break;
  5032. case TemplateArgument::NullPtr:
  5033. AddTypeRef(Arg.getNullPtrType());
  5034. break;
  5035. case TemplateArgument::Integral:
  5036. AddAPSInt(Arg.getAsIntegral());
  5037. AddTypeRef(Arg.getIntegralType());
  5038. break;
  5039. case TemplateArgument::Template:
  5040. AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
  5041. break;
  5042. case TemplateArgument::TemplateExpansion:
  5043. AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
  5044. if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
  5045. Record->push_back(*NumExpansions + 1);
  5046. else
  5047. Record->push_back(0);
  5048. break;
  5049. case TemplateArgument::Expression:
  5050. AddStmt(Arg.getAsExpr());
  5051. break;
  5052. case TemplateArgument::Pack:
  5053. Record->push_back(Arg.pack_size());
  5054. for (const auto &P : Arg.pack_elements())
  5055. AddTemplateArgument(P);
  5056. break;
  5057. }
  5058. }
  5059. void ASTRecordWriter::AddTemplateParameterList(
  5060. const TemplateParameterList *TemplateParams) {
  5061. assert(TemplateParams && "No TemplateParams!");
  5062. AddSourceLocation(TemplateParams->getTemplateLoc());
  5063. AddSourceLocation(TemplateParams->getLAngleLoc());
  5064. AddSourceLocation(TemplateParams->getRAngleLoc());
  5065. // TODO: Concepts
  5066. Record->push_back(TemplateParams->size());
  5067. for (const auto &P : *TemplateParams)
  5068. AddDeclRef(P);
  5069. }
  5070. /// Emit a template argument list.
  5071. void ASTRecordWriter::AddTemplateArgumentList(
  5072. const TemplateArgumentList *TemplateArgs) {
  5073. assert(TemplateArgs && "No TemplateArgs!");
  5074. Record->push_back(TemplateArgs->size());
  5075. for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
  5076. AddTemplateArgument(TemplateArgs->get(i));
  5077. }
  5078. void ASTRecordWriter::AddASTTemplateArgumentListInfo(
  5079. const ASTTemplateArgumentListInfo *ASTTemplArgList) {
  5080. assert(ASTTemplArgList && "No ASTTemplArgList!");
  5081. AddSourceLocation(ASTTemplArgList->LAngleLoc);
  5082. AddSourceLocation(ASTTemplArgList->RAngleLoc);
  5083. Record->push_back(ASTTemplArgList->NumTemplateArgs);
  5084. const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
  5085. for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
  5086. AddTemplateArgumentLoc(TemplArgs[i]);
  5087. }
  5088. void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
  5089. Record->push_back(Set.size());
  5090. for (ASTUnresolvedSet::const_iterator
  5091. I = Set.begin(), E = Set.end(); I != E; ++I) {
  5092. AddDeclRef(I.getDecl());
  5093. Record->push_back(I.getAccess());
  5094. }
  5095. }
  5096. // FIXME: Move this out of the main ASTRecordWriter interface.
  5097. void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
  5098. Record->push_back(Base.isVirtual());
  5099. Record->push_back(Base.isBaseOfClass());
  5100. Record->push_back(Base.getAccessSpecifierAsWritten());
  5101. Record->push_back(Base.getInheritConstructors());
  5102. AddTypeSourceInfo(Base.getTypeSourceInfo());
  5103. AddSourceRange(Base.getSourceRange());
  5104. AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
  5105. : SourceLocation());
  5106. }
  5107. static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
  5108. ArrayRef<CXXBaseSpecifier> Bases) {
  5109. ASTWriter::RecordData Record;
  5110. ASTRecordWriter Writer(W, Record);
  5111. Writer.push_back(Bases.size());
  5112. for (auto &Base : Bases)
  5113. Writer.AddCXXBaseSpecifier(Base);
  5114. return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
  5115. }
  5116. // FIXME: Move this out of the main ASTRecordWriter interface.
  5117. void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
  5118. AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
  5119. }
  5120. static uint64_t
  5121. EmitCXXCtorInitializers(ASTWriter &W,
  5122. ArrayRef<CXXCtorInitializer *> CtorInits) {
  5123. ASTWriter::RecordData Record;
  5124. ASTRecordWriter Writer(W, Record);
  5125. Writer.push_back(CtorInits.size());
  5126. for (auto *Init : CtorInits) {
  5127. if (Init->isBaseInitializer()) {
  5128. Writer.push_back(CTOR_INITIALIZER_BASE);
  5129. Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
  5130. Writer.push_back(Init->isBaseVirtual());
  5131. } else if (Init->isDelegatingInitializer()) {
  5132. Writer.push_back(CTOR_INITIALIZER_DELEGATING);
  5133. Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
  5134. } else if (Init->isMemberInitializer()){
  5135. Writer.push_back(CTOR_INITIALIZER_MEMBER);
  5136. Writer.AddDeclRef(Init->getMember());
  5137. } else {
  5138. Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
  5139. Writer.AddDeclRef(Init->getIndirectMember());
  5140. }
  5141. Writer.AddSourceLocation(Init->getMemberLocation());
  5142. Writer.AddStmt(Init->getInit());
  5143. Writer.AddSourceLocation(Init->getLParenLoc());
  5144. Writer.AddSourceLocation(Init->getRParenLoc());
  5145. Writer.push_back(Init->isWritten());
  5146. if (Init->isWritten())
  5147. Writer.push_back(Init->getSourceOrder());
  5148. }
  5149. return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
  5150. }
  5151. // FIXME: Move this out of the main ASTRecordWriter interface.
  5152. void ASTRecordWriter::AddCXXCtorInitializers(
  5153. ArrayRef<CXXCtorInitializer *> CtorInits) {
  5154. AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
  5155. }
  5156. void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
  5157. auto &Data = D->data();
  5158. Record->push_back(Data.IsLambda);
  5159. Record->push_back(Data.UserDeclaredConstructor);
  5160. Record->push_back(Data.UserDeclaredSpecialMembers);
  5161. Record->push_back(Data.Aggregate);
  5162. Record->push_back(Data.PlainOldData);
  5163. Record->push_back(Data.Empty);
  5164. Record->push_back(Data.Polymorphic);
  5165. Record->push_back(Data.Abstract);
  5166. Record->push_back(Data.IsStandardLayout);
  5167. Record->push_back(Data.IsCXX11StandardLayout);
  5168. Record->push_back(Data.HasBasesWithFields);
  5169. Record->push_back(Data.HasBasesWithNonStaticDataMembers);
  5170. Record->push_back(Data.HasPrivateFields);
  5171. Record->push_back(Data.HasProtectedFields);
  5172. Record->push_back(Data.HasPublicFields);
  5173. Record->push_back(Data.HasMutableFields);
  5174. Record->push_back(Data.HasVariantMembers);
  5175. Record->push_back(Data.HasOnlyCMembers);
  5176. Record->push_back(Data.HasInClassInitializer);
  5177. Record->push_back(Data.HasUninitializedReferenceMember);
  5178. Record->push_back(Data.HasUninitializedFields);
  5179. Record->push_back(Data.HasInheritedConstructor);
  5180. Record->push_back(Data.HasInheritedAssignment);
  5181. Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
  5182. Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
  5183. Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
  5184. Record->push_back(Data.NeedOverloadResolutionForDestructor);
  5185. Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
  5186. Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
  5187. Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
  5188. Record->push_back(Data.DefaultedDestructorIsDeleted);
  5189. Record->push_back(Data.HasTrivialSpecialMembers);
  5190. Record->push_back(Data.HasTrivialSpecialMembersForCall);
  5191. Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
  5192. Record->push_back(Data.DeclaredNonTrivialSpecialMembersForCall);
  5193. Record->push_back(Data.HasIrrelevantDestructor);
  5194. Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
  5195. Record->push_back(Data.HasDefaultedDefaultConstructor);
  5196. Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
  5197. Record->push_back(Data.HasConstexprDefaultConstructor);
  5198. Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
  5199. Record->push_back(Data.ComputedVisibleConversions);
  5200. Record->push_back(Data.UserProvidedDefaultConstructor);
  5201. Record->push_back(Data.DeclaredSpecialMembers);
  5202. Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
  5203. Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
  5204. Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
  5205. Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
  5206. Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
  5207. // getODRHash will compute the ODRHash if it has not been previously computed.
  5208. Record->push_back(D->getODRHash());
  5209. bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
  5210. Writer->WritingModule && !D->isDependentType();
  5211. Record->push_back(ModulesDebugInfo);
  5212. if (ModulesDebugInfo)
  5213. Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
  5214. // IsLambda bit is already saved.
  5215. Record->push_back(Data.NumBases);
  5216. if (Data.NumBases > 0)
  5217. AddCXXBaseSpecifiers(Data.bases());
  5218. // FIXME: Make VBases lazily computed when needed to avoid storing them.
  5219. Record->push_back(Data.NumVBases);
  5220. if (Data.NumVBases > 0)
  5221. AddCXXBaseSpecifiers(Data.vbases());
  5222. AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
  5223. AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
  5224. // Data.Definition is the owning decl, no need to write it.
  5225. AddDeclRef(D->getFirstFriend());
  5226. // Add lambda-specific data.
  5227. if (Data.IsLambda) {
  5228. auto &Lambda = D->getLambdaData();
  5229. Record->push_back(Lambda.Dependent);
  5230. Record->push_back(Lambda.IsGenericLambda);
  5231. Record->push_back(Lambda.CaptureDefault);
  5232. Record->push_back(Lambda.NumCaptures);
  5233. Record->push_back(Lambda.NumExplicitCaptures);
  5234. Record->push_back(Lambda.ManglingNumber);
  5235. AddDeclRef(D->getLambdaContextDecl());
  5236. AddTypeSourceInfo(Lambda.MethodTyInfo);
  5237. for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
  5238. const LambdaCapture &Capture = Lambda.Captures[I];
  5239. AddSourceLocation(Capture.getLocation());
  5240. Record->push_back(Capture.isImplicit());
  5241. Record->push_back(Capture.getCaptureKind());
  5242. switch (Capture.getCaptureKind()) {
  5243. case LCK_StarThis:
  5244. case LCK_This:
  5245. case LCK_VLAType:
  5246. break;
  5247. case LCK_ByCopy:
  5248. case LCK_ByRef:
  5249. VarDecl *Var =
  5250. Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
  5251. AddDeclRef(Var);
  5252. AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
  5253. : SourceLocation());
  5254. break;
  5255. }
  5256. }
  5257. }
  5258. }
  5259. void ASTWriter::ReaderInitialized(ASTReader *Reader) {
  5260. assert(Reader && "Cannot remove chain");
  5261. assert((!Chain || Chain == Reader) && "Cannot replace chain");
  5262. assert(FirstDeclID == NextDeclID &&
  5263. FirstTypeID == NextTypeID &&
  5264. FirstIdentID == NextIdentID &&
  5265. FirstMacroID == NextMacroID &&
  5266. FirstSubmoduleID == NextSubmoduleID &&
  5267. FirstSelectorID == NextSelectorID &&
  5268. "Setting chain after writing has started.");
  5269. Chain = Reader;
  5270. // Note, this will get called multiple times, once one the reader starts up
  5271. // and again each time it's done reading a PCH or module.
  5272. FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
  5273. FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
  5274. FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
  5275. FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
  5276. FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
  5277. FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
  5278. NextDeclID = FirstDeclID;
  5279. NextTypeID = FirstTypeID;
  5280. NextIdentID = FirstIdentID;
  5281. NextMacroID = FirstMacroID;
  5282. NextSelectorID = FirstSelectorID;
  5283. NextSubmoduleID = FirstSubmoduleID;
  5284. }
  5285. void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
  5286. // Always keep the highest ID. See \p TypeRead() for more information.
  5287. IdentID &StoredID = IdentifierIDs[II];
  5288. if (ID > StoredID)
  5289. StoredID = ID;
  5290. }
  5291. void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
  5292. // Always keep the highest ID. See \p TypeRead() for more information.
  5293. MacroID &StoredID = MacroIDs[MI];
  5294. if (ID > StoredID)
  5295. StoredID = ID;
  5296. }
  5297. void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
  5298. // Always take the highest-numbered type index. This copes with an interesting
  5299. // case for chained AST writing where we schedule writing the type and then,
  5300. // later, deserialize the type from another AST. In this case, we want to
  5301. // keep the higher-numbered entry so that we can properly write it out to
  5302. // the AST file.
  5303. TypeIdx &StoredIdx = TypeIdxs[T];
  5304. if (Idx.getIndex() >= StoredIdx.getIndex())
  5305. StoredIdx = Idx;
  5306. }
  5307. void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
  5308. // Always keep the highest ID. See \p TypeRead() for more information.
  5309. SelectorID &StoredID = SelectorIDs[S];
  5310. if (ID > StoredID)
  5311. StoredID = ID;
  5312. }
  5313. void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
  5314. MacroDefinitionRecord *MD) {
  5315. assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
  5316. MacroDefinitions[MD] = ID;
  5317. }
  5318. void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
  5319. assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
  5320. SubmoduleIDs[Mod] = ID;
  5321. }
  5322. void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
  5323. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5324. assert(D->isCompleteDefinition());
  5325. assert(!WritingAST && "Already writing the AST!");
  5326. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  5327. // We are interested when a PCH decl is modified.
  5328. if (RD->isFromASTFile()) {
  5329. // A forward reference was mutated into a definition. Rewrite it.
  5330. // FIXME: This happens during template instantiation, should we
  5331. // have created a new definition decl instead ?
  5332. assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
  5333. "completed a tag from another module but not by instantiation?");
  5334. DeclUpdates[RD].push_back(
  5335. DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
  5336. }
  5337. }
  5338. }
  5339. static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
  5340. if (D->isFromASTFile())
  5341. return true;
  5342. // The predefined __va_list_tag struct is imported if we imported any decls.
  5343. // FIXME: This is a gross hack.
  5344. return D == D->getASTContext().getVaListTagDecl();
  5345. }
  5346. void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
  5347. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5348. assert(DC->isLookupContext() &&
  5349. "Should not add lookup results to non-lookup contexts!");
  5350. // TU is handled elsewhere.
  5351. if (isa<TranslationUnitDecl>(DC))
  5352. return;
  5353. // Namespaces are handled elsewhere, except for template instantiations of
  5354. // FunctionTemplateDecls in namespaces. We are interested in cases where the
  5355. // local instantiations are added to an imported context. Only happens when
  5356. // adding ADL lookup candidates, for example templated friends.
  5357. if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
  5358. !isa<FunctionTemplateDecl>(D))
  5359. return;
  5360. // We're only interested in cases where a local declaration is added to an
  5361. // imported context.
  5362. if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
  5363. return;
  5364. assert(DC == DC->getPrimaryContext() && "added to non-primary context");
  5365. assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
  5366. assert(!WritingAST && "Already writing the AST!");
  5367. if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
  5368. // We're adding a visible declaration to a predefined decl context. Ensure
  5369. // that we write out all of its lookup results so we don't get a nasty
  5370. // surprise when we try to emit its lookup table.
  5371. for (auto *Child : DC->decls())
  5372. DeclsToEmitEvenIfUnreferenced.push_back(Child);
  5373. }
  5374. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5375. }
  5376. void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
  5377. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5378. assert(D->isImplicit());
  5379. // We're only interested in cases where a local declaration is added to an
  5380. // imported context.
  5381. if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
  5382. return;
  5383. if (!isa<CXXMethodDecl>(D))
  5384. return;
  5385. // A decl coming from PCH was modified.
  5386. assert(RD->isCompleteDefinition());
  5387. assert(!WritingAST && "Already writing the AST!");
  5388. DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
  5389. }
  5390. void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
  5391. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5392. assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
  5393. if (!Chain) return;
  5394. Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
  5395. // If we don't already know the exception specification for this redecl
  5396. // chain, add an update record for it.
  5397. if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
  5398. ->getType()
  5399. ->castAs<FunctionProtoType>()
  5400. ->getExceptionSpecType()))
  5401. DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
  5402. });
  5403. }
  5404. void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
  5405. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5406. assert(!WritingAST && "Already writing the AST!");
  5407. if (!Chain) return;
  5408. Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
  5409. DeclUpdates[D].push_back(
  5410. DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
  5411. });
  5412. }
  5413. void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
  5414. const FunctionDecl *Delete,
  5415. Expr *ThisArg) {
  5416. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5417. assert(!WritingAST && "Already writing the AST!");
  5418. assert(Delete && "Not given an operator delete");
  5419. if (!Chain) return;
  5420. Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
  5421. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
  5422. });
  5423. }
  5424. void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
  5425. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5426. assert(!WritingAST && "Already writing the AST!");
  5427. if (!D->isFromASTFile())
  5428. return; // Declaration not imported from PCH.
  5429. // Implicit function decl from a PCH was defined.
  5430. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
  5431. }
  5432. void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
  5433. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5434. assert(!WritingAST && "Already writing the AST!");
  5435. if (!D->isFromASTFile())
  5436. return;
  5437. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
  5438. }
  5439. void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
  5440. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5441. assert(!WritingAST && "Already writing the AST!");
  5442. if (!D->isFromASTFile())
  5443. return;
  5444. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
  5445. }
  5446. void ASTWriter::InstantiationRequested(const ValueDecl *D) {
  5447. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5448. assert(!WritingAST && "Already writing the AST!");
  5449. if (!D->isFromASTFile())
  5450. return;
  5451. // Since the actual instantiation is delayed, this really means that we need
  5452. // to update the instantiation location.
  5453. SourceLocation POI;
  5454. if (auto *VD = dyn_cast<VarDecl>(D))
  5455. POI = VD->getPointOfInstantiation();
  5456. else
  5457. POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
  5458. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
  5459. }
  5460. void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
  5461. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5462. assert(!WritingAST && "Already writing the AST!");
  5463. if (!D->isFromASTFile())
  5464. return;
  5465. DeclUpdates[D].push_back(
  5466. DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
  5467. }
  5468. void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
  5469. assert(!WritingAST && "Already writing the AST!");
  5470. if (!D->isFromASTFile())
  5471. return;
  5472. DeclUpdates[D].push_back(
  5473. DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
  5474. }
  5475. void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
  5476. const ObjCInterfaceDecl *IFD) {
  5477. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5478. assert(!WritingAST && "Already writing the AST!");
  5479. if (!IFD->isFromASTFile())
  5480. return; // Declaration not imported from PCH.
  5481. assert(IFD->getDefinition() && "Category on a class without a definition?");
  5482. ObjCClassesWithCategories.insert(
  5483. const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
  5484. }
  5485. void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
  5486. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5487. assert(!WritingAST && "Already writing the AST!");
  5488. // If there is *any* declaration of the entity that's not from an AST file,
  5489. // we can skip writing the update record. We make sure that isUsed() triggers
  5490. // completion of the redeclaration chain of the entity.
  5491. for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
  5492. if (IsLocalDecl(Prev))
  5493. return;
  5494. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
  5495. }
  5496. void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
  5497. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5498. assert(!WritingAST && "Already writing the AST!");
  5499. if (!D->isFromASTFile())
  5500. return;
  5501. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
  5502. }
  5503. void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
  5504. const Attr *Attr) {
  5505. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5506. assert(!WritingAST && "Already writing the AST!");
  5507. if (!D->isFromASTFile())
  5508. return;
  5509. DeclUpdates[D].push_back(
  5510. DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
  5511. }
  5512. void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
  5513. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5514. assert(!WritingAST && "Already writing the AST!");
  5515. assert(D->isHidden() && "expected a hidden declaration");
  5516. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
  5517. }
  5518. void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
  5519. const RecordDecl *Record) {
  5520. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5521. assert(!WritingAST && "Already writing the AST!");
  5522. if (!Record->isFromASTFile())
  5523. return;
  5524. DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
  5525. }
  5526. void ASTWriter::AddedCXXTemplateSpecialization(
  5527. const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
  5528. assert(!WritingAST && "Already writing the AST!");
  5529. if (!TD->getFirstDecl()->isFromASTFile())
  5530. return;
  5531. if (Chain && Chain->isProcessingUpdateRecords())
  5532. return;
  5533. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5534. }
  5535. void ASTWriter::AddedCXXTemplateSpecialization(
  5536. const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
  5537. assert(!WritingAST && "Already writing the AST!");
  5538. if (!TD->getFirstDecl()->isFromASTFile())
  5539. return;
  5540. if (Chain && Chain->isProcessingUpdateRecords())
  5541. return;
  5542. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5543. }
  5544. void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
  5545. const FunctionDecl *D) {
  5546. assert(!WritingAST && "Already writing the AST!");
  5547. if (!TD->getFirstDecl()->isFromASTFile())
  5548. return;
  5549. if (Chain && Chain->isProcessingUpdateRecords())
  5550. return;
  5551. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5552. }
  5553. //===----------------------------------------------------------------------===//
  5554. //// OMPClause Serialization
  5555. ////===----------------------------------------------------------------------===//
  5556. void OMPClauseWriter::writeClause(OMPClause *C) {
  5557. Record.push_back(C->getClauseKind());
  5558. Visit(C);
  5559. Record.AddSourceLocation(C->getBeginLoc());
  5560. Record.AddSourceLocation(C->getEndLoc());
  5561. }
  5562. void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
  5563. Record.push_back(C->getCaptureRegion());
  5564. Record.AddStmt(C->getPreInitStmt());
  5565. }
  5566. void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
  5567. VisitOMPClauseWithPreInit(C);
  5568. Record.AddStmt(C->getPostUpdateExpr());
  5569. }
  5570. void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
  5571. VisitOMPClauseWithPreInit(C);
  5572. Record.push_back(C->getNameModifier());
  5573. Record.AddSourceLocation(C->getNameModifierLoc());
  5574. Record.AddSourceLocation(C->getColonLoc());
  5575. Record.AddStmt(C->getCondition());
  5576. Record.AddSourceLocation(C->getLParenLoc());
  5577. }
  5578. void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
  5579. Record.AddStmt(C->getCondition());
  5580. Record.AddSourceLocation(C->getLParenLoc());
  5581. }
  5582. void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
  5583. VisitOMPClauseWithPreInit(C);
  5584. Record.AddStmt(C->getNumThreads());
  5585. Record.AddSourceLocation(C->getLParenLoc());
  5586. }
  5587. void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
  5588. Record.AddStmt(C->getSafelen());
  5589. Record.AddSourceLocation(C->getLParenLoc());
  5590. }
  5591. void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
  5592. Record.AddStmt(C->getSimdlen());
  5593. Record.AddSourceLocation(C->getLParenLoc());
  5594. }
  5595. void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
  5596. Record.AddStmt(C->getNumForLoops());
  5597. Record.AddSourceLocation(C->getLParenLoc());
  5598. }
  5599. void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
  5600. Record.push_back(C->getDefaultKind());
  5601. Record.AddSourceLocation(C->getLParenLoc());
  5602. Record.AddSourceLocation(C->getDefaultKindKwLoc());
  5603. }
  5604. void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
  5605. Record.push_back(C->getProcBindKind());
  5606. Record.AddSourceLocation(C->getLParenLoc());
  5607. Record.AddSourceLocation(C->getProcBindKindKwLoc());
  5608. }
  5609. void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
  5610. VisitOMPClauseWithPreInit(C);
  5611. Record.push_back(C->getScheduleKind());
  5612. Record.push_back(C->getFirstScheduleModifier());
  5613. Record.push_back(C->getSecondScheduleModifier());
  5614. Record.AddStmt(C->getChunkSize());
  5615. Record.AddSourceLocation(C->getLParenLoc());
  5616. Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
  5617. Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
  5618. Record.AddSourceLocation(C->getScheduleKindLoc());
  5619. Record.AddSourceLocation(C->getCommaLoc());
  5620. }
  5621. void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
  5622. Record.push_back(C->getLoopNumIterations().size());
  5623. Record.AddStmt(C->getNumForLoops());
  5624. for (Expr *NumIter : C->getLoopNumIterations())
  5625. Record.AddStmt(NumIter);
  5626. for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
  5627. Record.AddStmt(C->getLoopCounter(I));
  5628. Record.AddSourceLocation(C->getLParenLoc());
  5629. }
  5630. void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
  5631. void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
  5632. void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
  5633. void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
  5634. void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
  5635. void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
  5636. void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
  5637. void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
  5638. void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
  5639. void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
  5640. void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
  5641. void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
  5642. Record.push_back(C->varlist_size());
  5643. Record.AddSourceLocation(C->getLParenLoc());
  5644. for (auto *VE : C->varlists()) {
  5645. Record.AddStmt(VE);
  5646. }
  5647. for (auto *VE : C->private_copies()) {
  5648. Record.AddStmt(VE);
  5649. }
  5650. }
  5651. void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
  5652. Record.push_back(C->varlist_size());
  5653. VisitOMPClauseWithPreInit(C);
  5654. Record.AddSourceLocation(C->getLParenLoc());
  5655. for (auto *VE : C->varlists()) {
  5656. Record.AddStmt(VE);
  5657. }
  5658. for (auto *VE : C->private_copies()) {
  5659. Record.AddStmt(VE);
  5660. }
  5661. for (auto *VE : C->inits()) {
  5662. Record.AddStmt(VE);
  5663. }
  5664. }
  5665. void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
  5666. Record.push_back(C->varlist_size());
  5667. VisitOMPClauseWithPostUpdate(C);
  5668. Record.AddSourceLocation(C->getLParenLoc());
  5669. for (auto *VE : C->varlists())
  5670. Record.AddStmt(VE);
  5671. for (auto *E : C->private_copies())
  5672. Record.AddStmt(E);
  5673. for (auto *E : C->source_exprs())
  5674. Record.AddStmt(E);
  5675. for (auto *E : C->destination_exprs())
  5676. Record.AddStmt(E);
  5677. for (auto *E : C->assignment_ops())
  5678. Record.AddStmt(E);
  5679. }
  5680. void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
  5681. Record.push_back(C->varlist_size());
  5682. Record.AddSourceLocation(C->getLParenLoc());
  5683. for (auto *VE : C->varlists())
  5684. Record.AddStmt(VE);
  5685. }
  5686. void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
  5687. Record.push_back(C->varlist_size());
  5688. VisitOMPClauseWithPostUpdate(C);
  5689. Record.AddSourceLocation(C->getLParenLoc());
  5690. Record.AddSourceLocation(C->getColonLoc());
  5691. Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
  5692. Record.AddDeclarationNameInfo(C->getNameInfo());
  5693. for (auto *VE : C->varlists())
  5694. Record.AddStmt(VE);
  5695. for (auto *VE : C->privates())
  5696. Record.AddStmt(VE);
  5697. for (auto *E : C->lhs_exprs())
  5698. Record.AddStmt(E);
  5699. for (auto *E : C->rhs_exprs())
  5700. Record.AddStmt(E);
  5701. for (auto *E : C->reduction_ops())
  5702. Record.AddStmt(E);
  5703. }
  5704. void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
  5705. Record.push_back(C->varlist_size());
  5706. VisitOMPClauseWithPostUpdate(C);
  5707. Record.AddSourceLocation(C->getLParenLoc());
  5708. Record.AddSourceLocation(C->getColonLoc());
  5709. Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
  5710. Record.AddDeclarationNameInfo(C->getNameInfo());
  5711. for (auto *VE : C->varlists())
  5712. Record.AddStmt(VE);
  5713. for (auto *VE : C->privates())
  5714. Record.AddStmt(VE);
  5715. for (auto *E : C->lhs_exprs())
  5716. Record.AddStmt(E);
  5717. for (auto *E : C->rhs_exprs())
  5718. Record.AddStmt(E);
  5719. for (auto *E : C->reduction_ops())
  5720. Record.AddStmt(E);
  5721. }
  5722. void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
  5723. Record.push_back(C->varlist_size());
  5724. VisitOMPClauseWithPostUpdate(C);
  5725. Record.AddSourceLocation(C->getLParenLoc());
  5726. Record.AddSourceLocation(C->getColonLoc());
  5727. Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
  5728. Record.AddDeclarationNameInfo(C->getNameInfo());
  5729. for (auto *VE : C->varlists())
  5730. Record.AddStmt(VE);
  5731. for (auto *VE : C->privates())
  5732. Record.AddStmt(VE);
  5733. for (auto *E : C->lhs_exprs())
  5734. Record.AddStmt(E);
  5735. for (auto *E : C->rhs_exprs())
  5736. Record.AddStmt(E);
  5737. for (auto *E : C->reduction_ops())
  5738. Record.AddStmt(E);
  5739. for (auto *E : C->taskgroup_descriptors())
  5740. Record.AddStmt(E);
  5741. }
  5742. void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
  5743. Record.push_back(C->varlist_size());
  5744. VisitOMPClauseWithPostUpdate(C);
  5745. Record.AddSourceLocation(C->getLParenLoc());
  5746. Record.AddSourceLocation(C->getColonLoc());
  5747. Record.push_back(C->getModifier());
  5748. Record.AddSourceLocation(C->getModifierLoc());
  5749. for (auto *VE : C->varlists()) {
  5750. Record.AddStmt(VE);
  5751. }
  5752. for (auto *VE : C->privates()) {
  5753. Record.AddStmt(VE);
  5754. }
  5755. for (auto *VE : C->inits()) {
  5756. Record.AddStmt(VE);
  5757. }
  5758. for (auto *VE : C->updates()) {
  5759. Record.AddStmt(VE);
  5760. }
  5761. for (auto *VE : C->finals()) {
  5762. Record.AddStmt(VE);
  5763. }
  5764. Record.AddStmt(C->getStep());
  5765. Record.AddStmt(C->getCalcStep());
  5766. }
  5767. void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
  5768. Record.push_back(C->varlist_size());
  5769. Record.AddSourceLocation(C->getLParenLoc());
  5770. Record.AddSourceLocation(C->getColonLoc());
  5771. for (auto *VE : C->varlists())
  5772. Record.AddStmt(VE);
  5773. Record.AddStmt(C->getAlignment());
  5774. }
  5775. void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
  5776. Record.push_back(C->varlist_size());
  5777. Record.AddSourceLocation(C->getLParenLoc());
  5778. for (auto *VE : C->varlists())
  5779. Record.AddStmt(VE);
  5780. for (auto *E : C->source_exprs())
  5781. Record.AddStmt(E);
  5782. for (auto *E : C->destination_exprs())
  5783. Record.AddStmt(E);
  5784. for (auto *E : C->assignment_ops())
  5785. Record.AddStmt(E);
  5786. }
  5787. void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
  5788. Record.push_back(C->varlist_size());
  5789. Record.AddSourceLocation(C->getLParenLoc());
  5790. for (auto *VE : C->varlists())
  5791. Record.AddStmt(VE);
  5792. for (auto *E : C->source_exprs())
  5793. Record.AddStmt(E);
  5794. for (auto *E : C->destination_exprs())
  5795. Record.AddStmt(E);
  5796. for (auto *E : C->assignment_ops())
  5797. Record.AddStmt(E);
  5798. }
  5799. void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
  5800. Record.push_back(C->varlist_size());
  5801. Record.AddSourceLocation(C->getLParenLoc());
  5802. for (auto *VE : C->varlists())
  5803. Record.AddStmt(VE);
  5804. }
  5805. void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
  5806. Record.push_back(C->varlist_size());
  5807. Record.push_back(C->getNumLoops());
  5808. Record.AddSourceLocation(C->getLParenLoc());
  5809. Record.push_back(C->getDependencyKind());
  5810. Record.AddSourceLocation(C->getDependencyLoc());
  5811. Record.AddSourceLocation(C->getColonLoc());
  5812. for (auto *VE : C->varlists())
  5813. Record.AddStmt(VE);
  5814. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
  5815. Record.AddStmt(C->getLoopData(I));
  5816. }
  5817. void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
  5818. VisitOMPClauseWithPreInit(C);
  5819. Record.AddStmt(C->getDevice());
  5820. Record.AddSourceLocation(C->getLParenLoc());
  5821. }
  5822. void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
  5823. Record.push_back(C->varlist_size());
  5824. Record.push_back(C->getUniqueDeclarationsNum());
  5825. Record.push_back(C->getTotalComponentListNum());
  5826. Record.push_back(C->getTotalComponentsNum());
  5827. Record.AddSourceLocation(C->getLParenLoc());
  5828. Record.push_back(C->getMapTypeModifier());
  5829. Record.push_back(C->getMapType());
  5830. Record.AddSourceLocation(C->getMapLoc());
  5831. Record.AddSourceLocation(C->getColonLoc());
  5832. for (auto *E : C->varlists())
  5833. Record.AddStmt(E);
  5834. for (auto *D : C->all_decls())
  5835. Record.AddDeclRef(D);
  5836. for (auto N : C->all_num_lists())
  5837. Record.push_back(N);
  5838. for (auto N : C->all_lists_sizes())
  5839. Record.push_back(N);
  5840. for (auto &M : C->all_components()) {
  5841. Record.AddStmt(M.getAssociatedExpression());
  5842. Record.AddDeclRef(M.getAssociatedDeclaration());
  5843. }
  5844. }
  5845. void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
  5846. VisitOMPClauseWithPreInit(C);
  5847. Record.AddStmt(C->getNumTeams());
  5848. Record.AddSourceLocation(C->getLParenLoc());
  5849. }
  5850. void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
  5851. VisitOMPClauseWithPreInit(C);
  5852. Record.AddStmt(C->getThreadLimit());
  5853. Record.AddSourceLocation(C->getLParenLoc());
  5854. }
  5855. void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
  5856. Record.AddStmt(C->getPriority());
  5857. Record.AddSourceLocation(C->getLParenLoc());
  5858. }
  5859. void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
  5860. Record.AddStmt(C->getGrainsize());
  5861. Record.AddSourceLocation(C->getLParenLoc());
  5862. }
  5863. void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
  5864. Record.AddStmt(C->getNumTasks());
  5865. Record.AddSourceLocation(C->getLParenLoc());
  5866. }
  5867. void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
  5868. Record.AddStmt(C->getHint());
  5869. Record.AddSourceLocation(C->getLParenLoc());
  5870. }
  5871. void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
  5872. VisitOMPClauseWithPreInit(C);
  5873. Record.push_back(C->getDistScheduleKind());
  5874. Record.AddStmt(C->getChunkSize());
  5875. Record.AddSourceLocation(C->getLParenLoc());
  5876. Record.AddSourceLocation(C->getDistScheduleKindLoc());
  5877. Record.AddSourceLocation(C->getCommaLoc());
  5878. }
  5879. void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
  5880. Record.push_back(C->getDefaultmapKind());
  5881. Record.push_back(C->getDefaultmapModifier());
  5882. Record.AddSourceLocation(C->getLParenLoc());
  5883. Record.AddSourceLocation(C->getDefaultmapModifierLoc());
  5884. Record.AddSourceLocation(C->getDefaultmapKindLoc());
  5885. }
  5886. void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
  5887. Record.push_back(C->varlist_size());
  5888. Record.push_back(C->getUniqueDeclarationsNum());
  5889. Record.push_back(C->getTotalComponentListNum());
  5890. Record.push_back(C->getTotalComponentsNum());
  5891. Record.AddSourceLocation(C->getLParenLoc());
  5892. for (auto *E : C->varlists())
  5893. Record.AddStmt(E);
  5894. for (auto *D : C->all_decls())
  5895. Record.AddDeclRef(D);
  5896. for (auto N : C->all_num_lists())
  5897. Record.push_back(N);
  5898. for (auto N : C->all_lists_sizes())
  5899. Record.push_back(N);
  5900. for (auto &M : C->all_components()) {
  5901. Record.AddStmt(M.getAssociatedExpression());
  5902. Record.AddDeclRef(M.getAssociatedDeclaration());
  5903. }
  5904. }
  5905. void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
  5906. Record.push_back(C->varlist_size());
  5907. Record.push_back(C->getUniqueDeclarationsNum());
  5908. Record.push_back(C->getTotalComponentListNum());
  5909. Record.push_back(C->getTotalComponentsNum());
  5910. Record.AddSourceLocation(C->getLParenLoc());
  5911. for (auto *E : C->varlists())
  5912. Record.AddStmt(E);
  5913. for (auto *D : C->all_decls())
  5914. Record.AddDeclRef(D);
  5915. for (auto N : C->all_num_lists())
  5916. Record.push_back(N);
  5917. for (auto N : C->all_lists_sizes())
  5918. Record.push_back(N);
  5919. for (auto &M : C->all_components()) {
  5920. Record.AddStmt(M.getAssociatedExpression());
  5921. Record.AddDeclRef(M.getAssociatedDeclaration());
  5922. }
  5923. }
  5924. void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
  5925. Record.push_back(C->varlist_size());
  5926. Record.push_back(C->getUniqueDeclarationsNum());
  5927. Record.push_back(C->getTotalComponentListNum());
  5928. Record.push_back(C->getTotalComponentsNum());
  5929. Record.AddSourceLocation(C->getLParenLoc());
  5930. for (auto *E : C->varlists())
  5931. Record.AddStmt(E);
  5932. for (auto *VE : C->private_copies())
  5933. Record.AddStmt(VE);
  5934. for (auto *VE : C->inits())
  5935. Record.AddStmt(VE);
  5936. for (auto *D : C->all_decls())
  5937. Record.AddDeclRef(D);
  5938. for (auto N : C->all_num_lists())
  5939. Record.push_back(N);
  5940. for (auto N : C->all_lists_sizes())
  5941. Record.push_back(N);
  5942. for (auto &M : C->all_components()) {
  5943. Record.AddStmt(M.getAssociatedExpression());
  5944. Record.AddDeclRef(M.getAssociatedDeclaration());
  5945. }
  5946. }
  5947. void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
  5948. Record.push_back(C->varlist_size());
  5949. Record.push_back(C->getUniqueDeclarationsNum());
  5950. Record.push_back(C->getTotalComponentListNum());
  5951. Record.push_back(C->getTotalComponentsNum());
  5952. Record.AddSourceLocation(C->getLParenLoc());
  5953. for (auto *E : C->varlists())
  5954. Record.AddStmt(E);
  5955. for (auto *D : C->all_decls())
  5956. Record.AddDeclRef(D);
  5957. for (auto N : C->all_num_lists())
  5958. Record.push_back(N);
  5959. for (auto N : C->all_lists_sizes())
  5960. Record.push_back(N);
  5961. for (auto &M : C->all_components()) {
  5962. Record.AddStmt(M.getAssociatedExpression());
  5963. Record.AddDeclRef(M.getAssociatedDeclaration());
  5964. }
  5965. }
  5966. void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}