ASTWriter.cpp 253 KB

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