BitcodeWriter.cpp 63 KB

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