ASTWriter.cpp 256 KB

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