BitcodeWriter.cpp 63 KB

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