ASTWriter.cpp 252 KB

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