BitcodeWriter.cpp 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569
  1. //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode 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. // Bitcode writer implementation.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Bitcode/BitcodeWriter.h"
  13. #include "ValueEnumerator.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/None.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/StringMap.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/ADT/Triple.h"
  26. #include "llvm/Bitcode/BitCodes.h"
  27. #include "llvm/Bitcode/BitstreamWriter.h"
  28. #include "llvm/Bitcode/LLVMBitCodes.h"
  29. #include "llvm/Config/llvm-config.h"
  30. #include "llvm/IR/Attributes.h"
  31. #include "llvm/IR/BasicBlock.h"
  32. #include "llvm/IR/CallSite.h"
  33. #include "llvm/IR/Comdat.h"
  34. #include "llvm/IR/Constant.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/DebugInfoMetadata.h"
  37. #include "llvm/IR/DebugLoc.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Function.h"
  40. #include "llvm/IR/GlobalAlias.h"
  41. #include "llvm/IR/GlobalIFunc.h"
  42. #include "llvm/IR/GlobalObject.h"
  43. #include "llvm/IR/GlobalValue.h"
  44. #include "llvm/IR/GlobalVariable.h"
  45. #include "llvm/IR/InlineAsm.h"
  46. #include "llvm/IR/InstrTypes.h"
  47. #include "llvm/IR/Instruction.h"
  48. #include "llvm/IR/Instructions.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/Metadata.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/IR/ModuleSummaryIndex.h"
  53. #include "llvm/IR/Operator.h"
  54. #include "llvm/IR/Type.h"
  55. #include "llvm/IR/UseListOrder.h"
  56. #include "llvm/IR/Value.h"
  57. #include "llvm/IR/ValueSymbolTable.h"
  58. #include "llvm/MC/StringTableBuilder.h"
  59. #include "llvm/Object/IRSymtab.h"
  60. #include "llvm/Support/AtomicOrdering.h"
  61. #include "llvm/Support/Casting.h"
  62. #include "llvm/Support/CommandLine.h"
  63. #include "llvm/Support/Endian.h"
  64. #include "llvm/Support/Error.h"
  65. #include "llvm/Support/ErrorHandling.h"
  66. #include "llvm/Support/MathExtras.h"
  67. #include "llvm/Support/SHA1.h"
  68. #include "llvm/Support/TargetRegistry.h"
  69. #include "llvm/Support/raw_ostream.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <cstddef>
  73. #include <cstdint>
  74. #include <iterator>
  75. #include <map>
  76. #include <memory>
  77. #include <string>
  78. #include <utility>
  79. #include <vector>
  80. using namespace llvm;
  81. static cl::opt<unsigned>
  82. IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
  83. cl::desc("Number of metadatas above which we emit an index "
  84. "to enable lazy-loading"));
  85. cl::opt<bool> WriteRelBFToSummary(
  86. "write-relbf-to-summary", cl::Hidden, cl::init(false),
  87. cl::desc("Write relative block frequency to function summary "));
  88. extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
  89. namespace {
  90. /// These are manifest constants used by the bitcode writer. They do not need to
  91. /// be kept in sync with the reader, but need to be consistent within this file.
  92. enum {
  93. // VALUE_SYMTAB_BLOCK abbrev id's.
  94. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  95. VST_ENTRY_7_ABBREV,
  96. VST_ENTRY_6_ABBREV,
  97. VST_BBENTRY_6_ABBREV,
  98. // CONSTANTS_BLOCK abbrev id's.
  99. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  100. CONSTANTS_INTEGER_ABBREV,
  101. CONSTANTS_CE_CAST_Abbrev,
  102. CONSTANTS_NULL_Abbrev,
  103. // FUNCTION_BLOCK abbrev id's.
  104. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  105. FUNCTION_INST_UNOP_ABBREV,
  106. FUNCTION_INST_UNOP_FLAGS_ABBREV,
  107. FUNCTION_INST_BINOP_ABBREV,
  108. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  109. FUNCTION_INST_CAST_ABBREV,
  110. FUNCTION_INST_RET_VOID_ABBREV,
  111. FUNCTION_INST_RET_VAL_ABBREV,
  112. FUNCTION_INST_UNREACHABLE_ABBREV,
  113. FUNCTION_INST_GEP_ABBREV,
  114. };
  115. /// Abstract class to manage the bitcode writing, subclassed for each bitcode
  116. /// file type.
  117. class BitcodeWriterBase {
  118. protected:
  119. /// The stream created and owned by the client.
  120. BitstreamWriter &Stream;
  121. StringTableBuilder &StrtabBuilder;
  122. public:
  123. /// Constructs a BitcodeWriterBase object that writes to the provided
  124. /// \p Stream.
  125. BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
  126. : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
  127. protected:
  128. void writeBitcodeHeader();
  129. void writeModuleVersion();
  130. };
  131. void BitcodeWriterBase::writeModuleVersion() {
  132. // VERSION: [version#]
  133. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
  134. }
  135. /// Base class to manage the module bitcode writing, currently subclassed for
  136. /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
  137. class ModuleBitcodeWriterBase : public BitcodeWriterBase {
  138. protected:
  139. /// The Module to write to bitcode.
  140. const Module &M;
  141. /// Enumerates ids for all values in the module.
  142. ValueEnumerator VE;
  143. /// Optional per-module index to write for ThinLTO.
  144. const ModuleSummaryIndex *Index;
  145. /// Map that holds the correspondence between GUIDs in the summary index,
  146. /// that came from indirect call profiles, and a value id generated by this
  147. /// class to use in the VST and summary block records.
  148. std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
  149. /// Tracks the last value id recorded in the GUIDToValueMap.
  150. unsigned GlobalValueId;
  151. /// Saves the offset of the VSTOffset record that must eventually be
  152. /// backpatched with the offset of the actual VST.
  153. uint64_t VSTOffsetPlaceholder = 0;
  154. public:
  155. /// Constructs a ModuleBitcodeWriterBase object for the given Module,
  156. /// writing to the provided \p Buffer.
  157. ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
  158. BitstreamWriter &Stream,
  159. bool ShouldPreserveUseListOrder,
  160. const ModuleSummaryIndex *Index)
  161. : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
  162. VE(M, ShouldPreserveUseListOrder), Index(Index) {
  163. // Assign ValueIds to any callee values in the index that came from
  164. // indirect call profiles and were recorded as a GUID not a Value*
  165. // (which would have been assigned an ID by the ValueEnumerator).
  166. // The starting ValueId is just after the number of values in the
  167. // ValueEnumerator, so that they can be emitted in the VST.
  168. GlobalValueId = VE.getValues().size();
  169. if (!Index)
  170. return;
  171. for (const auto &GUIDSummaryLists : *Index)
  172. // Examine all summaries for this GUID.
  173. for (auto &Summary : GUIDSummaryLists.second.SummaryList)
  174. if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
  175. // For each call in the function summary, see if the call
  176. // is to a GUID (which means it is for an indirect call,
  177. // otherwise we would have a Value for it). If so, synthesize
  178. // a value id.
  179. for (auto &CallEdge : FS->calls())
  180. if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
  181. assignValueId(CallEdge.first.getGUID());
  182. }
  183. protected:
  184. void writePerModuleGlobalValueSummary();
  185. private:
  186. void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
  187. GlobalValueSummary *Summary,
  188. unsigned ValueID,
  189. unsigned FSCallsAbbrev,
  190. unsigned FSCallsProfileAbbrev,
  191. const Function &F);
  192. void writeModuleLevelReferences(const GlobalVariable &V,
  193. SmallVector<uint64_t, 64> &NameVals,
  194. unsigned FSModRefsAbbrev);
  195. void assignValueId(GlobalValue::GUID ValGUID) {
  196. GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
  197. }
  198. unsigned getValueId(GlobalValue::GUID ValGUID) {
  199. const auto &VMI = GUIDToValueIdMap.find(ValGUID);
  200. // Expect that any GUID value had a value Id assigned by an
  201. // earlier call to assignValueId.
  202. assert(VMI != GUIDToValueIdMap.end() &&
  203. "GUID does not have assigned value Id");
  204. return VMI->second;
  205. }
  206. // Helper to get the valueId for the type of value recorded in VI.
  207. unsigned getValueId(ValueInfo VI) {
  208. if (!VI.haveGVs() || !VI.getValue())
  209. return getValueId(VI.getGUID());
  210. return VE.getValueID(VI.getValue());
  211. }
  212. std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
  213. };
  214. /// Class to manage the bitcode writing for a module.
  215. class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
  216. /// Pointer to the buffer allocated by caller for bitcode writing.
  217. const SmallVectorImpl<char> &Buffer;
  218. /// True if a module hash record should be written.
  219. bool GenerateHash;
  220. /// If non-null, when GenerateHash is true, the resulting hash is written
  221. /// into ModHash.
  222. ModuleHash *ModHash;
  223. SHA1 Hasher;
  224. /// The start bit of the identification block.
  225. uint64_t BitcodeStartBit;
  226. public:
  227. /// Constructs a ModuleBitcodeWriter object for the given Module,
  228. /// writing to the provided \p Buffer.
  229. ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
  230. StringTableBuilder &StrtabBuilder,
  231. BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
  232. const ModuleSummaryIndex *Index, bool GenerateHash,
  233. ModuleHash *ModHash = nullptr)
  234. : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
  235. ShouldPreserveUseListOrder, Index),
  236. Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
  237. BitcodeStartBit(Stream.GetCurrentBitNo()) {}
  238. /// Emit the current module to the bitstream.
  239. void write();
  240. private:
  241. uint64_t bitcodeStartBit() { return BitcodeStartBit; }
  242. size_t addToStrtab(StringRef Str);
  243. void writeAttributeGroupTable();
  244. void writeAttributeTable();
  245. void writeTypeTable();
  246. void writeComdats();
  247. void writeValueSymbolTableForwardDecl();
  248. void writeModuleInfo();
  249. void writeValueAsMetadata(const ValueAsMetadata *MD,
  250. SmallVectorImpl<uint64_t> &Record);
  251. void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
  252. unsigned Abbrev);
  253. unsigned createDILocationAbbrev();
  254. void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
  255. unsigned &Abbrev);
  256. unsigned createGenericDINodeAbbrev();
  257. void writeGenericDINode(const GenericDINode *N,
  258. SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
  259. void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
  260. unsigned Abbrev);
  261. void writeDIEnumerator(const DIEnumerator *N,
  262. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  263. void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
  264. unsigned Abbrev);
  265. void writeDIDerivedType(const DIDerivedType *N,
  266. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  267. void writeDICompositeType(const DICompositeType *N,
  268. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  269. void writeDISubroutineType(const DISubroutineType *N,
  270. SmallVectorImpl<uint64_t> &Record,
  271. unsigned Abbrev);
  272. void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
  273. unsigned Abbrev);
  274. void writeDICompileUnit(const DICompileUnit *N,
  275. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  276. void writeDISubprogram(const DISubprogram *N,
  277. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  278. void writeDILexicalBlock(const DILexicalBlock *N,
  279. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  280. void writeDILexicalBlockFile(const DILexicalBlockFile *N,
  281. SmallVectorImpl<uint64_t> &Record,
  282. unsigned Abbrev);
  283. void writeDICommonBlock(const DICommonBlock *N,
  284. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  285. void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
  286. unsigned Abbrev);
  287. void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
  288. unsigned Abbrev);
  289. void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
  290. unsigned Abbrev);
  291. void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
  292. unsigned Abbrev);
  293. void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
  294. SmallVectorImpl<uint64_t> &Record,
  295. unsigned Abbrev);
  296. void writeDITemplateValueParameter(const DITemplateValueParameter *N,
  297. SmallVectorImpl<uint64_t> &Record,
  298. unsigned Abbrev);
  299. void writeDIGlobalVariable(const DIGlobalVariable *N,
  300. SmallVectorImpl<uint64_t> &Record,
  301. unsigned Abbrev);
  302. void writeDILocalVariable(const DILocalVariable *N,
  303. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  304. void writeDILabel(const DILabel *N,
  305. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  306. void writeDIExpression(const DIExpression *N,
  307. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  308. void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
  309. SmallVectorImpl<uint64_t> &Record,
  310. unsigned Abbrev);
  311. void writeDIObjCProperty(const DIObjCProperty *N,
  312. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
  313. void writeDIImportedEntity(const DIImportedEntity *N,
  314. SmallVectorImpl<uint64_t> &Record,
  315. unsigned Abbrev);
  316. unsigned createNamedMetadataAbbrev();
  317. void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
  318. unsigned createMetadataStringsAbbrev();
  319. void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
  320. SmallVectorImpl<uint64_t> &Record);
  321. void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
  322. SmallVectorImpl<uint64_t> &Record,
  323. std::vector<unsigned> *MDAbbrevs = nullptr,
  324. std::vector<uint64_t> *IndexPos = nullptr);
  325. void writeModuleMetadata();
  326. void writeFunctionMetadata(const Function &F);
  327. void writeFunctionMetadataAttachment(const Function &F);
  328. void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
  329. void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
  330. const GlobalObject &GO);
  331. void writeModuleMetadataKinds();
  332. void writeOperandBundleTags();
  333. void writeSyncScopeNames();
  334. void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
  335. void writeModuleConstants();
  336. bool pushValueAndType(const Value *V, unsigned InstID,
  337. SmallVectorImpl<unsigned> &Vals);
  338. void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
  339. void pushValue(const Value *V, unsigned InstID,
  340. SmallVectorImpl<unsigned> &Vals);
  341. void pushValueSigned(const Value *V, unsigned InstID,
  342. SmallVectorImpl<uint64_t> &Vals);
  343. void writeInstruction(const Instruction &I, unsigned InstID,
  344. SmallVectorImpl<unsigned> &Vals);
  345. void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
  346. void writeGlobalValueSymbolTable(
  347. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
  348. void writeUseList(UseListOrder &&Order);
  349. void writeUseListBlock(const Function *F);
  350. void
  351. writeFunction(const Function &F,
  352. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
  353. void writeBlockInfo();
  354. void writeModuleHash(size_t BlockStartPos);
  355. unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
  356. return unsigned(SSID);
  357. }
  358. };
  359. /// Class to manage the bitcode writing for a combined index.
  360. class IndexBitcodeWriter : public BitcodeWriterBase {
  361. /// The combined index to write to bitcode.
  362. const ModuleSummaryIndex &Index;
  363. /// When writing a subset of the index for distributed backends, client
  364. /// provides a map of modules to the corresponding GUIDs/summaries to write.
  365. const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
  366. /// Map that holds the correspondence between the GUID used in the combined
  367. /// index and a value id generated by this class to use in references.
  368. std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
  369. /// Tracks the last value id recorded in the GUIDToValueMap.
  370. unsigned GlobalValueId = 0;
  371. public:
  372. /// Constructs a IndexBitcodeWriter object for the given combined index,
  373. /// writing to the provided \p Buffer. When writing a subset of the index
  374. /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
  375. IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
  376. const ModuleSummaryIndex &Index,
  377. const std::map<std::string, GVSummaryMapTy>
  378. *ModuleToSummariesForIndex = nullptr)
  379. : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
  380. ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
  381. // Assign unique value ids to all summaries to be written, for use
  382. // in writing out the call graph edges. Save the mapping from GUID
  383. // to the new global value id to use when writing those edges, which
  384. // are currently saved in the index in terms of GUID.
  385. forEachSummary([&](GVInfo I, bool) {
  386. GUIDToValueIdMap[I.first] = ++GlobalValueId;
  387. });
  388. }
  389. /// The below iterator returns the GUID and associated summary.
  390. using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
  391. /// Calls the callback for each value GUID and summary to be written to
  392. /// bitcode. This hides the details of whether they are being pulled from the
  393. /// entire index or just those in a provided ModuleToSummariesForIndex map.
  394. template<typename Functor>
  395. void forEachSummary(Functor Callback) {
  396. if (ModuleToSummariesForIndex) {
  397. for (auto &M : *ModuleToSummariesForIndex)
  398. for (auto &Summary : M.second) {
  399. Callback(Summary, false);
  400. // Ensure aliasee is handled, e.g. for assigning a valueId,
  401. // even if we are not importing the aliasee directly (the
  402. // imported alias will contain a copy of aliasee).
  403. if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
  404. Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
  405. }
  406. } else {
  407. for (auto &Summaries : Index)
  408. for (auto &Summary : Summaries.second.SummaryList)
  409. Callback({Summaries.first, Summary.get()}, false);
  410. }
  411. }
  412. /// Calls the callback for each entry in the modulePaths StringMap that
  413. /// should be written to the module path string table. This hides the details
  414. /// of whether they are being pulled from the entire index or just those in a
  415. /// provided ModuleToSummariesForIndex map.
  416. template <typename Functor> void forEachModule(Functor Callback) {
  417. if (ModuleToSummariesForIndex) {
  418. for (const auto &M : *ModuleToSummariesForIndex) {
  419. const auto &MPI = Index.modulePaths().find(M.first);
  420. if (MPI == Index.modulePaths().end()) {
  421. // This should only happen if the bitcode file was empty, in which
  422. // case we shouldn't be importing (the ModuleToSummariesForIndex
  423. // would only include the module we are writing and index for).
  424. assert(ModuleToSummariesForIndex->size() == 1);
  425. continue;
  426. }
  427. Callback(*MPI);
  428. }
  429. } else {
  430. for (const auto &MPSE : Index.modulePaths())
  431. Callback(MPSE);
  432. }
  433. }
  434. /// Main entry point for writing a combined index to bitcode.
  435. void write();
  436. private:
  437. void writeModStrings();
  438. void writeCombinedGlobalValueSummary();
  439. Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
  440. auto VMI = GUIDToValueIdMap.find(ValGUID);
  441. if (VMI == GUIDToValueIdMap.end())
  442. return None;
  443. return VMI->second;
  444. }
  445. std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
  446. };
  447. } // end anonymous namespace
  448. static unsigned getEncodedCastOpcode(unsigned Opcode) {
  449. switch (Opcode) {
  450. default: llvm_unreachable("Unknown cast instruction!");
  451. case Instruction::Trunc : return bitc::CAST_TRUNC;
  452. case Instruction::ZExt : return bitc::CAST_ZEXT;
  453. case Instruction::SExt : return bitc::CAST_SEXT;
  454. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  455. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  456. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  457. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  458. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  459. case Instruction::FPExt : return bitc::CAST_FPEXT;
  460. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  461. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  462. case Instruction::BitCast : return bitc::CAST_BITCAST;
  463. case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
  464. }
  465. }
  466. static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
  467. switch (Opcode) {
  468. default: llvm_unreachable("Unknown binary instruction!");
  469. case Instruction::FNeg: return bitc::UNOP_NEG;
  470. }
  471. }
  472. static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
  473. switch (Opcode) {
  474. default: llvm_unreachable("Unknown binary instruction!");
  475. case Instruction::Add:
  476. case Instruction::FAdd: return bitc::BINOP_ADD;
  477. case Instruction::Sub:
  478. case Instruction::FSub: return bitc::BINOP_SUB;
  479. case Instruction::Mul:
  480. case Instruction::FMul: return bitc::BINOP_MUL;
  481. case Instruction::UDiv: return bitc::BINOP_UDIV;
  482. case Instruction::FDiv:
  483. case Instruction::SDiv: return bitc::BINOP_SDIV;
  484. case Instruction::URem: return bitc::BINOP_UREM;
  485. case Instruction::FRem:
  486. case Instruction::SRem: return bitc::BINOP_SREM;
  487. case Instruction::Shl: return bitc::BINOP_SHL;
  488. case Instruction::LShr: return bitc::BINOP_LSHR;
  489. case Instruction::AShr: return bitc::BINOP_ASHR;
  490. case Instruction::And: return bitc::BINOP_AND;
  491. case Instruction::Or: return bitc::BINOP_OR;
  492. case Instruction::Xor: return bitc::BINOP_XOR;
  493. }
  494. }
  495. static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
  496. switch (Op) {
  497. default: llvm_unreachable("Unknown RMW operation!");
  498. case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
  499. case AtomicRMWInst::Add: return bitc::RMW_ADD;
  500. case AtomicRMWInst::Sub: return bitc::RMW_SUB;
  501. case AtomicRMWInst::And: return bitc::RMW_AND;
  502. case AtomicRMWInst::Nand: return bitc::RMW_NAND;
  503. case AtomicRMWInst::Or: return bitc::RMW_OR;
  504. case AtomicRMWInst::Xor: return bitc::RMW_XOR;
  505. case AtomicRMWInst::Max: return bitc::RMW_MAX;
  506. case AtomicRMWInst::Min: return bitc::RMW_MIN;
  507. case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
  508. case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
  509. case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
  510. case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
  511. }
  512. }
  513. static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
  514. switch (Ordering) {
  515. case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
  516. case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
  517. case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
  518. case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
  519. case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
  520. case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
  521. case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
  522. }
  523. llvm_unreachable("Invalid ordering");
  524. }
  525. static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
  526. StringRef Str, unsigned AbbrevToUse) {
  527. SmallVector<unsigned, 64> Vals;
  528. // Code: [strchar x N]
  529. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  530. if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
  531. AbbrevToUse = 0;
  532. Vals.push_back(Str[i]);
  533. }
  534. // Emit the finished record.
  535. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  536. }
  537. static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
  538. switch (Kind) {
  539. case Attribute::Alignment:
  540. return bitc::ATTR_KIND_ALIGNMENT;
  541. case Attribute::AllocSize:
  542. return bitc::ATTR_KIND_ALLOC_SIZE;
  543. case Attribute::AlwaysInline:
  544. return bitc::ATTR_KIND_ALWAYS_INLINE;
  545. case Attribute::ArgMemOnly:
  546. return bitc::ATTR_KIND_ARGMEMONLY;
  547. case Attribute::Builtin:
  548. return bitc::ATTR_KIND_BUILTIN;
  549. case Attribute::ByVal:
  550. return bitc::ATTR_KIND_BY_VAL;
  551. case Attribute::Convergent:
  552. return bitc::ATTR_KIND_CONVERGENT;
  553. case Attribute::InAlloca:
  554. return bitc::ATTR_KIND_IN_ALLOCA;
  555. case Attribute::Cold:
  556. return bitc::ATTR_KIND_COLD;
  557. case Attribute::InaccessibleMemOnly:
  558. return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
  559. case Attribute::InaccessibleMemOrArgMemOnly:
  560. return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
  561. case Attribute::InlineHint:
  562. return bitc::ATTR_KIND_INLINE_HINT;
  563. case Attribute::InReg:
  564. return bitc::ATTR_KIND_IN_REG;
  565. case Attribute::JumpTable:
  566. return bitc::ATTR_KIND_JUMP_TABLE;
  567. case Attribute::MinSize:
  568. return bitc::ATTR_KIND_MIN_SIZE;
  569. case Attribute::Naked:
  570. return bitc::ATTR_KIND_NAKED;
  571. case Attribute::Nest:
  572. return bitc::ATTR_KIND_NEST;
  573. case Attribute::NoAlias:
  574. return bitc::ATTR_KIND_NO_ALIAS;
  575. case Attribute::NoBuiltin:
  576. return bitc::ATTR_KIND_NO_BUILTIN;
  577. case Attribute::NoCapture:
  578. return bitc::ATTR_KIND_NO_CAPTURE;
  579. case Attribute::NoDuplicate:
  580. return bitc::ATTR_KIND_NO_DUPLICATE;
  581. case Attribute::NoImplicitFloat:
  582. return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
  583. case Attribute::NoInline:
  584. return bitc::ATTR_KIND_NO_INLINE;
  585. case Attribute::NoRecurse:
  586. return bitc::ATTR_KIND_NO_RECURSE;
  587. case Attribute::NonLazyBind:
  588. return bitc::ATTR_KIND_NON_LAZY_BIND;
  589. case Attribute::NonNull:
  590. return bitc::ATTR_KIND_NON_NULL;
  591. case Attribute::Dereferenceable:
  592. return bitc::ATTR_KIND_DEREFERENCEABLE;
  593. case Attribute::DereferenceableOrNull:
  594. return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
  595. case Attribute::NoRedZone:
  596. return bitc::ATTR_KIND_NO_RED_ZONE;
  597. case Attribute::NoReturn:
  598. return bitc::ATTR_KIND_NO_RETURN;
  599. case Attribute::NoCfCheck:
  600. return bitc::ATTR_KIND_NOCF_CHECK;
  601. case Attribute::NoUnwind:
  602. return bitc::ATTR_KIND_NO_UNWIND;
  603. case Attribute::OptForFuzzing:
  604. return bitc::ATTR_KIND_OPT_FOR_FUZZING;
  605. case Attribute::OptimizeForSize:
  606. return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
  607. case Attribute::OptimizeNone:
  608. return bitc::ATTR_KIND_OPTIMIZE_NONE;
  609. case Attribute::ReadNone:
  610. return bitc::ATTR_KIND_READ_NONE;
  611. case Attribute::ReadOnly:
  612. return bitc::ATTR_KIND_READ_ONLY;
  613. case Attribute::Returned:
  614. return bitc::ATTR_KIND_RETURNED;
  615. case Attribute::ReturnsTwice:
  616. return bitc::ATTR_KIND_RETURNS_TWICE;
  617. case Attribute::SExt:
  618. return bitc::ATTR_KIND_S_EXT;
  619. case Attribute::Speculatable:
  620. return bitc::ATTR_KIND_SPECULATABLE;
  621. case Attribute::StackAlignment:
  622. return bitc::ATTR_KIND_STACK_ALIGNMENT;
  623. case Attribute::StackProtect:
  624. return bitc::ATTR_KIND_STACK_PROTECT;
  625. case Attribute::StackProtectReq:
  626. return bitc::ATTR_KIND_STACK_PROTECT_REQ;
  627. case Attribute::StackProtectStrong:
  628. return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
  629. case Attribute::SafeStack:
  630. return bitc::ATTR_KIND_SAFESTACK;
  631. case Attribute::ShadowCallStack:
  632. return bitc::ATTR_KIND_SHADOWCALLSTACK;
  633. case Attribute::StrictFP:
  634. return bitc::ATTR_KIND_STRICT_FP;
  635. case Attribute::StructRet:
  636. return bitc::ATTR_KIND_STRUCT_RET;
  637. case Attribute::SanitizeAddress:
  638. return bitc::ATTR_KIND_SANITIZE_ADDRESS;
  639. case Attribute::SanitizeHWAddress:
  640. return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
  641. case Attribute::SanitizeThread:
  642. return bitc::ATTR_KIND_SANITIZE_THREAD;
  643. case Attribute::SanitizeMemory:
  644. return bitc::ATTR_KIND_SANITIZE_MEMORY;
  645. case Attribute::SpeculativeLoadHardening:
  646. return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
  647. case Attribute::SwiftError:
  648. return bitc::ATTR_KIND_SWIFT_ERROR;
  649. case Attribute::SwiftSelf:
  650. return bitc::ATTR_KIND_SWIFT_SELF;
  651. case Attribute::UWTable:
  652. return bitc::ATTR_KIND_UW_TABLE;
  653. case Attribute::WriteOnly:
  654. return bitc::ATTR_KIND_WRITEONLY;
  655. case Attribute::ZExt:
  656. return bitc::ATTR_KIND_Z_EXT;
  657. case Attribute::ImmArg:
  658. return bitc::ATTR_KIND_IMMARG;
  659. case Attribute::EndAttrKinds:
  660. llvm_unreachable("Can not encode end-attribute kinds marker.");
  661. case Attribute::None:
  662. llvm_unreachable("Can not encode none-attribute.");
  663. }
  664. llvm_unreachable("Trying to encode unknown attribute");
  665. }
  666. void ModuleBitcodeWriter::writeAttributeGroupTable() {
  667. const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
  668. VE.getAttributeGroups();
  669. if (AttrGrps.empty()) return;
  670. Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
  671. SmallVector<uint64_t, 64> Record;
  672. for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
  673. unsigned AttrListIndex = Pair.first;
  674. AttributeSet AS = Pair.second;
  675. Record.push_back(VE.getAttributeGroupID(Pair));
  676. Record.push_back(AttrListIndex);
  677. for (Attribute Attr : AS) {
  678. if (Attr.isEnumAttribute()) {
  679. Record.push_back(0);
  680. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  681. } else if (Attr.isIntAttribute()) {
  682. Record.push_back(1);
  683. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  684. Record.push_back(Attr.getValueAsInt());
  685. } else {
  686. StringRef Kind = Attr.getKindAsString();
  687. StringRef Val = Attr.getValueAsString();
  688. Record.push_back(Val.empty() ? 3 : 4);
  689. Record.append(Kind.begin(), Kind.end());
  690. Record.push_back(0);
  691. if (!Val.empty()) {
  692. Record.append(Val.begin(), Val.end());
  693. Record.push_back(0);
  694. }
  695. }
  696. }
  697. Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
  698. Record.clear();
  699. }
  700. Stream.ExitBlock();
  701. }
  702. void ModuleBitcodeWriter::writeAttributeTable() {
  703. const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
  704. if (Attrs.empty()) return;
  705. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  706. SmallVector<uint64_t, 64> Record;
  707. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  708. AttributeList AL = Attrs[i];
  709. for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
  710. AttributeSet AS = AL.getAttributes(i);
  711. if (AS.hasAttributes())
  712. Record.push_back(VE.getAttributeGroupID({i, AS}));
  713. }
  714. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  715. Record.clear();
  716. }
  717. Stream.ExitBlock();
  718. }
  719. /// WriteTypeTable - Write out the type table for a module.
  720. void ModuleBitcodeWriter::writeTypeTable() {
  721. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  722. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
  723. SmallVector<uint64_t, 64> TypeVals;
  724. uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
  725. // Abbrev for TYPE_CODE_POINTER.
  726. auto Abbv = std::make_shared<BitCodeAbbrev>();
  727. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  728. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  729. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  730. unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  731. // Abbrev for TYPE_CODE_FUNCTION.
  732. Abbv = std::make_shared<BitCodeAbbrev>();
  733. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  734. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  735. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  736. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  737. unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  738. // Abbrev for TYPE_CODE_STRUCT_ANON.
  739. Abbv = std::make_shared<BitCodeAbbrev>();
  740. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
  741. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  742. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  743. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  744. unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  745. // Abbrev for TYPE_CODE_STRUCT_NAME.
  746. Abbv = std::make_shared<BitCodeAbbrev>();
  747. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
  748. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  749. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  750. unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  751. // Abbrev for TYPE_CODE_STRUCT_NAMED.
  752. Abbv = std::make_shared<BitCodeAbbrev>();
  753. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
  754. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  755. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  756. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  757. unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  758. // Abbrev for TYPE_CODE_ARRAY.
  759. Abbv = std::make_shared<BitCodeAbbrev>();
  760. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  761. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  762. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  763. unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  764. // Emit an entry count so the reader can reserve space.
  765. TypeVals.push_back(TypeList.size());
  766. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  767. TypeVals.clear();
  768. // Loop over all of the types, emitting each in turn.
  769. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  770. Type *T = TypeList[i];
  771. int AbbrevToUse = 0;
  772. unsigned Code = 0;
  773. switch (T->getTypeID()) {
  774. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  775. case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
  776. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  777. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  778. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  779. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  780. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  781. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  782. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  783. case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
  784. case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
  785. case Type::IntegerTyID:
  786. // INTEGER: [width]
  787. Code = bitc::TYPE_CODE_INTEGER;
  788. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  789. break;
  790. case Type::PointerTyID: {
  791. PointerType *PTy = cast<PointerType>(T);
  792. // POINTER: [pointee type, address space]
  793. Code = bitc::TYPE_CODE_POINTER;
  794. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  795. unsigned AddressSpace = PTy->getAddressSpace();
  796. TypeVals.push_back(AddressSpace);
  797. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  798. break;
  799. }
  800. case Type::FunctionTyID: {
  801. FunctionType *FT = cast<FunctionType>(T);
  802. // FUNCTION: [isvararg, retty, paramty x N]
  803. Code = bitc::TYPE_CODE_FUNCTION;
  804. TypeVals.push_back(FT->isVarArg());
  805. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  806. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  807. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  808. AbbrevToUse = FunctionAbbrev;
  809. break;
  810. }
  811. case Type::StructTyID: {
  812. StructType *ST = cast<StructType>(T);
  813. // STRUCT: [ispacked, eltty x N]
  814. TypeVals.push_back(ST->isPacked());
  815. // Output all of the element types.
  816. for (StructType::element_iterator I = ST->element_begin(),
  817. E = ST->element_end(); I != E; ++I)
  818. TypeVals.push_back(VE.getTypeID(*I));
  819. if (ST->isLiteral()) {
  820. Code = bitc::TYPE_CODE_STRUCT_ANON;
  821. AbbrevToUse = StructAnonAbbrev;
  822. } else {
  823. if (ST->isOpaque()) {
  824. Code = bitc::TYPE_CODE_OPAQUE;
  825. } else {
  826. Code = bitc::TYPE_CODE_STRUCT_NAMED;
  827. AbbrevToUse = StructNamedAbbrev;
  828. }
  829. // Emit the name if it is present.
  830. if (!ST->getName().empty())
  831. writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
  832. StructNameAbbrev);
  833. }
  834. break;
  835. }
  836. case Type::ArrayTyID: {
  837. ArrayType *AT = cast<ArrayType>(T);
  838. // ARRAY: [numelts, eltty]
  839. Code = bitc::TYPE_CODE_ARRAY;
  840. TypeVals.push_back(AT->getNumElements());
  841. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  842. AbbrevToUse = ArrayAbbrev;
  843. break;
  844. }
  845. case Type::VectorTyID: {
  846. VectorType *VT = cast<VectorType>(T);
  847. // VECTOR [numelts, eltty] or
  848. // [numelts, eltty, scalable]
  849. Code = bitc::TYPE_CODE_VECTOR;
  850. TypeVals.push_back(VT->getNumElements());
  851. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  852. if (VT->isScalable())
  853. TypeVals.push_back(VT->isScalable());
  854. break;
  855. }
  856. }
  857. // Emit the finished record.
  858. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  859. TypeVals.clear();
  860. }
  861. Stream.ExitBlock();
  862. }
  863. static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
  864. switch (Linkage) {
  865. case GlobalValue::ExternalLinkage:
  866. return 0;
  867. case GlobalValue::WeakAnyLinkage:
  868. return 16;
  869. case GlobalValue::AppendingLinkage:
  870. return 2;
  871. case GlobalValue::InternalLinkage:
  872. return 3;
  873. case GlobalValue::LinkOnceAnyLinkage:
  874. return 18;
  875. case GlobalValue::ExternalWeakLinkage:
  876. return 7;
  877. case GlobalValue::CommonLinkage:
  878. return 8;
  879. case GlobalValue::PrivateLinkage:
  880. return 9;
  881. case GlobalValue::WeakODRLinkage:
  882. return 17;
  883. case GlobalValue::LinkOnceODRLinkage:
  884. return 19;
  885. case GlobalValue::AvailableExternallyLinkage:
  886. return 12;
  887. }
  888. llvm_unreachable("Invalid linkage");
  889. }
  890. static unsigned getEncodedLinkage(const GlobalValue &GV) {
  891. return getEncodedLinkage(GV.getLinkage());
  892. }
  893. static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
  894. uint64_t RawFlags = 0;
  895. RawFlags |= Flags.ReadNone;
  896. RawFlags |= (Flags.ReadOnly << 1);
  897. RawFlags |= (Flags.NoRecurse << 2);
  898. RawFlags |= (Flags.ReturnDoesNotAlias << 3);
  899. RawFlags |= (Flags.NoInline << 4);
  900. return RawFlags;
  901. }
  902. // Decode the flags for GlobalValue in the summary
  903. static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
  904. uint64_t RawFlags = 0;
  905. RawFlags |= Flags.NotEligibleToImport; // bool
  906. RawFlags |= (Flags.Live << 1);
  907. RawFlags |= (Flags.DSOLocal << 2);
  908. RawFlags |= (Flags.CanAutoHide << 3);
  909. // Linkage don't need to be remapped at that time for the summary. Any future
  910. // change to the getEncodedLinkage() function will need to be taken into
  911. // account here as well.
  912. RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
  913. return RawFlags;
  914. }
  915. static uint64_t getEncodedGVarFlags(GlobalVarSummary::GVarFlags Flags) {
  916. uint64_t RawFlags = Flags.ReadOnly;
  917. return RawFlags;
  918. }
  919. static unsigned getEncodedVisibility(const GlobalValue &GV) {
  920. switch (GV.getVisibility()) {
  921. case GlobalValue::DefaultVisibility: return 0;
  922. case GlobalValue::HiddenVisibility: return 1;
  923. case GlobalValue::ProtectedVisibility: return 2;
  924. }
  925. llvm_unreachable("Invalid visibility");
  926. }
  927. static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
  928. switch (GV.getDLLStorageClass()) {
  929. case GlobalValue::DefaultStorageClass: return 0;
  930. case GlobalValue::DLLImportStorageClass: return 1;
  931. case GlobalValue::DLLExportStorageClass: return 2;
  932. }
  933. llvm_unreachable("Invalid DLL storage class");
  934. }
  935. static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
  936. switch (GV.getThreadLocalMode()) {
  937. case GlobalVariable::NotThreadLocal: return 0;
  938. case GlobalVariable::GeneralDynamicTLSModel: return 1;
  939. case GlobalVariable::LocalDynamicTLSModel: return 2;
  940. case GlobalVariable::InitialExecTLSModel: return 3;
  941. case GlobalVariable::LocalExecTLSModel: return 4;
  942. }
  943. llvm_unreachable("Invalid TLS model");
  944. }
  945. static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
  946. switch (C.getSelectionKind()) {
  947. case Comdat::Any:
  948. return bitc::COMDAT_SELECTION_KIND_ANY;
  949. case Comdat::ExactMatch:
  950. return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
  951. case Comdat::Largest:
  952. return bitc::COMDAT_SELECTION_KIND_LARGEST;
  953. case Comdat::NoDuplicates:
  954. return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
  955. case Comdat::SameSize:
  956. return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
  957. }
  958. llvm_unreachable("Invalid selection kind");
  959. }
  960. static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
  961. switch (GV.getUnnamedAddr()) {
  962. case GlobalValue::UnnamedAddr::None: return 0;
  963. case GlobalValue::UnnamedAddr::Local: return 2;
  964. case GlobalValue::UnnamedAddr::Global: return 1;
  965. }
  966. llvm_unreachable("Invalid unnamed_addr");
  967. }
  968. size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
  969. if (GenerateHash)
  970. Hasher.update(Str);
  971. return StrtabBuilder.add(Str);
  972. }
  973. void ModuleBitcodeWriter::writeComdats() {
  974. SmallVector<unsigned, 64> Vals;
  975. for (const Comdat *C : VE.getComdats()) {
  976. // COMDAT: [strtab offset, strtab size, selection_kind]
  977. Vals.push_back(addToStrtab(C->getName()));
  978. Vals.push_back(C->getName().size());
  979. Vals.push_back(getEncodedComdatSelectionKind(*C));
  980. Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
  981. Vals.clear();
  982. }
  983. }
  984. /// Write a record that will eventually hold the word offset of the
  985. /// module-level VST. For now the offset is 0, which will be backpatched
  986. /// after the real VST is written. Saves the bit offset to backpatch.
  987. void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
  988. // Write a placeholder value in for the offset of the real VST,
  989. // which is written after the function blocks so that it can include
  990. // the offset of each function. The placeholder offset will be
  991. // updated when the real VST is written.
  992. auto Abbv = std::make_shared<BitCodeAbbrev>();
  993. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
  994. // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
  995. // hold the real VST offset. Must use fixed instead of VBR as we don't
  996. // know how many VBR chunks to reserve ahead of time.
  997. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  998. unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  999. // Emit the placeholder
  1000. uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
  1001. Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
  1002. // Compute and save the bit offset to the placeholder, which will be
  1003. // patched when the real VST is written. We can simply subtract the 32-bit
  1004. // fixed size from the current bit number to get the location to backpatch.
  1005. VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
  1006. }
  1007. enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
  1008. /// Determine the encoding to use for the given string name and length.
  1009. static StringEncoding getStringEncoding(StringRef Str) {
  1010. bool isChar6 = true;
  1011. for (char C : Str) {
  1012. if (isChar6)
  1013. isChar6 = BitCodeAbbrevOp::isChar6(C);
  1014. if ((unsigned char)C & 128)
  1015. // don't bother scanning the rest.
  1016. return SE_Fixed8;
  1017. }
  1018. if (isChar6)
  1019. return SE_Char6;
  1020. return SE_Fixed7;
  1021. }
  1022. /// Emit top-level description of module, including target triple, inline asm,
  1023. /// descriptors for global variables, and function prototype info.
  1024. /// Returns the bit offset to backpatch with the location of the real VST.
  1025. void ModuleBitcodeWriter::writeModuleInfo() {
  1026. // Emit various pieces of data attached to a module.
  1027. if (!M.getTargetTriple().empty())
  1028. writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
  1029. 0 /*TODO*/);
  1030. const std::string &DL = M.getDataLayoutStr();
  1031. if (!DL.empty())
  1032. writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
  1033. if (!M.getModuleInlineAsm().empty())
  1034. writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
  1035. 0 /*TODO*/);
  1036. // Emit information about sections and GC, computing how many there are. Also
  1037. // compute the maximum alignment value.
  1038. std::map<std::string, unsigned> SectionMap;
  1039. std::map<std::string, unsigned> GCMap;
  1040. unsigned MaxAlignment = 0;
  1041. unsigned MaxGlobalType = 0;
  1042. for (const GlobalValue &GV : M.globals()) {
  1043. MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
  1044. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
  1045. if (GV.hasSection()) {
  1046. // Give section names unique ID's.
  1047. unsigned &Entry = SectionMap[GV.getSection()];
  1048. if (!Entry) {
  1049. writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
  1050. 0 /*TODO*/);
  1051. Entry = SectionMap.size();
  1052. }
  1053. }
  1054. }
  1055. for (const Function &F : M) {
  1056. MaxAlignment = std::max(MaxAlignment, F.getAlignment());
  1057. if (F.hasSection()) {
  1058. // Give section names unique ID's.
  1059. unsigned &Entry = SectionMap[F.getSection()];
  1060. if (!Entry) {
  1061. writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
  1062. 0 /*TODO*/);
  1063. Entry = SectionMap.size();
  1064. }
  1065. }
  1066. if (F.hasGC()) {
  1067. // Same for GC names.
  1068. unsigned &Entry = GCMap[F.getGC()];
  1069. if (!Entry) {
  1070. writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
  1071. 0 /*TODO*/);
  1072. Entry = GCMap.size();
  1073. }
  1074. }
  1075. }
  1076. // Emit abbrev for globals, now that we know # sections and max alignment.
  1077. unsigned SimpleGVarAbbrev = 0;
  1078. if (!M.global_empty()) {
  1079. // Add an abbrev for common globals with no visibility or thread localness.
  1080. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1081. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  1082. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1083. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1084. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1085. Log2_32_Ceil(MaxGlobalType+1)));
  1086. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
  1087. //| explicitType << 1
  1088. //| constant
  1089. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  1090. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
  1091. if (MaxAlignment == 0) // Alignment.
  1092. Abbv->Add(BitCodeAbbrevOp(0));
  1093. else {
  1094. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  1095. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1096. Log2_32_Ceil(MaxEncAlignment+1)));
  1097. }
  1098. if (SectionMap.empty()) // Section.
  1099. Abbv->Add(BitCodeAbbrevOp(0));
  1100. else
  1101. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1102. Log2_32_Ceil(SectionMap.size()+1)));
  1103. // Don't bother emitting vis + thread local.
  1104. SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1105. }
  1106. SmallVector<unsigned, 64> Vals;
  1107. // Emit the module's source file name.
  1108. {
  1109. StringEncoding Bits = getStringEncoding(M.getSourceFileName());
  1110. BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
  1111. if (Bits == SE_Char6)
  1112. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
  1113. else if (Bits == SE_Fixed7)
  1114. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
  1115. // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  1116. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1117. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
  1118. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1119. Abbv->Add(AbbrevOpToUse);
  1120. unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1121. for (const auto P : M.getSourceFileName())
  1122. Vals.push_back((unsigned char)P);
  1123. // Emit the finished record.
  1124. Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
  1125. Vals.clear();
  1126. }
  1127. // Emit the global variable information.
  1128. for (const GlobalVariable &GV : M.globals()) {
  1129. unsigned AbbrevToUse = 0;
  1130. // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
  1131. // linkage, alignment, section, visibility, threadlocal,
  1132. // unnamed_addr, externally_initialized, dllstorageclass,
  1133. // comdat, attributes, DSO_Local]
  1134. Vals.push_back(addToStrtab(GV.getName()));
  1135. Vals.push_back(GV.getName().size());
  1136. Vals.push_back(VE.getTypeID(GV.getValueType()));
  1137. Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
  1138. Vals.push_back(GV.isDeclaration() ? 0 :
  1139. (VE.getValueID(GV.getInitializer()) + 1));
  1140. Vals.push_back(getEncodedLinkage(GV));
  1141. Vals.push_back(Log2_32(GV.getAlignment())+1);
  1142. Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
  1143. if (GV.isThreadLocal() ||
  1144. GV.getVisibility() != GlobalValue::DefaultVisibility ||
  1145. GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
  1146. GV.isExternallyInitialized() ||
  1147. GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
  1148. GV.hasComdat() ||
  1149. GV.hasAttributes() ||
  1150. GV.isDSOLocal() ||
  1151. GV.hasPartition()) {
  1152. Vals.push_back(getEncodedVisibility(GV));
  1153. Vals.push_back(getEncodedThreadLocalMode(GV));
  1154. Vals.push_back(getEncodedUnnamedAddr(GV));
  1155. Vals.push_back(GV.isExternallyInitialized());
  1156. Vals.push_back(getEncodedDLLStorageClass(GV));
  1157. Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
  1158. auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
  1159. Vals.push_back(VE.getAttributeListID(AL));
  1160. Vals.push_back(GV.isDSOLocal());
  1161. Vals.push_back(addToStrtab(GV.getPartition()));
  1162. Vals.push_back(GV.getPartition().size());
  1163. } else {
  1164. AbbrevToUse = SimpleGVarAbbrev;
  1165. }
  1166. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  1167. Vals.clear();
  1168. }
  1169. // Emit the function proto information.
  1170. for (const Function &F : M) {
  1171. // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
  1172. // linkage, paramattrs, alignment, section, visibility, gc,
  1173. // unnamed_addr, prologuedata, dllstorageclass, comdat,
  1174. // prefixdata, personalityfn, DSO_Local, addrspace]
  1175. Vals.push_back(addToStrtab(F.getName()));
  1176. Vals.push_back(F.getName().size());
  1177. Vals.push_back(VE.getTypeID(F.getFunctionType()));
  1178. Vals.push_back(F.getCallingConv());
  1179. Vals.push_back(F.isDeclaration());
  1180. Vals.push_back(getEncodedLinkage(F));
  1181. Vals.push_back(VE.getAttributeListID(F.getAttributes()));
  1182. Vals.push_back(Log2_32(F.getAlignment())+1);
  1183. Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
  1184. Vals.push_back(getEncodedVisibility(F));
  1185. Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
  1186. Vals.push_back(getEncodedUnnamedAddr(F));
  1187. Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
  1188. : 0);
  1189. Vals.push_back(getEncodedDLLStorageClass(F));
  1190. Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
  1191. Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
  1192. : 0);
  1193. Vals.push_back(
  1194. F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
  1195. Vals.push_back(F.isDSOLocal());
  1196. Vals.push_back(F.getAddressSpace());
  1197. Vals.push_back(addToStrtab(F.getPartition()));
  1198. Vals.push_back(F.getPartition().size());
  1199. unsigned AbbrevToUse = 0;
  1200. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  1201. Vals.clear();
  1202. }
  1203. // Emit the alias information.
  1204. for (const GlobalAlias &A : M.aliases()) {
  1205. // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
  1206. // visibility, dllstorageclass, threadlocal, unnamed_addr,
  1207. // DSO_Local]
  1208. Vals.push_back(addToStrtab(A.getName()));
  1209. Vals.push_back(A.getName().size());
  1210. Vals.push_back(VE.getTypeID(A.getValueType()));
  1211. Vals.push_back(A.getType()->getAddressSpace());
  1212. Vals.push_back(VE.getValueID(A.getAliasee()));
  1213. Vals.push_back(getEncodedLinkage(A));
  1214. Vals.push_back(getEncodedVisibility(A));
  1215. Vals.push_back(getEncodedDLLStorageClass(A));
  1216. Vals.push_back(getEncodedThreadLocalMode(A));
  1217. Vals.push_back(getEncodedUnnamedAddr(A));
  1218. Vals.push_back(A.isDSOLocal());
  1219. Vals.push_back(addToStrtab(A.getPartition()));
  1220. Vals.push_back(A.getPartition().size());
  1221. unsigned AbbrevToUse = 0;
  1222. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  1223. Vals.clear();
  1224. }
  1225. // Emit the ifunc information.
  1226. for (const GlobalIFunc &I : M.ifuncs()) {
  1227. // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
  1228. // val#, linkage, visibility, DSO_Local]
  1229. Vals.push_back(addToStrtab(I.getName()));
  1230. Vals.push_back(I.getName().size());
  1231. Vals.push_back(VE.getTypeID(I.getValueType()));
  1232. Vals.push_back(I.getType()->getAddressSpace());
  1233. Vals.push_back(VE.getValueID(I.getResolver()));
  1234. Vals.push_back(getEncodedLinkage(I));
  1235. Vals.push_back(getEncodedVisibility(I));
  1236. Vals.push_back(I.isDSOLocal());
  1237. Vals.push_back(addToStrtab(I.getPartition()));
  1238. Vals.push_back(I.getPartition().size());
  1239. Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
  1240. Vals.clear();
  1241. }
  1242. writeValueSymbolTableForwardDecl();
  1243. }
  1244. static uint64_t getOptimizationFlags(const Value *V) {
  1245. uint64_t Flags = 0;
  1246. if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
  1247. if (OBO->hasNoSignedWrap())
  1248. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  1249. if (OBO->hasNoUnsignedWrap())
  1250. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  1251. } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
  1252. if (PEO->isExact())
  1253. Flags |= 1 << bitc::PEO_EXACT;
  1254. } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
  1255. if (FPMO->hasAllowReassoc())
  1256. Flags |= bitc::AllowReassoc;
  1257. if (FPMO->hasNoNaNs())
  1258. Flags |= bitc::NoNaNs;
  1259. if (FPMO->hasNoInfs())
  1260. Flags |= bitc::NoInfs;
  1261. if (FPMO->hasNoSignedZeros())
  1262. Flags |= bitc::NoSignedZeros;
  1263. if (FPMO->hasAllowReciprocal())
  1264. Flags |= bitc::AllowReciprocal;
  1265. if (FPMO->hasAllowContract())
  1266. Flags |= bitc::AllowContract;
  1267. if (FPMO->hasApproxFunc())
  1268. Flags |= bitc::ApproxFunc;
  1269. }
  1270. return Flags;
  1271. }
  1272. void ModuleBitcodeWriter::writeValueAsMetadata(
  1273. const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
  1274. // Mimic an MDNode with a value as one operand.
  1275. Value *V = MD->getValue();
  1276. Record.push_back(VE.getTypeID(V->getType()));
  1277. Record.push_back(VE.getValueID(V));
  1278. Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
  1279. Record.clear();
  1280. }
  1281. void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
  1282. SmallVectorImpl<uint64_t> &Record,
  1283. unsigned Abbrev) {
  1284. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  1285. Metadata *MD = N->getOperand(i);
  1286. assert(!(MD && isa<LocalAsMetadata>(MD)) &&
  1287. "Unexpected function-local metadata");
  1288. Record.push_back(VE.getMetadataOrNullID(MD));
  1289. }
  1290. Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
  1291. : bitc::METADATA_NODE,
  1292. Record, Abbrev);
  1293. Record.clear();
  1294. }
  1295. unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
  1296. // Assume the column is usually under 128, and always output the inlined-at
  1297. // location (it's never more expensive than building an array size 1).
  1298. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1299. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
  1300. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1301. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1302. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1303. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1304. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1305. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1306. return Stream.EmitAbbrev(std::move(Abbv));
  1307. }
  1308. void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
  1309. SmallVectorImpl<uint64_t> &Record,
  1310. unsigned &Abbrev) {
  1311. if (!Abbrev)
  1312. Abbrev = createDILocationAbbrev();
  1313. Record.push_back(N->isDistinct());
  1314. Record.push_back(N->getLine());
  1315. Record.push_back(N->getColumn());
  1316. Record.push_back(VE.getMetadataID(N->getScope()));
  1317. Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
  1318. Record.push_back(N->isImplicitCode());
  1319. Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
  1320. Record.clear();
  1321. }
  1322. unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
  1323. // Assume the column is usually under 128, and always output the inlined-at
  1324. // location (it's never more expensive than building an array size 1).
  1325. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1326. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
  1327. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1328. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1329. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1330. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1331. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1332. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1333. return Stream.EmitAbbrev(std::move(Abbv));
  1334. }
  1335. void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
  1336. SmallVectorImpl<uint64_t> &Record,
  1337. unsigned &Abbrev) {
  1338. if (!Abbrev)
  1339. Abbrev = createGenericDINodeAbbrev();
  1340. Record.push_back(N->isDistinct());
  1341. Record.push_back(N->getTag());
  1342. Record.push_back(0); // Per-tag version field; unused for now.
  1343. for (auto &I : N->operands())
  1344. Record.push_back(VE.getMetadataOrNullID(I));
  1345. Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
  1346. Record.clear();
  1347. }
  1348. static uint64_t rotateSign(int64_t I) {
  1349. uint64_t U = I;
  1350. return I < 0 ? ~(U << 1) : U << 1;
  1351. }
  1352. void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
  1353. SmallVectorImpl<uint64_t> &Record,
  1354. unsigned Abbrev) {
  1355. const uint64_t Version = 1 << 1;
  1356. Record.push_back((uint64_t)N->isDistinct() | Version);
  1357. Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
  1358. Record.push_back(rotateSign(N->getLowerBound()));
  1359. Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
  1360. Record.clear();
  1361. }
  1362. void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
  1363. SmallVectorImpl<uint64_t> &Record,
  1364. unsigned Abbrev) {
  1365. Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
  1366. Record.push_back(rotateSign(N->getValue()));
  1367. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1368. Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
  1369. Record.clear();
  1370. }
  1371. void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
  1372. SmallVectorImpl<uint64_t> &Record,
  1373. unsigned Abbrev) {
  1374. Record.push_back(N->isDistinct());
  1375. Record.push_back(N->getTag());
  1376. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1377. Record.push_back(N->getSizeInBits());
  1378. Record.push_back(N->getAlignInBits());
  1379. Record.push_back(N->getEncoding());
  1380. Record.push_back(N->getFlags());
  1381. Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
  1382. Record.clear();
  1383. }
  1384. void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
  1385. SmallVectorImpl<uint64_t> &Record,
  1386. unsigned Abbrev) {
  1387. Record.push_back(N->isDistinct());
  1388. Record.push_back(N->getTag());
  1389. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1390. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1391. Record.push_back(N->getLine());
  1392. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1393. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  1394. Record.push_back(N->getSizeInBits());
  1395. Record.push_back(N->getAlignInBits());
  1396. Record.push_back(N->getOffsetInBits());
  1397. Record.push_back(N->getFlags());
  1398. Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
  1399. // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
  1400. // that there is no DWARF address space associated with DIDerivedType.
  1401. if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
  1402. Record.push_back(*DWARFAddressSpace + 1);
  1403. else
  1404. Record.push_back(0);
  1405. Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
  1406. Record.clear();
  1407. }
  1408. void ModuleBitcodeWriter::writeDICompositeType(
  1409. const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
  1410. unsigned Abbrev) {
  1411. const unsigned IsNotUsedInOldTypeRef = 0x2;
  1412. Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
  1413. Record.push_back(N->getTag());
  1414. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1415. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1416. Record.push_back(N->getLine());
  1417. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1418. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  1419. Record.push_back(N->getSizeInBits());
  1420. Record.push_back(N->getAlignInBits());
  1421. Record.push_back(N->getOffsetInBits());
  1422. Record.push_back(N->getFlags());
  1423. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  1424. Record.push_back(N->getRuntimeLang());
  1425. Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
  1426. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  1427. Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
  1428. Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
  1429. Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
  1430. Record.clear();
  1431. }
  1432. void ModuleBitcodeWriter::writeDISubroutineType(
  1433. const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
  1434. unsigned Abbrev) {
  1435. const unsigned HasNoOldTypeRefs = 0x2;
  1436. Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
  1437. Record.push_back(N->getFlags());
  1438. Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
  1439. Record.push_back(N->getCC());
  1440. Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
  1441. Record.clear();
  1442. }
  1443. void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
  1444. SmallVectorImpl<uint64_t> &Record,
  1445. unsigned Abbrev) {
  1446. Record.push_back(N->isDistinct());
  1447. Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
  1448. Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
  1449. if (N->getRawChecksum()) {
  1450. Record.push_back(N->getRawChecksum()->Kind);
  1451. Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
  1452. } else {
  1453. // Maintain backwards compatibility with the old internal representation of
  1454. // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
  1455. Record.push_back(0);
  1456. Record.push_back(VE.getMetadataOrNullID(nullptr));
  1457. }
  1458. auto Source = N->getRawSource();
  1459. if (Source)
  1460. Record.push_back(VE.getMetadataOrNullID(*Source));
  1461. Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
  1462. Record.clear();
  1463. }
  1464. void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
  1465. SmallVectorImpl<uint64_t> &Record,
  1466. unsigned Abbrev) {
  1467. assert(N->isDistinct() && "Expected distinct compile units");
  1468. Record.push_back(/* IsDistinct */ true);
  1469. Record.push_back(N->getSourceLanguage());
  1470. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1471. Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
  1472. Record.push_back(N->isOptimized());
  1473. Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
  1474. Record.push_back(N->getRuntimeVersion());
  1475. Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
  1476. Record.push_back(N->getEmissionKind());
  1477. Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
  1478. Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
  1479. Record.push_back(/* subprograms */ 0);
  1480. Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
  1481. Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
  1482. Record.push_back(N->getDWOId());
  1483. Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
  1484. Record.push_back(N->getSplitDebugInlining());
  1485. Record.push_back(N->getDebugInfoForProfiling());
  1486. Record.push_back((unsigned)N->getNameTableKind());
  1487. Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
  1488. Record.clear();
  1489. }
  1490. void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
  1491. SmallVectorImpl<uint64_t> &Record,
  1492. unsigned Abbrev) {
  1493. const uint64_t HasUnitFlag = 1 << 1;
  1494. const uint64_t HasSPFlagsFlag = 1 << 2;
  1495. Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
  1496. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1497. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1498. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1499. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1500. Record.push_back(N->getLine());
  1501. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1502. Record.push_back(N->getScopeLine());
  1503. Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
  1504. Record.push_back(N->getSPFlags());
  1505. Record.push_back(N->getVirtualIndex());
  1506. Record.push_back(N->getFlags());
  1507. Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
  1508. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  1509. Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
  1510. Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
  1511. Record.push_back(N->getThisAdjustment());
  1512. Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
  1513. Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
  1514. Record.clear();
  1515. }
  1516. void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
  1517. SmallVectorImpl<uint64_t> &Record,
  1518. unsigned Abbrev) {
  1519. Record.push_back(N->isDistinct());
  1520. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1521. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1522. Record.push_back(N->getLine());
  1523. Record.push_back(N->getColumn());
  1524. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
  1525. Record.clear();
  1526. }
  1527. void ModuleBitcodeWriter::writeDILexicalBlockFile(
  1528. const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
  1529. unsigned Abbrev) {
  1530. Record.push_back(N->isDistinct());
  1531. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1532. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1533. Record.push_back(N->getDiscriminator());
  1534. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
  1535. Record.clear();
  1536. }
  1537. void ModuleBitcodeWriter::writeDICommonBlock(const DICommonBlock *N,
  1538. SmallVectorImpl<uint64_t> &Record,
  1539. unsigned Abbrev) {
  1540. Record.push_back(N->isDistinct());
  1541. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1542. Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
  1543. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1544. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1545. Record.push_back(N->getLineNo());
  1546. Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
  1547. Record.clear();
  1548. }
  1549. void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
  1550. SmallVectorImpl<uint64_t> &Record,
  1551. unsigned Abbrev) {
  1552. Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
  1553. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1554. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1555. Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
  1556. Record.clear();
  1557. }
  1558. void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
  1559. SmallVectorImpl<uint64_t> &Record,
  1560. unsigned Abbrev) {
  1561. Record.push_back(N->isDistinct());
  1562. Record.push_back(N->getMacinfoType());
  1563. Record.push_back(N->getLine());
  1564. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1565. Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
  1566. Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
  1567. Record.clear();
  1568. }
  1569. void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
  1570. SmallVectorImpl<uint64_t> &Record,
  1571. unsigned Abbrev) {
  1572. Record.push_back(N->isDistinct());
  1573. Record.push_back(N->getMacinfoType());
  1574. Record.push_back(N->getLine());
  1575. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1576. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  1577. Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
  1578. Record.clear();
  1579. }
  1580. void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
  1581. SmallVectorImpl<uint64_t> &Record,
  1582. unsigned Abbrev) {
  1583. Record.push_back(N->isDistinct());
  1584. for (auto &I : N->operands())
  1585. Record.push_back(VE.getMetadataOrNullID(I));
  1586. Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
  1587. Record.clear();
  1588. }
  1589. void ModuleBitcodeWriter::writeDITemplateTypeParameter(
  1590. const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
  1591. unsigned Abbrev) {
  1592. Record.push_back(N->isDistinct());
  1593. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1594. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1595. Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
  1596. Record.clear();
  1597. }
  1598. void ModuleBitcodeWriter::writeDITemplateValueParameter(
  1599. const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
  1600. unsigned Abbrev) {
  1601. Record.push_back(N->isDistinct());
  1602. Record.push_back(N->getTag());
  1603. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1604. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1605. Record.push_back(VE.getMetadataOrNullID(N->getValue()));
  1606. Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
  1607. Record.clear();
  1608. }
  1609. void ModuleBitcodeWriter::writeDIGlobalVariable(
  1610. const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
  1611. unsigned Abbrev) {
  1612. const uint64_t Version = 2 << 1;
  1613. Record.push_back((uint64_t)N->isDistinct() | Version);
  1614. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1615. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1616. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1617. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1618. Record.push_back(N->getLine());
  1619. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1620. Record.push_back(N->isLocalToUnit());
  1621. Record.push_back(N->isDefinition());
  1622. Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
  1623. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
  1624. Record.push_back(N->getAlignInBits());
  1625. Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
  1626. Record.clear();
  1627. }
  1628. void ModuleBitcodeWriter::writeDILocalVariable(
  1629. const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
  1630. unsigned Abbrev) {
  1631. // In order to support all possible bitcode formats in BitcodeReader we need
  1632. // to distinguish the following cases:
  1633. // 1) Record has no artificial tag (Record[1]),
  1634. // has no obsolete inlinedAt field (Record[9]).
  1635. // In this case Record size will be 8, HasAlignment flag is false.
  1636. // 2) Record has artificial tag (Record[1]),
  1637. // has no obsolete inlignedAt field (Record[9]).
  1638. // In this case Record size will be 9, HasAlignment flag is false.
  1639. // 3) Record has both artificial tag (Record[1]) and
  1640. // obsolete inlignedAt field (Record[9]).
  1641. // In this case Record size will be 10, HasAlignment flag is false.
  1642. // 4) Record has neither artificial tag, nor inlignedAt field, but
  1643. // HasAlignment flag is true and Record[8] contains alignment value.
  1644. const uint64_t HasAlignmentFlag = 1 << 1;
  1645. Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
  1646. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1647. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1648. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1649. Record.push_back(N->getLine());
  1650. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1651. Record.push_back(N->getArg());
  1652. Record.push_back(N->getFlags());
  1653. Record.push_back(N->getAlignInBits());
  1654. Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
  1655. Record.clear();
  1656. }
  1657. void ModuleBitcodeWriter::writeDILabel(
  1658. const DILabel *N, SmallVectorImpl<uint64_t> &Record,
  1659. unsigned Abbrev) {
  1660. Record.push_back((uint64_t)N->isDistinct());
  1661. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1662. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1663. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1664. Record.push_back(N->getLine());
  1665. Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
  1666. Record.clear();
  1667. }
  1668. void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
  1669. SmallVectorImpl<uint64_t> &Record,
  1670. unsigned Abbrev) {
  1671. Record.reserve(N->getElements().size() + 1);
  1672. const uint64_t Version = 3 << 1;
  1673. Record.push_back((uint64_t)N->isDistinct() | Version);
  1674. Record.append(N->elements_begin(), N->elements_end());
  1675. Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
  1676. Record.clear();
  1677. }
  1678. void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
  1679. const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
  1680. unsigned Abbrev) {
  1681. Record.push_back(N->isDistinct());
  1682. Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
  1683. Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
  1684. Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
  1685. Record.clear();
  1686. }
  1687. void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
  1688. SmallVectorImpl<uint64_t> &Record,
  1689. unsigned Abbrev) {
  1690. Record.push_back(N->isDistinct());
  1691. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1692. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1693. Record.push_back(N->getLine());
  1694. Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
  1695. Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
  1696. Record.push_back(N->getAttributes());
  1697. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1698. Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
  1699. Record.clear();
  1700. }
  1701. void ModuleBitcodeWriter::writeDIImportedEntity(
  1702. const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
  1703. unsigned Abbrev) {
  1704. Record.push_back(N->isDistinct());
  1705. Record.push_back(N->getTag());
  1706. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1707. Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
  1708. Record.push_back(N->getLine());
  1709. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1710. Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
  1711. Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
  1712. Record.clear();
  1713. }
  1714. unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
  1715. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1716. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
  1717. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1718. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1719. return Stream.EmitAbbrev(std::move(Abbv));
  1720. }
  1721. void ModuleBitcodeWriter::writeNamedMetadata(
  1722. SmallVectorImpl<uint64_t> &Record) {
  1723. if (M.named_metadata_empty())
  1724. return;
  1725. unsigned Abbrev = createNamedMetadataAbbrev();
  1726. for (const NamedMDNode &NMD : M.named_metadata()) {
  1727. // Write name.
  1728. StringRef Str = NMD.getName();
  1729. Record.append(Str.bytes_begin(), Str.bytes_end());
  1730. Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
  1731. Record.clear();
  1732. // Write named metadata operands.
  1733. for (const MDNode *N : NMD.operands())
  1734. Record.push_back(VE.getMetadataID(N));
  1735. Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
  1736. Record.clear();
  1737. }
  1738. }
  1739. unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
  1740. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1741. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
  1742. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
  1743. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
  1744. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1745. return Stream.EmitAbbrev(std::move(Abbv));
  1746. }
  1747. /// Write out a record for MDString.
  1748. ///
  1749. /// All the metadata strings in a metadata block are emitted in a single
  1750. /// record. The sizes and strings themselves are shoved into a blob.
  1751. void ModuleBitcodeWriter::writeMetadataStrings(
  1752. ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
  1753. if (Strings.empty())
  1754. return;
  1755. // Start the record with the number of strings.
  1756. Record.push_back(bitc::METADATA_STRINGS);
  1757. Record.push_back(Strings.size());
  1758. // Emit the sizes of the strings in the blob.
  1759. SmallString<256> Blob;
  1760. {
  1761. BitstreamWriter W(Blob);
  1762. for (const Metadata *MD : Strings)
  1763. W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
  1764. W.FlushToWord();
  1765. }
  1766. // Add the offset to the strings to the record.
  1767. Record.push_back(Blob.size());
  1768. // Add the strings to the blob.
  1769. for (const Metadata *MD : Strings)
  1770. Blob.append(cast<MDString>(MD)->getString());
  1771. // Emit the final record.
  1772. Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
  1773. Record.clear();
  1774. }
  1775. // Generates an enum to use as an index in the Abbrev array of Metadata record.
  1776. enum MetadataAbbrev : unsigned {
  1777. #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
  1778. #include "llvm/IR/Metadata.def"
  1779. LastPlusOne
  1780. };
  1781. void ModuleBitcodeWriter::writeMetadataRecords(
  1782. ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
  1783. std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
  1784. if (MDs.empty())
  1785. return;
  1786. // Initialize MDNode abbreviations.
  1787. #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
  1788. #include "llvm/IR/Metadata.def"
  1789. for (const Metadata *MD : MDs) {
  1790. if (IndexPos)
  1791. IndexPos->push_back(Stream.GetCurrentBitNo());
  1792. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  1793. assert(N->isResolved() && "Expected forward references to be resolved");
  1794. switch (N->getMetadataID()) {
  1795. default:
  1796. llvm_unreachable("Invalid MDNode subclass");
  1797. #define HANDLE_MDNODE_LEAF(CLASS) \
  1798. case Metadata::CLASS##Kind: \
  1799. if (MDAbbrevs) \
  1800. write##CLASS(cast<CLASS>(N), Record, \
  1801. (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
  1802. else \
  1803. write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
  1804. continue;
  1805. #include "llvm/IR/Metadata.def"
  1806. }
  1807. }
  1808. writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
  1809. }
  1810. }
  1811. void ModuleBitcodeWriter::writeModuleMetadata() {
  1812. if (!VE.hasMDs() && M.named_metadata_empty())
  1813. return;
  1814. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
  1815. SmallVector<uint64_t, 64> Record;
  1816. // Emit all abbrevs upfront, so that the reader can jump in the middle of the
  1817. // block and load any metadata.
  1818. std::vector<unsigned> MDAbbrevs;
  1819. MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
  1820. MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
  1821. MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
  1822. createGenericDINodeAbbrev();
  1823. auto Abbv = std::make_shared<BitCodeAbbrev>();
  1824. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
  1825. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1826. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1827. unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1828. Abbv = std::make_shared<BitCodeAbbrev>();
  1829. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
  1830. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1831. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1832. unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  1833. // Emit MDStrings together upfront.
  1834. writeMetadataStrings(VE.getMDStrings(), Record);
  1835. // We only emit an index for the metadata record if we have more than a given
  1836. // (naive) threshold of metadatas, otherwise it is not worth it.
  1837. if (VE.getNonMDStrings().size() > IndexThreshold) {
  1838. // Write a placeholder value in for the offset of the metadata index,
  1839. // which is written after the records, so that it can include
  1840. // the offset of each entry. The placeholder offset will be
  1841. // updated after all records are emitted.
  1842. uint64_t Vals[] = {0, 0};
  1843. Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
  1844. }
  1845. // Compute and save the bit offset to the current position, which will be
  1846. // patched when we emit the index later. We can simply subtract the 64-bit
  1847. // fixed size from the current bit number to get the location to backpatch.
  1848. uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
  1849. // This index will contain the bitpos for each individual record.
  1850. std::vector<uint64_t> IndexPos;
  1851. IndexPos.reserve(VE.getNonMDStrings().size());
  1852. // Write all the records
  1853. writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
  1854. if (VE.getNonMDStrings().size() > IndexThreshold) {
  1855. // Now that we have emitted all the records we will emit the index. But
  1856. // first
  1857. // backpatch the forward reference so that the reader can skip the records
  1858. // efficiently.
  1859. Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
  1860. Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
  1861. // Delta encode the index.
  1862. uint64_t PreviousValue = IndexOffsetRecordBitPos;
  1863. for (auto &Elt : IndexPos) {
  1864. auto EltDelta = Elt - PreviousValue;
  1865. PreviousValue = Elt;
  1866. Elt = EltDelta;
  1867. }
  1868. // Emit the index record.
  1869. Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
  1870. IndexPos.clear();
  1871. }
  1872. // Write the named metadata now.
  1873. writeNamedMetadata(Record);
  1874. auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
  1875. SmallVector<uint64_t, 4> Record;
  1876. Record.push_back(VE.getValueID(&GO));
  1877. pushGlobalMetadataAttachment(Record, GO);
  1878. Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
  1879. };
  1880. for (const Function &F : M)
  1881. if (F.isDeclaration() && F.hasMetadata())
  1882. AddDeclAttachedMetadata(F);
  1883. // FIXME: Only store metadata for declarations here, and move data for global
  1884. // variable definitions to a separate block (PR28134).
  1885. for (const GlobalVariable &GV : M.globals())
  1886. if (GV.hasMetadata())
  1887. AddDeclAttachedMetadata(GV);
  1888. Stream.ExitBlock();
  1889. }
  1890. void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
  1891. if (!VE.hasMDs())
  1892. return;
  1893. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  1894. SmallVector<uint64_t, 64> Record;
  1895. writeMetadataStrings(VE.getMDStrings(), Record);
  1896. writeMetadataRecords(VE.getNonMDStrings(), Record);
  1897. Stream.ExitBlock();
  1898. }
  1899. void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
  1900. SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
  1901. // [n x [id, mdnode]]
  1902. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1903. GO.getAllMetadata(MDs);
  1904. for (const auto &I : MDs) {
  1905. Record.push_back(I.first);
  1906. Record.push_back(VE.getMetadataID(I.second));
  1907. }
  1908. }
  1909. void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
  1910. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  1911. SmallVector<uint64_t, 64> Record;
  1912. if (F.hasMetadata()) {
  1913. pushGlobalMetadataAttachment(Record, F);
  1914. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1915. Record.clear();
  1916. }
  1917. // Write metadata attachments
  1918. // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
  1919. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1920. for (const BasicBlock &BB : F)
  1921. for (const Instruction &I : BB) {
  1922. MDs.clear();
  1923. I.getAllMetadataOtherThanDebugLoc(MDs);
  1924. // If no metadata, ignore instruction.
  1925. if (MDs.empty()) continue;
  1926. Record.push_back(VE.getInstructionID(&I));
  1927. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  1928. Record.push_back(MDs[i].first);
  1929. Record.push_back(VE.getMetadataID(MDs[i].second));
  1930. }
  1931. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1932. Record.clear();
  1933. }
  1934. Stream.ExitBlock();
  1935. }
  1936. void ModuleBitcodeWriter::writeModuleMetadataKinds() {
  1937. SmallVector<uint64_t, 64> Record;
  1938. // Write metadata kinds
  1939. // METADATA_KIND - [n x [id, name]]
  1940. SmallVector<StringRef, 8> Names;
  1941. M.getMDKindNames(Names);
  1942. if (Names.empty()) return;
  1943. Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
  1944. for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
  1945. Record.push_back(MDKindID);
  1946. StringRef KName = Names[MDKindID];
  1947. Record.append(KName.begin(), KName.end());
  1948. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  1949. Record.clear();
  1950. }
  1951. Stream.ExitBlock();
  1952. }
  1953. void ModuleBitcodeWriter::writeOperandBundleTags() {
  1954. // Write metadata kinds
  1955. //
  1956. // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
  1957. //
  1958. // OPERAND_BUNDLE_TAG - [strchr x N]
  1959. SmallVector<StringRef, 8> Tags;
  1960. M.getOperandBundleTags(Tags);
  1961. if (Tags.empty())
  1962. return;
  1963. Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
  1964. SmallVector<uint64_t, 64> Record;
  1965. for (auto Tag : Tags) {
  1966. Record.append(Tag.begin(), Tag.end());
  1967. Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
  1968. Record.clear();
  1969. }
  1970. Stream.ExitBlock();
  1971. }
  1972. void ModuleBitcodeWriter::writeSyncScopeNames() {
  1973. SmallVector<StringRef, 8> SSNs;
  1974. M.getContext().getSyncScopeNames(SSNs);
  1975. if (SSNs.empty())
  1976. return;
  1977. Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
  1978. SmallVector<uint64_t, 64> Record;
  1979. for (auto SSN : SSNs) {
  1980. Record.append(SSN.begin(), SSN.end());
  1981. Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
  1982. Record.clear();
  1983. }
  1984. Stream.ExitBlock();
  1985. }
  1986. static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
  1987. if ((int64_t)V >= 0)
  1988. Vals.push_back(V << 1);
  1989. else
  1990. Vals.push_back((-V << 1) | 1);
  1991. }
  1992. void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
  1993. bool isGlobal) {
  1994. if (FirstVal == LastVal) return;
  1995. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  1996. unsigned AggregateAbbrev = 0;
  1997. unsigned String8Abbrev = 0;
  1998. unsigned CString7Abbrev = 0;
  1999. unsigned CString6Abbrev = 0;
  2000. // If this is a constant pool for the module, emit module-specific abbrevs.
  2001. if (isGlobal) {
  2002. // Abbrev for CST_CODE_AGGREGATE.
  2003. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2004. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  2005. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2006. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  2007. AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  2008. // Abbrev for CST_CODE_STRING.
  2009. Abbv = std::make_shared<BitCodeAbbrev>();
  2010. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  2011. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2012. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2013. String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
  2014. // Abbrev for CST_CODE_CSTRING.
  2015. Abbv = std::make_shared<BitCodeAbbrev>();
  2016. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  2017. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2018. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2019. CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
  2020. // Abbrev for CST_CODE_CSTRING.
  2021. Abbv = std::make_shared<BitCodeAbbrev>();
  2022. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  2023. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2024. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2025. CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
  2026. }
  2027. SmallVector<uint64_t, 64> Record;
  2028. const ValueEnumerator::ValueList &Vals = VE.getValues();
  2029. Type *LastTy = nullptr;
  2030. for (unsigned i = FirstVal; i != LastVal; ++i) {
  2031. const Value *V = Vals[i].first;
  2032. // If we need to switch types, do so now.
  2033. if (V->getType() != LastTy) {
  2034. LastTy = V->getType();
  2035. Record.push_back(VE.getTypeID(LastTy));
  2036. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  2037. CONSTANTS_SETTYPE_ABBREV);
  2038. Record.clear();
  2039. }
  2040. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  2041. Record.push_back(unsigned(IA->hasSideEffects()) |
  2042. unsigned(IA->isAlignStack()) << 1 |
  2043. unsigned(IA->getDialect()&1) << 2);
  2044. // Add the asm string.
  2045. const std::string &AsmStr = IA->getAsmString();
  2046. Record.push_back(AsmStr.size());
  2047. Record.append(AsmStr.begin(), AsmStr.end());
  2048. // Add the constraint string.
  2049. const std::string &ConstraintStr = IA->getConstraintString();
  2050. Record.push_back(ConstraintStr.size());
  2051. Record.append(ConstraintStr.begin(), ConstraintStr.end());
  2052. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  2053. Record.clear();
  2054. continue;
  2055. }
  2056. const Constant *C = cast<Constant>(V);
  2057. unsigned Code = -1U;
  2058. unsigned AbbrevToUse = 0;
  2059. if (C->isNullValue()) {
  2060. Code = bitc::CST_CODE_NULL;
  2061. } else if (isa<UndefValue>(C)) {
  2062. Code = bitc::CST_CODE_UNDEF;
  2063. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  2064. if (IV->getBitWidth() <= 64) {
  2065. uint64_t V = IV->getSExtValue();
  2066. emitSignedInt64(Record, V);
  2067. Code = bitc::CST_CODE_INTEGER;
  2068. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  2069. } else { // Wide integers, > 64 bits in size.
  2070. // We have an arbitrary precision integer value to write whose
  2071. // bit width is > 64. However, in canonical unsigned integer
  2072. // format it is likely that the high bits are going to be zero.
  2073. // So, we only write the number of active words.
  2074. unsigned NWords = IV->getValue().getActiveWords();
  2075. const uint64_t *RawWords = IV->getValue().getRawData();
  2076. for (unsigned i = 0; i != NWords; ++i) {
  2077. emitSignedInt64(Record, RawWords[i]);
  2078. }
  2079. Code = bitc::CST_CODE_WIDE_INTEGER;
  2080. }
  2081. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  2082. Code = bitc::CST_CODE_FLOAT;
  2083. Type *Ty = CFP->getType();
  2084. if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
  2085. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  2086. } else if (Ty->isX86_FP80Ty()) {
  2087. // api needed to prevent premature destruction
  2088. // bits are not in the same order as a normal i80 APInt, compensate.
  2089. APInt api = CFP->getValueAPF().bitcastToAPInt();
  2090. const uint64_t *p = api.getRawData();
  2091. Record.push_back((p[1] << 48) | (p[0] >> 16));
  2092. Record.push_back(p[0] & 0xffffLL);
  2093. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  2094. APInt api = CFP->getValueAPF().bitcastToAPInt();
  2095. const uint64_t *p = api.getRawData();
  2096. Record.push_back(p[0]);
  2097. Record.push_back(p[1]);
  2098. } else {
  2099. assert(0 && "Unknown FP type!");
  2100. }
  2101. } else if (isa<ConstantDataSequential>(C) &&
  2102. cast<ConstantDataSequential>(C)->isString()) {
  2103. const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
  2104. // Emit constant strings specially.
  2105. unsigned NumElts = Str->getNumElements();
  2106. // If this is a null-terminated string, use the denser CSTRING encoding.
  2107. if (Str->isCString()) {
  2108. Code = bitc::CST_CODE_CSTRING;
  2109. --NumElts; // Don't encode the null, which isn't allowed by char6.
  2110. } else {
  2111. Code = bitc::CST_CODE_STRING;
  2112. AbbrevToUse = String8Abbrev;
  2113. }
  2114. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  2115. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  2116. for (unsigned i = 0; i != NumElts; ++i) {
  2117. unsigned char V = Str->getElementAsInteger(i);
  2118. Record.push_back(V);
  2119. isCStr7 &= (V & 128) == 0;
  2120. if (isCStrChar6)
  2121. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  2122. }
  2123. if (isCStrChar6)
  2124. AbbrevToUse = CString6Abbrev;
  2125. else if (isCStr7)
  2126. AbbrevToUse = CString7Abbrev;
  2127. } else if (const ConstantDataSequential *CDS =
  2128. dyn_cast<ConstantDataSequential>(C)) {
  2129. Code = bitc::CST_CODE_DATA;
  2130. Type *EltTy = CDS->getType()->getElementType();
  2131. if (isa<IntegerType>(EltTy)) {
  2132. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  2133. Record.push_back(CDS->getElementAsInteger(i));
  2134. } else {
  2135. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  2136. Record.push_back(
  2137. CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
  2138. }
  2139. } else if (isa<ConstantAggregate>(C)) {
  2140. Code = bitc::CST_CODE_AGGREGATE;
  2141. for (const Value *Op : C->operands())
  2142. Record.push_back(VE.getValueID(Op));
  2143. AbbrevToUse = AggregateAbbrev;
  2144. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  2145. switch (CE->getOpcode()) {
  2146. default:
  2147. if (Instruction::isCast(CE->getOpcode())) {
  2148. Code = bitc::CST_CODE_CE_CAST;
  2149. Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
  2150. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2151. Record.push_back(VE.getValueID(C->getOperand(0)));
  2152. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  2153. } else {
  2154. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  2155. Code = bitc::CST_CODE_CE_BINOP;
  2156. Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
  2157. Record.push_back(VE.getValueID(C->getOperand(0)));
  2158. Record.push_back(VE.getValueID(C->getOperand(1)));
  2159. uint64_t Flags = getOptimizationFlags(CE);
  2160. if (Flags != 0)
  2161. Record.push_back(Flags);
  2162. }
  2163. break;
  2164. case Instruction::FNeg: {
  2165. assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
  2166. Code = bitc::CST_CODE_CE_UNOP;
  2167. Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
  2168. Record.push_back(VE.getValueID(C->getOperand(0)));
  2169. uint64_t Flags = getOptimizationFlags(CE);
  2170. if (Flags != 0)
  2171. Record.push_back(Flags);
  2172. break;
  2173. }
  2174. case Instruction::GetElementPtr: {
  2175. Code = bitc::CST_CODE_CE_GEP;
  2176. const auto *GO = cast<GEPOperator>(C);
  2177. Record.push_back(VE.getTypeID(GO->getSourceElementType()));
  2178. if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
  2179. Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
  2180. Record.push_back((*Idx << 1) | GO->isInBounds());
  2181. } else if (GO->isInBounds())
  2182. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  2183. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  2184. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  2185. Record.push_back(VE.getValueID(C->getOperand(i)));
  2186. }
  2187. break;
  2188. }
  2189. case Instruction::Select:
  2190. Code = bitc::CST_CODE_CE_SELECT;
  2191. Record.push_back(VE.getValueID(C->getOperand(0)));
  2192. Record.push_back(VE.getValueID(C->getOperand(1)));
  2193. Record.push_back(VE.getValueID(C->getOperand(2)));
  2194. break;
  2195. case Instruction::ExtractElement:
  2196. Code = bitc::CST_CODE_CE_EXTRACTELT;
  2197. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2198. Record.push_back(VE.getValueID(C->getOperand(0)));
  2199. Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
  2200. Record.push_back(VE.getValueID(C->getOperand(1)));
  2201. break;
  2202. case Instruction::InsertElement:
  2203. Code = bitc::CST_CODE_CE_INSERTELT;
  2204. Record.push_back(VE.getValueID(C->getOperand(0)));
  2205. Record.push_back(VE.getValueID(C->getOperand(1)));
  2206. Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
  2207. Record.push_back(VE.getValueID(C->getOperand(2)));
  2208. break;
  2209. case Instruction::ShuffleVector:
  2210. // If the return type and argument types are the same, this is a
  2211. // standard shufflevector instruction. If the types are different,
  2212. // then the shuffle is widening or truncating the input vectors, and
  2213. // the argument type must also be encoded.
  2214. if (C->getType() == C->getOperand(0)->getType()) {
  2215. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  2216. } else {
  2217. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  2218. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2219. }
  2220. Record.push_back(VE.getValueID(C->getOperand(0)));
  2221. Record.push_back(VE.getValueID(C->getOperand(1)));
  2222. Record.push_back(VE.getValueID(C->getOperand(2)));
  2223. break;
  2224. case Instruction::ICmp:
  2225. case Instruction::FCmp:
  2226. Code = bitc::CST_CODE_CE_CMP;
  2227. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  2228. Record.push_back(VE.getValueID(C->getOperand(0)));
  2229. Record.push_back(VE.getValueID(C->getOperand(1)));
  2230. Record.push_back(CE->getPredicate());
  2231. break;
  2232. }
  2233. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  2234. Code = bitc::CST_CODE_BLOCKADDRESS;
  2235. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  2236. Record.push_back(VE.getValueID(BA->getFunction()));
  2237. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  2238. } else {
  2239. #ifndef NDEBUG
  2240. C->dump();
  2241. #endif
  2242. llvm_unreachable("Unknown constant!");
  2243. }
  2244. Stream.EmitRecord(Code, Record, AbbrevToUse);
  2245. Record.clear();
  2246. }
  2247. Stream.ExitBlock();
  2248. }
  2249. void ModuleBitcodeWriter::writeModuleConstants() {
  2250. const ValueEnumerator::ValueList &Vals = VE.getValues();
  2251. // Find the first constant to emit, which is the first non-globalvalue value.
  2252. // We know globalvalues have been emitted by WriteModuleInfo.
  2253. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  2254. if (!isa<GlobalValue>(Vals[i].first)) {
  2255. writeConstants(i, Vals.size(), true);
  2256. return;
  2257. }
  2258. }
  2259. }
  2260. /// pushValueAndType - The file has to encode both the value and type id for
  2261. /// many values, because we need to know what type to create for forward
  2262. /// references. However, most operands are not forward references, so this type
  2263. /// field is not needed.
  2264. ///
  2265. /// This function adds V's value ID to Vals. If the value ID is higher than the
  2266. /// instruction ID, then it is a forward reference, and it also includes the
  2267. /// type ID. The value ID that is written is encoded relative to the InstID.
  2268. bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
  2269. SmallVectorImpl<unsigned> &Vals) {
  2270. unsigned ValID = VE.getValueID(V);
  2271. // Make encoding relative to the InstID.
  2272. Vals.push_back(InstID - ValID);
  2273. if (ValID >= InstID) {
  2274. Vals.push_back(VE.getTypeID(V->getType()));
  2275. return true;
  2276. }
  2277. return false;
  2278. }
  2279. void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
  2280. unsigned InstID) {
  2281. SmallVector<unsigned, 64> Record;
  2282. LLVMContext &C = CS.getInstruction()->getContext();
  2283. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
  2284. const auto &Bundle = CS.getOperandBundleAt(i);
  2285. Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
  2286. for (auto &Input : Bundle.Inputs)
  2287. pushValueAndType(Input, InstID, Record);
  2288. Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
  2289. Record.clear();
  2290. }
  2291. }
  2292. /// pushValue - Like pushValueAndType, but where the type of the value is
  2293. /// omitted (perhaps it was already encoded in an earlier operand).
  2294. void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
  2295. SmallVectorImpl<unsigned> &Vals) {
  2296. unsigned ValID = VE.getValueID(V);
  2297. Vals.push_back(InstID - ValID);
  2298. }
  2299. void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
  2300. SmallVectorImpl<uint64_t> &Vals) {
  2301. unsigned ValID = VE.getValueID(V);
  2302. int64_t diff = ((int32_t)InstID - (int32_t)ValID);
  2303. emitSignedInt64(Vals, diff);
  2304. }
  2305. /// WriteInstruction - Emit an instruction to the specified stream.
  2306. void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
  2307. unsigned InstID,
  2308. SmallVectorImpl<unsigned> &Vals) {
  2309. unsigned Code = 0;
  2310. unsigned AbbrevToUse = 0;
  2311. VE.setInstructionID(&I);
  2312. switch (I.getOpcode()) {
  2313. default:
  2314. if (Instruction::isCast(I.getOpcode())) {
  2315. Code = bitc::FUNC_CODE_INST_CAST;
  2316. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2317. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  2318. Vals.push_back(VE.getTypeID(I.getType()));
  2319. Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
  2320. } else {
  2321. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  2322. Code = bitc::FUNC_CODE_INST_BINOP;
  2323. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2324. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  2325. pushValue(I.getOperand(1), InstID, Vals);
  2326. Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
  2327. uint64_t Flags = getOptimizationFlags(&I);
  2328. if (Flags != 0) {
  2329. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  2330. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  2331. Vals.push_back(Flags);
  2332. }
  2333. }
  2334. break;
  2335. case Instruction::FNeg: {
  2336. Code = bitc::FUNC_CODE_INST_UNOP;
  2337. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2338. AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
  2339. Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
  2340. uint64_t Flags = getOptimizationFlags(&I);
  2341. if (Flags != 0) {
  2342. if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
  2343. AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
  2344. Vals.push_back(Flags);
  2345. }
  2346. break;
  2347. }
  2348. case Instruction::GetElementPtr: {
  2349. Code = bitc::FUNC_CODE_INST_GEP;
  2350. AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
  2351. auto &GEPInst = cast<GetElementPtrInst>(I);
  2352. Vals.push_back(GEPInst.isInBounds());
  2353. Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
  2354. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  2355. pushValueAndType(I.getOperand(i), InstID, Vals);
  2356. break;
  2357. }
  2358. case Instruction::ExtractValue: {
  2359. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  2360. pushValueAndType(I.getOperand(0), InstID, Vals);
  2361. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  2362. Vals.append(EVI->idx_begin(), EVI->idx_end());
  2363. break;
  2364. }
  2365. case Instruction::InsertValue: {
  2366. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  2367. pushValueAndType(I.getOperand(0), InstID, Vals);
  2368. pushValueAndType(I.getOperand(1), InstID, Vals);
  2369. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  2370. Vals.append(IVI->idx_begin(), IVI->idx_end());
  2371. break;
  2372. }
  2373. case Instruction::Select: {
  2374. Code = bitc::FUNC_CODE_INST_VSELECT;
  2375. pushValueAndType(I.getOperand(1), InstID, Vals);
  2376. pushValue(I.getOperand(2), InstID, Vals);
  2377. pushValueAndType(I.getOperand(0), InstID, Vals);
  2378. uint64_t Flags = getOptimizationFlags(&I);
  2379. if (Flags != 0)
  2380. Vals.push_back(Flags);
  2381. break;
  2382. }
  2383. case Instruction::ExtractElement:
  2384. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  2385. pushValueAndType(I.getOperand(0), InstID, Vals);
  2386. pushValueAndType(I.getOperand(1), InstID, Vals);
  2387. break;
  2388. case Instruction::InsertElement:
  2389. Code = bitc::FUNC_CODE_INST_INSERTELT;
  2390. pushValueAndType(I.getOperand(0), InstID, Vals);
  2391. pushValue(I.getOperand(1), InstID, Vals);
  2392. pushValueAndType(I.getOperand(2), InstID, Vals);
  2393. break;
  2394. case Instruction::ShuffleVector:
  2395. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  2396. pushValueAndType(I.getOperand(0), InstID, Vals);
  2397. pushValue(I.getOperand(1), InstID, Vals);
  2398. pushValue(I.getOperand(2), InstID, Vals);
  2399. break;
  2400. case Instruction::ICmp:
  2401. case Instruction::FCmp: {
  2402. // compare returning Int1Ty or vector of Int1Ty
  2403. Code = bitc::FUNC_CODE_INST_CMP2;
  2404. pushValueAndType(I.getOperand(0), InstID, Vals);
  2405. pushValue(I.getOperand(1), InstID, Vals);
  2406. Vals.push_back(cast<CmpInst>(I).getPredicate());
  2407. uint64_t Flags = getOptimizationFlags(&I);
  2408. if (Flags != 0)
  2409. Vals.push_back(Flags);
  2410. break;
  2411. }
  2412. case Instruction::Ret:
  2413. {
  2414. Code = bitc::FUNC_CODE_INST_RET;
  2415. unsigned NumOperands = I.getNumOperands();
  2416. if (NumOperands == 0)
  2417. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  2418. else if (NumOperands == 1) {
  2419. if (!pushValueAndType(I.getOperand(0), InstID, Vals))
  2420. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  2421. } else {
  2422. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  2423. pushValueAndType(I.getOperand(i), InstID, Vals);
  2424. }
  2425. }
  2426. break;
  2427. case Instruction::Br:
  2428. {
  2429. Code = bitc::FUNC_CODE_INST_BR;
  2430. const BranchInst &II = cast<BranchInst>(I);
  2431. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  2432. if (II.isConditional()) {
  2433. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  2434. pushValue(II.getCondition(), InstID, Vals);
  2435. }
  2436. }
  2437. break;
  2438. case Instruction::Switch:
  2439. {
  2440. Code = bitc::FUNC_CODE_INST_SWITCH;
  2441. const SwitchInst &SI = cast<SwitchInst>(I);
  2442. Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
  2443. pushValue(SI.getCondition(), InstID, Vals);
  2444. Vals.push_back(VE.getValueID(SI.getDefaultDest()));
  2445. for (auto Case : SI.cases()) {
  2446. Vals.push_back(VE.getValueID(Case.getCaseValue()));
  2447. Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
  2448. }
  2449. }
  2450. break;
  2451. case Instruction::IndirectBr:
  2452. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  2453. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  2454. // Encode the address operand as relative, but not the basic blocks.
  2455. pushValue(I.getOperand(0), InstID, Vals);
  2456. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
  2457. Vals.push_back(VE.getValueID(I.getOperand(i)));
  2458. break;
  2459. case Instruction::Invoke: {
  2460. const InvokeInst *II = cast<InvokeInst>(&I);
  2461. const Value *Callee = II->getCalledValue();
  2462. FunctionType *FTy = II->getFunctionType();
  2463. if (II->hasOperandBundles())
  2464. writeOperandBundles(II, InstID);
  2465. Code = bitc::FUNC_CODE_INST_INVOKE;
  2466. Vals.push_back(VE.getAttributeListID(II->getAttributes()));
  2467. Vals.push_back(II->getCallingConv() | 1 << 13);
  2468. Vals.push_back(VE.getValueID(II->getNormalDest()));
  2469. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  2470. Vals.push_back(VE.getTypeID(FTy));
  2471. pushValueAndType(Callee, InstID, Vals);
  2472. // Emit value #'s for the fixed parameters.
  2473. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  2474. pushValue(I.getOperand(i), InstID, Vals); // fixed param.
  2475. // Emit type/value pairs for varargs params.
  2476. if (FTy->isVarArg()) {
  2477. for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
  2478. i != e; ++i)
  2479. pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
  2480. }
  2481. break;
  2482. }
  2483. case Instruction::Resume:
  2484. Code = bitc::FUNC_CODE_INST_RESUME;
  2485. pushValueAndType(I.getOperand(0), InstID, Vals);
  2486. break;
  2487. case Instruction::CleanupRet: {
  2488. Code = bitc::FUNC_CODE_INST_CLEANUPRET;
  2489. const auto &CRI = cast<CleanupReturnInst>(I);
  2490. pushValue(CRI.getCleanupPad(), InstID, Vals);
  2491. if (CRI.hasUnwindDest())
  2492. Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
  2493. break;
  2494. }
  2495. case Instruction::CatchRet: {
  2496. Code = bitc::FUNC_CODE_INST_CATCHRET;
  2497. const auto &CRI = cast<CatchReturnInst>(I);
  2498. pushValue(CRI.getCatchPad(), InstID, Vals);
  2499. Vals.push_back(VE.getValueID(CRI.getSuccessor()));
  2500. break;
  2501. }
  2502. case Instruction::CleanupPad:
  2503. case Instruction::CatchPad: {
  2504. const auto &FuncletPad = cast<FuncletPadInst>(I);
  2505. Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
  2506. : bitc::FUNC_CODE_INST_CLEANUPPAD;
  2507. pushValue(FuncletPad.getParentPad(), InstID, Vals);
  2508. unsigned NumArgOperands = FuncletPad.getNumArgOperands();
  2509. Vals.push_back(NumArgOperands);
  2510. for (unsigned Op = 0; Op != NumArgOperands; ++Op)
  2511. pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
  2512. break;
  2513. }
  2514. case Instruction::CatchSwitch: {
  2515. Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
  2516. const auto &CatchSwitch = cast<CatchSwitchInst>(I);
  2517. pushValue(CatchSwitch.getParentPad(), InstID, Vals);
  2518. unsigned NumHandlers = CatchSwitch.getNumHandlers();
  2519. Vals.push_back(NumHandlers);
  2520. for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
  2521. Vals.push_back(VE.getValueID(CatchPadBB));
  2522. if (CatchSwitch.hasUnwindDest())
  2523. Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
  2524. break;
  2525. }
  2526. case Instruction::CallBr: {
  2527. const CallBrInst *CBI = cast<CallBrInst>(&I);
  2528. const Value *Callee = CBI->getCalledValue();
  2529. FunctionType *FTy = CBI->getFunctionType();
  2530. if (CBI->hasOperandBundles())
  2531. writeOperandBundles(CBI, InstID);
  2532. Code = bitc::FUNC_CODE_INST_CALLBR;
  2533. Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
  2534. Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
  2535. 1 << bitc::CALL_EXPLICIT_TYPE);
  2536. Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
  2537. Vals.push_back(CBI->getNumIndirectDests());
  2538. for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
  2539. Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
  2540. Vals.push_back(VE.getTypeID(FTy));
  2541. pushValueAndType(Callee, InstID, Vals);
  2542. // Emit value #'s for the fixed parameters.
  2543. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  2544. pushValue(I.getOperand(i), InstID, Vals); // fixed param.
  2545. // Emit type/value pairs for varargs params.
  2546. if (FTy->isVarArg()) {
  2547. for (unsigned i = FTy->getNumParams(), e = CBI->getNumArgOperands();
  2548. i != e; ++i)
  2549. pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
  2550. }
  2551. break;
  2552. }
  2553. case Instruction::Unreachable:
  2554. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  2555. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  2556. break;
  2557. case Instruction::PHI: {
  2558. const PHINode &PN = cast<PHINode>(I);
  2559. Code = bitc::FUNC_CODE_INST_PHI;
  2560. // With the newer instruction encoding, forward references could give
  2561. // negative valued IDs. This is most common for PHIs, so we use
  2562. // signed VBRs.
  2563. SmallVector<uint64_t, 128> Vals64;
  2564. Vals64.push_back(VE.getTypeID(PN.getType()));
  2565. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  2566. pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
  2567. Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
  2568. }
  2569. // Emit a Vals64 vector and exit.
  2570. Stream.EmitRecord(Code, Vals64, AbbrevToUse);
  2571. Vals64.clear();
  2572. return;
  2573. }
  2574. case Instruction::LandingPad: {
  2575. const LandingPadInst &LP = cast<LandingPadInst>(I);
  2576. Code = bitc::FUNC_CODE_INST_LANDINGPAD;
  2577. Vals.push_back(VE.getTypeID(LP.getType()));
  2578. Vals.push_back(LP.isCleanup());
  2579. Vals.push_back(LP.getNumClauses());
  2580. for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
  2581. if (LP.isCatch(I))
  2582. Vals.push_back(LandingPadInst::Catch);
  2583. else
  2584. Vals.push_back(LandingPadInst::Filter);
  2585. pushValueAndType(LP.getClause(I), InstID, Vals);
  2586. }
  2587. break;
  2588. }
  2589. case Instruction::Alloca: {
  2590. Code = bitc::FUNC_CODE_INST_ALLOCA;
  2591. const AllocaInst &AI = cast<AllocaInst>(I);
  2592. Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
  2593. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  2594. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  2595. unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
  2596. assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
  2597. "not enough bits for maximum alignment");
  2598. assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
  2599. AlignRecord |= AI.isUsedWithInAlloca() << 5;
  2600. AlignRecord |= 1 << 6;
  2601. AlignRecord |= AI.isSwiftError() << 7;
  2602. Vals.push_back(AlignRecord);
  2603. break;
  2604. }
  2605. case Instruction::Load:
  2606. if (cast<LoadInst>(I).isAtomic()) {
  2607. Code = bitc::FUNC_CODE_INST_LOADATOMIC;
  2608. pushValueAndType(I.getOperand(0), InstID, Vals);
  2609. } else {
  2610. Code = bitc::FUNC_CODE_INST_LOAD;
  2611. if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
  2612. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  2613. }
  2614. Vals.push_back(VE.getTypeID(I.getType()));
  2615. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  2616. Vals.push_back(cast<LoadInst>(I).isVolatile());
  2617. if (cast<LoadInst>(I).isAtomic()) {
  2618. Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
  2619. Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
  2620. }
  2621. break;
  2622. case Instruction::Store:
  2623. if (cast<StoreInst>(I).isAtomic())
  2624. Code = bitc::FUNC_CODE_INST_STOREATOMIC;
  2625. else
  2626. Code = bitc::FUNC_CODE_INST_STORE;
  2627. pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
  2628. pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
  2629. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  2630. Vals.push_back(cast<StoreInst>(I).isVolatile());
  2631. if (cast<StoreInst>(I).isAtomic()) {
  2632. Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
  2633. Vals.push_back(
  2634. getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
  2635. }
  2636. break;
  2637. case Instruction::AtomicCmpXchg:
  2638. Code = bitc::FUNC_CODE_INST_CMPXCHG;
  2639. pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
  2640. pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
  2641. pushValue(I.getOperand(2), InstID, Vals); // newval.
  2642. Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
  2643. Vals.push_back(
  2644. getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
  2645. Vals.push_back(
  2646. getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
  2647. Vals.push_back(
  2648. getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
  2649. Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
  2650. break;
  2651. case Instruction::AtomicRMW:
  2652. Code = bitc::FUNC_CODE_INST_ATOMICRMW;
  2653. pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
  2654. pushValue(I.getOperand(1), InstID, Vals); // val.
  2655. Vals.push_back(
  2656. getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
  2657. Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
  2658. Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
  2659. Vals.push_back(
  2660. getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
  2661. break;
  2662. case Instruction::Fence:
  2663. Code = bitc::FUNC_CODE_INST_FENCE;
  2664. Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
  2665. Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
  2666. break;
  2667. case Instruction::Call: {
  2668. const CallInst &CI = cast<CallInst>(I);
  2669. FunctionType *FTy = CI.getFunctionType();
  2670. if (CI.hasOperandBundles())
  2671. writeOperandBundles(&CI, InstID);
  2672. Code = bitc::FUNC_CODE_INST_CALL;
  2673. Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
  2674. unsigned Flags = getOptimizationFlags(&I);
  2675. Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
  2676. unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
  2677. unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
  2678. 1 << bitc::CALL_EXPLICIT_TYPE |
  2679. unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
  2680. unsigned(Flags != 0) << bitc::CALL_FMF);
  2681. if (Flags != 0)
  2682. Vals.push_back(Flags);
  2683. Vals.push_back(VE.getTypeID(FTy));
  2684. pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
  2685. // Emit value #'s for the fixed parameters.
  2686. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  2687. // Check for labels (can happen with asm labels).
  2688. if (FTy->getParamType(i)->isLabelTy())
  2689. Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
  2690. else
  2691. pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
  2692. }
  2693. // Emit type/value pairs for varargs params.
  2694. if (FTy->isVarArg()) {
  2695. for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
  2696. i != e; ++i)
  2697. pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
  2698. }
  2699. break;
  2700. }
  2701. case Instruction::VAArg:
  2702. Code = bitc::FUNC_CODE_INST_VAARG;
  2703. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  2704. pushValue(I.getOperand(0), InstID, Vals); // valist.
  2705. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  2706. break;
  2707. }
  2708. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  2709. Vals.clear();
  2710. }
  2711. /// Write a GlobalValue VST to the module. The purpose of this data structure is
  2712. /// to allow clients to efficiently find the function body.
  2713. void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
  2714. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
  2715. // Get the offset of the VST we are writing, and backpatch it into
  2716. // the VST forward declaration record.
  2717. uint64_t VSTOffset = Stream.GetCurrentBitNo();
  2718. // The BitcodeStartBit was the stream offset of the identification block.
  2719. VSTOffset -= bitcodeStartBit();
  2720. assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
  2721. // Note that we add 1 here because the offset is relative to one word
  2722. // before the start of the identification block, which was historically
  2723. // always the start of the regular bitcode header.
  2724. Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
  2725. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2726. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2727. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2728. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2729. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2730. unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  2731. for (const Function &F : M) {
  2732. uint64_t Record[2];
  2733. if (F.isDeclaration())
  2734. continue;
  2735. Record[0] = VE.getValueID(&F);
  2736. // Save the word offset of the function (from the start of the
  2737. // actual bitcode written to the stream).
  2738. uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
  2739. assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
  2740. // Note that we add 1 here because the offset is relative to one word
  2741. // before the start of the identification block, which was historically
  2742. // always the start of the regular bitcode header.
  2743. Record[1] = BitcodeIndex / 32 + 1;
  2744. Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
  2745. }
  2746. Stream.ExitBlock();
  2747. }
  2748. /// Emit names for arguments, instructions and basic blocks in a function.
  2749. void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
  2750. const ValueSymbolTable &VST) {
  2751. if (VST.empty())
  2752. return;
  2753. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2754. // FIXME: Set up the abbrev, we know how many values there are!
  2755. // FIXME: We know if the type names can use 7-bit ascii.
  2756. SmallVector<uint64_t, 64> NameVals;
  2757. for (const ValueName &Name : VST) {
  2758. // Figure out the encoding to use for the name.
  2759. StringEncoding Bits = getStringEncoding(Name.getKey());
  2760. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  2761. NameVals.push_back(VE.getValueID(Name.getValue()));
  2762. // VST_CODE_ENTRY: [valueid, namechar x N]
  2763. // VST_CODE_BBENTRY: [bbid, namechar x N]
  2764. unsigned Code;
  2765. if (isa<BasicBlock>(Name.getValue())) {
  2766. Code = bitc::VST_CODE_BBENTRY;
  2767. if (Bits == SE_Char6)
  2768. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  2769. } else {
  2770. Code = bitc::VST_CODE_ENTRY;
  2771. if (Bits == SE_Char6)
  2772. AbbrevToUse = VST_ENTRY_6_ABBREV;
  2773. else if (Bits == SE_Fixed7)
  2774. AbbrevToUse = VST_ENTRY_7_ABBREV;
  2775. }
  2776. for (const auto P : Name.getKey())
  2777. NameVals.push_back((unsigned char)P);
  2778. // Emit the finished record.
  2779. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  2780. NameVals.clear();
  2781. }
  2782. Stream.ExitBlock();
  2783. }
  2784. void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
  2785. assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
  2786. unsigned Code;
  2787. if (isa<BasicBlock>(Order.V))
  2788. Code = bitc::USELIST_CODE_BB;
  2789. else
  2790. Code = bitc::USELIST_CODE_DEFAULT;
  2791. SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
  2792. Record.push_back(VE.getValueID(Order.V));
  2793. Stream.EmitRecord(Code, Record);
  2794. }
  2795. void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
  2796. assert(VE.shouldPreserveUseListOrder() &&
  2797. "Expected to be preserving use-list order");
  2798. auto hasMore = [&]() {
  2799. return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
  2800. };
  2801. if (!hasMore())
  2802. // Nothing to do.
  2803. return;
  2804. Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
  2805. while (hasMore()) {
  2806. writeUseList(std::move(VE.UseListOrders.back()));
  2807. VE.UseListOrders.pop_back();
  2808. }
  2809. Stream.ExitBlock();
  2810. }
  2811. /// Emit a function body to the module stream.
  2812. void ModuleBitcodeWriter::writeFunction(
  2813. const Function &F,
  2814. DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
  2815. // Save the bitcode index of the start of this function block for recording
  2816. // in the VST.
  2817. FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
  2818. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  2819. VE.incorporateFunction(F);
  2820. SmallVector<unsigned, 64> Vals;
  2821. // Emit the number of basic blocks, so the reader can create them ahead of
  2822. // time.
  2823. Vals.push_back(VE.getBasicBlocks().size());
  2824. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  2825. Vals.clear();
  2826. // If there are function-local constants, emit them now.
  2827. unsigned CstStart, CstEnd;
  2828. VE.getFunctionConstantRange(CstStart, CstEnd);
  2829. writeConstants(CstStart, CstEnd, false);
  2830. // If there is function-local metadata, emit it now.
  2831. writeFunctionMetadata(F);
  2832. // Keep a running idea of what the instruction ID is.
  2833. unsigned InstID = CstEnd;
  2834. bool NeedsMetadataAttachment = F.hasMetadata();
  2835. DILocation *LastDL = nullptr;
  2836. // Finally, emit all the instructions, in order.
  2837. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  2838. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  2839. I != E; ++I) {
  2840. writeInstruction(*I, InstID, Vals);
  2841. if (!I->getType()->isVoidTy())
  2842. ++InstID;
  2843. // If the instruction has metadata, write a metadata attachment later.
  2844. NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
  2845. // If the instruction has a debug location, emit it.
  2846. DILocation *DL = I->getDebugLoc();
  2847. if (!DL)
  2848. continue;
  2849. if (DL == LastDL) {
  2850. // Just repeat the same debug loc as last time.
  2851. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
  2852. continue;
  2853. }
  2854. Vals.push_back(DL->getLine());
  2855. Vals.push_back(DL->getColumn());
  2856. Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
  2857. Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
  2858. Vals.push_back(DL->isImplicitCode());
  2859. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
  2860. Vals.clear();
  2861. LastDL = DL;
  2862. }
  2863. // Emit names for all the instructions etc.
  2864. if (auto *Symtab = F.getValueSymbolTable())
  2865. writeFunctionLevelValueSymbolTable(*Symtab);
  2866. if (NeedsMetadataAttachment)
  2867. writeFunctionMetadataAttachment(F);
  2868. if (VE.shouldPreserveUseListOrder())
  2869. writeUseListBlock(&F);
  2870. VE.purgeFunction();
  2871. Stream.ExitBlock();
  2872. }
  2873. // Emit blockinfo, which defines the standard abbreviations etc.
  2874. void ModuleBitcodeWriter::writeBlockInfo() {
  2875. // We only want to emit block info records for blocks that have multiple
  2876. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
  2877. // Other blocks can define their abbrevs inline.
  2878. Stream.EnterBlockInfoBlock();
  2879. { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
  2880. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2881. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  2882. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2883. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2884. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2885. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2886. VST_ENTRY_8_ABBREV)
  2887. llvm_unreachable("Unexpected abbrev ordering!");
  2888. }
  2889. { // 7-bit fixed width VST_CODE_ENTRY strings.
  2890. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2891. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2892. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2893. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2894. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2895. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2896. VST_ENTRY_7_ABBREV)
  2897. llvm_unreachable("Unexpected abbrev ordering!");
  2898. }
  2899. { // 6-bit char6 VST_CODE_ENTRY strings.
  2900. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2901. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2902. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2903. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2904. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2905. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2906. VST_ENTRY_6_ABBREV)
  2907. llvm_unreachable("Unexpected abbrev ordering!");
  2908. }
  2909. { // 6-bit char6 VST_CODE_BBENTRY strings.
  2910. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2911. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  2912. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2913. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2914. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2915. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
  2916. VST_BBENTRY_6_ABBREV)
  2917. llvm_unreachable("Unexpected abbrev ordering!");
  2918. }
  2919. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  2920. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2921. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  2922. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  2923. VE.computeBitsRequiredForTypeIndicies()));
  2924. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2925. CONSTANTS_SETTYPE_ABBREV)
  2926. llvm_unreachable("Unexpected abbrev ordering!");
  2927. }
  2928. { // INTEGER abbrev for CONSTANTS_BLOCK.
  2929. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2930. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  2931. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2932. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2933. CONSTANTS_INTEGER_ABBREV)
  2934. llvm_unreachable("Unexpected abbrev ordering!");
  2935. }
  2936. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  2937. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2938. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  2939. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  2940. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  2941. VE.computeBitsRequiredForTypeIndicies()));
  2942. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2943. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2944. CONSTANTS_CE_CAST_Abbrev)
  2945. llvm_unreachable("Unexpected abbrev ordering!");
  2946. }
  2947. { // NULL abbrev for CONSTANTS_BLOCK.
  2948. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2949. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  2950. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
  2951. CONSTANTS_NULL_Abbrev)
  2952. llvm_unreachable("Unexpected abbrev ordering!");
  2953. }
  2954. // FIXME: This should only use space for first class types!
  2955. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  2956. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2957. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  2958. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  2959. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2960. VE.computeBitsRequiredForTypeIndicies()));
  2961. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  2962. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  2963. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2964. FUNCTION_INST_LOAD_ABBREV)
  2965. llvm_unreachable("Unexpected abbrev ordering!");
  2966. }
  2967. { // INST_UNOP abbrev for FUNCTION_BLOCK.
  2968. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2969. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
  2970. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2971. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2972. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2973. FUNCTION_INST_UNOP_ABBREV)
  2974. llvm_unreachable("Unexpected abbrev ordering!");
  2975. }
  2976. { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
  2977. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2978. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
  2979. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2980. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2981. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
  2982. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2983. FUNCTION_INST_UNOP_FLAGS_ABBREV)
  2984. llvm_unreachable("Unexpected abbrev ordering!");
  2985. }
  2986. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  2987. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2988. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2989. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2990. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  2991. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2992. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2993. FUNCTION_INST_BINOP_ABBREV)
  2994. llvm_unreachable("Unexpected abbrev ordering!");
  2995. }
  2996. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  2997. auto Abbv = std::make_shared<BitCodeAbbrev>();
  2998. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2999. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  3000. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  3001. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  3002. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
  3003. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3004. FUNCTION_INST_BINOP_FLAGS_ABBREV)
  3005. llvm_unreachable("Unexpected abbrev ordering!");
  3006. }
  3007. { // INST_CAST abbrev for FUNCTION_BLOCK.
  3008. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3009. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  3010. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  3011. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  3012. VE.computeBitsRequiredForTypeIndicies()));
  3013. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  3014. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3015. FUNCTION_INST_CAST_ABBREV)
  3016. llvm_unreachable("Unexpected abbrev ordering!");
  3017. }
  3018. { // INST_RET abbrev for FUNCTION_BLOCK.
  3019. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3020. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  3021. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3022. FUNCTION_INST_RET_VOID_ABBREV)
  3023. llvm_unreachable("Unexpected abbrev ordering!");
  3024. }
  3025. { // INST_RET abbrev for FUNCTION_BLOCK.
  3026. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3027. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  3028. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  3029. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3030. FUNCTION_INST_RET_VAL_ABBREV)
  3031. llvm_unreachable("Unexpected abbrev ordering!");
  3032. }
  3033. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  3034. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3035. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  3036. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3037. FUNCTION_INST_UNREACHABLE_ABBREV)
  3038. llvm_unreachable("Unexpected abbrev ordering!");
  3039. }
  3040. {
  3041. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3042. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
  3043. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  3044. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  3045. Log2_32_Ceil(VE.getTypes().size() + 1)));
  3046. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3047. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  3048. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  3049. FUNCTION_INST_GEP_ABBREV)
  3050. llvm_unreachable("Unexpected abbrev ordering!");
  3051. }
  3052. Stream.ExitBlock();
  3053. }
  3054. /// Write the module path strings, currently only used when generating
  3055. /// a combined index file.
  3056. void IndexBitcodeWriter::writeModStrings() {
  3057. Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
  3058. // TODO: See which abbrev sizes we actually need to emit
  3059. // 8-bit fixed-width MST_ENTRY strings.
  3060. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3061. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  3062. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3063. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3064. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  3065. unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
  3066. // 7-bit fixed width MST_ENTRY strings.
  3067. Abbv = std::make_shared<BitCodeAbbrev>();
  3068. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  3069. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3070. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3071. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  3072. unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
  3073. // 6-bit char6 MST_ENTRY strings.
  3074. Abbv = std::make_shared<BitCodeAbbrev>();
  3075. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  3076. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3077. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3078. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  3079. unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
  3080. // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
  3081. Abbv = std::make_shared<BitCodeAbbrev>();
  3082. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
  3083. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3084. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3085. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3086. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3087. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3088. unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
  3089. SmallVector<unsigned, 64> Vals;
  3090. forEachModule(
  3091. [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
  3092. StringRef Key = MPSE.getKey();
  3093. const auto &Value = MPSE.getValue();
  3094. StringEncoding Bits = getStringEncoding(Key);
  3095. unsigned AbbrevToUse = Abbrev8Bit;
  3096. if (Bits == SE_Char6)
  3097. AbbrevToUse = Abbrev6Bit;
  3098. else if (Bits == SE_Fixed7)
  3099. AbbrevToUse = Abbrev7Bit;
  3100. Vals.push_back(Value.first);
  3101. Vals.append(Key.begin(), Key.end());
  3102. // Emit the finished record.
  3103. Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
  3104. // Emit an optional hash for the module now
  3105. const auto &Hash = Value.second;
  3106. if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
  3107. Vals.assign(Hash.begin(), Hash.end());
  3108. // Emit the hash record.
  3109. Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
  3110. }
  3111. Vals.clear();
  3112. });
  3113. Stream.ExitBlock();
  3114. }
  3115. /// Write the function type metadata related records that need to appear before
  3116. /// a function summary entry (whether per-module or combined).
  3117. static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
  3118. FunctionSummary *FS) {
  3119. if (!FS->type_tests().empty())
  3120. Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
  3121. SmallVector<uint64_t, 64> Record;
  3122. auto WriteVFuncIdVec = [&](uint64_t Ty,
  3123. ArrayRef<FunctionSummary::VFuncId> VFs) {
  3124. if (VFs.empty())
  3125. return;
  3126. Record.clear();
  3127. for (auto &VF : VFs) {
  3128. Record.push_back(VF.GUID);
  3129. Record.push_back(VF.Offset);
  3130. }
  3131. Stream.EmitRecord(Ty, Record);
  3132. };
  3133. WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
  3134. FS->type_test_assume_vcalls());
  3135. WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
  3136. FS->type_checked_load_vcalls());
  3137. auto WriteConstVCallVec = [&](uint64_t Ty,
  3138. ArrayRef<FunctionSummary::ConstVCall> VCs) {
  3139. for (auto &VC : VCs) {
  3140. Record.clear();
  3141. Record.push_back(VC.VFunc.GUID);
  3142. Record.push_back(VC.VFunc.Offset);
  3143. Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
  3144. Stream.EmitRecord(Ty, Record);
  3145. }
  3146. };
  3147. WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
  3148. FS->type_test_assume_const_vcalls());
  3149. WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
  3150. FS->type_checked_load_const_vcalls());
  3151. }
  3152. /// Collect type IDs from type tests used by function.
  3153. static void
  3154. getReferencedTypeIds(FunctionSummary *FS,
  3155. std::set<GlobalValue::GUID> &ReferencedTypeIds) {
  3156. if (!FS->type_tests().empty())
  3157. for (auto &TT : FS->type_tests())
  3158. ReferencedTypeIds.insert(TT);
  3159. auto GetReferencedTypesFromVFuncIdVec =
  3160. [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
  3161. for (auto &VF : VFs)
  3162. ReferencedTypeIds.insert(VF.GUID);
  3163. };
  3164. GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
  3165. GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
  3166. auto GetReferencedTypesFromConstVCallVec =
  3167. [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
  3168. for (auto &VC : VCs)
  3169. ReferencedTypeIds.insert(VC.VFunc.GUID);
  3170. };
  3171. GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
  3172. GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
  3173. }
  3174. static void writeWholeProgramDevirtResolutionByArg(
  3175. SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
  3176. const WholeProgramDevirtResolution::ByArg &ByArg) {
  3177. NameVals.push_back(args.size());
  3178. NameVals.insert(NameVals.end(), args.begin(), args.end());
  3179. NameVals.push_back(ByArg.TheKind);
  3180. NameVals.push_back(ByArg.Info);
  3181. NameVals.push_back(ByArg.Byte);
  3182. NameVals.push_back(ByArg.Bit);
  3183. }
  3184. static void writeWholeProgramDevirtResolution(
  3185. SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
  3186. uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
  3187. NameVals.push_back(Id);
  3188. NameVals.push_back(Wpd.TheKind);
  3189. NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
  3190. NameVals.push_back(Wpd.SingleImplName.size());
  3191. NameVals.push_back(Wpd.ResByArg.size());
  3192. for (auto &A : Wpd.ResByArg)
  3193. writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
  3194. }
  3195. static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
  3196. StringTableBuilder &StrtabBuilder,
  3197. const std::string &Id,
  3198. const TypeIdSummary &Summary) {
  3199. NameVals.push_back(StrtabBuilder.add(Id));
  3200. NameVals.push_back(Id.size());
  3201. NameVals.push_back(Summary.TTRes.TheKind);
  3202. NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
  3203. NameVals.push_back(Summary.TTRes.AlignLog2);
  3204. NameVals.push_back(Summary.TTRes.SizeM1);
  3205. NameVals.push_back(Summary.TTRes.BitMask);
  3206. NameVals.push_back(Summary.TTRes.InlineBits);
  3207. for (auto &W : Summary.WPDRes)
  3208. writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
  3209. W.second);
  3210. }
  3211. // Helper to emit a single function summary record.
  3212. void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
  3213. SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
  3214. unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
  3215. const Function &F) {
  3216. NameVals.push_back(ValueID);
  3217. FunctionSummary *FS = cast<FunctionSummary>(Summary);
  3218. writeFunctionTypeMetadataRecords(Stream, FS);
  3219. NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
  3220. NameVals.push_back(FS->instCount());
  3221. NameVals.push_back(getEncodedFFlags(FS->fflags()));
  3222. NameVals.push_back(FS->refs().size());
  3223. NameVals.push_back(FS->immutableRefCount());
  3224. for (auto &RI : FS->refs())
  3225. NameVals.push_back(VE.getValueID(RI.getValue()));
  3226. bool HasProfileData =
  3227. F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
  3228. for (auto &ECI : FS->calls()) {
  3229. NameVals.push_back(getValueId(ECI.first));
  3230. if (HasProfileData)
  3231. NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
  3232. else if (WriteRelBFToSummary)
  3233. NameVals.push_back(ECI.second.RelBlockFreq);
  3234. }
  3235. unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
  3236. unsigned Code =
  3237. (HasProfileData ? bitc::FS_PERMODULE_PROFILE
  3238. : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
  3239. : bitc::FS_PERMODULE));
  3240. // Emit the finished record.
  3241. Stream.EmitRecord(Code, NameVals, FSAbbrev);
  3242. NameVals.clear();
  3243. }
  3244. // Collect the global value references in the given variable's initializer,
  3245. // and emit them in a summary record.
  3246. void ModuleBitcodeWriterBase::writeModuleLevelReferences(
  3247. const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
  3248. unsigned FSModRefsAbbrev) {
  3249. auto VI = Index->getValueInfo(V.getGUID());
  3250. if (!VI || VI.getSummaryList().empty()) {
  3251. // Only declarations should not have a summary (a declaration might however
  3252. // have a summary if the def was in module level asm).
  3253. assert(V.isDeclaration());
  3254. return;
  3255. }
  3256. auto *Summary = VI.getSummaryList()[0].get();
  3257. NameVals.push_back(VE.getValueID(&V));
  3258. GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
  3259. NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
  3260. NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
  3261. unsigned SizeBeforeRefs = NameVals.size();
  3262. for (auto &RI : VS->refs())
  3263. NameVals.push_back(VE.getValueID(RI.getValue()));
  3264. // Sort the refs for determinism output, the vector returned by FS->refs() has
  3265. // been initialized from a DenseSet.
  3266. llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
  3267. Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
  3268. FSModRefsAbbrev);
  3269. NameVals.clear();
  3270. }
  3271. // Current version for the summary.
  3272. // This is bumped whenever we introduce changes in the way some record are
  3273. // interpreted, like flags for instance.
  3274. static const uint64_t INDEX_VERSION = 6;
  3275. /// Emit the per-module summary section alongside the rest of
  3276. /// the module's bitcode.
  3277. void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
  3278. // By default we compile with ThinLTO if the module has a summary, but the
  3279. // client can request full LTO with a module flag.
  3280. bool IsThinLTO = true;
  3281. if (auto *MD =
  3282. mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
  3283. IsThinLTO = MD->getZExtValue();
  3284. Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
  3285. : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
  3286. 4);
  3287. Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
  3288. // Write the index flags.
  3289. uint64_t Flags = 0;
  3290. // Bits 1-3 are set only in the combined index, skip them.
  3291. if (Index->enableSplitLTOUnit())
  3292. Flags |= 0x8;
  3293. Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
  3294. if (Index->begin() == Index->end()) {
  3295. Stream.ExitBlock();
  3296. return;
  3297. }
  3298. for (const auto &GVI : valueIds()) {
  3299. Stream.EmitRecord(bitc::FS_VALUE_GUID,
  3300. ArrayRef<uint64_t>{GVI.second, GVI.first});
  3301. }
  3302. // Abbrev for FS_PERMODULE_PROFILE.
  3303. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3304. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
  3305. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3306. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3307. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3308. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3309. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3310. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3311. // numrefs x valueid, n x (valueid, hotness)
  3312. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3313. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3314. unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3315. // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
  3316. Abbv = std::make_shared<BitCodeAbbrev>();
  3317. if (WriteRelBFToSummary)
  3318. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
  3319. else
  3320. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
  3321. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3322. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3323. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3324. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3325. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3326. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3327. // numrefs x valueid, n x (valueid [, rel_block_freq])
  3328. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3329. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3330. unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3331. // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
  3332. Abbv = std::make_shared<BitCodeAbbrev>();
  3333. Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
  3334. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3335. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3336. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
  3337. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3338. unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3339. // Abbrev for FS_ALIAS.
  3340. Abbv = std::make_shared<BitCodeAbbrev>();
  3341. Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
  3342. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3344. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3345. unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3346. SmallVector<uint64_t, 64> NameVals;
  3347. // Iterate over the list of functions instead of the Index to
  3348. // ensure the ordering is stable.
  3349. for (const Function &F : M) {
  3350. // Summary emission does not support anonymous functions, they have to
  3351. // renamed using the anonymous function renaming pass.
  3352. if (!F.hasName())
  3353. report_fatal_error("Unexpected anonymous function when writing summary");
  3354. ValueInfo VI = Index->getValueInfo(F.getGUID());
  3355. if (!VI || VI.getSummaryList().empty()) {
  3356. // Only declarations should not have a summary (a declaration might
  3357. // however have a summary if the def was in module level asm).
  3358. assert(F.isDeclaration());
  3359. continue;
  3360. }
  3361. auto *Summary = VI.getSummaryList()[0].get();
  3362. writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
  3363. FSCallsAbbrev, FSCallsProfileAbbrev, F);
  3364. }
  3365. // Capture references from GlobalVariable initializers, which are outside
  3366. // of a function scope.
  3367. for (const GlobalVariable &G : M.globals())
  3368. writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
  3369. for (const GlobalAlias &A : M.aliases()) {
  3370. auto *Aliasee = A.getBaseObject();
  3371. if (!Aliasee->hasName())
  3372. // Nameless function don't have an entry in the summary, skip it.
  3373. continue;
  3374. auto AliasId = VE.getValueID(&A);
  3375. auto AliaseeId = VE.getValueID(Aliasee);
  3376. NameVals.push_back(AliasId);
  3377. auto *Summary = Index->getGlobalValueSummary(A);
  3378. AliasSummary *AS = cast<AliasSummary>(Summary);
  3379. NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
  3380. NameVals.push_back(AliaseeId);
  3381. Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
  3382. NameVals.clear();
  3383. }
  3384. Stream.ExitBlock();
  3385. }
  3386. /// Emit the combined summary section into the combined index file.
  3387. void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
  3388. Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
  3389. Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
  3390. // Write the index flags.
  3391. uint64_t Flags = 0;
  3392. if (Index.withGlobalValueDeadStripping())
  3393. Flags |= 0x1;
  3394. if (Index.skipModuleByDistributedBackend())
  3395. Flags |= 0x2;
  3396. if (Index.hasSyntheticEntryCounts())
  3397. Flags |= 0x4;
  3398. if (Index.enableSplitLTOUnit())
  3399. Flags |= 0x8;
  3400. if (Index.partiallySplitLTOUnits())
  3401. Flags |= 0x10;
  3402. Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
  3403. for (const auto &GVI : valueIds()) {
  3404. Stream.EmitRecord(bitc::FS_VALUE_GUID,
  3405. ArrayRef<uint64_t>{GVI.second, GVI.first});
  3406. }
  3407. // Abbrev for FS_COMBINED.
  3408. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3409. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
  3410. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3411. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3412. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3413. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3414. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3415. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
  3416. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3417. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3418. // numrefs x valueid, n x (valueid)
  3419. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3420. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3421. unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3422. // Abbrev for FS_COMBINED_PROFILE.
  3423. Abbv = std::make_shared<BitCodeAbbrev>();
  3424. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
  3425. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3426. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3427. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3428. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  3429. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
  3430. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
  3431. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // immutablerefcnt
  3432. // numrefs x valueid, n x (valueid, hotness)
  3433. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3434. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3435. unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3436. // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
  3437. Abbv = std::make_shared<BitCodeAbbrev>();
  3438. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
  3439. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3440. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3441. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3442. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
  3443. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  3444. unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3445. // Abbrev for FS_COMBINED_ALIAS.
  3446. Abbv = std::make_shared<BitCodeAbbrev>();
  3447. Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
  3448. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3449. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  3450. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
  3451. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  3452. unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3453. // The aliases are emitted as a post-pass, and will point to the value
  3454. // id of the aliasee. Save them in a vector for post-processing.
  3455. SmallVector<AliasSummary *, 64> Aliases;
  3456. // Save the value id for each summary for alias emission.
  3457. DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
  3458. SmallVector<uint64_t, 64> NameVals;
  3459. // Set that will be populated during call to writeFunctionTypeMetadataRecords
  3460. // with the type ids referenced by this index file.
  3461. std::set<GlobalValue::GUID> ReferencedTypeIds;
  3462. // For local linkage, we also emit the original name separately
  3463. // immediately after the record.
  3464. auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
  3465. if (!GlobalValue::isLocalLinkage(S.linkage()))
  3466. return;
  3467. NameVals.push_back(S.getOriginalName());
  3468. Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
  3469. NameVals.clear();
  3470. };
  3471. forEachSummary([&](GVInfo I, bool IsAliasee) {
  3472. GlobalValueSummary *S = I.second;
  3473. assert(S);
  3474. auto ValueId = getValueId(I.first);
  3475. assert(ValueId);
  3476. SummaryToValueIdMap[S] = *ValueId;
  3477. // If this is invoked for an aliasee, we want to record the above
  3478. // mapping, but then not emit a summary entry (if the aliasee is
  3479. // to be imported, we will invoke this separately with IsAliasee=false).
  3480. if (IsAliasee)
  3481. return;
  3482. if (auto *AS = dyn_cast<AliasSummary>(S)) {
  3483. // Will process aliases as a post-pass because the reader wants all
  3484. // global to be loaded first.
  3485. Aliases.push_back(AS);
  3486. return;
  3487. }
  3488. if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
  3489. NameVals.push_back(*ValueId);
  3490. NameVals.push_back(Index.getModuleId(VS->modulePath()));
  3491. NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
  3492. NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
  3493. for (auto &RI : VS->refs()) {
  3494. auto RefValueId = getValueId(RI.getGUID());
  3495. if (!RefValueId)
  3496. continue;
  3497. NameVals.push_back(*RefValueId);
  3498. }
  3499. // Emit the finished record.
  3500. Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
  3501. FSModRefsAbbrev);
  3502. NameVals.clear();
  3503. MaybeEmitOriginalName(*S);
  3504. return;
  3505. }
  3506. auto *FS = cast<FunctionSummary>(S);
  3507. writeFunctionTypeMetadataRecords(Stream, FS);
  3508. getReferencedTypeIds(FS, ReferencedTypeIds);
  3509. NameVals.push_back(*ValueId);
  3510. NameVals.push_back(Index.getModuleId(FS->modulePath()));
  3511. NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
  3512. NameVals.push_back(FS->instCount());
  3513. NameVals.push_back(getEncodedFFlags(FS->fflags()));
  3514. NameVals.push_back(FS->entryCount());
  3515. // Fill in below
  3516. NameVals.push_back(0); // numrefs
  3517. NameVals.push_back(0); // immutablerefcnt
  3518. unsigned Count = 0, ImmutableRefCnt = 0;
  3519. for (auto &RI : FS->refs()) {
  3520. auto RefValueId = getValueId(RI.getGUID());
  3521. if (!RefValueId)
  3522. continue;
  3523. NameVals.push_back(*RefValueId);
  3524. if (RI.isReadOnly())
  3525. ImmutableRefCnt++;
  3526. Count++;
  3527. }
  3528. NameVals[6] = Count;
  3529. NameVals[7] = ImmutableRefCnt;
  3530. bool HasProfileData = false;
  3531. for (auto &EI : FS->calls()) {
  3532. HasProfileData |=
  3533. EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
  3534. if (HasProfileData)
  3535. break;
  3536. }
  3537. for (auto &EI : FS->calls()) {
  3538. // If this GUID doesn't have a value id, it doesn't have a function
  3539. // summary and we don't need to record any calls to it.
  3540. GlobalValue::GUID GUID = EI.first.getGUID();
  3541. auto CallValueId = getValueId(GUID);
  3542. if (!CallValueId) {
  3543. // For SamplePGO, the indirect call targets for local functions will
  3544. // have its original name annotated in profile. We try to find the
  3545. // corresponding PGOFuncName as the GUID.
  3546. GUID = Index.getGUIDFromOriginalID(GUID);
  3547. if (GUID == 0)
  3548. continue;
  3549. CallValueId = getValueId(GUID);
  3550. if (!CallValueId)
  3551. continue;
  3552. // The mapping from OriginalId to GUID may return a GUID
  3553. // that corresponds to a static variable. Filter it out here.
  3554. // This can happen when
  3555. // 1) There is a call to a library function which does not have
  3556. // a CallValidId;
  3557. // 2) There is a static variable with the OriginalGUID identical
  3558. // to the GUID of the library function in 1);
  3559. // When this happens, the logic for SamplePGO kicks in and
  3560. // the static variable in 2) will be found, which needs to be
  3561. // filtered out.
  3562. auto *GVSum = Index.getGlobalValueSummary(GUID, false);
  3563. if (GVSum &&
  3564. GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
  3565. continue;
  3566. }
  3567. NameVals.push_back(*CallValueId);
  3568. if (HasProfileData)
  3569. NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
  3570. }
  3571. unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
  3572. unsigned Code =
  3573. (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
  3574. // Emit the finished record.
  3575. Stream.EmitRecord(Code, NameVals, FSAbbrev);
  3576. NameVals.clear();
  3577. MaybeEmitOriginalName(*S);
  3578. });
  3579. for (auto *AS : Aliases) {
  3580. auto AliasValueId = SummaryToValueIdMap[AS];
  3581. assert(AliasValueId);
  3582. NameVals.push_back(AliasValueId);
  3583. NameVals.push_back(Index.getModuleId(AS->modulePath()));
  3584. NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
  3585. auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
  3586. assert(AliaseeValueId);
  3587. NameVals.push_back(AliaseeValueId);
  3588. // Emit the finished record.
  3589. Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
  3590. NameVals.clear();
  3591. MaybeEmitOriginalName(*AS);
  3592. if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
  3593. getReferencedTypeIds(FS, ReferencedTypeIds);
  3594. }
  3595. if (!Index.cfiFunctionDefs().empty()) {
  3596. for (auto &S : Index.cfiFunctionDefs()) {
  3597. NameVals.push_back(StrtabBuilder.add(S));
  3598. NameVals.push_back(S.size());
  3599. }
  3600. Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
  3601. NameVals.clear();
  3602. }
  3603. if (!Index.cfiFunctionDecls().empty()) {
  3604. for (auto &S : Index.cfiFunctionDecls()) {
  3605. NameVals.push_back(StrtabBuilder.add(S));
  3606. NameVals.push_back(S.size());
  3607. }
  3608. Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
  3609. NameVals.clear();
  3610. }
  3611. // Walk the GUIDs that were referenced, and write the
  3612. // corresponding type id records.
  3613. for (auto &T : ReferencedTypeIds) {
  3614. auto TidIter = Index.typeIds().equal_range(T);
  3615. for (auto It = TidIter.first; It != TidIter.second; ++It) {
  3616. writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
  3617. It->second.second);
  3618. Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
  3619. NameVals.clear();
  3620. }
  3621. }
  3622. Stream.ExitBlock();
  3623. }
  3624. /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
  3625. /// current llvm version, and a record for the epoch number.
  3626. static void writeIdentificationBlock(BitstreamWriter &Stream) {
  3627. Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
  3628. // Write the "user readable" string identifying the bitcode producer
  3629. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3630. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
  3631. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3632. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  3633. auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3634. writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
  3635. "LLVM" LLVM_VERSION_STRING, StringAbbrev);
  3636. // Write the epoch version
  3637. Abbv = std::make_shared<BitCodeAbbrev>();
  3638. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
  3639. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  3640. auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3641. SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
  3642. Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
  3643. Stream.ExitBlock();
  3644. }
  3645. void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
  3646. // Emit the module's hash.
  3647. // MODULE_CODE_HASH: [5*i32]
  3648. if (GenerateHash) {
  3649. uint32_t Vals[5];
  3650. Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
  3651. Buffer.size() - BlockStartPos));
  3652. StringRef Hash = Hasher.result();
  3653. for (int Pos = 0; Pos < 20; Pos += 4) {
  3654. Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
  3655. }
  3656. // Emit the finished record.
  3657. Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
  3658. if (ModHash)
  3659. // Save the written hash value.
  3660. llvm::copy(Vals, std::begin(*ModHash));
  3661. }
  3662. }
  3663. void ModuleBitcodeWriter::write() {
  3664. writeIdentificationBlock(Stream);
  3665. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  3666. size_t BlockStartPos = Buffer.size();
  3667. writeModuleVersion();
  3668. // Emit blockinfo, which defines the standard abbreviations etc.
  3669. writeBlockInfo();
  3670. // Emit information about attribute groups.
  3671. writeAttributeGroupTable();
  3672. // Emit information about parameter attributes.
  3673. writeAttributeTable();
  3674. // Emit information describing all of the types in the module.
  3675. writeTypeTable();
  3676. writeComdats();
  3677. // Emit top-level description of module, including target triple, inline asm,
  3678. // descriptors for global variables, and function prototype info.
  3679. writeModuleInfo();
  3680. // Emit constants.
  3681. writeModuleConstants();
  3682. // Emit metadata kind names.
  3683. writeModuleMetadataKinds();
  3684. // Emit metadata.
  3685. writeModuleMetadata();
  3686. // Emit module-level use-lists.
  3687. if (VE.shouldPreserveUseListOrder())
  3688. writeUseListBlock(nullptr);
  3689. writeOperandBundleTags();
  3690. writeSyncScopeNames();
  3691. // Emit function bodies.
  3692. DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
  3693. for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
  3694. if (!F->isDeclaration())
  3695. writeFunction(*F, FunctionToBitcodeIndex);
  3696. // Need to write after the above call to WriteFunction which populates
  3697. // the summary information in the index.
  3698. if (Index)
  3699. writePerModuleGlobalValueSummary();
  3700. writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
  3701. writeModuleHash(BlockStartPos);
  3702. Stream.ExitBlock();
  3703. }
  3704. static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
  3705. uint32_t &Position) {
  3706. support::endian::write32le(&Buffer[Position], Value);
  3707. Position += 4;
  3708. }
  3709. /// If generating a bc file on darwin, we have to emit a
  3710. /// header and trailer to make it compatible with the system archiver. To do
  3711. /// this we emit the following header, and then emit a trailer that pads the
  3712. /// file out to be a multiple of 16 bytes.
  3713. ///
  3714. /// struct bc_header {
  3715. /// uint32_t Magic; // 0x0B17C0DE
  3716. /// uint32_t Version; // Version, currently always 0.
  3717. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  3718. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  3719. /// uint32_t CPUType; // CPU specifier.
  3720. /// ... potentially more later ...
  3721. /// };
  3722. static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
  3723. const Triple &TT) {
  3724. unsigned CPUType = ~0U;
  3725. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
  3726. // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
  3727. // number from /usr/include/mach/machine.h. It is ok to reproduce the
  3728. // specific constants here because they are implicitly part of the Darwin ABI.
  3729. enum {
  3730. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  3731. DARWIN_CPU_TYPE_X86 = 7,
  3732. DARWIN_CPU_TYPE_ARM = 12,
  3733. DARWIN_CPU_TYPE_POWERPC = 18
  3734. };
  3735. Triple::ArchType Arch = TT.getArch();
  3736. if (Arch == Triple::x86_64)
  3737. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  3738. else if (Arch == Triple::x86)
  3739. CPUType = DARWIN_CPU_TYPE_X86;
  3740. else if (Arch == Triple::ppc)
  3741. CPUType = DARWIN_CPU_TYPE_POWERPC;
  3742. else if (Arch == Triple::ppc64)
  3743. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  3744. else if (Arch == Triple::arm || Arch == Triple::thumb)
  3745. CPUType = DARWIN_CPU_TYPE_ARM;
  3746. // Traditional Bitcode starts after header.
  3747. assert(Buffer.size() >= BWH_HeaderSize &&
  3748. "Expected header size to be reserved");
  3749. unsigned BCOffset = BWH_HeaderSize;
  3750. unsigned BCSize = Buffer.size() - BWH_HeaderSize;
  3751. // Write the magic and version.
  3752. unsigned Position = 0;
  3753. writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
  3754. writeInt32ToBuffer(0, Buffer, Position); // Version.
  3755. writeInt32ToBuffer(BCOffset, Buffer, Position);
  3756. writeInt32ToBuffer(BCSize, Buffer, Position);
  3757. writeInt32ToBuffer(CPUType, Buffer, Position);
  3758. // If the file is not a multiple of 16 bytes, insert dummy padding.
  3759. while (Buffer.size() & 15)
  3760. Buffer.push_back(0);
  3761. }
  3762. /// Helper to write the header common to all bitcode files.
  3763. static void writeBitcodeHeader(BitstreamWriter &Stream) {
  3764. // Emit the file header.
  3765. Stream.Emit((unsigned)'B', 8);
  3766. Stream.Emit((unsigned)'C', 8);
  3767. Stream.Emit(0x0, 4);
  3768. Stream.Emit(0xC, 4);
  3769. Stream.Emit(0xE, 4);
  3770. Stream.Emit(0xD, 4);
  3771. }
  3772. BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
  3773. : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
  3774. writeBitcodeHeader(*Stream);
  3775. }
  3776. BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
  3777. void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
  3778. Stream->EnterSubblock(Block, 3);
  3779. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3780. Abbv->Add(BitCodeAbbrevOp(Record));
  3781. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3782. auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
  3783. Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
  3784. Stream->ExitBlock();
  3785. }
  3786. void BitcodeWriter::writeSymtab() {
  3787. assert(!WroteStrtab && !WroteSymtab);
  3788. // If any module has module-level inline asm, we will require a registered asm
  3789. // parser for the target so that we can create an accurate symbol table for
  3790. // the module.
  3791. for (Module *M : Mods) {
  3792. if (M->getModuleInlineAsm().empty())
  3793. continue;
  3794. std::string Err;
  3795. const Triple TT(M->getTargetTriple());
  3796. const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
  3797. if (!T || !T->hasMCAsmParser())
  3798. return;
  3799. }
  3800. WroteSymtab = true;
  3801. SmallVector<char, 0> Symtab;
  3802. // The irsymtab::build function may be unable to create a symbol table if the
  3803. // module is malformed (e.g. it contains an invalid alias). Writing a symbol
  3804. // table is not required for correctness, but we still want to be able to
  3805. // write malformed modules to bitcode files, so swallow the error.
  3806. if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
  3807. consumeError(std::move(E));
  3808. return;
  3809. }
  3810. writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
  3811. {Symtab.data(), Symtab.size()});
  3812. }
  3813. void BitcodeWriter::writeStrtab() {
  3814. assert(!WroteStrtab);
  3815. std::vector<char> Strtab;
  3816. StrtabBuilder.finalizeInOrder();
  3817. Strtab.resize(StrtabBuilder.getSize());
  3818. StrtabBuilder.write((uint8_t *)Strtab.data());
  3819. writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
  3820. {Strtab.data(), Strtab.size()});
  3821. WroteStrtab = true;
  3822. }
  3823. void BitcodeWriter::copyStrtab(StringRef Strtab) {
  3824. writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
  3825. WroteStrtab = true;
  3826. }
  3827. void BitcodeWriter::writeModule(const Module &M,
  3828. bool ShouldPreserveUseListOrder,
  3829. const ModuleSummaryIndex *Index,
  3830. bool GenerateHash, ModuleHash *ModHash) {
  3831. assert(!WroteStrtab);
  3832. // The Mods vector is used by irsymtab::build, which requires non-const
  3833. // Modules in case it needs to materialize metadata. But the bitcode writer
  3834. // requires that the module is materialized, so we can cast to non-const here,
  3835. // after checking that it is in fact materialized.
  3836. assert(M.isMaterialized());
  3837. Mods.push_back(const_cast<Module *>(&M));
  3838. ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
  3839. ShouldPreserveUseListOrder, Index,
  3840. GenerateHash, ModHash);
  3841. ModuleWriter.write();
  3842. }
  3843. void BitcodeWriter::writeIndex(
  3844. const ModuleSummaryIndex *Index,
  3845. const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
  3846. IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
  3847. ModuleToSummariesForIndex);
  3848. IndexWriter.write();
  3849. }
  3850. /// Write the specified module to the specified output stream.
  3851. void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
  3852. bool ShouldPreserveUseListOrder,
  3853. const ModuleSummaryIndex *Index,
  3854. bool GenerateHash, ModuleHash *ModHash) {
  3855. SmallVector<char, 0> Buffer;
  3856. Buffer.reserve(256*1024);
  3857. // If this is darwin or another generic macho target, reserve space for the
  3858. // header.
  3859. Triple TT(M.getTargetTriple());
  3860. if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
  3861. Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
  3862. BitcodeWriter Writer(Buffer);
  3863. Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
  3864. ModHash);
  3865. Writer.writeSymtab();
  3866. Writer.writeStrtab();
  3867. if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
  3868. emitDarwinBCHeaderAndTrailer(Buffer, TT);
  3869. // Write the generated bitstream to "Out".
  3870. Out.write((char*)&Buffer.front(), Buffer.size());
  3871. }
  3872. void IndexBitcodeWriter::write() {
  3873. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  3874. writeModuleVersion();
  3875. // Write the module paths in the combined index.
  3876. writeModStrings();
  3877. // Write the summary combined index records.
  3878. writeCombinedGlobalValueSummary();
  3879. Stream.ExitBlock();
  3880. }
  3881. // Write the specified module summary index to the given raw output stream,
  3882. // where it will be written in a new bitcode block. This is used when
  3883. // writing the combined index file for ThinLTO. When writing a subset of the
  3884. // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
  3885. void llvm::WriteIndexToFile(
  3886. const ModuleSummaryIndex &Index, raw_ostream &Out,
  3887. const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
  3888. SmallVector<char, 0> Buffer;
  3889. Buffer.reserve(256 * 1024);
  3890. BitcodeWriter Writer(Buffer);
  3891. Writer.writeIndex(&Index, ModuleToSummariesForIndex);
  3892. Writer.writeStrtab();
  3893. Out.write((char *)&Buffer.front(), Buffer.size());
  3894. }
  3895. namespace {
  3896. /// Class to manage the bitcode writing for a thin link bitcode file.
  3897. class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
  3898. /// ModHash is for use in ThinLTO incremental build, generated while writing
  3899. /// the module bitcode file.
  3900. const ModuleHash *ModHash;
  3901. public:
  3902. ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
  3903. BitstreamWriter &Stream,
  3904. const ModuleSummaryIndex &Index,
  3905. const ModuleHash &ModHash)
  3906. : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
  3907. /*ShouldPreserveUseListOrder=*/false, &Index),
  3908. ModHash(&ModHash) {}
  3909. void write();
  3910. private:
  3911. void writeSimplifiedModuleInfo();
  3912. };
  3913. } // end anonymous namespace
  3914. // This function writes a simpilified module info for thin link bitcode file.
  3915. // It only contains the source file name along with the name(the offset and
  3916. // size in strtab) and linkage for global values. For the global value info
  3917. // entry, in order to keep linkage at offset 5, there are three zeros used
  3918. // as padding.
  3919. void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
  3920. SmallVector<unsigned, 64> Vals;
  3921. // Emit the module's source file name.
  3922. {
  3923. StringEncoding Bits = getStringEncoding(M.getSourceFileName());
  3924. BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
  3925. if (Bits == SE_Char6)
  3926. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
  3927. else if (Bits == SE_Fixed7)
  3928. AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
  3929. // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  3930. auto Abbv = std::make_shared<BitCodeAbbrev>();
  3931. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
  3932. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  3933. Abbv->Add(AbbrevOpToUse);
  3934. unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
  3935. for (const auto P : M.getSourceFileName())
  3936. Vals.push_back((unsigned char)P);
  3937. Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
  3938. Vals.clear();
  3939. }
  3940. // Emit the global variable information.
  3941. for (const GlobalVariable &GV : M.globals()) {
  3942. // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
  3943. Vals.push_back(StrtabBuilder.add(GV.getName()));
  3944. Vals.push_back(GV.getName().size());
  3945. Vals.push_back(0);
  3946. Vals.push_back(0);
  3947. Vals.push_back(0);
  3948. Vals.push_back(getEncodedLinkage(GV));
  3949. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
  3950. Vals.clear();
  3951. }
  3952. // Emit the function proto information.
  3953. for (const Function &F : M) {
  3954. // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
  3955. Vals.push_back(StrtabBuilder.add(F.getName()));
  3956. Vals.push_back(F.getName().size());
  3957. Vals.push_back(0);
  3958. Vals.push_back(0);
  3959. Vals.push_back(0);
  3960. Vals.push_back(getEncodedLinkage(F));
  3961. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
  3962. Vals.clear();
  3963. }
  3964. // Emit the alias information.
  3965. for (const GlobalAlias &A : M.aliases()) {
  3966. // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
  3967. Vals.push_back(StrtabBuilder.add(A.getName()));
  3968. Vals.push_back(A.getName().size());
  3969. Vals.push_back(0);
  3970. Vals.push_back(0);
  3971. Vals.push_back(0);
  3972. Vals.push_back(getEncodedLinkage(A));
  3973. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
  3974. Vals.clear();
  3975. }
  3976. // Emit the ifunc information.
  3977. for (const GlobalIFunc &I : M.ifuncs()) {
  3978. // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
  3979. Vals.push_back(StrtabBuilder.add(I.getName()));
  3980. Vals.push_back(I.getName().size());
  3981. Vals.push_back(0);
  3982. Vals.push_back(0);
  3983. Vals.push_back(0);
  3984. Vals.push_back(getEncodedLinkage(I));
  3985. Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
  3986. Vals.clear();
  3987. }
  3988. }
  3989. void ThinLinkBitcodeWriter::write() {
  3990. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  3991. writeModuleVersion();
  3992. writeSimplifiedModuleInfo();
  3993. writePerModuleGlobalValueSummary();
  3994. // Write module hash.
  3995. Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
  3996. Stream.ExitBlock();
  3997. }
  3998. void BitcodeWriter::writeThinLinkBitcode(const Module &M,
  3999. const ModuleSummaryIndex &Index,
  4000. const ModuleHash &ModHash) {
  4001. assert(!WroteStrtab);
  4002. // The Mods vector is used by irsymtab::build, which requires non-const
  4003. // Modules in case it needs to materialize metadata. But the bitcode writer
  4004. // requires that the module is materialized, so we can cast to non-const here,
  4005. // after checking that it is in fact materialized.
  4006. assert(M.isMaterialized());
  4007. Mods.push_back(const_cast<Module *>(&M));
  4008. ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
  4009. ModHash);
  4010. ThinLinkWriter.write();
  4011. }
  4012. // Write the specified thin link bitcode file to the given raw output stream,
  4013. // where it will be written in a new bitcode block. This is used when
  4014. // writing the per-module index file for ThinLTO.
  4015. void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
  4016. const ModuleSummaryIndex &Index,
  4017. const ModuleHash &ModHash) {
  4018. SmallVector<char, 0> Buffer;
  4019. Buffer.reserve(256 * 1024);
  4020. BitcodeWriter Writer(Buffer);
  4021. Writer.writeThinLinkBitcode(M, Index, ModHash);
  4022. Writer.writeSymtab();
  4023. Writer.writeStrtab();
  4024. Out.write((char *)&Buffer.front(), Buffer.size());
  4025. }