BitcodeWriter.cpp 177 KB

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