ASTWriter.cpp 228 KB

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