ASTWriter.cpp 231 KB

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