BitcodeWriter.cpp 156 KB

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