BitcodeWriter.cpp 63 KB

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