BitcodeWriter.cpp 164 KB

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