BitcodeWriter.cpp 154 KB

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