BitcodeWriter.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  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->getAllMetadataOtherThanDebugLoc(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. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  555. Record.clear();
  556. }
  557. Stream.ExitBlock();
  558. }
  559. static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
  560. SmallVector<uint64_t, 64> Record;
  561. // Write metadata kinds
  562. // METADATA_KIND - [n x [id, name]]
  563. SmallVector<StringRef, 4> Names;
  564. M->getMDKindNames(Names);
  565. assert(Names[0] == "" && "MDKind #0 is invalid");
  566. if (Names.size() == 1) return;
  567. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  568. for (unsigned MDKindID = 1, e = Names.size(); MDKindID != e; ++MDKindID) {
  569. Record.push_back(MDKindID);
  570. StringRef KName = Names[MDKindID];
  571. Record.append(KName.begin(), KName.end());
  572. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  573. Record.clear();
  574. }
  575. Stream.ExitBlock();
  576. }
  577. static void WriteConstants(unsigned FirstVal, unsigned LastVal,
  578. const ValueEnumerator &VE,
  579. BitstreamWriter &Stream, bool isGlobal) {
  580. if (FirstVal == LastVal) return;
  581. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  582. unsigned AggregateAbbrev = 0;
  583. unsigned String8Abbrev = 0;
  584. unsigned CString7Abbrev = 0;
  585. unsigned CString6Abbrev = 0;
  586. // If this is a constant pool for the module, emit module-specific abbrevs.
  587. if (isGlobal) {
  588. // Abbrev for CST_CODE_AGGREGATE.
  589. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  590. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  591. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  592. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  593. AggregateAbbrev = Stream.EmitAbbrev(Abbv);
  594. // Abbrev for CST_CODE_STRING.
  595. Abbv = new BitCodeAbbrev();
  596. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  597. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  598. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  599. String8Abbrev = Stream.EmitAbbrev(Abbv);
  600. // Abbrev for CST_CODE_CSTRING.
  601. Abbv = new BitCodeAbbrev();
  602. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  603. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  604. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  605. CString7Abbrev = Stream.EmitAbbrev(Abbv);
  606. // Abbrev for CST_CODE_CSTRING.
  607. Abbv = new BitCodeAbbrev();
  608. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  609. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  610. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  611. CString6Abbrev = Stream.EmitAbbrev(Abbv);
  612. }
  613. SmallVector<uint64_t, 64> Record;
  614. const ValueEnumerator::ValueList &Vals = VE.getValues();
  615. const Type *LastTy = 0;
  616. for (unsigned i = FirstVal; i != LastVal; ++i) {
  617. const Value *V = Vals[i].first;
  618. // If we need to switch types, do so now.
  619. if (V->getType() != LastTy) {
  620. LastTy = V->getType();
  621. Record.push_back(VE.getTypeID(LastTy));
  622. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  623. CONSTANTS_SETTYPE_ABBREV);
  624. Record.clear();
  625. }
  626. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  627. Record.push_back(unsigned(IA->hasSideEffects()) |
  628. unsigned(IA->isAlignStack()) << 1);
  629. // Add the asm string.
  630. const std::string &AsmStr = IA->getAsmString();
  631. Record.push_back(AsmStr.size());
  632. for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
  633. Record.push_back(AsmStr[i]);
  634. // Add the constraint string.
  635. const std::string &ConstraintStr = IA->getConstraintString();
  636. Record.push_back(ConstraintStr.size());
  637. for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
  638. Record.push_back(ConstraintStr[i]);
  639. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  640. Record.clear();
  641. continue;
  642. }
  643. const Constant *C = cast<Constant>(V);
  644. unsigned Code = -1U;
  645. unsigned AbbrevToUse = 0;
  646. if (C->isNullValue()) {
  647. Code = bitc::CST_CODE_NULL;
  648. } else if (isa<UndefValue>(C)) {
  649. Code = bitc::CST_CODE_UNDEF;
  650. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  651. if (IV->getBitWidth() <= 64) {
  652. int64_t V = IV->getSExtValue();
  653. if (V >= 0)
  654. Record.push_back(V << 1);
  655. else
  656. Record.push_back((-V << 1) | 1);
  657. Code = bitc::CST_CODE_INTEGER;
  658. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  659. } else { // Wide integers, > 64 bits in size.
  660. // We have an arbitrary precision integer value to write whose
  661. // bit width is > 64. However, in canonical unsigned integer
  662. // format it is likely that the high bits are going to be zero.
  663. // So, we only write the number of active words.
  664. unsigned NWords = IV->getValue().getActiveWords();
  665. const uint64_t *RawWords = IV->getValue().getRawData();
  666. for (unsigned i = 0; i != NWords; ++i) {
  667. int64_t V = RawWords[i];
  668. if (V >= 0)
  669. Record.push_back(V << 1);
  670. else
  671. Record.push_back((-V << 1) | 1);
  672. }
  673. Code = bitc::CST_CODE_WIDE_INTEGER;
  674. }
  675. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  676. Code = bitc::CST_CODE_FLOAT;
  677. const Type *Ty = CFP->getType();
  678. if (Ty->isFloatTy() || Ty->isDoubleTy()) {
  679. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  680. } else if (Ty->isX86_FP80Ty()) {
  681. // api needed to prevent premature destruction
  682. // bits are not in the same order as a normal i80 APInt, compensate.
  683. APInt api = CFP->getValueAPF().bitcastToAPInt();
  684. const uint64_t *p = api.getRawData();
  685. Record.push_back((p[1] << 48) | (p[0] >> 16));
  686. Record.push_back(p[0] & 0xffffLL);
  687. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  688. APInt api = CFP->getValueAPF().bitcastToAPInt();
  689. const uint64_t *p = api.getRawData();
  690. Record.push_back(p[0]);
  691. Record.push_back(p[1]);
  692. } else {
  693. assert (0 && "Unknown FP type!");
  694. }
  695. } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
  696. const ConstantArray *CA = cast<ConstantArray>(C);
  697. // Emit constant strings specially.
  698. unsigned NumOps = CA->getNumOperands();
  699. // If this is a null-terminated string, use the denser CSTRING encoding.
  700. if (CA->getOperand(NumOps-1)->isNullValue()) {
  701. Code = bitc::CST_CODE_CSTRING;
  702. --NumOps; // Don't encode the null, which isn't allowed by char6.
  703. } else {
  704. Code = bitc::CST_CODE_STRING;
  705. AbbrevToUse = String8Abbrev;
  706. }
  707. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  708. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  709. for (unsigned i = 0; i != NumOps; ++i) {
  710. unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
  711. Record.push_back(V);
  712. isCStr7 &= (V & 128) == 0;
  713. if (isCStrChar6)
  714. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  715. }
  716. if (isCStrChar6)
  717. AbbrevToUse = CString6Abbrev;
  718. else if (isCStr7)
  719. AbbrevToUse = CString7Abbrev;
  720. } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
  721. isa<ConstantVector>(V)) {
  722. Code = bitc::CST_CODE_AGGREGATE;
  723. for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
  724. Record.push_back(VE.getValueID(C->getOperand(i)));
  725. AbbrevToUse = AggregateAbbrev;
  726. } else if (isa<ConstantUnion>(C)) {
  727. Code = bitc::CST_CODE_AGGREGATE;
  728. // Unions only have one entry but we must send type along with it.
  729. const Type *EntryKind = C->getOperand(0)->getType();
  730. const UnionType *UnTy = cast<UnionType>(C->getType());
  731. int UnionIndex = UnTy->getElementTypeIndex(EntryKind);
  732. assert(UnionIndex != -1 && "Constant union contains invalid entry");
  733. Record.push_back(UnionIndex);
  734. Record.push_back(VE.getValueID(C->getOperand(0)));
  735. AbbrevToUse = AggregateAbbrev;
  736. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  737. switch (CE->getOpcode()) {
  738. default:
  739. if (Instruction::isCast(CE->getOpcode())) {
  740. Code = bitc::CST_CODE_CE_CAST;
  741. Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
  742. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  743. Record.push_back(VE.getValueID(C->getOperand(0)));
  744. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  745. } else {
  746. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  747. Code = bitc::CST_CODE_CE_BINOP;
  748. Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
  749. Record.push_back(VE.getValueID(C->getOperand(0)));
  750. Record.push_back(VE.getValueID(C->getOperand(1)));
  751. uint64_t Flags = GetOptimizationFlags(CE);
  752. if (Flags != 0)
  753. Record.push_back(Flags);
  754. }
  755. break;
  756. case Instruction::GetElementPtr:
  757. Code = bitc::CST_CODE_CE_GEP;
  758. if (cast<GEPOperator>(C)->isInBounds())
  759. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  760. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  761. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  762. Record.push_back(VE.getValueID(C->getOperand(i)));
  763. }
  764. break;
  765. case Instruction::Select:
  766. Code = bitc::CST_CODE_CE_SELECT;
  767. Record.push_back(VE.getValueID(C->getOperand(0)));
  768. Record.push_back(VE.getValueID(C->getOperand(1)));
  769. Record.push_back(VE.getValueID(C->getOperand(2)));
  770. break;
  771. case Instruction::ExtractElement:
  772. Code = bitc::CST_CODE_CE_EXTRACTELT;
  773. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  774. Record.push_back(VE.getValueID(C->getOperand(0)));
  775. Record.push_back(VE.getValueID(C->getOperand(1)));
  776. break;
  777. case Instruction::InsertElement:
  778. Code = bitc::CST_CODE_CE_INSERTELT;
  779. Record.push_back(VE.getValueID(C->getOperand(0)));
  780. Record.push_back(VE.getValueID(C->getOperand(1)));
  781. Record.push_back(VE.getValueID(C->getOperand(2)));
  782. break;
  783. case Instruction::ShuffleVector:
  784. // If the return type and argument types are the same, this is a
  785. // standard shufflevector instruction. If the types are different,
  786. // then the shuffle is widening or truncating the input vectors, and
  787. // the argument type must also be encoded.
  788. if (C->getType() == C->getOperand(0)->getType()) {
  789. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  790. } else {
  791. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  792. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  793. }
  794. Record.push_back(VE.getValueID(C->getOperand(0)));
  795. Record.push_back(VE.getValueID(C->getOperand(1)));
  796. Record.push_back(VE.getValueID(C->getOperand(2)));
  797. break;
  798. case Instruction::ICmp:
  799. case Instruction::FCmp:
  800. Code = bitc::CST_CODE_CE_CMP;
  801. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  802. Record.push_back(VE.getValueID(C->getOperand(0)));
  803. Record.push_back(VE.getValueID(C->getOperand(1)));
  804. Record.push_back(CE->getPredicate());
  805. break;
  806. }
  807. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  808. assert(BA->getFunction() == BA->getBasicBlock()->getParent() &&
  809. "Malformed blockaddress");
  810. Code = bitc::CST_CODE_BLOCKADDRESS;
  811. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  812. Record.push_back(VE.getValueID(BA->getFunction()));
  813. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  814. } else {
  815. llvm_unreachable("Unknown constant!");
  816. }
  817. Stream.EmitRecord(Code, Record, AbbrevToUse);
  818. Record.clear();
  819. }
  820. Stream.ExitBlock();
  821. }
  822. static void WriteModuleConstants(const ValueEnumerator &VE,
  823. BitstreamWriter &Stream) {
  824. const ValueEnumerator::ValueList &Vals = VE.getValues();
  825. // Find the first constant to emit, which is the first non-globalvalue value.
  826. // We know globalvalues have been emitted by WriteModuleInfo.
  827. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  828. if (!isa<GlobalValue>(Vals[i].first)) {
  829. WriteConstants(i, Vals.size(), VE, Stream, true);
  830. return;
  831. }
  832. }
  833. }
  834. /// PushValueAndType - The file has to encode both the value and type id for
  835. /// many values, because we need to know what type to create for forward
  836. /// references. However, most operands are not forward references, so this type
  837. /// field is not needed.
  838. ///
  839. /// This function adds V's value ID to Vals. If the value ID is higher than the
  840. /// instruction ID, then it is a forward reference, and it also includes the
  841. /// type ID.
  842. static bool PushValueAndType(const Value *V, unsigned InstID,
  843. SmallVector<unsigned, 64> &Vals,
  844. ValueEnumerator &VE) {
  845. unsigned ValID = VE.getValueID(V);
  846. Vals.push_back(ValID);
  847. if (ValID >= InstID) {
  848. Vals.push_back(VE.getTypeID(V->getType()));
  849. return true;
  850. }
  851. return false;
  852. }
  853. /// WriteInstruction - Emit an instruction to the specified stream.
  854. static void WriteInstruction(const Instruction &I, unsigned InstID,
  855. ValueEnumerator &VE, BitstreamWriter &Stream,
  856. SmallVector<unsigned, 64> &Vals) {
  857. unsigned Code = 0;
  858. unsigned AbbrevToUse = 0;
  859. VE.setInstructionID(&I);
  860. switch (I.getOpcode()) {
  861. default:
  862. if (Instruction::isCast(I.getOpcode())) {
  863. Code = bitc::FUNC_CODE_INST_CAST;
  864. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  865. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  866. Vals.push_back(VE.getTypeID(I.getType()));
  867. Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
  868. } else {
  869. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  870. Code = bitc::FUNC_CODE_INST_BINOP;
  871. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  872. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  873. Vals.push_back(VE.getValueID(I.getOperand(1)));
  874. Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
  875. uint64_t Flags = GetOptimizationFlags(&I);
  876. if (Flags != 0) {
  877. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  878. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  879. Vals.push_back(Flags);
  880. }
  881. }
  882. break;
  883. case Instruction::GetElementPtr:
  884. Code = bitc::FUNC_CODE_INST_GEP;
  885. if (cast<GEPOperator>(&I)->isInBounds())
  886. Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
  887. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  888. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  889. break;
  890. case Instruction::ExtractValue: {
  891. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  892. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  893. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  894. for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
  895. Vals.push_back(*i);
  896. break;
  897. }
  898. case Instruction::InsertValue: {
  899. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  900. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  901. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  902. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  903. for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
  904. Vals.push_back(*i);
  905. break;
  906. }
  907. case Instruction::Select:
  908. Code = bitc::FUNC_CODE_INST_VSELECT;
  909. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  910. Vals.push_back(VE.getValueID(I.getOperand(2)));
  911. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  912. break;
  913. case Instruction::ExtractElement:
  914. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  915. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  916. Vals.push_back(VE.getValueID(I.getOperand(1)));
  917. break;
  918. case Instruction::InsertElement:
  919. Code = bitc::FUNC_CODE_INST_INSERTELT;
  920. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  921. Vals.push_back(VE.getValueID(I.getOperand(1)));
  922. Vals.push_back(VE.getValueID(I.getOperand(2)));
  923. break;
  924. case Instruction::ShuffleVector:
  925. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  926. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  927. Vals.push_back(VE.getValueID(I.getOperand(1)));
  928. Vals.push_back(VE.getValueID(I.getOperand(2)));
  929. break;
  930. case Instruction::ICmp:
  931. case Instruction::FCmp:
  932. // compare returning Int1Ty or vector of Int1Ty
  933. Code = bitc::FUNC_CODE_INST_CMP2;
  934. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  935. Vals.push_back(VE.getValueID(I.getOperand(1)));
  936. Vals.push_back(cast<CmpInst>(I).getPredicate());
  937. break;
  938. case Instruction::Ret:
  939. {
  940. Code = bitc::FUNC_CODE_INST_RET;
  941. unsigned NumOperands = I.getNumOperands();
  942. if (NumOperands == 0)
  943. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  944. else if (NumOperands == 1) {
  945. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  946. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  947. } else {
  948. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  949. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  950. }
  951. }
  952. break;
  953. case Instruction::Br:
  954. {
  955. Code = bitc::FUNC_CODE_INST_BR;
  956. BranchInst &II = cast<BranchInst>(I);
  957. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  958. if (II.isConditional()) {
  959. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  960. Vals.push_back(VE.getValueID(II.getCondition()));
  961. }
  962. }
  963. break;
  964. case Instruction::Switch:
  965. Code = bitc::FUNC_CODE_INST_SWITCH;
  966. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  967. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  968. Vals.push_back(VE.getValueID(I.getOperand(i)));
  969. break;
  970. case Instruction::IndirectBr:
  971. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  972. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  973. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  974. Vals.push_back(VE.getValueID(I.getOperand(i)));
  975. break;
  976. case Instruction::Invoke: {
  977. const InvokeInst *II = cast<InvokeInst>(&I);
  978. const Value *Callee(II->getCalledValue());
  979. const PointerType *PTy = cast<PointerType>(Callee->getType());
  980. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  981. Code = bitc::FUNC_CODE_INST_INVOKE;
  982. Vals.push_back(VE.getAttributeID(II->getAttributes()));
  983. Vals.push_back(II->getCallingConv());
  984. Vals.push_back(VE.getValueID(II->getNormalDest()));
  985. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  986. PushValueAndType(Callee, InstID, Vals, VE);
  987. // Emit value #'s for the fixed parameters.
  988. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  989. Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
  990. // Emit type/value pairs for varargs params.
  991. if (FTy->isVarArg()) {
  992. for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
  993. i != e; ++i)
  994. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
  995. }
  996. break;
  997. }
  998. case Instruction::Unwind:
  999. Code = bitc::FUNC_CODE_INST_UNWIND;
  1000. break;
  1001. case Instruction::Unreachable:
  1002. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  1003. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  1004. break;
  1005. case Instruction::PHI:
  1006. Code = bitc::FUNC_CODE_INST_PHI;
  1007. Vals.push_back(VE.getTypeID(I.getType()));
  1008. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  1009. Vals.push_back(VE.getValueID(I.getOperand(i)));
  1010. break;
  1011. case Instruction::Alloca:
  1012. Code = bitc::FUNC_CODE_INST_ALLOCA;
  1013. Vals.push_back(VE.getTypeID(I.getType()));
  1014. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  1015. Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
  1016. break;
  1017. case Instruction::Load:
  1018. Code = bitc::FUNC_CODE_INST_LOAD;
  1019. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
  1020. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  1021. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  1022. Vals.push_back(cast<LoadInst>(I).isVolatile());
  1023. break;
  1024. case Instruction::Store:
  1025. Code = bitc::FUNC_CODE_INST_STORE2;
  1026. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
  1027. Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
  1028. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  1029. Vals.push_back(cast<StoreInst>(I).isVolatile());
  1030. break;
  1031. case Instruction::Call: {
  1032. const CallInst &CI = cast<CallInst>(I);
  1033. const PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
  1034. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  1035. Code = bitc::FUNC_CODE_INST_CALL;
  1036. Vals.push_back(VE.getAttributeID(CI.getAttributes()));
  1037. Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
  1038. PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee
  1039. // Emit value #'s for the fixed parameters.
  1040. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  1041. Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
  1042. // Emit type/value pairs for varargs params.
  1043. if (FTy->isVarArg()) {
  1044. for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-1;
  1045. i != e; ++i)
  1046. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
  1047. }
  1048. break;
  1049. }
  1050. case Instruction::VAArg:
  1051. Code = bitc::FUNC_CODE_INST_VAARG;
  1052. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  1053. Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
  1054. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  1055. break;
  1056. }
  1057. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  1058. Vals.clear();
  1059. }
  1060. // Emit names for globals/functions etc.
  1061. static void WriteValueSymbolTable(const ValueSymbolTable &VST,
  1062. const ValueEnumerator &VE,
  1063. BitstreamWriter &Stream) {
  1064. if (VST.empty()) return;
  1065. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  1066. // FIXME: Set up the abbrev, we know how many values there are!
  1067. // FIXME: We know if the type names can use 7-bit ascii.
  1068. SmallVector<unsigned, 64> NameVals;
  1069. for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
  1070. SI != SE; ++SI) {
  1071. const ValueName &Name = *SI;
  1072. // Figure out the encoding to use for the name.
  1073. bool is7Bit = true;
  1074. bool isChar6 = true;
  1075. for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
  1076. C != E; ++C) {
  1077. if (isChar6)
  1078. isChar6 = BitCodeAbbrevOp::isChar6(*C);
  1079. if ((unsigned char)*C & 128) {
  1080. is7Bit = false;
  1081. break; // don't bother scanning the rest.
  1082. }
  1083. }
  1084. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  1085. // VST_ENTRY: [valueid, namechar x N]
  1086. // VST_BBENTRY: [bbid, namechar x N]
  1087. unsigned Code;
  1088. if (isa<BasicBlock>(SI->getValue())) {
  1089. Code = bitc::VST_CODE_BBENTRY;
  1090. if (isChar6)
  1091. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  1092. } else {
  1093. Code = bitc::VST_CODE_ENTRY;
  1094. if (isChar6)
  1095. AbbrevToUse = VST_ENTRY_6_ABBREV;
  1096. else if (is7Bit)
  1097. AbbrevToUse = VST_ENTRY_7_ABBREV;
  1098. }
  1099. NameVals.push_back(VE.getValueID(SI->getValue()));
  1100. for (const char *P = Name.getKeyData(),
  1101. *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
  1102. NameVals.push_back((unsigned char)*P);
  1103. // Emit the finished record.
  1104. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  1105. NameVals.clear();
  1106. }
  1107. Stream.ExitBlock();
  1108. }
  1109. /// WriteFunction - Emit a function body to the module stream.
  1110. static void WriteFunction(const Function &F, ValueEnumerator &VE,
  1111. BitstreamWriter &Stream) {
  1112. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  1113. VE.incorporateFunction(F);
  1114. SmallVector<unsigned, 64> Vals;
  1115. // Emit the number of basic blocks, so the reader can create them ahead of
  1116. // time.
  1117. Vals.push_back(VE.getBasicBlocks().size());
  1118. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  1119. Vals.clear();
  1120. // If there are function-local constants, emit them now.
  1121. unsigned CstStart, CstEnd;
  1122. VE.getFunctionConstantRange(CstStart, CstEnd);
  1123. WriteConstants(CstStart, CstEnd, VE, Stream, false);
  1124. // If there is function-local metadata, emit it now.
  1125. WriteFunctionLocalMetadata(F, VE, Stream);
  1126. // Keep a running idea of what the instruction ID is.
  1127. unsigned InstID = CstEnd;
  1128. bool NeedsMetadataAttachment = false;
  1129. DebugLoc LastDL;
  1130. // Finally, emit all the instructions, in order.
  1131. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  1132. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  1133. I != E; ++I) {
  1134. WriteInstruction(*I, InstID, VE, Stream, Vals);
  1135. if (!I->getType()->isVoidTy())
  1136. ++InstID;
  1137. // If the instruction has metadata, write a metadata attachment later.
  1138. NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
  1139. // If the instruction has a debug location, emit it.
  1140. DebugLoc DL = I->getDebugLoc();
  1141. if (DL.isUnknown()) {
  1142. // nothing todo.
  1143. } else if (DL == LastDL) {
  1144. // Just repeat the same debug loc as last time.
  1145. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
  1146. } else {
  1147. MDNode *Scope, *IA;
  1148. DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
  1149. Vals.push_back(DL.getLine());
  1150. Vals.push_back(DL.getCol());
  1151. Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
  1152. Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
  1153. Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
  1154. Vals.clear();
  1155. LastDL = DL;
  1156. }
  1157. }
  1158. // Emit names for all the instructions etc.
  1159. WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
  1160. if (NeedsMetadataAttachment)
  1161. WriteMetadataAttachment(F, VE, Stream);
  1162. VE.purgeFunction();
  1163. Stream.ExitBlock();
  1164. }
  1165. /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
  1166. static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
  1167. const ValueEnumerator &VE,
  1168. BitstreamWriter &Stream) {
  1169. if (TST.empty()) return;
  1170. Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
  1171. // 7-bit fixed width VST_CODE_ENTRY strings.
  1172. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1173. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1174. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1175. Log2_32_Ceil(VE.getTypes().size()+1)));
  1176. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1177. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1178. unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
  1179. SmallVector<unsigned, 64> NameVals;
  1180. for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
  1181. TI != TE; ++TI) {
  1182. // TST_ENTRY: [typeid, namechar x N]
  1183. NameVals.push_back(VE.getTypeID(TI->second));
  1184. const std::string &Str = TI->first;
  1185. bool is7Bit = true;
  1186. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  1187. NameVals.push_back((unsigned char)Str[i]);
  1188. if (Str[i] & 128)
  1189. is7Bit = false;
  1190. }
  1191. // Emit the finished record.
  1192. Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
  1193. NameVals.clear();
  1194. }
  1195. Stream.ExitBlock();
  1196. }
  1197. // Emit blockinfo, which defines the standard abbreviations etc.
  1198. static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  1199. // We only want to emit block info records for blocks that have multiple
  1200. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
  1201. // blocks can defined their abbrevs inline.
  1202. Stream.EnterBlockInfoBlock(2);
  1203. { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
  1204. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1205. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  1206. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1207. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1208. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1209. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1210. Abbv) != VST_ENTRY_8_ABBREV)
  1211. llvm_unreachable("Unexpected abbrev ordering!");
  1212. }
  1213. { // 7-bit fixed width VST_ENTRY strings.
  1214. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1215. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1216. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1217. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1218. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1219. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1220. Abbv) != VST_ENTRY_7_ABBREV)
  1221. llvm_unreachable("Unexpected abbrev ordering!");
  1222. }
  1223. { // 6-bit char6 VST_ENTRY strings.
  1224. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1225. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1226. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1227. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1228. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1229. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1230. Abbv) != VST_ENTRY_6_ABBREV)
  1231. llvm_unreachable("Unexpected abbrev ordering!");
  1232. }
  1233. { // 6-bit char6 VST_BBENTRY strings.
  1234. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1235. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  1236. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1237. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1238. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1239. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1240. Abbv) != VST_BBENTRY_6_ABBREV)
  1241. llvm_unreachable("Unexpected abbrev ordering!");
  1242. }
  1243. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  1244. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1245. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  1246. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1247. Log2_32_Ceil(VE.getTypes().size()+1)));
  1248. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1249. Abbv) != CONSTANTS_SETTYPE_ABBREV)
  1250. llvm_unreachable("Unexpected abbrev ordering!");
  1251. }
  1252. { // INTEGER abbrev for CONSTANTS_BLOCK.
  1253. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1254. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  1255. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1256. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1257. Abbv) != CONSTANTS_INTEGER_ABBREV)
  1258. llvm_unreachable("Unexpected abbrev ordering!");
  1259. }
  1260. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  1261. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1262. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  1263. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  1264. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  1265. Log2_32_Ceil(VE.getTypes().size()+1)));
  1266. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  1267. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1268. Abbv) != CONSTANTS_CE_CAST_Abbrev)
  1269. llvm_unreachable("Unexpected abbrev ordering!");
  1270. }
  1271. { // NULL abbrev for CONSTANTS_BLOCK.
  1272. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1273. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  1274. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1275. Abbv) != CONSTANTS_NULL_Abbrev)
  1276. llvm_unreachable("Unexpected abbrev ordering!");
  1277. }
  1278. // FIXME: This should only use space for first class types!
  1279. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  1280. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1281. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  1282. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  1283. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  1284. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  1285. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1286. Abbv) != FUNCTION_INST_LOAD_ABBREV)
  1287. llvm_unreachable("Unexpected abbrev ordering!");
  1288. }
  1289. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  1290. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1291. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  1292. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  1293. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  1294. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1295. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1296. Abbv) != FUNCTION_INST_BINOP_ABBREV)
  1297. llvm_unreachable("Unexpected abbrev ordering!");
  1298. }
  1299. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  1300. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1301. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  1302. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  1303. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  1304. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1305. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
  1306. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1307. Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
  1308. llvm_unreachable("Unexpected abbrev ordering!");
  1309. }
  1310. { // INST_CAST abbrev for FUNCTION_BLOCK.
  1311. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1312. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  1313. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  1314. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  1315. Log2_32_Ceil(VE.getTypes().size()+1)));
  1316. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1317. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1318. Abbv) != FUNCTION_INST_CAST_ABBREV)
  1319. llvm_unreachable("Unexpected abbrev ordering!");
  1320. }
  1321. { // INST_RET abbrev for FUNCTION_BLOCK.
  1322. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1323. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  1324. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1325. Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
  1326. llvm_unreachable("Unexpected abbrev ordering!");
  1327. }
  1328. { // INST_RET abbrev for FUNCTION_BLOCK.
  1329. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1330. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  1331. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  1332. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1333. Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
  1334. llvm_unreachable("Unexpected abbrev ordering!");
  1335. }
  1336. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  1337. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1338. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  1339. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1340. Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
  1341. llvm_unreachable("Unexpected abbrev ordering!");
  1342. }
  1343. Stream.ExitBlock();
  1344. }
  1345. /// WriteModule - Emit the specified module to the bitstream.
  1346. static void WriteModule(const Module *M, BitstreamWriter &Stream) {
  1347. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  1348. // Emit the version number if it is non-zero.
  1349. if (CurVersion) {
  1350. SmallVector<unsigned, 1> Vals;
  1351. Vals.push_back(CurVersion);
  1352. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  1353. }
  1354. // Analyze the module, enumerating globals, functions, etc.
  1355. ValueEnumerator VE(M);
  1356. // Emit blockinfo, which defines the standard abbreviations etc.
  1357. WriteBlockInfo(VE, Stream);
  1358. // Emit information about parameter attributes.
  1359. WriteAttributeTable(VE, Stream);
  1360. // Emit information describing all of the types in the module.
  1361. WriteTypeTable(VE, Stream);
  1362. // Emit top-level description of module, including target triple, inline asm,
  1363. // descriptors for global variables, and function prototype info.
  1364. WriteModuleInfo(M, VE, Stream);
  1365. // Emit constants.
  1366. WriteModuleConstants(VE, Stream);
  1367. // Emit metadata.
  1368. WriteModuleMetadata(VE, Stream);
  1369. // Emit function bodies.
  1370. for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
  1371. if (!I->isDeclaration())
  1372. WriteFunction(*I, VE, Stream);
  1373. // Emit metadata.
  1374. WriteModuleMetadataStore(M, Stream);
  1375. // Emit the type symbol table information.
  1376. WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
  1377. // Emit names for globals/functions etc.
  1378. WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
  1379. Stream.ExitBlock();
  1380. }
  1381. /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
  1382. /// header and trailer to make it compatible with the system archiver. To do
  1383. /// this we emit the following header, and then emit a trailer that pads the
  1384. /// file out to be a multiple of 16 bytes.
  1385. ///
  1386. /// struct bc_header {
  1387. /// uint32_t Magic; // 0x0B17C0DE
  1388. /// uint32_t Version; // Version, currently always 0.
  1389. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  1390. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  1391. /// uint32_t CPUType; // CPU specifier.
  1392. /// ... potentially more later ...
  1393. /// };
  1394. enum {
  1395. DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
  1396. DarwinBCHeaderSize = 5*4
  1397. };
  1398. /// isARMTriplet - Return true if the triplet looks like:
  1399. /// arm-*, thumb-*, armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*.
  1400. static bool isARMTriplet(const std::string &TT) {
  1401. size_t Pos = 0;
  1402. size_t Size = TT.size();
  1403. if (Size >= 6 &&
  1404. TT[0] == 't' && TT[1] == 'h' && TT[2] == 'u' &&
  1405. TT[3] == 'm' && TT[4] == 'b')
  1406. Pos = 5;
  1407. else if (Size >= 4 && TT[0] == 'a' && TT[1] == 'r' && TT[2] == 'm')
  1408. Pos = 3;
  1409. else
  1410. return false;
  1411. if (TT[Pos] == '-')
  1412. return true;
  1413. else if (TT[Pos] == 'v') {
  1414. if (Size >= Pos+4 &&
  1415. TT[Pos+1] == '6' && TT[Pos+2] == 't' && TT[Pos+3] == '2')
  1416. return true;
  1417. else if (Size >= Pos+4 &&
  1418. TT[Pos+1] == '5' && TT[Pos+2] == 't' && TT[Pos+3] == 'e')
  1419. return true;
  1420. } else
  1421. return false;
  1422. while (++Pos < Size && TT[Pos] != '-') {
  1423. if (!isdigit(TT[Pos]))
  1424. return false;
  1425. }
  1426. return true;
  1427. }
  1428. static void EmitDarwinBCHeader(BitstreamWriter &Stream,
  1429. const std::string &TT) {
  1430. unsigned CPUType = ~0U;
  1431. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
  1432. // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
  1433. // number from /usr/include/mach/machine.h. It is ok to reproduce the
  1434. // specific constants here because they are implicitly part of the Darwin ABI.
  1435. enum {
  1436. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  1437. DARWIN_CPU_TYPE_X86 = 7,
  1438. DARWIN_CPU_TYPE_ARM = 12,
  1439. DARWIN_CPU_TYPE_POWERPC = 18
  1440. };
  1441. if (TT.find("x86_64-") == 0)
  1442. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  1443. else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
  1444. TT[4] == '-' && TT[1] - '3' < 6)
  1445. CPUType = DARWIN_CPU_TYPE_X86;
  1446. else if (TT.find("powerpc-") == 0)
  1447. CPUType = DARWIN_CPU_TYPE_POWERPC;
  1448. else if (TT.find("powerpc64-") == 0)
  1449. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  1450. else if (isARMTriplet(TT))
  1451. CPUType = DARWIN_CPU_TYPE_ARM;
  1452. // Traditional Bitcode starts after header.
  1453. unsigned BCOffset = DarwinBCHeaderSize;
  1454. Stream.Emit(0x0B17C0DE, 32);
  1455. Stream.Emit(0 , 32); // Version.
  1456. Stream.Emit(BCOffset , 32);
  1457. Stream.Emit(0 , 32); // Filled in later.
  1458. Stream.Emit(CPUType , 32);
  1459. }
  1460. /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
  1461. /// finalize the header.
  1462. static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
  1463. // Update the size field in the header.
  1464. Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
  1465. // If the file is not a multiple of 16 bytes, insert dummy padding.
  1466. while (BufferSize & 15) {
  1467. Stream.Emit(0, 8);
  1468. ++BufferSize;
  1469. }
  1470. }
  1471. /// WriteBitcodeToFile - Write the specified module to the specified output
  1472. /// stream.
  1473. void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
  1474. std::vector<unsigned char> Buffer;
  1475. BitstreamWriter Stream(Buffer);
  1476. Buffer.reserve(256*1024);
  1477. WriteBitcodeToStream( M, Stream );
  1478. // If writing to stdout, set binary mode.
  1479. if (&llvm::outs() == &Out)
  1480. sys::Program::ChangeStdoutToBinary();
  1481. // Write the generated bitstream to "Out".
  1482. Out.write((char*)&Buffer.front(), Buffer.size());
  1483. // Make sure it hits disk now.
  1484. Out.flush();
  1485. }
  1486. /// WriteBitcodeToStream - Write the specified module to the specified output
  1487. /// stream.
  1488. void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
  1489. // If this is darwin, emit a file header and trailer if needed.
  1490. bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
  1491. if (isDarwin)
  1492. EmitDarwinBCHeader(Stream, M->getTargetTriple());
  1493. // Emit the file header.
  1494. Stream.Emit((unsigned)'B', 8);
  1495. Stream.Emit((unsigned)'C', 8);
  1496. Stream.Emit(0x0, 4);
  1497. Stream.Emit(0xC, 4);
  1498. Stream.Emit(0xE, 4);
  1499. Stream.Emit(0xD, 4);
  1500. // Emit the module.
  1501. WriteModule(M, Stream);
  1502. if (isDarwin)
  1503. EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
  1504. }