BitcodeWriter.cpp 173 KB

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