BitcodeWriter.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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 "llvm/Bitcode/BitstreamWriter.h"
  15. #include "llvm/Bitcode/LLVMBitCodes.h"
  16. #include "ValueEnumerator.h"
  17. #include "llvm/Constants.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/InlineAsm.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/Module.h"
  22. #include "llvm/Operator.h"
  23. #include "llvm/TypeSymbolTable.h"
  24. #include "llvm/ValueSymbolTable.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include "llvm/System/Program.h"
  29. using namespace llvm;
  30. /// These are manifest constants used by the bitcode writer. They do not need to
  31. /// be kept in sync with the reader, but need to be consistent within this file.
  32. enum {
  33. CurVersion = 0,
  34. // VALUE_SYMTAB_BLOCK abbrev id's.
  35. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  36. VST_ENTRY_7_ABBREV,
  37. VST_ENTRY_6_ABBREV,
  38. VST_BBENTRY_6_ABBREV,
  39. // CONSTANTS_BLOCK abbrev id's.
  40. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  41. CONSTANTS_INTEGER_ABBREV,
  42. CONSTANTS_CE_CAST_Abbrev,
  43. CONSTANTS_NULL_Abbrev,
  44. // FUNCTION_BLOCK abbrev id's.
  45. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  46. FUNCTION_INST_BINOP_ABBREV,
  47. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  48. FUNCTION_INST_CAST_ABBREV,
  49. FUNCTION_INST_RET_VOID_ABBREV,
  50. FUNCTION_INST_RET_VAL_ABBREV,
  51. FUNCTION_INST_UNREACHABLE_ABBREV
  52. };
  53. static unsigned GetEncodedCastOpcode(unsigned Opcode) {
  54. switch (Opcode) {
  55. default: llvm_unreachable("Unknown cast instruction!");
  56. case Instruction::Trunc : return bitc::CAST_TRUNC;
  57. case Instruction::ZExt : return bitc::CAST_ZEXT;
  58. case Instruction::SExt : return bitc::CAST_SEXT;
  59. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  60. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  61. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  62. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  63. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  64. case Instruction::FPExt : return bitc::CAST_FPEXT;
  65. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  66. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  67. case Instruction::BitCast : return bitc::CAST_BITCAST;
  68. }
  69. }
  70. static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
  71. switch (Opcode) {
  72. default: llvm_unreachable("Unknown binary instruction!");
  73. case Instruction::Add:
  74. case Instruction::FAdd: return bitc::BINOP_ADD;
  75. case Instruction::Sub:
  76. case Instruction::FSub: return bitc::BINOP_SUB;
  77. case Instruction::Mul:
  78. case Instruction::FMul: return bitc::BINOP_MUL;
  79. case Instruction::UDiv: return bitc::BINOP_UDIV;
  80. case Instruction::FDiv:
  81. case Instruction::SDiv: return bitc::BINOP_SDIV;
  82. case Instruction::URem: return bitc::BINOP_UREM;
  83. case Instruction::FRem:
  84. case Instruction::SRem: return bitc::BINOP_SREM;
  85. case Instruction::Shl: return bitc::BINOP_SHL;
  86. case Instruction::LShr: return bitc::BINOP_LSHR;
  87. case Instruction::AShr: return bitc::BINOP_ASHR;
  88. case Instruction::And: return bitc::BINOP_AND;
  89. case Instruction::Or: return bitc::BINOP_OR;
  90. case Instruction::Xor: return bitc::BINOP_XOR;
  91. }
  92. }
  93. static void WriteStringRecord(unsigned Code, const std::string &Str,
  94. unsigned AbbrevToUse, BitstreamWriter &Stream) {
  95. SmallVector<unsigned, 64> Vals;
  96. // Code: [strchar x N]
  97. for (unsigned i = 0, e = Str.size(); i != e; ++i)
  98. Vals.push_back(Str[i]);
  99. // Emit the finished record.
  100. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  101. }
  102. // Emit information about parameter attributes.
  103. static void WriteAttributeTable(const ValueEnumerator &VE,
  104. BitstreamWriter &Stream) {
  105. const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
  106. if (Attrs.empty()) return;
  107. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  108. SmallVector<uint64_t, 64> Record;
  109. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  110. const AttrListPtr &A = Attrs[i];
  111. for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
  112. const AttributeWithIndex &PAWI = A.getSlot(i);
  113. Record.push_back(PAWI.Index);
  114. // FIXME: remove in LLVM 3.0
  115. // Store the alignment in the bitcode as a 16-bit raw value instead of a
  116. // 5-bit log2 encoded value. Shift the bits above the alignment up by
  117. // 11 bits.
  118. uint64_t FauxAttr = PAWI.Attrs & 0xffff;
  119. if (PAWI.Attrs & Attribute::Alignment)
  120. FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
  121. FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
  122. Record.push_back(FauxAttr);
  123. }
  124. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  125. Record.clear();
  126. }
  127. Stream.ExitBlock();
  128. }
  129. /// WriteTypeTable - Write out the type table for a module.
  130. static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  131. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  132. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
  133. SmallVector<uint64_t, 64> TypeVals;
  134. // Abbrev for TYPE_CODE_POINTER.
  135. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  136. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  137. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  138. Log2_32_Ceil(VE.getTypes().size()+1)));
  139. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  140. unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
  141. // Abbrev for TYPE_CODE_FUNCTION.
  142. Abbv = new BitCodeAbbrev();
  143. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  144. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  145. Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
  146. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  147. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  148. Log2_32_Ceil(VE.getTypes().size()+1)));
  149. unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
  150. // Abbrev for TYPE_CODE_STRUCT.
  151. Abbv = new BitCodeAbbrev();
  152. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
  153. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  154. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  155. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  156. Log2_32_Ceil(VE.getTypes().size()+1)));
  157. unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
  158. // Abbrev for TYPE_CODE_ARRAY.
  159. Abbv = new BitCodeAbbrev();
  160. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  161. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  162. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  163. Log2_32_Ceil(VE.getTypes().size()+1)));
  164. unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
  165. // Emit an entry count so the reader can reserve space.
  166. TypeVals.push_back(TypeList.size());
  167. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  168. TypeVals.clear();
  169. // Loop over all of the types, emitting each in turn.
  170. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  171. const Type *T = TypeList[i].first;
  172. int AbbrevToUse = 0;
  173. unsigned Code = 0;
  174. switch (T->getTypeID()) {
  175. default: llvm_unreachable("Unknown type!");
  176. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  177. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  178. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  179. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  180. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  181. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  182. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  183. case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
  184. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  185. case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
  186. case Type::IntegerTyID:
  187. // INTEGER: [width]
  188. Code = bitc::TYPE_CODE_INTEGER;
  189. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  190. break;
  191. case Type::PointerTyID: {
  192. const PointerType *PTy = cast<PointerType>(T);
  193. // POINTER: [pointee type, address space]
  194. Code = bitc::TYPE_CODE_POINTER;
  195. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  196. unsigned AddressSpace = PTy->getAddressSpace();
  197. TypeVals.push_back(AddressSpace);
  198. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  199. break;
  200. }
  201. case Type::FunctionTyID: {
  202. const FunctionType *FT = cast<FunctionType>(T);
  203. // FUNCTION: [isvararg, attrid, retty, paramty x N]
  204. Code = bitc::TYPE_CODE_FUNCTION;
  205. TypeVals.push_back(FT->isVarArg());
  206. TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
  207. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  208. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  209. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  210. AbbrevToUse = FunctionAbbrev;
  211. break;
  212. }
  213. case Type::StructTyID: {
  214. const StructType *ST = cast<StructType>(T);
  215. // STRUCT: [ispacked, eltty x N]
  216. Code = bitc::TYPE_CODE_STRUCT;
  217. TypeVals.push_back(ST->isPacked());
  218. // Output all of the element types.
  219. for (StructType::element_iterator I = ST->element_begin(),
  220. E = ST->element_end(); I != E; ++I)
  221. TypeVals.push_back(VE.getTypeID(*I));
  222. AbbrevToUse = StructAbbrev;
  223. break;
  224. }
  225. case Type::ArrayTyID: {
  226. const ArrayType *AT = cast<ArrayType>(T);
  227. // ARRAY: [numelts, eltty]
  228. Code = bitc::TYPE_CODE_ARRAY;
  229. TypeVals.push_back(AT->getNumElements());
  230. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  231. AbbrevToUse = ArrayAbbrev;
  232. break;
  233. }
  234. case Type::VectorTyID: {
  235. const VectorType *VT = cast<VectorType>(T);
  236. // VECTOR [numelts, eltty]
  237. Code = bitc::TYPE_CODE_VECTOR;
  238. TypeVals.push_back(VT->getNumElements());
  239. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  240. break;
  241. }
  242. }
  243. // Emit the finished record.
  244. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  245. TypeVals.clear();
  246. }
  247. Stream.ExitBlock();
  248. }
  249. static unsigned getEncodedLinkage(const GlobalValue *GV) {
  250. switch (GV->getLinkage()) {
  251. default: llvm_unreachable("Invalid linkage!");
  252. case GlobalValue::ExternalLinkage: return 0;
  253. case GlobalValue::WeakAnyLinkage: return 1;
  254. case GlobalValue::AppendingLinkage: return 2;
  255. case GlobalValue::InternalLinkage: return 3;
  256. case GlobalValue::LinkOnceAnyLinkage: return 4;
  257. case GlobalValue::DLLImportLinkage: return 5;
  258. case GlobalValue::DLLExportLinkage: return 6;
  259. case GlobalValue::ExternalWeakLinkage: return 7;
  260. case GlobalValue::CommonLinkage: return 8;
  261. case GlobalValue::PrivateLinkage: return 9;
  262. case GlobalValue::WeakODRLinkage: return 10;
  263. case GlobalValue::LinkOnceODRLinkage: return 11;
  264. case GlobalValue::AvailableExternallyLinkage: return 12;
  265. case GlobalValue::LinkerPrivateLinkage: return 13;
  266. case GlobalValue::LinkerPrivateWeakLinkage: return 14;
  267. case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15;
  268. }
  269. }
  270. static unsigned getEncodedVisibility(const GlobalValue *GV) {
  271. switch (GV->getVisibility()) {
  272. default: llvm_unreachable("Invalid visibility!");
  273. case GlobalValue::DefaultVisibility: return 0;
  274. case GlobalValue::HiddenVisibility: return 1;
  275. case GlobalValue::ProtectedVisibility: return 2;
  276. }
  277. }
  278. // Emit top-level description of module, including target triple, inline asm,
  279. // descriptors for global variables, and function prototype info.
  280. static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
  281. BitstreamWriter &Stream) {
  282. // Emit the list of dependent libraries for the Module.
  283. for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
  284. WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
  285. // Emit various pieces of data attached to a module.
  286. if (!M->getTargetTriple().empty())
  287. WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
  288. 0/*TODO*/, Stream);
  289. if (!M->getDataLayout().empty())
  290. WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
  291. 0/*TODO*/, Stream);
  292. if (!M->getModuleInlineAsm().empty())
  293. WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
  294. 0/*TODO*/, Stream);
  295. // Emit information about sections and GC, computing how many there are. Also
  296. // compute the maximum alignment value.
  297. std::map<std::string, unsigned> SectionMap;
  298. std::map<std::string, unsigned> GCMap;
  299. unsigned MaxAlignment = 0;
  300. unsigned MaxGlobalType = 0;
  301. for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
  302. GV != E; ++GV) {
  303. MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
  304. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
  305. if (!GV->hasSection()) continue;
  306. // Give section names unique ID's.
  307. unsigned &Entry = SectionMap[GV->getSection()];
  308. if (Entry != 0) continue;
  309. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
  310. 0/*TODO*/, Stream);
  311. Entry = SectionMap.size();
  312. }
  313. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
  314. MaxAlignment = std::max(MaxAlignment, F->getAlignment());
  315. if (F->hasSection()) {
  316. // Give section names unique ID's.
  317. unsigned &Entry = SectionMap[F->getSection()];
  318. if (!Entry) {
  319. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
  320. 0/*TODO*/, Stream);
  321. Entry = SectionMap.size();
  322. }
  323. }
  324. if (F->hasGC()) {
  325. // Same for GC names.
  326. unsigned &Entry = GCMap[F->getGC()];
  327. if (!Entry) {
  328. WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
  329. 0/*TODO*/, Stream);
  330. Entry = GCMap.size();
  331. }
  332. }
  333. }
  334. // Emit abbrev for globals, now that we know # sections and max alignment.
  335. unsigned SimpleGVarAbbrev = 0;
  336. if (!M->global_empty()) {
  337. // Add an abbrev for common globals with no visibility or thread localness.
  338. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  339. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  340. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  341. Log2_32_Ceil(MaxGlobalType+1)));
  342. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
  343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  344. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
  345. if (MaxAlignment == 0) // Alignment.
  346. Abbv->Add(BitCodeAbbrevOp(0));
  347. else {
  348. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  349. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  350. Log2_32_Ceil(MaxEncAlignment+1)));
  351. }
  352. if (SectionMap.empty()) // Section.
  353. Abbv->Add(BitCodeAbbrevOp(0));
  354. else
  355. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  356. Log2_32_Ceil(SectionMap.size()+1)));
  357. // Don't bother emitting vis + thread local.
  358. SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
  359. }
  360. // Emit the global variable information.
  361. SmallVector<unsigned, 64> Vals;
  362. for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
  363. GV != E; ++GV) {
  364. unsigned AbbrevToUse = 0;
  365. // GLOBALVAR: [type, isconst, initid,
  366. // linkage, alignment, section, visibility, threadlocal]
  367. Vals.push_back(VE.getTypeID(GV->getType()));
  368. Vals.push_back(GV->isConstant());
  369. Vals.push_back(GV->isDeclaration() ? 0 :
  370. (VE.getValueID(GV->getInitializer()) + 1));
  371. Vals.push_back(getEncodedLinkage(GV));
  372. Vals.push_back(Log2_32(GV->getAlignment())+1);
  373. Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
  374. if (GV->isThreadLocal() ||
  375. GV->getVisibility() != GlobalValue::DefaultVisibility) {
  376. Vals.push_back(getEncodedVisibility(GV));
  377. Vals.push_back(GV->isThreadLocal());
  378. } else {
  379. AbbrevToUse = SimpleGVarAbbrev;
  380. }
  381. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  382. Vals.clear();
  383. }
  384. // Emit the function proto information.
  385. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
  386. // FUNCTION: [type, callingconv, isproto, paramattr,
  387. // linkage, alignment, section, visibility, gc]
  388. Vals.push_back(VE.getTypeID(F->getType()));
  389. Vals.push_back(F->getCallingConv());
  390. Vals.push_back(F->isDeclaration());
  391. Vals.push_back(getEncodedLinkage(F));
  392. Vals.push_back(VE.getAttributeID(F->getAttributes()));
  393. Vals.push_back(Log2_32(F->getAlignment())+1);
  394. Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
  395. Vals.push_back(getEncodedVisibility(F));
  396. Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
  397. unsigned AbbrevToUse = 0;
  398. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  399. Vals.clear();
  400. }
  401. // Emit the alias information.
  402. for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
  403. AI != E; ++AI) {
  404. Vals.push_back(VE.getTypeID(AI->getType()));
  405. Vals.push_back(VE.getValueID(AI->getAliasee()));
  406. Vals.push_back(getEncodedLinkage(AI));
  407. Vals.push_back(getEncodedVisibility(AI));
  408. unsigned AbbrevToUse = 0;
  409. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  410. Vals.clear();
  411. }
  412. }
  413. static uint64_t GetOptimizationFlags(const Value *V) {
  414. uint64_t Flags = 0;
  415. if (const OverflowingBinaryOperator *OBO =
  416. dyn_cast<OverflowingBinaryOperator>(V)) {
  417. if (OBO->hasNoSignedWrap())
  418. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  419. if (OBO->hasNoUnsignedWrap())
  420. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  421. } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
  422. if (Div->isExact())
  423. Flags |= 1 << bitc::SDIV_EXACT;
  424. }
  425. return Flags;
  426. }
  427. static void WriteMDNode(const MDNode *N,
  428. const ValueEnumerator &VE,
  429. BitstreamWriter &Stream,
  430. SmallVector<uint64_t, 64> &Record) {
  431. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  432. if (N->getOperand(i)) {
  433. Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
  434. Record.push_back(VE.getValueID(N->getOperand(i)));
  435. } else {
  436. Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
  437. Record.push_back(0);
  438. }
  439. }
  440. unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE2 :
  441. bitc::METADATA_NODE2;
  442. Stream.EmitRecord(MDCode, Record, 0);
  443. Record.clear();
  444. }
  445. static void WriteModuleMetadata(const Module *M,
  446. const ValueEnumerator &VE,
  447. BitstreamWriter &Stream) {
  448. const ValueEnumerator::ValueList &Vals = VE.getMDValues();
  449. bool StartedMetadataBlock = false;
  450. unsigned MDSAbbrev = 0;
  451. SmallVector<uint64_t, 64> Record;
  452. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  453. if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
  454. if (!N->isFunctionLocal() || !N->getFunction()) {
  455. if (!StartedMetadataBlock) {
  456. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  457. StartedMetadataBlock = true;
  458. }
  459. WriteMDNode(N, VE, Stream, Record);
  460. }
  461. } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
  462. if (!StartedMetadataBlock) {
  463. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  464. // Abbrev for METADATA_STRING.
  465. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  466. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
  467. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  468. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  469. MDSAbbrev = Stream.EmitAbbrev(Abbv);
  470. StartedMetadataBlock = true;
  471. }
  472. // Code: [strchar x N]
  473. Record.append(MDS->begin(), MDS->end());
  474. // Emit the finished record.
  475. Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
  476. Record.clear();
  477. }
  478. }
  479. // Write named metadata.
  480. for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
  481. E = M->named_metadata_end(); I != E; ++I) {
  482. const NamedMDNode *NMD = I;
  483. if (!StartedMetadataBlock) {
  484. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  485. StartedMetadataBlock = true;
  486. }
  487. // Write name.
  488. StringRef Str = NMD->getName();
  489. for (unsigned i = 0, e = Str.size(); i != e; ++i)
  490. Record.push_back(Str[i]);
  491. Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
  492. Record.clear();
  493. // Write named metadata operands.
  494. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
  495. Record.push_back(VE.getValueID(NMD->getOperand(i)));
  496. Stream.EmitRecord(bitc::METADATA_NAMED_NODE2, Record, 0);
  497. Record.clear();
  498. }
  499. if (StartedMetadataBlock)
  500. Stream.ExitBlock();
  501. }
  502. static void WriteFunctionLocalMetadata(const Function &F,
  503. const ValueEnumerator &VE,
  504. BitstreamWriter &Stream) {
  505. bool StartedMetadataBlock = false;
  506. SmallVector<uint64_t, 64> Record;
  507. const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
  508. for (unsigned i = 0, e = Vals.size(); i != e; ++i)
  509. if (const MDNode *N = Vals[i])
  510. if (N->isFunctionLocal() && N->getFunction() == &F) {
  511. if (!StartedMetadataBlock) {
  512. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  513. StartedMetadataBlock = true;
  514. }
  515. WriteMDNode(N, VE, Stream, Record);
  516. }
  517. if (StartedMetadataBlock)
  518. Stream.ExitBlock();
  519. }
  520. static void WriteMetadataAttachment(const Function &F,
  521. const ValueEnumerator &VE,
  522. BitstreamWriter &Stream) {
  523. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  524. SmallVector<uint64_t, 64> Record;
  525. // Write metadata attachments
  526. // METADATA_ATTACHMENT2 - [m x [value, [n x [id, mdnode]]]
  527. SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
  528. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  529. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  530. I != E; ++I) {
  531. MDs.clear();
  532. I->getAllMetadataOtherThanDebugLoc(MDs);
  533. // If no metadata, ignore instruction.
  534. if (MDs.empty()) continue;
  535. Record.push_back(VE.getInstructionID(I));
  536. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  537. Record.push_back(MDs[i].first);
  538. Record.push_back(VE.getValueID(MDs[i].second));
  539. }
  540. Stream.EmitRecord(bitc::METADATA_ATTACHMENT2, Record, 0);
  541. Record.clear();
  542. }
  543. Stream.ExitBlock();
  544. }
  545. static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
  546. SmallVector<uint64_t, 64> Record;
  547. // Write metadata kinds
  548. // METADATA_KIND - [n x [id, name]]
  549. SmallVector<StringRef, 4> Names;
  550. M->getMDKindNames(Names);
  551. if (Names.empty()) return;
  552. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  553. for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
  554. Record.push_back(MDKindID);
  555. StringRef KName = Names[MDKindID];
  556. Record.append(KName.begin(), KName.end());
  557. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  558. Record.clear();
  559. }
  560. Stream.ExitBlock();
  561. }
  562. static void WriteConstants(unsigned FirstVal, unsigned LastVal,
  563. const ValueEnumerator &VE,
  564. BitstreamWriter &Stream, bool isGlobal) {
  565. if (FirstVal == LastVal) return;
  566. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  567. unsigned AggregateAbbrev = 0;
  568. unsigned String8Abbrev = 0;
  569. unsigned CString7Abbrev = 0;
  570. unsigned CString6Abbrev = 0;
  571. // If this is a constant pool for the module, emit module-specific abbrevs.
  572. if (isGlobal) {
  573. // Abbrev for CST_CODE_AGGREGATE.
  574. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  575. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  576. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  577. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  578. AggregateAbbrev = Stream.EmitAbbrev(Abbv);
  579. // Abbrev for CST_CODE_STRING.
  580. Abbv = new BitCodeAbbrev();
  581. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  582. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  583. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  584. String8Abbrev = Stream.EmitAbbrev(Abbv);
  585. // Abbrev for CST_CODE_CSTRING.
  586. Abbv = new BitCodeAbbrev();
  587. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  588. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  589. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  590. CString7Abbrev = Stream.EmitAbbrev(Abbv);
  591. // Abbrev for CST_CODE_CSTRING.
  592. Abbv = new BitCodeAbbrev();
  593. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  594. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  595. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  596. CString6Abbrev = Stream.EmitAbbrev(Abbv);
  597. }
  598. SmallVector<uint64_t, 64> Record;
  599. const ValueEnumerator::ValueList &Vals = VE.getValues();
  600. const Type *LastTy = 0;
  601. for (unsigned i = FirstVal; i != LastVal; ++i) {
  602. const Value *V = Vals[i].first;
  603. // If we need to switch types, do so now.
  604. if (V->getType() != LastTy) {
  605. LastTy = V->getType();
  606. Record.push_back(VE.getTypeID(LastTy));
  607. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  608. CONSTANTS_SETTYPE_ABBREV);
  609. Record.clear();
  610. }
  611. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  612. Record.push_back(unsigned(IA->hasSideEffects()) |
  613. unsigned(IA->isAlignStack()) << 1);
  614. // Add the asm string.
  615. const std::string &AsmStr = IA->getAsmString();
  616. Record.push_back(AsmStr.size());
  617. for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
  618. Record.push_back(AsmStr[i]);
  619. // Add the constraint string.
  620. const std::string &ConstraintStr = IA->getConstraintString();
  621. Record.push_back(ConstraintStr.size());
  622. for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
  623. Record.push_back(ConstraintStr[i]);
  624. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  625. Record.clear();
  626. continue;
  627. }
  628. const Constant *C = cast<Constant>(V);
  629. unsigned Code = -1U;
  630. unsigned AbbrevToUse = 0;
  631. if (C->isNullValue()) {
  632. Code = bitc::CST_CODE_NULL;
  633. } else if (isa<UndefValue>(C)) {
  634. Code = bitc::CST_CODE_UNDEF;
  635. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  636. if (IV->getBitWidth() <= 64) {
  637. uint64_t V = IV->getSExtValue();
  638. if ((int64_t)V >= 0)
  639. Record.push_back(V << 1);
  640. else
  641. Record.push_back((-V << 1) | 1);
  642. Code = bitc::CST_CODE_INTEGER;
  643. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  644. } else { // Wide integers, > 64 bits in size.
  645. // We have an arbitrary precision integer value to write whose
  646. // bit width is > 64. However, in canonical unsigned integer
  647. // format it is likely that the high bits are going to be zero.
  648. // So, we only write the number of active words.
  649. unsigned NWords = IV->getValue().getActiveWords();
  650. const uint64_t *RawWords = IV->getValue().getRawData();
  651. for (unsigned i = 0; i != NWords; ++i) {
  652. int64_t V = RawWords[i];
  653. if (V >= 0)
  654. Record.push_back(V << 1);
  655. else
  656. Record.push_back((-V << 1) | 1);
  657. }
  658. Code = bitc::CST_CODE_WIDE_INTEGER;
  659. }
  660. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  661. Code = bitc::CST_CODE_FLOAT;
  662. const Type *Ty = CFP->getType();
  663. if (Ty->isFloatTy() || Ty->isDoubleTy()) {
  664. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  665. } else if (Ty->isX86_FP80Ty()) {
  666. // api needed to prevent premature destruction
  667. // bits are not in the same order as a normal i80 APInt, compensate.
  668. APInt api = CFP->getValueAPF().bitcastToAPInt();
  669. const uint64_t *p = api.getRawData();
  670. Record.push_back((p[1] << 48) | (p[0] >> 16));
  671. Record.push_back(p[0] & 0xffffLL);
  672. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  673. APInt api = CFP->getValueAPF().bitcastToAPInt();
  674. const uint64_t *p = api.getRawData();
  675. Record.push_back(p[0]);
  676. Record.push_back(p[1]);
  677. } else {
  678. assert (0 && "Unknown FP type!");
  679. }
  680. } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
  681. const ConstantArray *CA = cast<ConstantArray>(C);
  682. // Emit constant strings specially.
  683. unsigned NumOps = CA->getNumOperands();
  684. // If this is a null-terminated string, use the denser CSTRING encoding.
  685. if (CA->getOperand(NumOps-1)->isNullValue()) {
  686. Code = bitc::CST_CODE_CSTRING;
  687. --NumOps; // Don't encode the null, which isn't allowed by char6.
  688. } else {
  689. Code = bitc::CST_CODE_STRING;
  690. AbbrevToUse = String8Abbrev;
  691. }
  692. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  693. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  694. for (unsigned i = 0; i != NumOps; ++i) {
  695. unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
  696. Record.push_back(V);
  697. isCStr7 &= (V & 128) == 0;
  698. if (isCStrChar6)
  699. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  700. }
  701. if (isCStrChar6)
  702. AbbrevToUse = CString6Abbrev;
  703. else if (isCStr7)
  704. AbbrevToUse = CString7Abbrev;
  705. } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
  706. isa<ConstantVector>(V)) {
  707. Code = bitc::CST_CODE_AGGREGATE;
  708. for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
  709. Record.push_back(VE.getValueID(C->getOperand(i)));
  710. AbbrevToUse = AggregateAbbrev;
  711. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  712. switch (CE->getOpcode()) {
  713. default:
  714. if (Instruction::isCast(CE->getOpcode())) {
  715. Code = bitc::CST_CODE_CE_CAST;
  716. Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
  717. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  718. Record.push_back(VE.getValueID(C->getOperand(0)));
  719. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  720. } else {
  721. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  722. Code = bitc::CST_CODE_CE_BINOP;
  723. Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
  724. Record.push_back(VE.getValueID(C->getOperand(0)));
  725. Record.push_back(VE.getValueID(C->getOperand(1)));
  726. uint64_t Flags = GetOptimizationFlags(CE);
  727. if (Flags != 0)
  728. Record.push_back(Flags);
  729. }
  730. break;
  731. case Instruction::GetElementPtr:
  732. Code = bitc::CST_CODE_CE_GEP;
  733. if (cast<GEPOperator>(C)->isInBounds())
  734. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  735. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  736. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  737. Record.push_back(VE.getValueID(C->getOperand(i)));
  738. }
  739. break;
  740. case Instruction::Select:
  741. Code = bitc::CST_CODE_CE_SELECT;
  742. Record.push_back(VE.getValueID(C->getOperand(0)));
  743. Record.push_back(VE.getValueID(C->getOperand(1)));
  744. Record.push_back(VE.getValueID(C->getOperand(2)));
  745. break;
  746. case Instruction::ExtractElement:
  747. Code = bitc::CST_CODE_CE_EXTRACTELT;
  748. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  749. Record.push_back(VE.getValueID(C->getOperand(0)));
  750. Record.push_back(VE.getValueID(C->getOperand(1)));
  751. break;
  752. case Instruction::InsertElement:
  753. Code = bitc::CST_CODE_CE_INSERTELT;
  754. Record.push_back(VE.getValueID(C->getOperand(0)));
  755. Record.push_back(VE.getValueID(C->getOperand(1)));
  756. Record.push_back(VE.getValueID(C->getOperand(2)));
  757. break;
  758. case Instruction::ShuffleVector:
  759. // If the return type and argument types are the same, this is a
  760. // standard shufflevector instruction. If the types are different,
  761. // then the shuffle is widening or truncating the input vectors, and
  762. // the argument type must also be encoded.
  763. if (C->getType() == C->getOperand(0)->getType()) {
  764. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  765. } else {
  766. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  767. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  768. }
  769. Record.push_back(VE.getValueID(C->getOperand(0)));
  770. Record.push_back(VE.getValueID(C->getOperand(1)));
  771. Record.push_back(VE.getValueID(C->getOperand(2)));
  772. break;
  773. case Instruction::ICmp:
  774. case Instruction::FCmp:
  775. Code = bitc::CST_CODE_CE_CMP;
  776. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  777. Record.push_back(VE.getValueID(C->getOperand(0)));
  778. Record.push_back(VE.getValueID(C->getOperand(1)));
  779. Record.push_back(CE->getPredicate());
  780. break;
  781. }
  782. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  783. assert(BA->getFunction() == BA->getBasicBlock()->getParent() &&
  784. "Malformed blockaddress");
  785. Code = bitc::CST_CODE_BLOCKADDRESS;
  786. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  787. Record.push_back(VE.getValueID(BA->getFunction()));
  788. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  789. } else {
  790. #ifndef NDEBUG
  791. C->dump();
  792. #endif
  793. llvm_unreachable("Unknown constant!");
  794. }
  795. Stream.EmitRecord(Code, Record, AbbrevToUse);
  796. Record.clear();
  797. }
  798. Stream.ExitBlock();
  799. }
  800. static void WriteModuleConstants(const ValueEnumerator &VE,
  801. BitstreamWriter &Stream) {
  802. const ValueEnumerator::ValueList &Vals = VE.getValues();
  803. // Find the first constant to emit, which is the first non-globalvalue value.
  804. // We know globalvalues have been emitted by WriteModuleInfo.
  805. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  806. if (!isa<GlobalValue>(Vals[i].first)) {
  807. WriteConstants(i, Vals.size(), VE, Stream, true);
  808. return;
  809. }
  810. }
  811. }
  812. /// PushValueAndType - The file has to encode both the value and type id for
  813. /// many values, because we need to know what type to create for forward
  814. /// references. However, most operands are not forward references, so this type
  815. /// field is not needed.
  816. ///
  817. /// This function adds V's value ID to Vals. If the value ID is higher than the
  818. /// instruction ID, then it is a forward reference, and it also includes the
  819. /// type ID.
  820. static bool PushValueAndType(const Value *V, unsigned InstID,
  821. SmallVector<unsigned, 64> &Vals,
  822. ValueEnumerator &VE) {
  823. unsigned ValID = VE.getValueID(V);
  824. Vals.push_back(ValID);
  825. if (ValID >= InstID) {
  826. Vals.push_back(VE.getTypeID(V->getType()));
  827. return true;
  828. }
  829. return false;
  830. }
  831. /// WriteInstruction - Emit an instruction to the specified stream.
  832. static void WriteInstruction(const Instruction &I, unsigned InstID,
  833. ValueEnumerator &VE, BitstreamWriter &Stream,
  834. SmallVector<unsigned, 64> &Vals) {
  835. unsigned Code = 0;
  836. unsigned AbbrevToUse = 0;
  837. VE.setInstructionID(&I);
  838. switch (I.getOpcode()) {
  839. default:
  840. if (Instruction::isCast(I.getOpcode())) {
  841. Code = bitc::FUNC_CODE_INST_CAST;
  842. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  843. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  844. Vals.push_back(VE.getTypeID(I.getType()));
  845. Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
  846. } else {
  847. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  848. Code = bitc::FUNC_CODE_INST_BINOP;
  849. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  850. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  851. Vals.push_back(VE.getValueID(I.getOperand(1)));
  852. Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
  853. uint64_t Flags = GetOptimizationFlags(&I);
  854. if (Flags != 0) {
  855. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  856. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  857. Vals.push_back(Flags);
  858. }
  859. }
  860. break;
  861. case Instruction::GetElementPtr:
  862. Code = bitc::FUNC_CODE_INST_GEP;
  863. if (cast<GEPOperator>(&I)->isInBounds())
  864. Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
  865. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  866. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  867. break;
  868. case Instruction::ExtractValue: {
  869. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  870. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  871. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  872. for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
  873. Vals.push_back(*i);
  874. break;
  875. }
  876. case Instruction::InsertValue: {
  877. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  878. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  879. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  880. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  881. for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
  882. Vals.push_back(*i);
  883. break;
  884. }
  885. case Instruction::Select:
  886. Code = bitc::FUNC_CODE_INST_VSELECT;
  887. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  888. Vals.push_back(VE.getValueID(I.getOperand(2)));
  889. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  890. break;
  891. case Instruction::ExtractElement:
  892. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  893. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  894. Vals.push_back(VE.getValueID(I.getOperand(1)));
  895. break;
  896. case Instruction::InsertElement:
  897. Code = bitc::FUNC_CODE_INST_INSERTELT;
  898. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  899. Vals.push_back(VE.getValueID(I.getOperand(1)));
  900. Vals.push_back(VE.getValueID(I.getOperand(2)));
  901. break;
  902. case Instruction::ShuffleVector:
  903. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  904. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  905. Vals.push_back(VE.getValueID(I.getOperand(1)));
  906. Vals.push_back(VE.getValueID(I.getOperand(2)));
  907. break;
  908. case Instruction::ICmp:
  909. case Instruction::FCmp:
  910. // compare returning Int1Ty or vector of Int1Ty
  911. Code = bitc::FUNC_CODE_INST_CMP2;
  912. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  913. Vals.push_back(VE.getValueID(I.getOperand(1)));
  914. Vals.push_back(cast<CmpInst>(I).getPredicate());
  915. break;
  916. case Instruction::Ret:
  917. {
  918. Code = bitc::FUNC_CODE_INST_RET;
  919. unsigned NumOperands = I.getNumOperands();
  920. if (NumOperands == 0)
  921. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  922. else if (NumOperands == 1) {
  923. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  924. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  925. } else {
  926. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  927. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  928. }
  929. }
  930. break;
  931. case Instruction::Br:
  932. {
  933. Code = bitc::FUNC_CODE_INST_BR;
  934. BranchInst &II = cast<BranchInst>(I);
  935. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  936. if (II.isConditional()) {
  937. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  938. Vals.push_back(VE.getValueID(II.getCondition()));
  939. }
  940. }
  941. break;
  942. case Instruction::Switch:
  943. Code = bitc::FUNC_CODE_INST_SWITCH;
  944. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  945. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  946. Vals.push_back(VE.getValueID(I.getOperand(i)));
  947. break;
  948. case Instruction::IndirectBr:
  949. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  950. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  951. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  952. Vals.push_back(VE.getValueID(I.getOperand(i)));
  953. break;
  954. case Instruction::Invoke: {
  955. const InvokeInst *II = cast<InvokeInst>(&I);
  956. const Value *Callee(II->getCalledValue());
  957. const PointerType *PTy = cast<PointerType>(Callee->getType());
  958. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  959. Code = bitc::FUNC_CODE_INST_INVOKE;
  960. Vals.push_back(VE.getAttributeID(II->getAttributes()));
  961. Vals.push_back(II->getCallingConv());
  962. Vals.push_back(VE.getValueID(II->getNormalDest()));
  963. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  964. PushValueAndType(Callee, InstID, Vals, VE);
  965. // Emit value #'s for the fixed parameters.
  966. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  967. Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
  968. // Emit type/value pairs for varargs params.
  969. if (FTy->isVarArg()) {
  970. for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
  971. i != e; ++i)
  972. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
  973. }
  974. break;
  975. }
  976. case Instruction::Unwind:
  977. Code = bitc::FUNC_CODE_INST_UNWIND;
  978. break;
  979. case Instruction::Unreachable:
  980. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  981. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  982. break;
  983. case Instruction::PHI:
  984. Code = bitc::FUNC_CODE_INST_PHI;
  985. Vals.push_back(VE.getTypeID(I.getType()));
  986. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  987. Vals.push_back(VE.getValueID(I.getOperand(i)));
  988. break;
  989. case Instruction::Alloca:
  990. Code = bitc::FUNC_CODE_INST_ALLOCA;
  991. Vals.push_back(VE.getTypeID(I.getType()));
  992. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  993. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  994. Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
  995. break;
  996. case Instruction::Load:
  997. Code = bitc::FUNC_CODE_INST_LOAD;
  998. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
  999. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  1000. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  1001. Vals.push_back(cast<LoadInst>(I).isVolatile());
  1002. break;
  1003. case Instruction::Store:
  1004. Code = bitc::FUNC_CODE_INST_STORE2;
  1005. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
  1006. Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
  1007. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  1008. Vals.push_back(cast<StoreInst>(I).isVolatile());
  1009. break;
  1010. case Instruction::Call: {
  1011. const CallInst &CI = cast<CallInst>(I);
  1012. const PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
  1013. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  1014. Code = bitc::FUNC_CODE_INST_CALL2;
  1015. Vals.push_back(VE.getAttributeID(CI.getAttributes()));
  1016. Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
  1017. PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
  1018. // Emit value #'s for the fixed parameters.
  1019. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  1020. Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param.
  1021. // Emit type/value pairs for varargs params.
  1022. if (FTy->isVarArg()) {
  1023. for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
  1024. i != e; ++i)
  1025. PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs
  1026. }
  1027. break;
  1028. }
  1029. case Instruction::VAArg:
  1030. Code = bitc::FUNC_CODE_INST_VAARG;
  1031. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  1032. Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
  1033. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  1034. break;
  1035. }
  1036. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  1037. Vals.clear();
  1038. }
  1039. // Emit names for globals/functions etc.
  1040. static void WriteValueSymbolTable(const ValueSymbolTable &VST,
  1041. const ValueEnumerator &VE,
  1042. BitstreamWriter &Stream) {
  1043. if (VST.empty()) return;
  1044. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  1045. // FIXME: Set up the abbrev, we know how many values there are!
  1046. // FIXME: We know if the type names can use 7-bit ascii.
  1047. SmallVector<unsigned, 64> NameVals;
  1048. for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
  1049. SI != SE; ++SI) {
  1050. const ValueName &Name = *SI;
  1051. // Figure out the encoding to use for the name.
  1052. bool is7Bit = true;
  1053. bool isChar6 = true;
  1054. for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
  1055. C != E; ++C) {
  1056. if (isChar6)
  1057. isChar6 = BitCodeAbbrevOp::isChar6(*C);
  1058. if ((unsigned char)*C & 128) {
  1059. is7Bit = false;
  1060. break; // don't bother scanning the rest.
  1061. }
  1062. }
  1063. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  1064. // VST_ENTRY: [valueid, namechar x N]
  1065. // VST_BBENTRY: [bbid, namechar x N]
  1066. unsigned Code;
  1067. if (isa<BasicBlock>(SI->getValue())) {
  1068. Code = bitc::VST_CODE_BBENTRY;
  1069. if (isChar6)
  1070. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  1071. } else {
  1072. Code = bitc::VST_CODE_ENTRY;
  1073. if (isChar6)
  1074. AbbrevToUse = VST_ENTRY_6_ABBREV;
  1075. else if (is7Bit)
  1076. AbbrevToUse = VST_ENTRY_7_ABBREV;
  1077. }
  1078. NameVals.push_back(VE.getValueID(SI->getValue()));
  1079. for (const char *P = Name.getKeyData(),
  1080. *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
  1081. NameVals.push_back((unsigned char)*P);
  1082. // Emit the finished record.
  1083. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  1084. NameVals.clear();
  1085. }
  1086. Stream.ExitBlock();
  1087. }
  1088. /// WriteFunction - Emit a function body to the module stream.
  1089. static void WriteFunction(const Function &F, ValueEnumerator &VE,
  1090. BitstreamWriter &Stream) {
  1091. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  1092. VE.incorporateFunction(F);
  1093. SmallVector<unsigned, 64> Vals;
  1094. // Emit the number of basic blocks, so the reader can create them ahead of
  1095. // time.
  1096. Vals.push_back(VE.getBasicBlocks().size());
  1097. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  1098. Vals.clear();
  1099. // If there are function-local constants, emit them now.
  1100. unsigned CstStart, CstEnd;
  1101. VE.getFunctionConstantRange(CstStart, CstEnd);
  1102. WriteConstants(CstStart, CstEnd, VE, Stream, false);
  1103. // If there is function-local metadata, emit it now.
  1104. WriteFunctionLocalMetadata(F, VE, Stream);
  1105. // Keep a running idea of what the instruction ID is.
  1106. unsigned InstID = CstEnd;
  1107. bool NeedsMetadataAttachment = false;
  1108. DebugLoc LastDL;
  1109. // Finally, emit all the instructions, in order.
  1110. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  1111. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  1112. I != E; ++I) {
  1113. WriteInstruction(*I, InstID, VE, Stream, Vals);
  1114. if (!I->getType()->isVoidTy())
  1115. ++InstID;
  1116. // If the instruction has metadata, write a metadata attachment later.
  1117. NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
  1118. // If the instruction has a debug location, emit it.
  1119. DebugLoc DL = I->getDebugLoc();
  1120. if (DL.isUnknown()) {
  1121. // nothing todo.
  1122. } else if (DL == LastDL) {
  1123. // Just repeat the same debug loc as last time.
  1124. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
  1125. } else {
  1126. MDNode *Scope, *IA;
  1127. DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
  1128. Vals.push_back(DL.getLine());
  1129. Vals.push_back(DL.getCol());
  1130. Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
  1131. Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
  1132. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC2, Vals);
  1133. Vals.clear();
  1134. LastDL = DL;
  1135. }
  1136. }
  1137. // Emit names for all the instructions etc.
  1138. WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
  1139. if (NeedsMetadataAttachment)
  1140. WriteMetadataAttachment(F, VE, Stream);
  1141. VE.purgeFunction();
  1142. Stream.ExitBlock();
  1143. }
  1144. /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
  1145. static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
  1146. const ValueEnumerator &VE,
  1147. BitstreamWriter &Stream) {
  1148. if (TST.empty()) return;
  1149. Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
  1150. // 7-bit fixed width VST_CODE_ENTRY strings.
  1151. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1152. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1153. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1154. Log2_32_Ceil(VE.getTypes().size()+1)));
  1155. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1156. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1157. unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
  1158. SmallVector<unsigned, 64> NameVals;
  1159. for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
  1160. TI != TE; ++TI) {
  1161. // TST_ENTRY: [typeid, namechar x N]
  1162. NameVals.push_back(VE.getTypeID(TI->second));
  1163. const std::string &Str = TI->first;
  1164. bool is7Bit = true;
  1165. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  1166. NameVals.push_back((unsigned char)Str[i]);
  1167. if (Str[i] & 128)
  1168. is7Bit = false;
  1169. }
  1170. // Emit the finished record.
  1171. Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
  1172. NameVals.clear();
  1173. }
  1174. Stream.ExitBlock();
  1175. }
  1176. // Emit blockinfo, which defines the standard abbreviations etc.
  1177. static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  1178. // We only want to emit block info records for blocks that have multiple
  1179. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
  1180. // blocks can defined their abbrevs inline.
  1181. Stream.EnterBlockInfoBlock(2);
  1182. { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
  1183. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1184. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  1185. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1186. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1187. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1188. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1189. Abbv) != VST_ENTRY_8_ABBREV)
  1190. llvm_unreachable("Unexpected abbrev ordering!");
  1191. }
  1192. { // 7-bit fixed width VST_ENTRY strings.
  1193. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1194. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1195. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1196. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1197. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1198. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1199. Abbv) != VST_ENTRY_7_ABBREV)
  1200. llvm_unreachable("Unexpected abbrev ordering!");
  1201. }
  1202. { // 6-bit char6 VST_ENTRY strings.
  1203. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1204. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1205. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1206. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1207. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1208. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1209. Abbv) != VST_ENTRY_6_ABBREV)
  1210. llvm_unreachable("Unexpected abbrev ordering!");
  1211. }
  1212. { // 6-bit char6 VST_BBENTRY strings.
  1213. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1214. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  1215. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1216. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1217. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1218. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1219. Abbv) != VST_BBENTRY_6_ABBREV)
  1220. llvm_unreachable("Unexpected abbrev ordering!");
  1221. }
  1222. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  1223. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1224. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  1225. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1226. Log2_32_Ceil(VE.getTypes().size()+1)));
  1227. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1228. Abbv) != CONSTANTS_SETTYPE_ABBREV)
  1229. llvm_unreachable("Unexpected abbrev ordering!");
  1230. }
  1231. { // INTEGER abbrev for CONSTANTS_BLOCK.
  1232. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1233. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  1234. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1235. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1236. Abbv) != CONSTANTS_INTEGER_ABBREV)
  1237. llvm_unreachable("Unexpected abbrev ordering!");
  1238. }
  1239. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  1240. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1241. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  1242. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  1243. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  1244. Log2_32_Ceil(VE.getTypes().size()+1)));
  1245. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  1246. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1247. Abbv) != CONSTANTS_CE_CAST_Abbrev)
  1248. llvm_unreachable("Unexpected abbrev ordering!");
  1249. }
  1250. { // NULL abbrev for CONSTANTS_BLOCK.
  1251. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1252. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  1253. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1254. Abbv) != CONSTANTS_NULL_Abbrev)
  1255. llvm_unreachable("Unexpected abbrev ordering!");
  1256. }
  1257. // FIXME: This should only use space for first class types!
  1258. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  1259. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1260. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  1261. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  1262. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  1263. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  1264. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1265. Abbv) != FUNCTION_INST_LOAD_ABBREV)
  1266. llvm_unreachable("Unexpected abbrev ordering!");
  1267. }
  1268. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  1269. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1270. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  1271. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  1272. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  1273. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1274. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1275. Abbv) != FUNCTION_INST_BINOP_ABBREV)
  1276. llvm_unreachable("Unexpected abbrev ordering!");
  1277. }
  1278. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  1279. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1280. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  1281. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  1282. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  1283. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1284. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
  1285. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1286. Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
  1287. llvm_unreachable("Unexpected abbrev ordering!");
  1288. }
  1289. { // INST_CAST abbrev for FUNCTION_BLOCK.
  1290. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1291. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  1292. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  1293. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  1294. Log2_32_Ceil(VE.getTypes().size()+1)));
  1295. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1296. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1297. Abbv) != FUNCTION_INST_CAST_ABBREV)
  1298. llvm_unreachable("Unexpected abbrev ordering!");
  1299. }
  1300. { // INST_RET abbrev for FUNCTION_BLOCK.
  1301. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1302. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  1303. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1304. Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
  1305. llvm_unreachable("Unexpected abbrev ordering!");
  1306. }
  1307. { // INST_RET abbrev for FUNCTION_BLOCK.
  1308. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1309. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  1310. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  1311. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1312. Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
  1313. llvm_unreachable("Unexpected abbrev ordering!");
  1314. }
  1315. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  1316. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1317. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  1318. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1319. Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
  1320. llvm_unreachable("Unexpected abbrev ordering!");
  1321. }
  1322. Stream.ExitBlock();
  1323. }
  1324. /// WriteModule - Emit the specified module to the bitstream.
  1325. static void WriteModule(const Module *M, BitstreamWriter &Stream) {
  1326. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  1327. // Emit the version number if it is non-zero.
  1328. if (CurVersion) {
  1329. SmallVector<unsigned, 1> Vals;
  1330. Vals.push_back(CurVersion);
  1331. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  1332. }
  1333. // Analyze the module, enumerating globals, functions, etc.
  1334. ValueEnumerator VE(M);
  1335. // Emit blockinfo, which defines the standard abbreviations etc.
  1336. WriteBlockInfo(VE, Stream);
  1337. // Emit information about parameter attributes.
  1338. WriteAttributeTable(VE, Stream);
  1339. // Emit information describing all of the types in the module.
  1340. WriteTypeTable(VE, Stream);
  1341. // Emit top-level description of module, including target triple, inline asm,
  1342. // descriptors for global variables, and function prototype info.
  1343. WriteModuleInfo(M, VE, Stream);
  1344. // Emit constants.
  1345. WriteModuleConstants(VE, Stream);
  1346. // Emit metadata.
  1347. WriteModuleMetadata(M, VE, Stream);
  1348. // Emit function bodies.
  1349. for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
  1350. if (!I->isDeclaration())
  1351. WriteFunction(*I, VE, Stream);
  1352. // Emit metadata.
  1353. WriteModuleMetadataStore(M, Stream);
  1354. // Emit the type symbol table information.
  1355. WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
  1356. // Emit names for globals/functions etc.
  1357. WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
  1358. Stream.ExitBlock();
  1359. }
  1360. /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
  1361. /// header and trailer to make it compatible with the system archiver. To do
  1362. /// this we emit the following header, and then emit a trailer that pads the
  1363. /// file out to be a multiple of 16 bytes.
  1364. ///
  1365. /// struct bc_header {
  1366. /// uint32_t Magic; // 0x0B17C0DE
  1367. /// uint32_t Version; // Version, currently always 0.
  1368. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  1369. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  1370. /// uint32_t CPUType; // CPU specifier.
  1371. /// ... potentially more later ...
  1372. /// };
  1373. enum {
  1374. DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
  1375. DarwinBCHeaderSize = 5*4
  1376. };
  1377. /// isARMTriplet - Return true if the triplet looks like:
  1378. /// arm-*, thumb-*, armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*.
  1379. static bool isARMTriplet(const std::string &TT) {
  1380. size_t Pos = 0;
  1381. size_t Size = TT.size();
  1382. if (Size >= 6 &&
  1383. TT[0] == 't' && TT[1] == 'h' && TT[2] == 'u' &&
  1384. TT[3] == 'm' && TT[4] == 'b')
  1385. Pos = 5;
  1386. else if (Size >= 4 && TT[0] == 'a' && TT[1] == 'r' && TT[2] == 'm')
  1387. Pos = 3;
  1388. else
  1389. return false;
  1390. if (TT[Pos] == '-')
  1391. return true;
  1392. else if (TT[Pos] == 'v') {
  1393. if (Size >= Pos+4 &&
  1394. TT[Pos+1] == '6' && TT[Pos+2] == 't' && TT[Pos+3] == '2')
  1395. return true;
  1396. else if (Size >= Pos+4 &&
  1397. TT[Pos+1] == '5' && TT[Pos+2] == 't' && TT[Pos+3] == 'e')
  1398. return true;
  1399. } else
  1400. return false;
  1401. while (++Pos < Size && TT[Pos] != '-') {
  1402. if (!isdigit(TT[Pos]))
  1403. return false;
  1404. }
  1405. return true;
  1406. }
  1407. static void EmitDarwinBCHeader(BitstreamWriter &Stream,
  1408. const std::string &TT) {
  1409. unsigned CPUType = ~0U;
  1410. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
  1411. // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
  1412. // number from /usr/include/mach/machine.h. It is ok to reproduce the
  1413. // specific constants here because they are implicitly part of the Darwin ABI.
  1414. enum {
  1415. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  1416. DARWIN_CPU_TYPE_X86 = 7,
  1417. DARWIN_CPU_TYPE_ARM = 12,
  1418. DARWIN_CPU_TYPE_POWERPC = 18
  1419. };
  1420. if (TT.find("x86_64-") == 0)
  1421. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  1422. else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
  1423. TT[4] == '-' && TT[1] - '3' < 6)
  1424. CPUType = DARWIN_CPU_TYPE_X86;
  1425. else if (TT.find("powerpc-") == 0)
  1426. CPUType = DARWIN_CPU_TYPE_POWERPC;
  1427. else if (TT.find("powerpc64-") == 0)
  1428. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  1429. else if (isARMTriplet(TT))
  1430. CPUType = DARWIN_CPU_TYPE_ARM;
  1431. // Traditional Bitcode starts after header.
  1432. unsigned BCOffset = DarwinBCHeaderSize;
  1433. Stream.Emit(0x0B17C0DE, 32);
  1434. Stream.Emit(0 , 32); // Version.
  1435. Stream.Emit(BCOffset , 32);
  1436. Stream.Emit(0 , 32); // Filled in later.
  1437. Stream.Emit(CPUType , 32);
  1438. }
  1439. /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
  1440. /// finalize the header.
  1441. static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
  1442. // Update the size field in the header.
  1443. Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
  1444. // If the file is not a multiple of 16 bytes, insert dummy padding.
  1445. while (BufferSize & 15) {
  1446. Stream.Emit(0, 8);
  1447. ++BufferSize;
  1448. }
  1449. }
  1450. /// WriteBitcodeToFile - Write the specified module to the specified output
  1451. /// stream.
  1452. void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
  1453. std::vector<unsigned char> Buffer;
  1454. BitstreamWriter Stream(Buffer);
  1455. Buffer.reserve(256*1024);
  1456. WriteBitcodeToStream( M, Stream );
  1457. // Write the generated bitstream to "Out".
  1458. Out.write((char*)&Buffer.front(), Buffer.size());
  1459. }
  1460. /// WriteBitcodeToStream - Write the specified module to the specified output
  1461. /// stream.
  1462. void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
  1463. // If this is darwin, emit a file header and trailer if needed.
  1464. bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
  1465. if (isDarwin)
  1466. EmitDarwinBCHeader(Stream, M->getTargetTriple());
  1467. // Emit the file header.
  1468. Stream.Emit((unsigned)'B', 8);
  1469. Stream.Emit((unsigned)'C', 8);
  1470. Stream.Emit(0x0, 4);
  1471. Stream.Emit(0xC, 4);
  1472. Stream.Emit(0xE, 4);
  1473. Stream.Emit(0xD, 4);
  1474. // Emit the module.
  1475. WriteModule(M, Stream);
  1476. if (isDarwin)
  1477. EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
  1478. }