ASTWriter.cpp 218 KB

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