BitcodeWriter.cpp 58 KB

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