BitcodeWriter.cpp 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124
  1. //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Bitcode writer implementation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "ValueEnumerator.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/Triple.h"
  17. #include "llvm/Bitcode/BitstreamWriter.h"
  18. #include "llvm/Bitcode/LLVMBitCodes.h"
  19. #include "llvm/IR/CallSite.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/DebugInfoMetadata.h"
  22. #include "llvm/IR/DerivedTypes.h"
  23. #include "llvm/IR/InlineAsm.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/UseListOrder.h"
  30. #include "llvm/IR/ValueSymbolTable.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/MathExtras.h"
  34. #include "llvm/Support/Program.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <cctype>
  37. #include <map>
  38. using namespace llvm;
  39. /// These are manifest constants used by the bitcode writer. They do not need to
  40. /// be kept in sync with the reader, but need to be consistent within this file.
  41. enum {
  42. // VALUE_SYMTAB_BLOCK abbrev id's.
  43. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  44. VST_ENTRY_7_ABBREV,
  45. VST_ENTRY_6_ABBREV,
  46. VST_BBENTRY_6_ABBREV,
  47. // CONSTANTS_BLOCK abbrev id's.
  48. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  49. CONSTANTS_INTEGER_ABBREV,
  50. CONSTANTS_CE_CAST_Abbrev,
  51. CONSTANTS_NULL_Abbrev,
  52. // FUNCTION_BLOCK abbrev id's.
  53. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  54. FUNCTION_INST_BINOP_ABBREV,
  55. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  56. FUNCTION_INST_CAST_ABBREV,
  57. FUNCTION_INST_RET_VOID_ABBREV,
  58. FUNCTION_INST_RET_VAL_ABBREV,
  59. FUNCTION_INST_UNREACHABLE_ABBREV,
  60. FUNCTION_INST_GEP_ABBREV,
  61. };
  62. static unsigned GetEncodedCastOpcode(unsigned Opcode) {
  63. switch (Opcode) {
  64. default: llvm_unreachable("Unknown cast instruction!");
  65. case Instruction::Trunc : return bitc::CAST_TRUNC;
  66. case Instruction::ZExt : return bitc::CAST_ZEXT;
  67. case Instruction::SExt : return bitc::CAST_SEXT;
  68. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  69. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  70. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  71. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  72. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  73. case Instruction::FPExt : return bitc::CAST_FPEXT;
  74. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  75. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  76. case Instruction::BitCast : return bitc::CAST_BITCAST;
  77. case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
  78. }
  79. }
  80. static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
  81. switch (Opcode) {
  82. default: llvm_unreachable("Unknown binary instruction!");
  83. case Instruction::Add:
  84. case Instruction::FAdd: return bitc::BINOP_ADD;
  85. case Instruction::Sub:
  86. case Instruction::FSub: return bitc::BINOP_SUB;
  87. case Instruction::Mul:
  88. case Instruction::FMul: return bitc::BINOP_MUL;
  89. case Instruction::UDiv: return bitc::BINOP_UDIV;
  90. case Instruction::FDiv:
  91. case Instruction::SDiv: return bitc::BINOP_SDIV;
  92. case Instruction::URem: return bitc::BINOP_UREM;
  93. case Instruction::FRem:
  94. case Instruction::SRem: return bitc::BINOP_SREM;
  95. case Instruction::Shl: return bitc::BINOP_SHL;
  96. case Instruction::LShr: return bitc::BINOP_LSHR;
  97. case Instruction::AShr: return bitc::BINOP_ASHR;
  98. case Instruction::And: return bitc::BINOP_AND;
  99. case Instruction::Or: return bitc::BINOP_OR;
  100. case Instruction::Xor: return bitc::BINOP_XOR;
  101. }
  102. }
  103. static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
  104. switch (Op) {
  105. default: llvm_unreachable("Unknown RMW operation!");
  106. case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
  107. case AtomicRMWInst::Add: return bitc::RMW_ADD;
  108. case AtomicRMWInst::Sub: return bitc::RMW_SUB;
  109. case AtomicRMWInst::And: return bitc::RMW_AND;
  110. case AtomicRMWInst::Nand: return bitc::RMW_NAND;
  111. case AtomicRMWInst::Or: return bitc::RMW_OR;
  112. case AtomicRMWInst::Xor: return bitc::RMW_XOR;
  113. case AtomicRMWInst::Max: return bitc::RMW_MAX;
  114. case AtomicRMWInst::Min: return bitc::RMW_MIN;
  115. case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
  116. case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
  117. }
  118. }
  119. static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
  120. switch (Ordering) {
  121. case NotAtomic: return bitc::ORDERING_NOTATOMIC;
  122. case Unordered: return bitc::ORDERING_UNORDERED;
  123. case Monotonic: return bitc::ORDERING_MONOTONIC;
  124. case Acquire: return bitc::ORDERING_ACQUIRE;
  125. case Release: return bitc::ORDERING_RELEASE;
  126. case AcquireRelease: return bitc::ORDERING_ACQREL;
  127. case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
  128. }
  129. llvm_unreachable("Invalid ordering");
  130. }
  131. static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
  132. switch (SynchScope) {
  133. case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
  134. case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
  135. }
  136. llvm_unreachable("Invalid synch scope");
  137. }
  138. static void WriteStringRecord(unsigned Code, StringRef Str,
  139. unsigned AbbrevToUse, BitstreamWriter &Stream) {
  140. SmallVector<unsigned, 64> Vals;
  141. // Code: [strchar x N]
  142. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  143. if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
  144. AbbrevToUse = 0;
  145. Vals.push_back(Str[i]);
  146. }
  147. // Emit the finished record.
  148. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  149. }
  150. static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
  151. switch (Kind) {
  152. case Attribute::Alignment:
  153. return bitc::ATTR_KIND_ALIGNMENT;
  154. case Attribute::AlwaysInline:
  155. return bitc::ATTR_KIND_ALWAYS_INLINE;
  156. case Attribute::ArgMemOnly:
  157. return bitc::ATTR_KIND_ARGMEMONLY;
  158. case Attribute::Builtin:
  159. return bitc::ATTR_KIND_BUILTIN;
  160. case Attribute::ByVal:
  161. return bitc::ATTR_KIND_BY_VAL;
  162. case Attribute::Convergent:
  163. return bitc::ATTR_KIND_CONVERGENT;
  164. case Attribute::InAlloca:
  165. return bitc::ATTR_KIND_IN_ALLOCA;
  166. case Attribute::Cold:
  167. return bitc::ATTR_KIND_COLD;
  168. case Attribute::InlineHint:
  169. return bitc::ATTR_KIND_INLINE_HINT;
  170. case Attribute::InReg:
  171. return bitc::ATTR_KIND_IN_REG;
  172. case Attribute::JumpTable:
  173. return bitc::ATTR_KIND_JUMP_TABLE;
  174. case Attribute::MinSize:
  175. return bitc::ATTR_KIND_MIN_SIZE;
  176. case Attribute::Naked:
  177. return bitc::ATTR_KIND_NAKED;
  178. case Attribute::Nest:
  179. return bitc::ATTR_KIND_NEST;
  180. case Attribute::NoAlias:
  181. return bitc::ATTR_KIND_NO_ALIAS;
  182. case Attribute::NoBuiltin:
  183. return bitc::ATTR_KIND_NO_BUILTIN;
  184. case Attribute::NoCapture:
  185. return bitc::ATTR_KIND_NO_CAPTURE;
  186. case Attribute::NoDuplicate:
  187. return bitc::ATTR_KIND_NO_DUPLICATE;
  188. case Attribute::NoImplicitFloat:
  189. return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
  190. case Attribute::NoInline:
  191. return bitc::ATTR_KIND_NO_INLINE;
  192. case Attribute::NoRecurse:
  193. return bitc::ATTR_KIND_NO_RECURSE;
  194. case Attribute::NonLazyBind:
  195. return bitc::ATTR_KIND_NON_LAZY_BIND;
  196. case Attribute::NonNull:
  197. return bitc::ATTR_KIND_NON_NULL;
  198. case Attribute::Dereferenceable:
  199. return bitc::ATTR_KIND_DEREFERENCEABLE;
  200. case Attribute::DereferenceableOrNull:
  201. return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
  202. case Attribute::NoRedZone:
  203. return bitc::ATTR_KIND_NO_RED_ZONE;
  204. case Attribute::NoReturn:
  205. return bitc::ATTR_KIND_NO_RETURN;
  206. case Attribute::NoUnwind:
  207. return bitc::ATTR_KIND_NO_UNWIND;
  208. case Attribute::OptimizeForSize:
  209. return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
  210. case Attribute::OptimizeNone:
  211. return bitc::ATTR_KIND_OPTIMIZE_NONE;
  212. case Attribute::ReadNone:
  213. return bitc::ATTR_KIND_READ_NONE;
  214. case Attribute::ReadOnly:
  215. return bitc::ATTR_KIND_READ_ONLY;
  216. case Attribute::Returned:
  217. return bitc::ATTR_KIND_RETURNED;
  218. case Attribute::ReturnsTwice:
  219. return bitc::ATTR_KIND_RETURNS_TWICE;
  220. case Attribute::SExt:
  221. return bitc::ATTR_KIND_S_EXT;
  222. case Attribute::StackAlignment:
  223. return bitc::ATTR_KIND_STACK_ALIGNMENT;
  224. case Attribute::StackProtect:
  225. return bitc::ATTR_KIND_STACK_PROTECT;
  226. case Attribute::StackProtectReq:
  227. return bitc::ATTR_KIND_STACK_PROTECT_REQ;
  228. case Attribute::StackProtectStrong:
  229. return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
  230. case Attribute::SafeStack:
  231. return bitc::ATTR_KIND_SAFESTACK;
  232. case Attribute::StructRet:
  233. return bitc::ATTR_KIND_STRUCT_RET;
  234. case Attribute::SanitizeAddress:
  235. return bitc::ATTR_KIND_SANITIZE_ADDRESS;
  236. case Attribute::SanitizeThread:
  237. return bitc::ATTR_KIND_SANITIZE_THREAD;
  238. case Attribute::SanitizeMemory:
  239. return bitc::ATTR_KIND_SANITIZE_MEMORY;
  240. case Attribute::UWTable:
  241. return bitc::ATTR_KIND_UW_TABLE;
  242. case Attribute::ZExt:
  243. return bitc::ATTR_KIND_Z_EXT;
  244. case Attribute::EndAttrKinds:
  245. llvm_unreachable("Can not encode end-attribute kinds marker.");
  246. case Attribute::None:
  247. llvm_unreachable("Can not encode none-attribute.");
  248. }
  249. llvm_unreachable("Trying to encode unknown attribute");
  250. }
  251. static void WriteAttributeGroupTable(const ValueEnumerator &VE,
  252. BitstreamWriter &Stream) {
  253. const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
  254. if (AttrGrps.empty()) return;
  255. Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
  256. SmallVector<uint64_t, 64> Record;
  257. for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
  258. AttributeSet AS = AttrGrps[i];
  259. for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
  260. AttributeSet A = AS.getSlotAttributes(i);
  261. Record.push_back(VE.getAttributeGroupID(A));
  262. Record.push_back(AS.getSlotIndex(i));
  263. for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
  264. I != E; ++I) {
  265. Attribute Attr = *I;
  266. if (Attr.isEnumAttribute()) {
  267. Record.push_back(0);
  268. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  269. } else if (Attr.isIntAttribute()) {
  270. Record.push_back(1);
  271. Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
  272. Record.push_back(Attr.getValueAsInt());
  273. } else {
  274. StringRef Kind = Attr.getKindAsString();
  275. StringRef Val = Attr.getValueAsString();
  276. Record.push_back(Val.empty() ? 3 : 4);
  277. Record.append(Kind.begin(), Kind.end());
  278. Record.push_back(0);
  279. if (!Val.empty()) {
  280. Record.append(Val.begin(), Val.end());
  281. Record.push_back(0);
  282. }
  283. }
  284. }
  285. Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
  286. Record.clear();
  287. }
  288. }
  289. Stream.ExitBlock();
  290. }
  291. static void WriteAttributeTable(const ValueEnumerator &VE,
  292. BitstreamWriter &Stream) {
  293. const std::vector<AttributeSet> &Attrs = VE.getAttributes();
  294. if (Attrs.empty()) return;
  295. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  296. SmallVector<uint64_t, 64> Record;
  297. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  298. const AttributeSet &A = Attrs[i];
  299. for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
  300. Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
  301. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  302. Record.clear();
  303. }
  304. Stream.ExitBlock();
  305. }
  306. /// WriteTypeTable - Write out the type table for a module.
  307. static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  308. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  309. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
  310. SmallVector<uint64_t, 64> TypeVals;
  311. uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
  312. // Abbrev for TYPE_CODE_POINTER.
  313. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  314. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  315. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  316. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  317. unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
  318. // Abbrev for TYPE_CODE_FUNCTION.
  319. Abbv = new BitCodeAbbrev();
  320. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  321. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  322. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  323. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  324. unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
  325. // Abbrev for TYPE_CODE_STRUCT_ANON.
  326. Abbv = new BitCodeAbbrev();
  327. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
  328. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  329. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  330. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  331. unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
  332. // Abbrev for TYPE_CODE_STRUCT_NAME.
  333. Abbv = new BitCodeAbbrev();
  334. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
  335. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  336. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  337. unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
  338. // Abbrev for TYPE_CODE_STRUCT_NAMED.
  339. Abbv = new BitCodeAbbrev();
  340. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
  341. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  342. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  344. unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
  345. // Abbrev for TYPE_CODE_ARRAY.
  346. Abbv = new BitCodeAbbrev();
  347. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  348. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  349. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
  350. unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
  351. // Emit an entry count so the reader can reserve space.
  352. TypeVals.push_back(TypeList.size());
  353. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  354. TypeVals.clear();
  355. // Loop over all of the types, emitting each in turn.
  356. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  357. Type *T = TypeList[i];
  358. int AbbrevToUse = 0;
  359. unsigned Code = 0;
  360. switch (T->getTypeID()) {
  361. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  362. case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
  363. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  364. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  365. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  366. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  367. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  368. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  369. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  370. case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
  371. case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
  372. case Type::IntegerTyID:
  373. // INTEGER: [width]
  374. Code = bitc::TYPE_CODE_INTEGER;
  375. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  376. break;
  377. case Type::PointerTyID: {
  378. PointerType *PTy = cast<PointerType>(T);
  379. // POINTER: [pointee type, address space]
  380. Code = bitc::TYPE_CODE_POINTER;
  381. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  382. unsigned AddressSpace = PTy->getAddressSpace();
  383. TypeVals.push_back(AddressSpace);
  384. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  385. break;
  386. }
  387. case Type::FunctionTyID: {
  388. FunctionType *FT = cast<FunctionType>(T);
  389. // FUNCTION: [isvararg, retty, paramty x N]
  390. Code = bitc::TYPE_CODE_FUNCTION;
  391. TypeVals.push_back(FT->isVarArg());
  392. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  393. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  394. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  395. AbbrevToUse = FunctionAbbrev;
  396. break;
  397. }
  398. case Type::StructTyID: {
  399. StructType *ST = cast<StructType>(T);
  400. // STRUCT: [ispacked, eltty x N]
  401. TypeVals.push_back(ST->isPacked());
  402. // Output all of the element types.
  403. for (StructType::element_iterator I = ST->element_begin(),
  404. E = ST->element_end(); I != E; ++I)
  405. TypeVals.push_back(VE.getTypeID(*I));
  406. if (ST->isLiteral()) {
  407. Code = bitc::TYPE_CODE_STRUCT_ANON;
  408. AbbrevToUse = StructAnonAbbrev;
  409. } else {
  410. if (ST->isOpaque()) {
  411. Code = bitc::TYPE_CODE_OPAQUE;
  412. } else {
  413. Code = bitc::TYPE_CODE_STRUCT_NAMED;
  414. AbbrevToUse = StructNamedAbbrev;
  415. }
  416. // Emit the name if it is present.
  417. if (!ST->getName().empty())
  418. WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
  419. StructNameAbbrev, Stream);
  420. }
  421. break;
  422. }
  423. case Type::ArrayTyID: {
  424. ArrayType *AT = cast<ArrayType>(T);
  425. // ARRAY: [numelts, eltty]
  426. Code = bitc::TYPE_CODE_ARRAY;
  427. TypeVals.push_back(AT->getNumElements());
  428. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  429. AbbrevToUse = ArrayAbbrev;
  430. break;
  431. }
  432. case Type::VectorTyID: {
  433. VectorType *VT = cast<VectorType>(T);
  434. // VECTOR [numelts, eltty]
  435. Code = bitc::TYPE_CODE_VECTOR;
  436. TypeVals.push_back(VT->getNumElements());
  437. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  438. break;
  439. }
  440. }
  441. // Emit the finished record.
  442. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  443. TypeVals.clear();
  444. }
  445. Stream.ExitBlock();
  446. }
  447. static unsigned getEncodedLinkage(const GlobalValue &GV) {
  448. switch (GV.getLinkage()) {
  449. case GlobalValue::ExternalLinkage:
  450. return 0;
  451. case GlobalValue::WeakAnyLinkage:
  452. return 16;
  453. case GlobalValue::AppendingLinkage:
  454. return 2;
  455. case GlobalValue::InternalLinkage:
  456. return 3;
  457. case GlobalValue::LinkOnceAnyLinkage:
  458. return 18;
  459. case GlobalValue::ExternalWeakLinkage:
  460. return 7;
  461. case GlobalValue::CommonLinkage:
  462. return 8;
  463. case GlobalValue::PrivateLinkage:
  464. return 9;
  465. case GlobalValue::WeakODRLinkage:
  466. return 17;
  467. case GlobalValue::LinkOnceODRLinkage:
  468. return 19;
  469. case GlobalValue::AvailableExternallyLinkage:
  470. return 12;
  471. }
  472. llvm_unreachable("Invalid linkage");
  473. }
  474. static unsigned getEncodedVisibility(const GlobalValue &GV) {
  475. switch (GV.getVisibility()) {
  476. case GlobalValue::DefaultVisibility: return 0;
  477. case GlobalValue::HiddenVisibility: return 1;
  478. case GlobalValue::ProtectedVisibility: return 2;
  479. }
  480. llvm_unreachable("Invalid visibility");
  481. }
  482. static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
  483. switch (GV.getDLLStorageClass()) {
  484. case GlobalValue::DefaultStorageClass: return 0;
  485. case GlobalValue::DLLImportStorageClass: return 1;
  486. case GlobalValue::DLLExportStorageClass: return 2;
  487. }
  488. llvm_unreachable("Invalid DLL storage class");
  489. }
  490. static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
  491. switch (GV.getThreadLocalMode()) {
  492. case GlobalVariable::NotThreadLocal: return 0;
  493. case GlobalVariable::GeneralDynamicTLSModel: return 1;
  494. case GlobalVariable::LocalDynamicTLSModel: return 2;
  495. case GlobalVariable::InitialExecTLSModel: return 3;
  496. case GlobalVariable::LocalExecTLSModel: return 4;
  497. }
  498. llvm_unreachable("Invalid TLS model");
  499. }
  500. static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
  501. switch (C.getSelectionKind()) {
  502. case Comdat::Any:
  503. return bitc::COMDAT_SELECTION_KIND_ANY;
  504. case Comdat::ExactMatch:
  505. return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
  506. case Comdat::Largest:
  507. return bitc::COMDAT_SELECTION_KIND_LARGEST;
  508. case Comdat::NoDuplicates:
  509. return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
  510. case Comdat::SameSize:
  511. return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
  512. }
  513. llvm_unreachable("Invalid selection kind");
  514. }
  515. static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  516. SmallVector<uint16_t, 64> Vals;
  517. for (const Comdat *C : VE.getComdats()) {
  518. // COMDAT: [selection_kind, name]
  519. Vals.push_back(getEncodedComdatSelectionKind(*C));
  520. size_t Size = C->getName().size();
  521. assert(isUInt<16>(Size));
  522. Vals.push_back(Size);
  523. for (char Chr : C->getName())
  524. Vals.push_back((unsigned char)Chr);
  525. Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
  526. Vals.clear();
  527. }
  528. }
  529. /// Write a record that will eventually hold the word offset of the
  530. /// module-level VST. For now the offset is 0, which will be backpatched
  531. /// after the real VST is written. Returns the bit offset to backpatch.
  532. static uint64_t WriteValueSymbolTableForwardDecl(const ValueSymbolTable &VST,
  533. BitstreamWriter &Stream) {
  534. if (VST.empty())
  535. return 0;
  536. // Write a placeholder value in for the offset of the real VST,
  537. // which is written after the function blocks so that it can include
  538. // the offset of each function. The placeholder offset will be
  539. // updated when the real VST is written.
  540. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  541. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
  542. // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
  543. // hold the real VST offset. Must use fixed instead of VBR as we don't
  544. // know how many VBR chunks to reserve ahead of time.
  545. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  546. unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
  547. // Emit the placeholder
  548. uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
  549. Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
  550. // Compute and return the bit offset to the placeholder, which will be
  551. // patched when the real VST is written. We can simply subtract the 32-bit
  552. // fixed size from the current bit number to get the location to backpatch.
  553. return Stream.GetCurrentBitNo() - 32;
  554. }
  555. /// Emit top-level description of module, including target triple, inline asm,
  556. /// descriptors for global variables, and function prototype info.
  557. /// Returns the bit offset to backpatch with the location of the real VST.
  558. static uint64_t WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
  559. BitstreamWriter &Stream) {
  560. // Emit various pieces of data attached to a module.
  561. if (!M->getTargetTriple().empty())
  562. WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
  563. 0/*TODO*/, Stream);
  564. const std::string &DL = M->getDataLayoutStr();
  565. if (!DL.empty())
  566. WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
  567. if (!M->getModuleInlineAsm().empty())
  568. WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
  569. 0/*TODO*/, Stream);
  570. // Emit information about sections and GC, computing how many there are. Also
  571. // compute the maximum alignment value.
  572. std::map<std::string, unsigned> SectionMap;
  573. std::map<std::string, unsigned> GCMap;
  574. unsigned MaxAlignment = 0;
  575. unsigned MaxGlobalType = 0;
  576. for (const GlobalValue &GV : M->globals()) {
  577. MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
  578. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
  579. if (GV.hasSection()) {
  580. // Give section names unique ID's.
  581. unsigned &Entry = SectionMap[GV.getSection()];
  582. if (!Entry) {
  583. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
  584. 0/*TODO*/, Stream);
  585. Entry = SectionMap.size();
  586. }
  587. }
  588. }
  589. for (const Function &F : *M) {
  590. MaxAlignment = std::max(MaxAlignment, F.getAlignment());
  591. if (F.hasSection()) {
  592. // Give section names unique ID's.
  593. unsigned &Entry = SectionMap[F.getSection()];
  594. if (!Entry) {
  595. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
  596. 0/*TODO*/, Stream);
  597. Entry = SectionMap.size();
  598. }
  599. }
  600. if (F.hasGC()) {
  601. // Same for GC names.
  602. unsigned &Entry = GCMap[F.getGC()];
  603. if (!Entry) {
  604. WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
  605. 0/*TODO*/, Stream);
  606. Entry = GCMap.size();
  607. }
  608. }
  609. }
  610. // Emit abbrev for globals, now that we know # sections and max alignment.
  611. unsigned SimpleGVarAbbrev = 0;
  612. if (!M->global_empty()) {
  613. // Add an abbrev for common globals with no visibility or thread localness.
  614. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  615. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  616. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  617. Log2_32_Ceil(MaxGlobalType+1)));
  618. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
  619. //| explicitType << 1
  620. //| constant
  621. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  622. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
  623. if (MaxAlignment == 0) // Alignment.
  624. Abbv->Add(BitCodeAbbrevOp(0));
  625. else {
  626. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  627. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  628. Log2_32_Ceil(MaxEncAlignment+1)));
  629. }
  630. if (SectionMap.empty()) // Section.
  631. Abbv->Add(BitCodeAbbrevOp(0));
  632. else
  633. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  634. Log2_32_Ceil(SectionMap.size()+1)));
  635. // Don't bother emitting vis + thread local.
  636. SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
  637. }
  638. // Emit the global variable information.
  639. SmallVector<unsigned, 64> Vals;
  640. for (const GlobalVariable &GV : M->globals()) {
  641. unsigned AbbrevToUse = 0;
  642. // GLOBALVAR: [type, isconst, initid,
  643. // linkage, alignment, section, visibility, threadlocal,
  644. // unnamed_addr, externally_initialized, dllstorageclass,
  645. // comdat]
  646. Vals.push_back(VE.getTypeID(GV.getValueType()));
  647. Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
  648. Vals.push_back(GV.isDeclaration() ? 0 :
  649. (VE.getValueID(GV.getInitializer()) + 1));
  650. Vals.push_back(getEncodedLinkage(GV));
  651. Vals.push_back(Log2_32(GV.getAlignment())+1);
  652. Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
  653. if (GV.isThreadLocal() ||
  654. GV.getVisibility() != GlobalValue::DefaultVisibility ||
  655. GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
  656. GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
  657. GV.hasComdat()) {
  658. Vals.push_back(getEncodedVisibility(GV));
  659. Vals.push_back(getEncodedThreadLocalMode(GV));
  660. Vals.push_back(GV.hasUnnamedAddr());
  661. Vals.push_back(GV.isExternallyInitialized());
  662. Vals.push_back(getEncodedDLLStorageClass(GV));
  663. Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
  664. } else {
  665. AbbrevToUse = SimpleGVarAbbrev;
  666. }
  667. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  668. Vals.clear();
  669. }
  670. // Emit the function proto information.
  671. for (const Function &F : *M) {
  672. // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
  673. // section, visibility, gc, unnamed_addr, prologuedata,
  674. // dllstorageclass, comdat, prefixdata, personalityfn]
  675. Vals.push_back(VE.getTypeID(F.getFunctionType()));
  676. Vals.push_back(F.getCallingConv());
  677. Vals.push_back(F.isDeclaration());
  678. Vals.push_back(getEncodedLinkage(F));
  679. Vals.push_back(VE.getAttributeID(F.getAttributes()));
  680. Vals.push_back(Log2_32(F.getAlignment())+1);
  681. Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
  682. Vals.push_back(getEncodedVisibility(F));
  683. Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
  684. Vals.push_back(F.hasUnnamedAddr());
  685. Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
  686. : 0);
  687. Vals.push_back(getEncodedDLLStorageClass(F));
  688. Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
  689. Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
  690. : 0);
  691. Vals.push_back(
  692. F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
  693. unsigned AbbrevToUse = 0;
  694. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  695. Vals.clear();
  696. }
  697. // Emit the alias information.
  698. for (const GlobalAlias &A : M->aliases()) {
  699. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  700. Vals.push_back(VE.getTypeID(A.getValueType()));
  701. Vals.push_back(A.getType()->getAddressSpace());
  702. Vals.push_back(VE.getValueID(A.getAliasee()));
  703. Vals.push_back(getEncodedLinkage(A));
  704. Vals.push_back(getEncodedVisibility(A));
  705. Vals.push_back(getEncodedDLLStorageClass(A));
  706. Vals.push_back(getEncodedThreadLocalMode(A));
  707. Vals.push_back(A.hasUnnamedAddr());
  708. unsigned AbbrevToUse = 0;
  709. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  710. Vals.clear();
  711. }
  712. // Write a record indicating the number of module-level metadata IDs
  713. // This is needed because the ids of metadata are assigned implicitly
  714. // based on their ordering in the bitcode, with the function-level
  715. // metadata ids starting after the module-level metadata ids. For
  716. // function importing where we lazy load the metadata as a postpass,
  717. // we want to avoid parsing the module-level metadata before parsing
  718. // the imported functions.
  719. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  720. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_METADATA_VALUES));
  721. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  722. unsigned MDValsAbbrev = Stream.EmitAbbrev(Abbv);
  723. Vals.push_back(VE.numMDs());
  724. Stream.EmitRecord(bitc::MODULE_CODE_METADATA_VALUES, Vals, MDValsAbbrev);
  725. Vals.clear();
  726. uint64_t VSTOffsetPlaceholder =
  727. WriteValueSymbolTableForwardDecl(M->getValueSymbolTable(), Stream);
  728. return VSTOffsetPlaceholder;
  729. }
  730. static uint64_t GetOptimizationFlags(const Value *V) {
  731. uint64_t Flags = 0;
  732. if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
  733. if (OBO->hasNoSignedWrap())
  734. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  735. if (OBO->hasNoUnsignedWrap())
  736. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  737. } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
  738. if (PEO->isExact())
  739. Flags |= 1 << bitc::PEO_EXACT;
  740. } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
  741. if (FPMO->hasUnsafeAlgebra())
  742. Flags |= FastMathFlags::UnsafeAlgebra;
  743. if (FPMO->hasNoNaNs())
  744. Flags |= FastMathFlags::NoNaNs;
  745. if (FPMO->hasNoInfs())
  746. Flags |= FastMathFlags::NoInfs;
  747. if (FPMO->hasNoSignedZeros())
  748. Flags |= FastMathFlags::NoSignedZeros;
  749. if (FPMO->hasAllowReciprocal())
  750. Flags |= FastMathFlags::AllowReciprocal;
  751. }
  752. return Flags;
  753. }
  754. static void WriteValueAsMetadata(const ValueAsMetadata *MD,
  755. const ValueEnumerator &VE,
  756. BitstreamWriter &Stream,
  757. SmallVectorImpl<uint64_t> &Record) {
  758. // Mimic an MDNode with a value as one operand.
  759. Value *V = MD->getValue();
  760. Record.push_back(VE.getTypeID(V->getType()));
  761. Record.push_back(VE.getValueID(V));
  762. Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
  763. Record.clear();
  764. }
  765. static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
  766. BitstreamWriter &Stream,
  767. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  768. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  769. Metadata *MD = N->getOperand(i);
  770. assert(!(MD && isa<LocalAsMetadata>(MD)) &&
  771. "Unexpected function-local metadata");
  772. Record.push_back(VE.getMetadataOrNullID(MD));
  773. }
  774. Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
  775. : bitc::METADATA_NODE,
  776. Record, Abbrev);
  777. Record.clear();
  778. }
  779. static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
  780. BitstreamWriter &Stream,
  781. SmallVectorImpl<uint64_t> &Record,
  782. unsigned Abbrev) {
  783. Record.push_back(N->isDistinct());
  784. Record.push_back(N->getLine());
  785. Record.push_back(N->getColumn());
  786. Record.push_back(VE.getMetadataID(N->getScope()));
  787. Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
  788. Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
  789. Record.clear();
  790. }
  791. static void WriteGenericDINode(const GenericDINode *N,
  792. const ValueEnumerator &VE,
  793. BitstreamWriter &Stream,
  794. SmallVectorImpl<uint64_t> &Record,
  795. unsigned Abbrev) {
  796. Record.push_back(N->isDistinct());
  797. Record.push_back(N->getTag());
  798. Record.push_back(0); // Per-tag version field; unused for now.
  799. for (auto &I : N->operands())
  800. Record.push_back(VE.getMetadataOrNullID(I));
  801. Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
  802. Record.clear();
  803. }
  804. static uint64_t rotateSign(int64_t I) {
  805. uint64_t U = I;
  806. return I < 0 ? ~(U << 1) : U << 1;
  807. }
  808. static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
  809. BitstreamWriter &Stream,
  810. SmallVectorImpl<uint64_t> &Record,
  811. unsigned Abbrev) {
  812. Record.push_back(N->isDistinct());
  813. Record.push_back(N->getCount());
  814. Record.push_back(rotateSign(N->getLowerBound()));
  815. Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
  816. Record.clear();
  817. }
  818. static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
  819. BitstreamWriter &Stream,
  820. SmallVectorImpl<uint64_t> &Record,
  821. unsigned Abbrev) {
  822. Record.push_back(N->isDistinct());
  823. Record.push_back(rotateSign(N->getValue()));
  824. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  825. Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
  826. Record.clear();
  827. }
  828. static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
  829. BitstreamWriter &Stream,
  830. SmallVectorImpl<uint64_t> &Record,
  831. unsigned Abbrev) {
  832. Record.push_back(N->isDistinct());
  833. Record.push_back(N->getTag());
  834. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  835. Record.push_back(N->getSizeInBits());
  836. Record.push_back(N->getAlignInBits());
  837. Record.push_back(N->getEncoding());
  838. Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
  839. Record.clear();
  840. }
  841. static void WriteDIDerivedType(const DIDerivedType *N,
  842. const ValueEnumerator &VE,
  843. BitstreamWriter &Stream,
  844. SmallVectorImpl<uint64_t> &Record,
  845. unsigned Abbrev) {
  846. Record.push_back(N->isDistinct());
  847. Record.push_back(N->getTag());
  848. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  849. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  850. Record.push_back(N->getLine());
  851. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  852. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  853. Record.push_back(N->getSizeInBits());
  854. Record.push_back(N->getAlignInBits());
  855. Record.push_back(N->getOffsetInBits());
  856. Record.push_back(N->getFlags());
  857. Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
  858. Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
  859. Record.clear();
  860. }
  861. static void WriteDICompositeType(const DICompositeType *N,
  862. const ValueEnumerator &VE,
  863. BitstreamWriter &Stream,
  864. SmallVectorImpl<uint64_t> &Record,
  865. unsigned Abbrev) {
  866. Record.push_back(N->isDistinct());
  867. Record.push_back(N->getTag());
  868. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  869. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  870. Record.push_back(N->getLine());
  871. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  872. Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
  873. Record.push_back(N->getSizeInBits());
  874. Record.push_back(N->getAlignInBits());
  875. Record.push_back(N->getOffsetInBits());
  876. Record.push_back(N->getFlags());
  877. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  878. Record.push_back(N->getRuntimeLang());
  879. Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
  880. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  881. Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
  882. Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
  883. Record.clear();
  884. }
  885. static void WriteDISubroutineType(const DISubroutineType *N,
  886. const ValueEnumerator &VE,
  887. BitstreamWriter &Stream,
  888. SmallVectorImpl<uint64_t> &Record,
  889. unsigned Abbrev) {
  890. Record.push_back(N->isDistinct());
  891. Record.push_back(N->getFlags());
  892. Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
  893. Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
  894. Record.clear();
  895. }
  896. static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
  897. BitstreamWriter &Stream,
  898. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  899. Record.push_back(N->isDistinct());
  900. Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
  901. Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
  902. Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
  903. Record.clear();
  904. }
  905. static void WriteDICompileUnit(const DICompileUnit *N,
  906. const ValueEnumerator &VE,
  907. BitstreamWriter &Stream,
  908. SmallVectorImpl<uint64_t> &Record,
  909. unsigned Abbrev) {
  910. assert(N->isDistinct() && "Expected distinct compile units");
  911. Record.push_back(/* IsDistinct */ true);
  912. Record.push_back(N->getSourceLanguage());
  913. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  914. Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
  915. Record.push_back(N->isOptimized());
  916. Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
  917. Record.push_back(N->getRuntimeVersion());
  918. Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
  919. Record.push_back(N->getEmissionKind());
  920. Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
  921. Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
  922. Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
  923. Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
  924. Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
  925. Record.push_back(N->getDWOId());
  926. Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
  927. Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
  928. Record.clear();
  929. }
  930. static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
  931. BitstreamWriter &Stream,
  932. SmallVectorImpl<uint64_t> &Record,
  933. unsigned Abbrev) {
  934. Record.push_back(N->isDistinct());
  935. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  936. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  937. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  938. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  939. Record.push_back(N->getLine());
  940. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  941. Record.push_back(N->isLocalToUnit());
  942. Record.push_back(N->isDefinition());
  943. Record.push_back(N->getScopeLine());
  944. Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
  945. Record.push_back(N->getVirtuality());
  946. Record.push_back(N->getVirtualIndex());
  947. Record.push_back(N->getFlags());
  948. Record.push_back(N->isOptimized());
  949. Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
  950. Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
  951. Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
  952. Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
  953. Record.clear();
  954. }
  955. static void WriteDILexicalBlock(const DILexicalBlock *N,
  956. const ValueEnumerator &VE,
  957. BitstreamWriter &Stream,
  958. SmallVectorImpl<uint64_t> &Record,
  959. unsigned Abbrev) {
  960. Record.push_back(N->isDistinct());
  961. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  962. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  963. Record.push_back(N->getLine());
  964. Record.push_back(N->getColumn());
  965. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
  966. Record.clear();
  967. }
  968. static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
  969. const ValueEnumerator &VE,
  970. BitstreamWriter &Stream,
  971. SmallVectorImpl<uint64_t> &Record,
  972. unsigned Abbrev) {
  973. Record.push_back(N->isDistinct());
  974. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  975. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  976. Record.push_back(N->getDiscriminator());
  977. Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
  978. Record.clear();
  979. }
  980. static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
  981. BitstreamWriter &Stream,
  982. SmallVectorImpl<uint64_t> &Record,
  983. unsigned Abbrev) {
  984. Record.push_back(N->isDistinct());
  985. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  986. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  987. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  988. Record.push_back(N->getLine());
  989. Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
  990. Record.clear();
  991. }
  992. static void WriteDIMacro(const DIMacro *N, const ValueEnumerator &VE,
  993. BitstreamWriter &Stream,
  994. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  995. Record.push_back(N->isDistinct());
  996. Record.push_back(N->getMacinfoType());
  997. Record.push_back(N->getLine());
  998. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  999. Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
  1000. Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
  1001. Record.clear();
  1002. }
  1003. static void WriteDIMacroFile(const DIMacroFile *N, const ValueEnumerator &VE,
  1004. BitstreamWriter &Stream,
  1005. SmallVectorImpl<uint64_t> &Record,
  1006. unsigned Abbrev) {
  1007. Record.push_back(N->isDistinct());
  1008. Record.push_back(N->getMacinfoType());
  1009. Record.push_back(N->getLine());
  1010. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1011. Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
  1012. Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
  1013. Record.clear();
  1014. }
  1015. static void WriteDIModule(const DIModule *N, const ValueEnumerator &VE,
  1016. BitstreamWriter &Stream,
  1017. SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
  1018. Record.push_back(N->isDistinct());
  1019. for (auto &I : N->operands())
  1020. Record.push_back(VE.getMetadataOrNullID(I));
  1021. Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
  1022. Record.clear();
  1023. }
  1024. static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
  1025. const ValueEnumerator &VE,
  1026. BitstreamWriter &Stream,
  1027. SmallVectorImpl<uint64_t> &Record,
  1028. unsigned Abbrev) {
  1029. Record.push_back(N->isDistinct());
  1030. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1031. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1032. Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
  1033. Record.clear();
  1034. }
  1035. static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
  1036. const ValueEnumerator &VE,
  1037. BitstreamWriter &Stream,
  1038. SmallVectorImpl<uint64_t> &Record,
  1039. unsigned Abbrev) {
  1040. Record.push_back(N->isDistinct());
  1041. Record.push_back(N->getTag());
  1042. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1043. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1044. Record.push_back(VE.getMetadataOrNullID(N->getValue()));
  1045. Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
  1046. Record.clear();
  1047. }
  1048. static void WriteDIGlobalVariable(const DIGlobalVariable *N,
  1049. const ValueEnumerator &VE,
  1050. BitstreamWriter &Stream,
  1051. SmallVectorImpl<uint64_t> &Record,
  1052. unsigned Abbrev) {
  1053. Record.push_back(N->isDistinct());
  1054. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1055. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1056. Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
  1057. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1058. Record.push_back(N->getLine());
  1059. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1060. Record.push_back(N->isLocalToUnit());
  1061. Record.push_back(N->isDefinition());
  1062. Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
  1063. Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
  1064. Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
  1065. Record.clear();
  1066. }
  1067. static void WriteDILocalVariable(const DILocalVariable *N,
  1068. const ValueEnumerator &VE,
  1069. BitstreamWriter &Stream,
  1070. SmallVectorImpl<uint64_t> &Record,
  1071. unsigned Abbrev) {
  1072. Record.push_back(N->isDistinct());
  1073. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1074. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1075. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1076. Record.push_back(N->getLine());
  1077. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1078. Record.push_back(N->getArg());
  1079. Record.push_back(N->getFlags());
  1080. Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
  1081. Record.clear();
  1082. }
  1083. static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
  1084. BitstreamWriter &Stream,
  1085. SmallVectorImpl<uint64_t> &Record,
  1086. unsigned Abbrev) {
  1087. Record.reserve(N->getElements().size() + 1);
  1088. Record.push_back(N->isDistinct());
  1089. Record.append(N->elements_begin(), N->elements_end());
  1090. Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
  1091. Record.clear();
  1092. }
  1093. static void WriteDIObjCProperty(const DIObjCProperty *N,
  1094. const ValueEnumerator &VE,
  1095. BitstreamWriter &Stream,
  1096. SmallVectorImpl<uint64_t> &Record,
  1097. unsigned Abbrev) {
  1098. Record.push_back(N->isDistinct());
  1099. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1100. Record.push_back(VE.getMetadataOrNullID(N->getFile()));
  1101. Record.push_back(N->getLine());
  1102. Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
  1103. Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
  1104. Record.push_back(N->getAttributes());
  1105. Record.push_back(VE.getMetadataOrNullID(N->getType()));
  1106. Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
  1107. Record.clear();
  1108. }
  1109. static void WriteDIImportedEntity(const DIImportedEntity *N,
  1110. const ValueEnumerator &VE,
  1111. BitstreamWriter &Stream,
  1112. SmallVectorImpl<uint64_t> &Record,
  1113. unsigned Abbrev) {
  1114. Record.push_back(N->isDistinct());
  1115. Record.push_back(N->getTag());
  1116. Record.push_back(VE.getMetadataOrNullID(N->getScope()));
  1117. Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
  1118. Record.push_back(N->getLine());
  1119. Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
  1120. Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
  1121. Record.clear();
  1122. }
  1123. static void WriteModuleMetadata(const Module *M,
  1124. const ValueEnumerator &VE,
  1125. BitstreamWriter &Stream) {
  1126. const auto &MDs = VE.getMDs();
  1127. if (MDs.empty() && M->named_metadata_empty())
  1128. return;
  1129. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  1130. unsigned MDSAbbrev = 0;
  1131. if (VE.hasMDString()) {
  1132. // Abbrev for METADATA_STRING.
  1133. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1134. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
  1135. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1136. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1137. MDSAbbrev = Stream.EmitAbbrev(Abbv);
  1138. }
  1139. // Initialize MDNode abbreviations.
  1140. #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
  1141. #include "llvm/IR/Metadata.def"
  1142. if (VE.hasDILocation()) {
  1143. // Abbrev for METADATA_LOCATION.
  1144. //
  1145. // Assume the column is usually under 128, and always output the inlined-at
  1146. // location (it's never more expensive than building an array size 1).
  1147. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1148. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
  1149. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1150. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1151. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1152. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1153. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1154. DILocationAbbrev = Stream.EmitAbbrev(Abbv);
  1155. }
  1156. if (VE.hasGenericDINode()) {
  1157. // Abbrev for METADATA_GENERIC_DEBUG.
  1158. //
  1159. // Assume the column is usually under 128, and always output the inlined-at
  1160. // location (it's never more expensive than building an array size 1).
  1161. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1162. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
  1163. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1164. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1165. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  1166. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1167. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1168. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  1169. GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
  1170. }
  1171. unsigned NameAbbrev = 0;
  1172. if (!M->named_metadata_empty()) {
  1173. // Abbrev for METADATA_NAME.
  1174. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1175. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
  1176. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1177. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1178. NameAbbrev = Stream.EmitAbbrev(Abbv);
  1179. }
  1180. SmallVector<uint64_t, 64> Record;
  1181. for (const Metadata *MD : MDs) {
  1182. if (const MDNode *N = dyn_cast<MDNode>(MD)) {
  1183. assert(N->isResolved() && "Expected forward references to be resolved");
  1184. switch (N->getMetadataID()) {
  1185. default:
  1186. llvm_unreachable("Invalid MDNode subclass");
  1187. #define HANDLE_MDNODE_LEAF(CLASS) \
  1188. case Metadata::CLASS##Kind: \
  1189. Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev); \
  1190. continue;
  1191. #include "llvm/IR/Metadata.def"
  1192. }
  1193. }
  1194. if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
  1195. WriteValueAsMetadata(MDC, VE, Stream, Record);
  1196. continue;
  1197. }
  1198. const MDString *MDS = cast<MDString>(MD);
  1199. // Code: [strchar x N]
  1200. Record.append(MDS->bytes_begin(), MDS->bytes_end());
  1201. // Emit the finished record.
  1202. Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
  1203. Record.clear();
  1204. }
  1205. // Write named metadata.
  1206. for (const NamedMDNode &NMD : M->named_metadata()) {
  1207. // Write name.
  1208. StringRef Str = NMD.getName();
  1209. Record.append(Str.bytes_begin(), Str.bytes_end());
  1210. Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
  1211. Record.clear();
  1212. // Write named metadata operands.
  1213. for (const MDNode *N : NMD.operands())
  1214. Record.push_back(VE.getMetadataID(N));
  1215. Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
  1216. Record.clear();
  1217. }
  1218. Stream.ExitBlock();
  1219. }
  1220. static void WriteFunctionLocalMetadata(const Function &F,
  1221. const ValueEnumerator &VE,
  1222. BitstreamWriter &Stream) {
  1223. bool StartedMetadataBlock = false;
  1224. SmallVector<uint64_t, 64> Record;
  1225. const SmallVectorImpl<const LocalAsMetadata *> &MDs =
  1226. VE.getFunctionLocalMDs();
  1227. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  1228. assert(MDs[i] && "Expected valid function-local metadata");
  1229. if (!StartedMetadataBlock) {
  1230. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  1231. StartedMetadataBlock = true;
  1232. }
  1233. WriteValueAsMetadata(MDs[i], VE, Stream, Record);
  1234. }
  1235. if (StartedMetadataBlock)
  1236. Stream.ExitBlock();
  1237. }
  1238. static void WriteMetadataAttachment(const Function &F,
  1239. const ValueEnumerator &VE,
  1240. BitstreamWriter &Stream) {
  1241. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  1242. SmallVector<uint64_t, 64> Record;
  1243. // Write metadata attachments
  1244. // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
  1245. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  1246. F.getAllMetadata(MDs);
  1247. if (!MDs.empty()) {
  1248. for (const auto &I : MDs) {
  1249. Record.push_back(I.first);
  1250. Record.push_back(VE.getMetadataID(I.second));
  1251. }
  1252. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1253. Record.clear();
  1254. }
  1255. for (const BasicBlock &BB : F)
  1256. for (const Instruction &I : BB) {
  1257. MDs.clear();
  1258. I.getAllMetadataOtherThanDebugLoc(MDs);
  1259. // If no metadata, ignore instruction.
  1260. if (MDs.empty()) continue;
  1261. Record.push_back(VE.getInstructionID(&I));
  1262. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  1263. Record.push_back(MDs[i].first);
  1264. Record.push_back(VE.getMetadataID(MDs[i].second));
  1265. }
  1266. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  1267. Record.clear();
  1268. }
  1269. Stream.ExitBlock();
  1270. }
  1271. static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
  1272. SmallVector<uint64_t, 64> Record;
  1273. // Write metadata kinds
  1274. // METADATA_KIND - [n x [id, name]]
  1275. SmallVector<StringRef, 8> Names;
  1276. M->getMDKindNames(Names);
  1277. if (Names.empty()) return;
  1278. Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
  1279. for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
  1280. Record.push_back(MDKindID);
  1281. StringRef KName = Names[MDKindID];
  1282. Record.append(KName.begin(), KName.end());
  1283. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  1284. Record.clear();
  1285. }
  1286. Stream.ExitBlock();
  1287. }
  1288. static void WriteOperandBundleTags(const Module *M, BitstreamWriter &Stream) {
  1289. // Write metadata kinds
  1290. //
  1291. // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
  1292. //
  1293. // OPERAND_BUNDLE_TAG - [strchr x N]
  1294. SmallVector<StringRef, 8> Tags;
  1295. M->getOperandBundleTags(Tags);
  1296. if (Tags.empty())
  1297. return;
  1298. Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
  1299. SmallVector<uint64_t, 64> Record;
  1300. for (auto Tag : Tags) {
  1301. Record.append(Tag.begin(), Tag.end());
  1302. Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
  1303. Record.clear();
  1304. }
  1305. Stream.ExitBlock();
  1306. }
  1307. static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
  1308. if ((int64_t)V >= 0)
  1309. Vals.push_back(V << 1);
  1310. else
  1311. Vals.push_back((-V << 1) | 1);
  1312. }
  1313. static void WriteConstants(unsigned FirstVal, unsigned LastVal,
  1314. const ValueEnumerator &VE,
  1315. BitstreamWriter &Stream, bool isGlobal) {
  1316. if (FirstVal == LastVal) return;
  1317. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  1318. unsigned AggregateAbbrev = 0;
  1319. unsigned String8Abbrev = 0;
  1320. unsigned CString7Abbrev = 0;
  1321. unsigned CString6Abbrev = 0;
  1322. // If this is a constant pool for the module, emit module-specific abbrevs.
  1323. if (isGlobal) {
  1324. // Abbrev for CST_CODE_AGGREGATE.
  1325. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1326. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  1327. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1328. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  1329. AggregateAbbrev = Stream.EmitAbbrev(Abbv);
  1330. // Abbrev for CST_CODE_STRING.
  1331. Abbv = new BitCodeAbbrev();
  1332. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  1333. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1334. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1335. String8Abbrev = Stream.EmitAbbrev(Abbv);
  1336. // Abbrev for CST_CODE_CSTRING.
  1337. Abbv = new BitCodeAbbrev();
  1338. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  1339. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1340. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1341. CString7Abbrev = Stream.EmitAbbrev(Abbv);
  1342. // Abbrev for CST_CODE_CSTRING.
  1343. Abbv = new BitCodeAbbrev();
  1344. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  1345. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1346. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1347. CString6Abbrev = Stream.EmitAbbrev(Abbv);
  1348. }
  1349. SmallVector<uint64_t, 64> Record;
  1350. const ValueEnumerator::ValueList &Vals = VE.getValues();
  1351. Type *LastTy = nullptr;
  1352. for (unsigned i = FirstVal; i != LastVal; ++i) {
  1353. const Value *V = Vals[i].first;
  1354. // If we need to switch types, do so now.
  1355. if (V->getType() != LastTy) {
  1356. LastTy = V->getType();
  1357. Record.push_back(VE.getTypeID(LastTy));
  1358. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  1359. CONSTANTS_SETTYPE_ABBREV);
  1360. Record.clear();
  1361. }
  1362. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  1363. Record.push_back(unsigned(IA->hasSideEffects()) |
  1364. unsigned(IA->isAlignStack()) << 1 |
  1365. unsigned(IA->getDialect()&1) << 2);
  1366. // Add the asm string.
  1367. const std::string &AsmStr = IA->getAsmString();
  1368. Record.push_back(AsmStr.size());
  1369. Record.append(AsmStr.begin(), AsmStr.end());
  1370. // Add the constraint string.
  1371. const std::string &ConstraintStr = IA->getConstraintString();
  1372. Record.push_back(ConstraintStr.size());
  1373. Record.append(ConstraintStr.begin(), ConstraintStr.end());
  1374. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  1375. Record.clear();
  1376. continue;
  1377. }
  1378. const Constant *C = cast<Constant>(V);
  1379. unsigned Code = -1U;
  1380. unsigned AbbrevToUse = 0;
  1381. if (C->isNullValue()) {
  1382. Code = bitc::CST_CODE_NULL;
  1383. } else if (isa<UndefValue>(C)) {
  1384. Code = bitc::CST_CODE_UNDEF;
  1385. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  1386. if (IV->getBitWidth() <= 64) {
  1387. uint64_t V = IV->getSExtValue();
  1388. emitSignedInt64(Record, V);
  1389. Code = bitc::CST_CODE_INTEGER;
  1390. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  1391. } else { // Wide integers, > 64 bits in size.
  1392. // We have an arbitrary precision integer value to write whose
  1393. // bit width is > 64. However, in canonical unsigned integer
  1394. // format it is likely that the high bits are going to be zero.
  1395. // So, we only write the number of active words.
  1396. unsigned NWords = IV->getValue().getActiveWords();
  1397. const uint64_t *RawWords = IV->getValue().getRawData();
  1398. for (unsigned i = 0; i != NWords; ++i) {
  1399. emitSignedInt64(Record, RawWords[i]);
  1400. }
  1401. Code = bitc::CST_CODE_WIDE_INTEGER;
  1402. }
  1403. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  1404. Code = bitc::CST_CODE_FLOAT;
  1405. Type *Ty = CFP->getType();
  1406. if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
  1407. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  1408. } else if (Ty->isX86_FP80Ty()) {
  1409. // api needed to prevent premature destruction
  1410. // bits are not in the same order as a normal i80 APInt, compensate.
  1411. APInt api = CFP->getValueAPF().bitcastToAPInt();
  1412. const uint64_t *p = api.getRawData();
  1413. Record.push_back((p[1] << 48) | (p[0] >> 16));
  1414. Record.push_back(p[0] & 0xffffLL);
  1415. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  1416. APInt api = CFP->getValueAPF().bitcastToAPInt();
  1417. const uint64_t *p = api.getRawData();
  1418. Record.push_back(p[0]);
  1419. Record.push_back(p[1]);
  1420. } else {
  1421. assert (0 && "Unknown FP type!");
  1422. }
  1423. } else if (isa<ConstantDataSequential>(C) &&
  1424. cast<ConstantDataSequential>(C)->isString()) {
  1425. const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
  1426. // Emit constant strings specially.
  1427. unsigned NumElts = Str->getNumElements();
  1428. // If this is a null-terminated string, use the denser CSTRING encoding.
  1429. if (Str->isCString()) {
  1430. Code = bitc::CST_CODE_CSTRING;
  1431. --NumElts; // Don't encode the null, which isn't allowed by char6.
  1432. } else {
  1433. Code = bitc::CST_CODE_STRING;
  1434. AbbrevToUse = String8Abbrev;
  1435. }
  1436. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  1437. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  1438. for (unsigned i = 0; i != NumElts; ++i) {
  1439. unsigned char V = Str->getElementAsInteger(i);
  1440. Record.push_back(V);
  1441. isCStr7 &= (V & 128) == 0;
  1442. if (isCStrChar6)
  1443. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  1444. }
  1445. if (isCStrChar6)
  1446. AbbrevToUse = CString6Abbrev;
  1447. else if (isCStr7)
  1448. AbbrevToUse = CString7Abbrev;
  1449. } else if (const ConstantDataSequential *CDS =
  1450. dyn_cast<ConstantDataSequential>(C)) {
  1451. Code = bitc::CST_CODE_DATA;
  1452. Type *EltTy = CDS->getType()->getElementType();
  1453. if (isa<IntegerType>(EltTy)) {
  1454. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
  1455. Record.push_back(CDS->getElementAsInteger(i));
  1456. } else if (EltTy->isFloatTy()) {
  1457. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1458. union { float F; uint32_t I; };
  1459. F = CDS->getElementAsFloat(i);
  1460. Record.push_back(I);
  1461. }
  1462. } else {
  1463. assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
  1464. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1465. union { double F; uint64_t I; };
  1466. F = CDS->getElementAsDouble(i);
  1467. Record.push_back(I);
  1468. }
  1469. }
  1470. } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
  1471. isa<ConstantVector>(C)) {
  1472. Code = bitc::CST_CODE_AGGREGATE;
  1473. for (const Value *Op : C->operands())
  1474. Record.push_back(VE.getValueID(Op));
  1475. AbbrevToUse = AggregateAbbrev;
  1476. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1477. switch (CE->getOpcode()) {
  1478. default:
  1479. if (Instruction::isCast(CE->getOpcode())) {
  1480. Code = bitc::CST_CODE_CE_CAST;
  1481. Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
  1482. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1483. Record.push_back(VE.getValueID(C->getOperand(0)));
  1484. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  1485. } else {
  1486. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  1487. Code = bitc::CST_CODE_CE_BINOP;
  1488. Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
  1489. Record.push_back(VE.getValueID(C->getOperand(0)));
  1490. Record.push_back(VE.getValueID(C->getOperand(1)));
  1491. uint64_t Flags = GetOptimizationFlags(CE);
  1492. if (Flags != 0)
  1493. Record.push_back(Flags);
  1494. }
  1495. break;
  1496. case Instruction::GetElementPtr: {
  1497. Code = bitc::CST_CODE_CE_GEP;
  1498. const auto *GO = cast<GEPOperator>(C);
  1499. if (GO->isInBounds())
  1500. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  1501. Record.push_back(VE.getTypeID(GO->getSourceElementType()));
  1502. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  1503. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  1504. Record.push_back(VE.getValueID(C->getOperand(i)));
  1505. }
  1506. break;
  1507. }
  1508. case Instruction::Select:
  1509. Code = bitc::CST_CODE_CE_SELECT;
  1510. Record.push_back(VE.getValueID(C->getOperand(0)));
  1511. Record.push_back(VE.getValueID(C->getOperand(1)));
  1512. Record.push_back(VE.getValueID(C->getOperand(2)));
  1513. break;
  1514. case Instruction::ExtractElement:
  1515. Code = bitc::CST_CODE_CE_EXTRACTELT;
  1516. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1517. Record.push_back(VE.getValueID(C->getOperand(0)));
  1518. Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
  1519. Record.push_back(VE.getValueID(C->getOperand(1)));
  1520. break;
  1521. case Instruction::InsertElement:
  1522. Code = bitc::CST_CODE_CE_INSERTELT;
  1523. Record.push_back(VE.getValueID(C->getOperand(0)));
  1524. Record.push_back(VE.getValueID(C->getOperand(1)));
  1525. Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
  1526. Record.push_back(VE.getValueID(C->getOperand(2)));
  1527. break;
  1528. case Instruction::ShuffleVector:
  1529. // If the return type and argument types are the same, this is a
  1530. // standard shufflevector instruction. If the types are different,
  1531. // then the shuffle is widening or truncating the input vectors, and
  1532. // the argument type must also be encoded.
  1533. if (C->getType() == C->getOperand(0)->getType()) {
  1534. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  1535. } else {
  1536. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  1537. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1538. }
  1539. Record.push_back(VE.getValueID(C->getOperand(0)));
  1540. Record.push_back(VE.getValueID(C->getOperand(1)));
  1541. Record.push_back(VE.getValueID(C->getOperand(2)));
  1542. break;
  1543. case Instruction::ICmp:
  1544. case Instruction::FCmp:
  1545. Code = bitc::CST_CODE_CE_CMP;
  1546. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  1547. Record.push_back(VE.getValueID(C->getOperand(0)));
  1548. Record.push_back(VE.getValueID(C->getOperand(1)));
  1549. Record.push_back(CE->getPredicate());
  1550. break;
  1551. }
  1552. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  1553. Code = bitc::CST_CODE_BLOCKADDRESS;
  1554. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  1555. Record.push_back(VE.getValueID(BA->getFunction()));
  1556. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  1557. } else {
  1558. #ifndef NDEBUG
  1559. C->dump();
  1560. #endif
  1561. llvm_unreachable("Unknown constant!");
  1562. }
  1563. Stream.EmitRecord(Code, Record, AbbrevToUse);
  1564. Record.clear();
  1565. }
  1566. Stream.ExitBlock();
  1567. }
  1568. static void WriteModuleConstants(const ValueEnumerator &VE,
  1569. BitstreamWriter &Stream) {
  1570. const ValueEnumerator::ValueList &Vals = VE.getValues();
  1571. // Find the first constant to emit, which is the first non-globalvalue value.
  1572. // We know globalvalues have been emitted by WriteModuleInfo.
  1573. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1574. if (!isa<GlobalValue>(Vals[i].first)) {
  1575. WriteConstants(i, Vals.size(), VE, Stream, true);
  1576. return;
  1577. }
  1578. }
  1579. }
  1580. /// PushValueAndType - The file has to encode both the value and type id for
  1581. /// many values, because we need to know what type to create for forward
  1582. /// references. However, most operands are not forward references, so this type
  1583. /// field is not needed.
  1584. ///
  1585. /// This function adds V's value ID to Vals. If the value ID is higher than the
  1586. /// instruction ID, then it is a forward reference, and it also includes the
  1587. /// type ID. The value ID that is written is encoded relative to the InstID.
  1588. static bool PushValueAndType(const Value *V, unsigned InstID,
  1589. SmallVectorImpl<unsigned> &Vals,
  1590. ValueEnumerator &VE) {
  1591. unsigned ValID = VE.getValueID(V);
  1592. // Make encoding relative to the InstID.
  1593. Vals.push_back(InstID - ValID);
  1594. if (ValID >= InstID) {
  1595. Vals.push_back(VE.getTypeID(V->getType()));
  1596. return true;
  1597. }
  1598. return false;
  1599. }
  1600. static void WriteOperandBundles(BitstreamWriter &Stream, ImmutableCallSite CS,
  1601. unsigned InstID, ValueEnumerator &VE) {
  1602. SmallVector<unsigned, 64> Record;
  1603. LLVMContext &C = CS.getInstruction()->getContext();
  1604. for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
  1605. const auto &Bundle = CS.getOperandBundleAt(i);
  1606. Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
  1607. for (auto &Input : Bundle.Inputs)
  1608. PushValueAndType(Input, InstID, Record, VE);
  1609. Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
  1610. Record.clear();
  1611. }
  1612. }
  1613. /// pushValue - Like PushValueAndType, but where the type of the value is
  1614. /// omitted (perhaps it was already encoded in an earlier operand).
  1615. static void pushValue(const Value *V, unsigned InstID,
  1616. SmallVectorImpl<unsigned> &Vals,
  1617. ValueEnumerator &VE) {
  1618. unsigned ValID = VE.getValueID(V);
  1619. Vals.push_back(InstID - ValID);
  1620. }
  1621. static void pushValueSigned(const Value *V, unsigned InstID,
  1622. SmallVectorImpl<uint64_t> &Vals,
  1623. ValueEnumerator &VE) {
  1624. unsigned ValID = VE.getValueID(V);
  1625. int64_t diff = ((int32_t)InstID - (int32_t)ValID);
  1626. emitSignedInt64(Vals, diff);
  1627. }
  1628. /// WriteInstruction - Emit an instruction to the specified stream.
  1629. static void WriteInstruction(const Instruction &I, unsigned InstID,
  1630. ValueEnumerator &VE, BitstreamWriter &Stream,
  1631. SmallVectorImpl<unsigned> &Vals) {
  1632. unsigned Code = 0;
  1633. unsigned AbbrevToUse = 0;
  1634. VE.setInstructionID(&I);
  1635. switch (I.getOpcode()) {
  1636. default:
  1637. if (Instruction::isCast(I.getOpcode())) {
  1638. Code = bitc::FUNC_CODE_INST_CAST;
  1639. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  1640. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  1641. Vals.push_back(VE.getTypeID(I.getType()));
  1642. Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
  1643. } else {
  1644. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  1645. Code = bitc::FUNC_CODE_INST_BINOP;
  1646. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  1647. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  1648. pushValue(I.getOperand(1), InstID, Vals, VE);
  1649. Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
  1650. uint64_t Flags = GetOptimizationFlags(&I);
  1651. if (Flags != 0) {
  1652. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  1653. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  1654. Vals.push_back(Flags);
  1655. }
  1656. }
  1657. break;
  1658. case Instruction::GetElementPtr: {
  1659. Code = bitc::FUNC_CODE_INST_GEP;
  1660. AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
  1661. auto &GEPInst = cast<GetElementPtrInst>(I);
  1662. Vals.push_back(GEPInst.isInBounds());
  1663. Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
  1664. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  1665. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  1666. break;
  1667. }
  1668. case Instruction::ExtractValue: {
  1669. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  1670. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1671. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  1672. Vals.append(EVI->idx_begin(), EVI->idx_end());
  1673. break;
  1674. }
  1675. case Instruction::InsertValue: {
  1676. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  1677. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1678. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  1679. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  1680. Vals.append(IVI->idx_begin(), IVI->idx_end());
  1681. break;
  1682. }
  1683. case Instruction::Select:
  1684. Code = bitc::FUNC_CODE_INST_VSELECT;
  1685. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  1686. pushValue(I.getOperand(2), InstID, Vals, VE);
  1687. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1688. break;
  1689. case Instruction::ExtractElement:
  1690. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  1691. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1692. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  1693. break;
  1694. case Instruction::InsertElement:
  1695. Code = bitc::FUNC_CODE_INST_INSERTELT;
  1696. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1697. pushValue(I.getOperand(1), InstID, Vals, VE);
  1698. PushValueAndType(I.getOperand(2), InstID, Vals, VE);
  1699. break;
  1700. case Instruction::ShuffleVector:
  1701. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  1702. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1703. pushValue(I.getOperand(1), InstID, Vals, VE);
  1704. pushValue(I.getOperand(2), InstID, Vals, VE);
  1705. break;
  1706. case Instruction::ICmp:
  1707. case Instruction::FCmp: {
  1708. // compare returning Int1Ty or vector of Int1Ty
  1709. Code = bitc::FUNC_CODE_INST_CMP2;
  1710. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1711. pushValue(I.getOperand(1), InstID, Vals, VE);
  1712. Vals.push_back(cast<CmpInst>(I).getPredicate());
  1713. uint64_t Flags = GetOptimizationFlags(&I);
  1714. if (Flags != 0)
  1715. Vals.push_back(Flags);
  1716. break;
  1717. }
  1718. case Instruction::Ret:
  1719. {
  1720. Code = bitc::FUNC_CODE_INST_RET;
  1721. unsigned NumOperands = I.getNumOperands();
  1722. if (NumOperands == 0)
  1723. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  1724. else if (NumOperands == 1) {
  1725. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  1726. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  1727. } else {
  1728. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  1729. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  1730. }
  1731. }
  1732. break;
  1733. case Instruction::Br:
  1734. {
  1735. Code = bitc::FUNC_CODE_INST_BR;
  1736. const BranchInst &II = cast<BranchInst>(I);
  1737. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  1738. if (II.isConditional()) {
  1739. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  1740. pushValue(II.getCondition(), InstID, Vals, VE);
  1741. }
  1742. }
  1743. break;
  1744. case Instruction::Switch:
  1745. {
  1746. Code = bitc::FUNC_CODE_INST_SWITCH;
  1747. const SwitchInst &SI = cast<SwitchInst>(I);
  1748. Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
  1749. pushValue(SI.getCondition(), InstID, Vals, VE);
  1750. Vals.push_back(VE.getValueID(SI.getDefaultDest()));
  1751. for (SwitchInst::ConstCaseIt Case : SI.cases()) {
  1752. Vals.push_back(VE.getValueID(Case.getCaseValue()));
  1753. Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
  1754. }
  1755. }
  1756. break;
  1757. case Instruction::IndirectBr:
  1758. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  1759. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  1760. // Encode the address operand as relative, but not the basic blocks.
  1761. pushValue(I.getOperand(0), InstID, Vals, VE);
  1762. for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
  1763. Vals.push_back(VE.getValueID(I.getOperand(i)));
  1764. break;
  1765. case Instruction::Invoke: {
  1766. const InvokeInst *II = cast<InvokeInst>(&I);
  1767. const Value *Callee = II->getCalledValue();
  1768. FunctionType *FTy = II->getFunctionType();
  1769. if (II->hasOperandBundles())
  1770. WriteOperandBundles(Stream, II, InstID, VE);
  1771. Code = bitc::FUNC_CODE_INST_INVOKE;
  1772. Vals.push_back(VE.getAttributeID(II->getAttributes()));
  1773. Vals.push_back(II->getCallingConv() | 1 << 13);
  1774. Vals.push_back(VE.getValueID(II->getNormalDest()));
  1775. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  1776. Vals.push_back(VE.getTypeID(FTy));
  1777. PushValueAndType(Callee, InstID, Vals, VE);
  1778. // Emit value #'s for the fixed parameters.
  1779. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  1780. pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param.
  1781. // Emit type/value pairs for varargs params.
  1782. if (FTy->isVarArg()) {
  1783. for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
  1784. i != e; ++i)
  1785. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
  1786. }
  1787. break;
  1788. }
  1789. case Instruction::Resume:
  1790. Code = bitc::FUNC_CODE_INST_RESUME;
  1791. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1792. break;
  1793. case Instruction::CleanupRet: {
  1794. Code = bitc::FUNC_CODE_INST_CLEANUPRET;
  1795. const auto &CRI = cast<CleanupReturnInst>(I);
  1796. pushValue(CRI.getCleanupPad(), InstID, Vals, VE);
  1797. if (CRI.hasUnwindDest())
  1798. Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
  1799. break;
  1800. }
  1801. case Instruction::CatchRet: {
  1802. Code = bitc::FUNC_CODE_INST_CATCHRET;
  1803. const auto &CRI = cast<CatchReturnInst>(I);
  1804. pushValue(CRI.getCatchPad(), InstID, Vals, VE);
  1805. Vals.push_back(VE.getValueID(CRI.getSuccessor()));
  1806. break;
  1807. }
  1808. case Instruction::CleanupPad:
  1809. case Instruction::CatchPad: {
  1810. const auto &FuncletPad = cast<FuncletPadInst>(I);
  1811. Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
  1812. : bitc::FUNC_CODE_INST_CLEANUPPAD;
  1813. pushValue(FuncletPad.getParentPad(), InstID, Vals, VE);
  1814. unsigned NumArgOperands = FuncletPad.getNumArgOperands();
  1815. Vals.push_back(NumArgOperands);
  1816. for (unsigned Op = 0; Op != NumArgOperands; ++Op)
  1817. PushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals, VE);
  1818. break;
  1819. }
  1820. case Instruction::CatchSwitch: {
  1821. Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
  1822. const auto &CatchSwitch = cast<CatchSwitchInst>(I);
  1823. pushValue(CatchSwitch.getParentPad(), InstID, Vals, VE);
  1824. unsigned NumHandlers = CatchSwitch.getNumHandlers();
  1825. Vals.push_back(NumHandlers);
  1826. for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
  1827. Vals.push_back(VE.getValueID(CatchPadBB));
  1828. if (CatchSwitch.hasUnwindDest())
  1829. Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
  1830. break;
  1831. }
  1832. case Instruction::TerminatePad: {
  1833. Code = bitc::FUNC_CODE_INST_TERMINATEPAD;
  1834. const auto &TPI = cast<TerminatePadInst>(I);
  1835. pushValue(TPI.getParentPad(), InstID, Vals, VE);
  1836. unsigned NumArgOperands = TPI.getNumArgOperands();
  1837. Vals.push_back(NumArgOperands);
  1838. for (unsigned Op = 0; Op != NumArgOperands; ++Op)
  1839. PushValueAndType(TPI.getArgOperand(Op), InstID, Vals, VE);
  1840. if (TPI.hasUnwindDest())
  1841. Vals.push_back(VE.getValueID(TPI.getUnwindDest()));
  1842. break;
  1843. }
  1844. case Instruction::Unreachable:
  1845. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  1846. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  1847. break;
  1848. case Instruction::PHI: {
  1849. const PHINode &PN = cast<PHINode>(I);
  1850. Code = bitc::FUNC_CODE_INST_PHI;
  1851. // With the newer instruction encoding, forward references could give
  1852. // negative valued IDs. This is most common for PHIs, so we use
  1853. // signed VBRs.
  1854. SmallVector<uint64_t, 128> Vals64;
  1855. Vals64.push_back(VE.getTypeID(PN.getType()));
  1856. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
  1857. pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
  1858. Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
  1859. }
  1860. // Emit a Vals64 vector and exit.
  1861. Stream.EmitRecord(Code, Vals64, AbbrevToUse);
  1862. Vals64.clear();
  1863. return;
  1864. }
  1865. case Instruction::LandingPad: {
  1866. const LandingPadInst &LP = cast<LandingPadInst>(I);
  1867. Code = bitc::FUNC_CODE_INST_LANDINGPAD;
  1868. Vals.push_back(VE.getTypeID(LP.getType()));
  1869. Vals.push_back(LP.isCleanup());
  1870. Vals.push_back(LP.getNumClauses());
  1871. for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
  1872. if (LP.isCatch(I))
  1873. Vals.push_back(LandingPadInst::Catch);
  1874. else
  1875. Vals.push_back(LandingPadInst::Filter);
  1876. PushValueAndType(LP.getClause(I), InstID, Vals, VE);
  1877. }
  1878. break;
  1879. }
  1880. case Instruction::Alloca: {
  1881. Code = bitc::FUNC_CODE_INST_ALLOCA;
  1882. const AllocaInst &AI = cast<AllocaInst>(I);
  1883. Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
  1884. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  1885. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  1886. unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
  1887. assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
  1888. "not enough bits for maximum alignment");
  1889. assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
  1890. AlignRecord |= AI.isUsedWithInAlloca() << 5;
  1891. AlignRecord |= 1 << 6;
  1892. // Reserve bit 7 for SwiftError flag.
  1893. // AlignRecord |= AI.isSwiftError() << 7;
  1894. Vals.push_back(AlignRecord);
  1895. break;
  1896. }
  1897. case Instruction::Load:
  1898. if (cast<LoadInst>(I).isAtomic()) {
  1899. Code = bitc::FUNC_CODE_INST_LOADATOMIC;
  1900. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  1901. } else {
  1902. Code = bitc::FUNC_CODE_INST_LOAD;
  1903. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
  1904. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  1905. }
  1906. Vals.push_back(VE.getTypeID(I.getType()));
  1907. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  1908. Vals.push_back(cast<LoadInst>(I).isVolatile());
  1909. if (cast<LoadInst>(I).isAtomic()) {
  1910. Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
  1911. Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
  1912. }
  1913. break;
  1914. case Instruction::Store:
  1915. if (cast<StoreInst>(I).isAtomic())
  1916. Code = bitc::FUNC_CODE_INST_STOREATOMIC;
  1917. else
  1918. Code = bitc::FUNC_CODE_INST_STORE;
  1919. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
  1920. PushValueAndType(I.getOperand(0), InstID, Vals, VE); // valty + val
  1921. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  1922. Vals.push_back(cast<StoreInst>(I).isVolatile());
  1923. if (cast<StoreInst>(I).isAtomic()) {
  1924. Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
  1925. Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
  1926. }
  1927. break;
  1928. case Instruction::AtomicCmpXchg:
  1929. Code = bitc::FUNC_CODE_INST_CMPXCHG;
  1930. PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
  1931. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // cmp.
  1932. pushValue(I.getOperand(2), InstID, Vals, VE); // newval.
  1933. Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
  1934. Vals.push_back(GetEncodedOrdering(
  1935. cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
  1936. Vals.push_back(GetEncodedSynchScope(
  1937. cast<AtomicCmpXchgInst>(I).getSynchScope()));
  1938. Vals.push_back(GetEncodedOrdering(
  1939. cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
  1940. Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
  1941. break;
  1942. case Instruction::AtomicRMW:
  1943. Code = bitc::FUNC_CODE_INST_ATOMICRMW;
  1944. PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr
  1945. pushValue(I.getOperand(1), InstID, Vals, VE); // val.
  1946. Vals.push_back(GetEncodedRMWOperation(
  1947. cast<AtomicRMWInst>(I).getOperation()));
  1948. Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
  1949. Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
  1950. Vals.push_back(GetEncodedSynchScope(
  1951. cast<AtomicRMWInst>(I).getSynchScope()));
  1952. break;
  1953. case Instruction::Fence:
  1954. Code = bitc::FUNC_CODE_INST_FENCE;
  1955. Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
  1956. Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
  1957. break;
  1958. case Instruction::Call: {
  1959. const CallInst &CI = cast<CallInst>(I);
  1960. FunctionType *FTy = CI.getFunctionType();
  1961. if (CI.hasOperandBundles())
  1962. WriteOperandBundles(Stream, &CI, InstID, VE);
  1963. Code = bitc::FUNC_CODE_INST_CALL;
  1964. Vals.push_back(VE.getAttributeID(CI.getAttributes()));
  1965. Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
  1966. unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
  1967. unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
  1968. 1 << bitc::CALL_EXPLICIT_TYPE |
  1969. unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL);
  1970. Vals.push_back(VE.getTypeID(FTy));
  1971. PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
  1972. // Emit value #'s for the fixed parameters.
  1973. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  1974. // Check for labels (can happen with asm labels).
  1975. if (FTy->getParamType(i)->isLabelTy())
  1976. Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
  1977. else
  1978. pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param.
  1979. }
  1980. // Emit type/value pairs for varargs params.
  1981. if (FTy->isVarArg()) {
  1982. for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
  1983. i != e; ++i)
  1984. PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
  1985. }
  1986. break;
  1987. }
  1988. case Instruction::VAArg:
  1989. Code = bitc::FUNC_CODE_INST_VAARG;
  1990. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  1991. pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
  1992. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  1993. break;
  1994. }
  1995. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  1996. Vals.clear();
  1997. }
  1998. enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
  1999. /// Determine the encoding to use for the given string name and length.
  2000. static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
  2001. bool isChar6 = true;
  2002. for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
  2003. if (isChar6)
  2004. isChar6 = BitCodeAbbrevOp::isChar6(*C);
  2005. if ((unsigned char)*C & 128)
  2006. // don't bother scanning the rest.
  2007. return SE_Fixed8;
  2008. }
  2009. if (isChar6)
  2010. return SE_Char6;
  2011. else
  2012. return SE_Fixed7;
  2013. }
  2014. /// Emit names for globals/functions etc. The VSTOffsetPlaceholder,
  2015. /// BitcodeStartBit and FunctionIndex are only passed for the module-level
  2016. /// VST, where we are including a function bitcode index and need to
  2017. /// backpatch the VST forward declaration record.
  2018. static void WriteValueSymbolTable(
  2019. const ValueSymbolTable &VST, const ValueEnumerator &VE,
  2020. BitstreamWriter &Stream, uint64_t VSTOffsetPlaceholder = 0,
  2021. uint64_t BitcodeStartBit = 0,
  2022. DenseMap<const Function *, std::unique_ptr<FunctionInfo>> *FunctionIndex =
  2023. nullptr) {
  2024. if (VST.empty()) {
  2025. // WriteValueSymbolTableForwardDecl should have returned early as
  2026. // well. Ensure this handling remains in sync by asserting that
  2027. // the placeholder offset is not set.
  2028. assert(VSTOffsetPlaceholder == 0);
  2029. return;
  2030. }
  2031. if (VSTOffsetPlaceholder > 0) {
  2032. // Get the offset of the VST we are writing, and backpatch it into
  2033. // the VST forward declaration record.
  2034. uint64_t VSTOffset = Stream.GetCurrentBitNo();
  2035. // The BitcodeStartBit was the stream offset of the actual bitcode
  2036. // (e.g. excluding any initial darwin header).
  2037. VSTOffset -= BitcodeStartBit;
  2038. assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
  2039. Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
  2040. }
  2041. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2042. // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
  2043. // records, which are not used in the per-function VSTs.
  2044. unsigned FnEntry8BitAbbrev;
  2045. unsigned FnEntry7BitAbbrev;
  2046. unsigned FnEntry6BitAbbrev;
  2047. if (VSTOffsetPlaceholder > 0) {
  2048. // 8-bit fixed-width VST_FNENTRY function strings.
  2049. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2050. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2051. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2052. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2053. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2054. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2055. FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
  2056. // 7-bit fixed width VST_FNENTRY function strings.
  2057. Abbv = new BitCodeAbbrev();
  2058. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2059. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2060. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2061. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2062. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2063. FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
  2064. // 6-bit char6 VST_FNENTRY function strings.
  2065. Abbv = new BitCodeAbbrev();
  2066. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
  2067. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2068. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2069. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2070. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2071. FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
  2072. }
  2073. // FIXME: Set up the abbrev, we know how many values there are!
  2074. // FIXME: We know if the type names can use 7-bit ascii.
  2075. SmallVector<unsigned, 64> NameVals;
  2076. for (const ValueName &Name : VST) {
  2077. // Figure out the encoding to use for the name.
  2078. StringEncoding Bits =
  2079. getStringEncoding(Name.getKeyData(), Name.getKeyLength());
  2080. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  2081. NameVals.push_back(VE.getValueID(Name.getValue()));
  2082. Function *F = dyn_cast<Function>(Name.getValue());
  2083. if (!F) {
  2084. // If value is an alias, need to get the aliased base object to
  2085. // see if it is a function.
  2086. auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
  2087. if (GA && GA->getBaseObject())
  2088. F = dyn_cast<Function>(GA->getBaseObject());
  2089. }
  2090. // VST_ENTRY: [valueid, namechar x N]
  2091. // VST_FNENTRY: [valueid, funcoffset, namechar x N]
  2092. // VST_BBENTRY: [bbid, namechar x N]
  2093. unsigned Code;
  2094. if (isa<BasicBlock>(Name.getValue())) {
  2095. Code = bitc::VST_CODE_BBENTRY;
  2096. if (Bits == SE_Char6)
  2097. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  2098. } else if (F && !F->isDeclaration()) {
  2099. // Must be the module-level VST, where we pass in the Index and
  2100. // have a VSTOffsetPlaceholder. The function-level VST should not
  2101. // contain any Function symbols.
  2102. assert(FunctionIndex);
  2103. assert(VSTOffsetPlaceholder > 0);
  2104. // Save the word offset of the function (from the start of the
  2105. // actual bitcode written to the stream).
  2106. assert(FunctionIndex->count(F) == 1);
  2107. uint64_t BitcodeIndex =
  2108. (*FunctionIndex)[F]->bitcodeIndex() - BitcodeStartBit;
  2109. assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
  2110. NameVals.push_back(BitcodeIndex / 32);
  2111. Code = bitc::VST_CODE_FNENTRY;
  2112. AbbrevToUse = FnEntry8BitAbbrev;
  2113. if (Bits == SE_Char6)
  2114. AbbrevToUse = FnEntry6BitAbbrev;
  2115. else if (Bits == SE_Fixed7)
  2116. AbbrevToUse = FnEntry7BitAbbrev;
  2117. } else {
  2118. Code = bitc::VST_CODE_ENTRY;
  2119. if (Bits == SE_Char6)
  2120. AbbrevToUse = VST_ENTRY_6_ABBREV;
  2121. else if (Bits == SE_Fixed7)
  2122. AbbrevToUse = VST_ENTRY_7_ABBREV;
  2123. }
  2124. for (const auto P : Name.getKey())
  2125. NameVals.push_back((unsigned char)P);
  2126. // Emit the finished record.
  2127. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  2128. NameVals.clear();
  2129. }
  2130. Stream.ExitBlock();
  2131. }
  2132. /// Emit function names and summary offsets for the combined index
  2133. /// used by ThinLTO.
  2134. static void WriteCombinedValueSymbolTable(const FunctionInfoIndex &Index,
  2135. BitstreamWriter &Stream) {
  2136. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  2137. // 8-bit fixed-width VST_COMBINED_FNENTRY function strings.
  2138. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2139. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
  2140. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2141. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2142. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2143. unsigned FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
  2144. // 7-bit fixed width VST_COMBINED_FNENTRY function strings.
  2145. Abbv = new BitCodeAbbrev();
  2146. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
  2147. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2148. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2149. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2150. unsigned FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
  2151. // 6-bit char6 VST_COMBINED_FNENTRY function strings.
  2152. Abbv = new BitCodeAbbrev();
  2153. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_FNENTRY));
  2154. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
  2155. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2156. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2157. unsigned FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
  2158. // FIXME: We know if the type names can use 7-bit ascii.
  2159. SmallVector<unsigned, 64> NameVals;
  2160. for (const auto &FII : Index) {
  2161. for (const auto &FI : FII.getValue()) {
  2162. NameVals.push_back(FI->bitcodeIndex());
  2163. StringRef FuncName = FII.first();
  2164. // Figure out the encoding to use for the name.
  2165. StringEncoding Bits = getStringEncoding(FuncName.data(), FuncName.size());
  2166. // VST_COMBINED_FNENTRY: [funcsumoffset, namechar x N]
  2167. unsigned AbbrevToUse = FnEntry8BitAbbrev;
  2168. if (Bits == SE_Char6)
  2169. AbbrevToUse = FnEntry6BitAbbrev;
  2170. else if (Bits == SE_Fixed7)
  2171. AbbrevToUse = FnEntry7BitAbbrev;
  2172. for (const auto P : FuncName)
  2173. NameVals.push_back((unsigned char)P);
  2174. // Emit the finished record.
  2175. Stream.EmitRecord(bitc::VST_CODE_COMBINED_FNENTRY, NameVals, AbbrevToUse);
  2176. NameVals.clear();
  2177. }
  2178. }
  2179. Stream.ExitBlock();
  2180. }
  2181. static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
  2182. BitstreamWriter &Stream) {
  2183. assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
  2184. unsigned Code;
  2185. if (isa<BasicBlock>(Order.V))
  2186. Code = bitc::USELIST_CODE_BB;
  2187. else
  2188. Code = bitc::USELIST_CODE_DEFAULT;
  2189. SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
  2190. Record.push_back(VE.getValueID(Order.V));
  2191. Stream.EmitRecord(Code, Record);
  2192. }
  2193. static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
  2194. BitstreamWriter &Stream) {
  2195. assert(VE.shouldPreserveUseListOrder() &&
  2196. "Expected to be preserving use-list order");
  2197. auto hasMore = [&]() {
  2198. return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
  2199. };
  2200. if (!hasMore())
  2201. // Nothing to do.
  2202. return;
  2203. Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
  2204. while (hasMore()) {
  2205. WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
  2206. VE.UseListOrders.pop_back();
  2207. }
  2208. Stream.ExitBlock();
  2209. }
  2210. /// \brief Save information for the given function into the function index.
  2211. ///
  2212. /// At a minimum this saves the bitcode index of the function record that
  2213. /// was just written. However, if we are emitting function summary information,
  2214. /// for example for ThinLTO, then a \a FunctionSummary object is created
  2215. /// to hold the provided summary information.
  2216. static void SaveFunctionInfo(
  2217. const Function &F,
  2218. DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
  2219. unsigned NumInsts, uint64_t BitcodeIndex, bool EmitFunctionSummary) {
  2220. std::unique_ptr<FunctionSummary> FuncSummary;
  2221. if (EmitFunctionSummary) {
  2222. FuncSummary = llvm::make_unique<FunctionSummary>(NumInsts);
  2223. FuncSummary->setLocalFunction(F.hasLocalLinkage());
  2224. }
  2225. FunctionIndex[&F] =
  2226. llvm::make_unique<FunctionInfo>(BitcodeIndex, std::move(FuncSummary));
  2227. }
  2228. /// Emit a function body to the module stream.
  2229. static void WriteFunction(
  2230. const Function &F, ValueEnumerator &VE, BitstreamWriter &Stream,
  2231. DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
  2232. bool EmitFunctionSummary) {
  2233. // Save the bitcode index of the start of this function block for recording
  2234. // in the VST.
  2235. uint64_t BitcodeIndex = Stream.GetCurrentBitNo();
  2236. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  2237. VE.incorporateFunction(F);
  2238. SmallVector<unsigned, 64> Vals;
  2239. // Emit the number of basic blocks, so the reader can create them ahead of
  2240. // time.
  2241. Vals.push_back(VE.getBasicBlocks().size());
  2242. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  2243. Vals.clear();
  2244. // If there are function-local constants, emit them now.
  2245. unsigned CstStart, CstEnd;
  2246. VE.getFunctionConstantRange(CstStart, CstEnd);
  2247. WriteConstants(CstStart, CstEnd, VE, Stream, false);
  2248. // If there is function-local metadata, emit it now.
  2249. WriteFunctionLocalMetadata(F, VE, Stream);
  2250. // Keep a running idea of what the instruction ID is.
  2251. unsigned InstID = CstEnd;
  2252. bool NeedsMetadataAttachment = F.hasMetadata();
  2253. DILocation *LastDL = nullptr;
  2254. unsigned NumInsts = 0;
  2255. // Finally, emit all the instructions, in order.
  2256. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  2257. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  2258. I != E; ++I) {
  2259. WriteInstruction(*I, InstID, VE, Stream, Vals);
  2260. if (!isa<DbgInfoIntrinsic>(I))
  2261. ++NumInsts;
  2262. if (!I->getType()->isVoidTy())
  2263. ++InstID;
  2264. // If the instruction has metadata, write a metadata attachment later.
  2265. NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
  2266. // If the instruction has a debug location, emit it.
  2267. DILocation *DL = I->getDebugLoc();
  2268. if (!DL)
  2269. continue;
  2270. if (DL == LastDL) {
  2271. // Just repeat the same debug loc as last time.
  2272. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
  2273. continue;
  2274. }
  2275. Vals.push_back(DL->getLine());
  2276. Vals.push_back(DL->getColumn());
  2277. Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
  2278. Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
  2279. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
  2280. Vals.clear();
  2281. LastDL = DL;
  2282. }
  2283. // Emit names for all the instructions etc.
  2284. WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
  2285. if (NeedsMetadataAttachment)
  2286. WriteMetadataAttachment(F, VE, Stream);
  2287. if (VE.shouldPreserveUseListOrder())
  2288. WriteUseListBlock(&F, VE, Stream);
  2289. VE.purgeFunction();
  2290. Stream.ExitBlock();
  2291. SaveFunctionInfo(F, FunctionIndex, NumInsts, BitcodeIndex,
  2292. EmitFunctionSummary);
  2293. }
  2294. // Emit blockinfo, which defines the standard abbreviations etc.
  2295. static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  2296. // We only want to emit block info records for blocks that have multiple
  2297. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
  2298. // Other blocks can define their abbrevs inline.
  2299. Stream.EnterBlockInfoBlock(2);
  2300. { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
  2301. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2302. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  2303. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2304. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2305. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2306. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2307. Abbv) != VST_ENTRY_8_ABBREV)
  2308. llvm_unreachable("Unexpected abbrev ordering!");
  2309. }
  2310. { // 7-bit fixed width VST_ENTRY strings.
  2311. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2312. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2313. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2314. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2315. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2316. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2317. Abbv) != VST_ENTRY_7_ABBREV)
  2318. llvm_unreachable("Unexpected abbrev ordering!");
  2319. }
  2320. { // 6-bit char6 VST_ENTRY strings.
  2321. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2322. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  2323. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2324. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2325. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2326. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2327. Abbv) != VST_ENTRY_6_ABBREV)
  2328. llvm_unreachable("Unexpected abbrev ordering!");
  2329. }
  2330. { // 6-bit char6 VST_BBENTRY strings.
  2331. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2332. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  2333. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2334. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2335. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2336. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  2337. Abbv) != VST_BBENTRY_6_ABBREV)
  2338. llvm_unreachable("Unexpected abbrev ordering!");
  2339. }
  2340. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  2341. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2342. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  2343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  2344. VE.computeBitsRequiredForTypeIndicies()));
  2345. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2346. Abbv) != CONSTANTS_SETTYPE_ABBREV)
  2347. llvm_unreachable("Unexpected abbrev ordering!");
  2348. }
  2349. { // INTEGER abbrev for CONSTANTS_BLOCK.
  2350. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2351. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  2352. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2353. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2354. Abbv) != CONSTANTS_INTEGER_ABBREV)
  2355. llvm_unreachable("Unexpected abbrev ordering!");
  2356. }
  2357. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  2358. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2359. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  2360. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  2361. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  2362. VE.computeBitsRequiredForTypeIndicies()));
  2363. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  2364. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2365. Abbv) != CONSTANTS_CE_CAST_Abbrev)
  2366. llvm_unreachable("Unexpected abbrev ordering!");
  2367. }
  2368. { // NULL abbrev for CONSTANTS_BLOCK.
  2369. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2370. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  2371. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  2372. Abbv) != CONSTANTS_NULL_Abbrev)
  2373. llvm_unreachable("Unexpected abbrev ordering!");
  2374. }
  2375. // FIXME: This should only use space for first class types!
  2376. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  2377. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2378. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  2379. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  2380. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2381. VE.computeBitsRequiredForTypeIndicies()));
  2382. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  2383. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  2384. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2385. Abbv) != FUNCTION_INST_LOAD_ABBREV)
  2386. llvm_unreachable("Unexpected abbrev ordering!");
  2387. }
  2388. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  2389. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2390. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2391. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2392. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  2393. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2394. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2395. Abbv) != FUNCTION_INST_BINOP_ABBREV)
  2396. llvm_unreachable("Unexpected abbrev ordering!");
  2397. }
  2398. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  2399. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2400. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  2401. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  2402. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  2403. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2404. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
  2405. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2406. Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
  2407. llvm_unreachable("Unexpected abbrev ordering!");
  2408. }
  2409. { // INST_CAST abbrev for FUNCTION_BLOCK.
  2410. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2411. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  2412. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  2413. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2414. VE.computeBitsRequiredForTypeIndicies()));
  2415. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  2416. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2417. Abbv) != FUNCTION_INST_CAST_ABBREV)
  2418. llvm_unreachable("Unexpected abbrev ordering!");
  2419. }
  2420. { // INST_RET abbrev for FUNCTION_BLOCK.
  2421. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2422. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  2423. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2424. Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
  2425. llvm_unreachable("Unexpected abbrev ordering!");
  2426. }
  2427. { // INST_RET abbrev for FUNCTION_BLOCK.
  2428. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2429. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  2430. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  2431. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2432. Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
  2433. llvm_unreachable("Unexpected abbrev ordering!");
  2434. }
  2435. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  2436. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2437. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  2438. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  2439. Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
  2440. llvm_unreachable("Unexpected abbrev ordering!");
  2441. }
  2442. {
  2443. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2444. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
  2445. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
  2446. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  2447. Log2_32_Ceil(VE.getTypes().size() + 1)));
  2448. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2449. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  2450. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
  2451. FUNCTION_INST_GEP_ABBREV)
  2452. llvm_unreachable("Unexpected abbrev ordering!");
  2453. }
  2454. Stream.ExitBlock();
  2455. }
  2456. /// Write the module path strings, currently only used when generating
  2457. /// a combined index file.
  2458. static void WriteModStrings(const FunctionInfoIndex &I,
  2459. BitstreamWriter &Stream) {
  2460. Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
  2461. // TODO: See which abbrev sizes we actually need to emit
  2462. // 8-bit fixed-width MST_ENTRY strings.
  2463. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2464. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  2465. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2466. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2467. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  2468. unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
  2469. // 7-bit fixed width MST_ENTRY strings.
  2470. Abbv = new BitCodeAbbrev();
  2471. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  2472. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2473. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2474. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  2475. unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
  2476. // 6-bit char6 MST_ENTRY strings.
  2477. Abbv = new BitCodeAbbrev();
  2478. Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
  2479. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  2480. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2481. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2482. unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
  2483. SmallVector<unsigned, 64> NameVals;
  2484. for (const StringMapEntry<uint64_t> &MPSE : I.modPathStringEntries()) {
  2485. StringEncoding Bits =
  2486. getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
  2487. unsigned AbbrevToUse = Abbrev8Bit;
  2488. if (Bits == SE_Char6)
  2489. AbbrevToUse = Abbrev6Bit;
  2490. else if (Bits == SE_Fixed7)
  2491. AbbrevToUse = Abbrev7Bit;
  2492. NameVals.push_back(MPSE.getValue());
  2493. for (const auto P : MPSE.getKey())
  2494. NameVals.push_back((unsigned char)P);
  2495. // Emit the finished record.
  2496. Stream.EmitRecord(bitc::MST_CODE_ENTRY, NameVals, AbbrevToUse);
  2497. NameVals.clear();
  2498. }
  2499. Stream.ExitBlock();
  2500. }
  2501. // Helper to emit a single function summary record.
  2502. static void WritePerModuleFunctionSummaryRecord(
  2503. SmallVector<unsigned, 64> &NameVals, FunctionSummary *FS, unsigned ValueID,
  2504. unsigned FSAbbrev, BitstreamWriter &Stream) {
  2505. assert(FS);
  2506. NameVals.push_back(ValueID);
  2507. NameVals.push_back(FS->isLocalFunction());
  2508. NameVals.push_back(FS->instCount());
  2509. // Emit the finished record.
  2510. Stream.EmitRecord(bitc::FS_CODE_PERMODULE_ENTRY, NameVals, FSAbbrev);
  2511. NameVals.clear();
  2512. }
  2513. /// Emit the per-module function summary section alongside the rest of
  2514. /// the module's bitcode.
  2515. static void WritePerModuleFunctionSummary(
  2516. DenseMap<const Function *, std::unique_ptr<FunctionInfo>> &FunctionIndex,
  2517. const Module *M, const ValueEnumerator &VE, BitstreamWriter &Stream) {
  2518. Stream.EnterSubblock(bitc::FUNCTION_SUMMARY_BLOCK_ID, 3);
  2519. // Abbrev for FS_CODE_PERMODULE_ENTRY.
  2520. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2521. Abbv->Add(BitCodeAbbrevOp(bitc::FS_CODE_PERMODULE_ENTRY));
  2522. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
  2523. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // islocal
  2524. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  2525. unsigned FSAbbrev = Stream.EmitAbbrev(Abbv);
  2526. SmallVector<unsigned, 64> NameVals;
  2527. for (auto &I : FunctionIndex) {
  2528. // Skip anonymous functions. We will emit a function summary for
  2529. // any aliases below.
  2530. if (!I.first->hasName())
  2531. continue;
  2532. WritePerModuleFunctionSummaryRecord(
  2533. NameVals, I.second->functionSummary(),
  2534. VE.getValueID(M->getValueSymbolTable().lookup(I.first->getName())),
  2535. FSAbbrev, Stream);
  2536. }
  2537. for (const GlobalAlias &A : M->aliases()) {
  2538. if (!A.getBaseObject())
  2539. continue;
  2540. const Function *F = dyn_cast<Function>(A.getBaseObject());
  2541. if (!F || F->isDeclaration())
  2542. continue;
  2543. assert(FunctionIndex.count(F) == 1);
  2544. WritePerModuleFunctionSummaryRecord(
  2545. NameVals, FunctionIndex[F]->functionSummary(),
  2546. VE.getValueID(M->getValueSymbolTable().lookup(A.getName())), FSAbbrev,
  2547. Stream);
  2548. }
  2549. Stream.ExitBlock();
  2550. }
  2551. /// Emit the combined function summary section into the combined index
  2552. /// file.
  2553. static void WriteCombinedFunctionSummary(const FunctionInfoIndex &I,
  2554. BitstreamWriter &Stream) {
  2555. Stream.EnterSubblock(bitc::FUNCTION_SUMMARY_BLOCK_ID, 3);
  2556. // Abbrev for FS_CODE_COMBINED_ENTRY.
  2557. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2558. Abbv->Add(BitCodeAbbrevOp(bitc::FS_CODE_COMBINED_ENTRY));
  2559. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
  2560. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
  2561. unsigned FSAbbrev = Stream.EmitAbbrev(Abbv);
  2562. SmallVector<unsigned, 64> NameVals;
  2563. for (const auto &FII : I) {
  2564. for (auto &FI : FII.getValue()) {
  2565. FunctionSummary *FS = FI->functionSummary();
  2566. assert(FS);
  2567. NameVals.push_back(I.getModuleId(FS->modulePath()));
  2568. NameVals.push_back(FS->instCount());
  2569. // Record the starting offset of this summary entry for use
  2570. // in the VST entry. Add the current code size since the
  2571. // reader will invoke readRecord after the abbrev id read.
  2572. FI->setBitcodeIndex(Stream.GetCurrentBitNo() + Stream.GetAbbrevIDWidth());
  2573. // Emit the finished record.
  2574. Stream.EmitRecord(bitc::FS_CODE_COMBINED_ENTRY, NameVals, FSAbbrev);
  2575. NameVals.clear();
  2576. }
  2577. }
  2578. Stream.ExitBlock();
  2579. }
  2580. // Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
  2581. // current llvm version, and a record for the epoch number.
  2582. static void WriteIdentificationBlock(const Module *M, BitstreamWriter &Stream) {
  2583. Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
  2584. // Write the "user readable" string identifying the bitcode producer
  2585. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  2586. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
  2587. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  2588. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  2589. auto StringAbbrev = Stream.EmitAbbrev(Abbv);
  2590. WriteStringRecord(bitc::IDENTIFICATION_CODE_STRING,
  2591. "LLVM" LLVM_VERSION_STRING, StringAbbrev, Stream);
  2592. // Write the epoch version
  2593. Abbv = new BitCodeAbbrev();
  2594. Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
  2595. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
  2596. auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
  2597. SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
  2598. Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
  2599. Stream.ExitBlock();
  2600. }
  2601. /// WriteModule - Emit the specified module to the bitstream.
  2602. static void WriteModule(const Module *M, BitstreamWriter &Stream,
  2603. bool ShouldPreserveUseListOrder,
  2604. uint64_t BitcodeStartBit, bool EmitFunctionSummary) {
  2605. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  2606. SmallVector<unsigned, 1> Vals;
  2607. unsigned CurVersion = 1;
  2608. Vals.push_back(CurVersion);
  2609. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  2610. // Analyze the module, enumerating globals, functions, etc.
  2611. ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
  2612. // Emit blockinfo, which defines the standard abbreviations etc.
  2613. WriteBlockInfo(VE, Stream);
  2614. // Emit information about attribute groups.
  2615. WriteAttributeGroupTable(VE, Stream);
  2616. // Emit information about parameter attributes.
  2617. WriteAttributeTable(VE, Stream);
  2618. // Emit information describing all of the types in the module.
  2619. WriteTypeTable(VE, Stream);
  2620. writeComdats(VE, Stream);
  2621. // Emit top-level description of module, including target triple, inline asm,
  2622. // descriptors for global variables, and function prototype info.
  2623. uint64_t VSTOffsetPlaceholder = WriteModuleInfo(M, VE, Stream);
  2624. // Emit constants.
  2625. WriteModuleConstants(VE, Stream);
  2626. // Emit metadata.
  2627. WriteModuleMetadata(M, VE, Stream);
  2628. // Emit metadata.
  2629. WriteModuleMetadataStore(M, Stream);
  2630. // Emit module-level use-lists.
  2631. if (VE.shouldPreserveUseListOrder())
  2632. WriteUseListBlock(nullptr, VE, Stream);
  2633. WriteOperandBundleTags(M, Stream);
  2634. // Emit function bodies.
  2635. DenseMap<const Function *, std::unique_ptr<FunctionInfo>> FunctionIndex;
  2636. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
  2637. if (!F->isDeclaration())
  2638. WriteFunction(*F, VE, Stream, FunctionIndex, EmitFunctionSummary);
  2639. // Need to write after the above call to WriteFunction which populates
  2640. // the summary information in the index.
  2641. if (EmitFunctionSummary)
  2642. WritePerModuleFunctionSummary(FunctionIndex, M, VE, Stream);
  2643. WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream,
  2644. VSTOffsetPlaceholder, BitcodeStartBit, &FunctionIndex);
  2645. Stream.ExitBlock();
  2646. }
  2647. /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
  2648. /// header and trailer to make it compatible with the system archiver. To do
  2649. /// this we emit the following header, and then emit a trailer that pads the
  2650. /// file out to be a multiple of 16 bytes.
  2651. ///
  2652. /// struct bc_header {
  2653. /// uint32_t Magic; // 0x0B17C0DE
  2654. /// uint32_t Version; // Version, currently always 0.
  2655. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  2656. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  2657. /// uint32_t CPUType; // CPU specifier.
  2658. /// ... potentially more later ...
  2659. /// };
  2660. enum {
  2661. DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
  2662. DarwinBCHeaderSize = 5*4
  2663. };
  2664. static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
  2665. uint32_t &Position) {
  2666. support::endian::write32le(&Buffer[Position], Value);
  2667. Position += 4;
  2668. }
  2669. static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
  2670. const Triple &TT) {
  2671. unsigned CPUType = ~0U;
  2672. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
  2673. // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
  2674. // number from /usr/include/mach/machine.h. It is ok to reproduce the
  2675. // specific constants here because they are implicitly part of the Darwin ABI.
  2676. enum {
  2677. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  2678. DARWIN_CPU_TYPE_X86 = 7,
  2679. DARWIN_CPU_TYPE_ARM = 12,
  2680. DARWIN_CPU_TYPE_POWERPC = 18
  2681. };
  2682. Triple::ArchType Arch = TT.getArch();
  2683. if (Arch == Triple::x86_64)
  2684. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  2685. else if (Arch == Triple::x86)
  2686. CPUType = DARWIN_CPU_TYPE_X86;
  2687. else if (Arch == Triple::ppc)
  2688. CPUType = DARWIN_CPU_TYPE_POWERPC;
  2689. else if (Arch == Triple::ppc64)
  2690. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  2691. else if (Arch == Triple::arm || Arch == Triple::thumb)
  2692. CPUType = DARWIN_CPU_TYPE_ARM;
  2693. // Traditional Bitcode starts after header.
  2694. assert(Buffer.size() >= DarwinBCHeaderSize &&
  2695. "Expected header size to be reserved");
  2696. unsigned BCOffset = DarwinBCHeaderSize;
  2697. unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
  2698. // Write the magic and version.
  2699. unsigned Position = 0;
  2700. WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
  2701. WriteInt32ToBuffer(0 , Buffer, Position); // Version.
  2702. WriteInt32ToBuffer(BCOffset , Buffer, Position);
  2703. WriteInt32ToBuffer(BCSize , Buffer, Position);
  2704. WriteInt32ToBuffer(CPUType , Buffer, Position);
  2705. // If the file is not a multiple of 16 bytes, insert dummy padding.
  2706. while (Buffer.size() & 15)
  2707. Buffer.push_back(0);
  2708. }
  2709. /// Helper to write the header common to all bitcode files.
  2710. static void WriteBitcodeHeader(BitstreamWriter &Stream) {
  2711. // Emit the file header.
  2712. Stream.Emit((unsigned)'B', 8);
  2713. Stream.Emit((unsigned)'C', 8);
  2714. Stream.Emit(0x0, 4);
  2715. Stream.Emit(0xC, 4);
  2716. Stream.Emit(0xE, 4);
  2717. Stream.Emit(0xD, 4);
  2718. }
  2719. /// WriteBitcodeToFile - Write the specified module to the specified output
  2720. /// stream.
  2721. void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
  2722. bool ShouldPreserveUseListOrder,
  2723. bool EmitFunctionSummary) {
  2724. SmallVector<char, 0> Buffer;
  2725. Buffer.reserve(256*1024);
  2726. // If this is darwin or another generic macho target, reserve space for the
  2727. // header.
  2728. Triple TT(M->getTargetTriple());
  2729. if (TT.isOSDarwin())
  2730. Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
  2731. // Emit the module into the buffer.
  2732. {
  2733. BitstreamWriter Stream(Buffer);
  2734. // Save the start bit of the actual bitcode, in case there is space
  2735. // saved at the start for the darwin header above. The reader stream
  2736. // will start at the bitcode, and we need the offset of the VST
  2737. // to line up.
  2738. uint64_t BitcodeStartBit = Stream.GetCurrentBitNo();
  2739. // Emit the file header.
  2740. WriteBitcodeHeader(Stream);
  2741. WriteIdentificationBlock(M, Stream);
  2742. // Emit the module.
  2743. WriteModule(M, Stream, ShouldPreserveUseListOrder, BitcodeStartBit,
  2744. EmitFunctionSummary);
  2745. }
  2746. if (TT.isOSDarwin())
  2747. EmitDarwinBCHeaderAndTrailer(Buffer, TT);
  2748. // Write the generated bitstream to "Out".
  2749. Out.write((char*)&Buffer.front(), Buffer.size());
  2750. }
  2751. // Write the specified function summary index to the given raw output stream,
  2752. // where it will be written in a new bitcode block. This is used when
  2753. // writing the combined index file for ThinLTO.
  2754. void llvm::WriteFunctionSummaryToFile(const FunctionInfoIndex &Index,
  2755. raw_ostream &Out) {
  2756. SmallVector<char, 0> Buffer;
  2757. Buffer.reserve(256 * 1024);
  2758. BitstreamWriter Stream(Buffer);
  2759. // Emit the bitcode header.
  2760. WriteBitcodeHeader(Stream);
  2761. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  2762. SmallVector<unsigned, 1> Vals;
  2763. unsigned CurVersion = 1;
  2764. Vals.push_back(CurVersion);
  2765. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  2766. // Write the module paths in the combined index.
  2767. WriteModStrings(Index, Stream);
  2768. // Write the function summary combined index records.
  2769. WriteCombinedFunctionSummary(Index, Stream);
  2770. // Need a special VST writer for the combined index (we don't have a
  2771. // real VST and real values when this is invoked).
  2772. WriteCombinedValueSymbolTable(Index, Stream);
  2773. Stream.ExitBlock();
  2774. Out.write((char *)&Buffer.front(), Buffer.size());
  2775. }