BitcodeWriter.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691
  1. //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Bitcode writer implementation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "llvm/Bitcode/BitstreamWriter.h"
  15. #include "llvm/Bitcode/LLVMBitCodes.h"
  16. #include "ValueEnumerator.h"
  17. #include "llvm/Constants.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/InlineAsm.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/Module.h"
  22. #include "llvm/Operator.h"
  23. #include "llvm/TypeSymbolTable.h"
  24. #include "llvm/ValueSymbolTable.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include "llvm/System/Program.h"
  29. using namespace llvm;
  30. /// These are manifest constants used by the bitcode writer. They do not need to
  31. /// be kept in sync with the reader, but need to be consistent within this file.
  32. enum {
  33. CurVersion = 0,
  34. // VALUE_SYMTAB_BLOCK abbrev id's.
  35. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  36. VST_ENTRY_7_ABBREV,
  37. VST_ENTRY_6_ABBREV,
  38. VST_BBENTRY_6_ABBREV,
  39. // CONSTANTS_BLOCK abbrev id's.
  40. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  41. CONSTANTS_INTEGER_ABBREV,
  42. CONSTANTS_CE_CAST_Abbrev,
  43. CONSTANTS_NULL_Abbrev,
  44. // FUNCTION_BLOCK abbrev id's.
  45. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  46. FUNCTION_INST_BINOP_ABBREV,
  47. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  48. FUNCTION_INST_CAST_ABBREV,
  49. FUNCTION_INST_RET_VOID_ABBREV,
  50. FUNCTION_INST_RET_VAL_ABBREV,
  51. FUNCTION_INST_UNREACHABLE_ABBREV
  52. };
  53. static unsigned GetEncodedCastOpcode(unsigned Opcode) {
  54. switch (Opcode) {
  55. default: llvm_unreachable("Unknown cast instruction!");
  56. case Instruction::Trunc : return bitc::CAST_TRUNC;
  57. case Instruction::ZExt : return bitc::CAST_ZEXT;
  58. case Instruction::SExt : return bitc::CAST_SEXT;
  59. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  60. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  61. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  62. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  63. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  64. case Instruction::FPExt : return bitc::CAST_FPEXT;
  65. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  66. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  67. case Instruction::BitCast : return bitc::CAST_BITCAST;
  68. }
  69. }
  70. static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
  71. switch (Opcode) {
  72. default: llvm_unreachable("Unknown binary instruction!");
  73. case Instruction::Add:
  74. case Instruction::FAdd: return bitc::BINOP_ADD;
  75. case Instruction::Sub:
  76. case Instruction::FSub: return bitc::BINOP_SUB;
  77. case Instruction::Mul:
  78. case Instruction::FMul: return bitc::BINOP_MUL;
  79. case Instruction::UDiv: return bitc::BINOP_UDIV;
  80. case Instruction::FDiv:
  81. case Instruction::SDiv: return bitc::BINOP_SDIV;
  82. case Instruction::URem: return bitc::BINOP_UREM;
  83. case Instruction::FRem:
  84. case Instruction::SRem: return bitc::BINOP_SREM;
  85. case Instruction::Shl: return bitc::BINOP_SHL;
  86. case Instruction::LShr: return bitc::BINOP_LSHR;
  87. case Instruction::AShr: return bitc::BINOP_ASHR;
  88. case Instruction::And: return bitc::BINOP_AND;
  89. case Instruction::Or: return bitc::BINOP_OR;
  90. case Instruction::Xor: return bitc::BINOP_XOR;
  91. }
  92. }
  93. static void WriteStringRecord(unsigned Code, const std::string &Str,
  94. unsigned AbbrevToUse, BitstreamWriter &Stream) {
  95. SmallVector<unsigned, 64> Vals;
  96. // Code: [strchar x N]
  97. for (unsigned i = 0, e = Str.size(); i != e; ++i)
  98. Vals.push_back(Str[i]);
  99. // Emit the finished record.
  100. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  101. }
  102. // Emit information about parameter attributes.
  103. static void WriteAttributeTable(const ValueEnumerator &VE,
  104. BitstreamWriter &Stream) {
  105. const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
  106. if (Attrs.empty()) return;
  107. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  108. SmallVector<uint64_t, 64> Record;
  109. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  110. const AttrListPtr &A = Attrs[i];
  111. for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
  112. const AttributeWithIndex &PAWI = A.getSlot(i);
  113. Record.push_back(PAWI.Index);
  114. // FIXME: remove in LLVM 3.0
  115. // Store the alignment in the bitcode as a 16-bit raw value instead of a
  116. // 5-bit log2 encoded value. Shift the bits above the alignment up by
  117. // 11 bits.
  118. uint64_t FauxAttr = PAWI.Attrs & 0xffff;
  119. if (PAWI.Attrs & Attribute::Alignment)
  120. FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
  121. FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
  122. Record.push_back(FauxAttr);
  123. }
  124. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  125. Record.clear();
  126. }
  127. Stream.ExitBlock();
  128. }
  129. /// WriteTypeTable - Write out the type table for a module.
  130. static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  131. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  132. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
  133. SmallVector<uint64_t, 64> TypeVals;
  134. // Abbrev for TYPE_CODE_POINTER.
  135. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  136. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  137. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  138. Log2_32_Ceil(VE.getTypes().size()+1)));
  139. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  140. unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
  141. // Abbrev for TYPE_CODE_FUNCTION.
  142. Abbv = new BitCodeAbbrev();
  143. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  144. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  145. Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
  146. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  147. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  148. Log2_32_Ceil(VE.getTypes().size()+1)));
  149. unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
  150. // Abbrev for TYPE_CODE_STRUCT.
  151. Abbv = new BitCodeAbbrev();
  152. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
  153. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  154. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  155. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  156. Log2_32_Ceil(VE.getTypes().size()+1)));
  157. unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
  158. // Abbrev for TYPE_CODE_UNION.
  159. Abbv = new BitCodeAbbrev();
  160. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_UNION));
  161. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  162. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  163. Log2_32_Ceil(VE.getTypes().size()+1)));
  164. unsigned UnionAbbrev = Stream.EmitAbbrev(Abbv);
  165. // Abbrev for TYPE_CODE_ARRAY.
  166. Abbv = new BitCodeAbbrev();
  167. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  168. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  169. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  170. Log2_32_Ceil(VE.getTypes().size()+1)));
  171. unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
  172. // Emit an entry count so the reader can reserve space.
  173. TypeVals.push_back(TypeList.size());
  174. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  175. TypeVals.clear();
  176. // Loop over all of the types, emitting each in turn.
  177. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  178. const Type *T = TypeList[i].first;
  179. int AbbrevToUse = 0;
  180. unsigned Code = 0;
  181. switch (T->getTypeID()) {
  182. default: llvm_unreachable("Unknown type!");
  183. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  184. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  185. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  186. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  187. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  188. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  189. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  190. case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
  191. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  192. case Type::IntegerTyID:
  193. // INTEGER: [width]
  194. Code = bitc::TYPE_CODE_INTEGER;
  195. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  196. break;
  197. case Type::PointerTyID: {
  198. const PointerType *PTy = cast<PointerType>(T);
  199. // POINTER: [pointee type, address space]
  200. Code = bitc::TYPE_CODE_POINTER;
  201. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  202. unsigned AddressSpace = PTy->getAddressSpace();
  203. TypeVals.push_back(AddressSpace);
  204. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  205. break;
  206. }
  207. case Type::FunctionTyID: {
  208. const FunctionType *FT = cast<FunctionType>(T);
  209. // FUNCTION: [isvararg, attrid, retty, paramty x N]
  210. Code = bitc::TYPE_CODE_FUNCTION;
  211. TypeVals.push_back(FT->isVarArg());
  212. TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
  213. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  214. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  215. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  216. AbbrevToUse = FunctionAbbrev;
  217. break;
  218. }
  219. case Type::StructTyID: {
  220. const StructType *ST = cast<StructType>(T);
  221. // STRUCT: [ispacked, eltty x N]
  222. Code = bitc::TYPE_CODE_STRUCT;
  223. TypeVals.push_back(ST->isPacked());
  224. // Output all of the element types.
  225. for (StructType::element_iterator I = ST->element_begin(),
  226. E = ST->element_end(); I != E; ++I)
  227. TypeVals.push_back(VE.getTypeID(*I));
  228. AbbrevToUse = StructAbbrev;
  229. break;
  230. }
  231. case Type::UnionTyID: {
  232. const UnionType *UT = cast<UnionType>(T);
  233. // UNION: [eltty x N]
  234. Code = bitc::TYPE_CODE_UNION;
  235. // Output all of the element types.
  236. for (UnionType::element_iterator I = UT->element_begin(),
  237. E = UT->element_end(); I != E; ++I)
  238. TypeVals.push_back(VE.getTypeID(*I));
  239. AbbrevToUse = UnionAbbrev;
  240. break;
  241. }
  242. case Type::ArrayTyID: {
  243. const ArrayType *AT = cast<ArrayType>(T);
  244. // ARRAY: [numelts, eltty]
  245. Code = bitc::TYPE_CODE_ARRAY;
  246. TypeVals.push_back(AT->getNumElements());
  247. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  248. AbbrevToUse = ArrayAbbrev;
  249. break;
  250. }
  251. case Type::VectorTyID: {
  252. const VectorType *VT = cast<VectorType>(T);
  253. // VECTOR [numelts, eltty]
  254. Code = bitc::TYPE_CODE_VECTOR;
  255. TypeVals.push_back(VT->getNumElements());
  256. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  257. break;
  258. }
  259. }
  260. // Emit the finished record.
  261. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  262. TypeVals.clear();
  263. }
  264. Stream.ExitBlock();
  265. }
  266. static unsigned getEncodedLinkage(const GlobalValue *GV) {
  267. switch (GV->getLinkage()) {
  268. default: llvm_unreachable("Invalid linkage!");
  269. case GlobalValue::ExternalLinkage: return 0;
  270. case GlobalValue::WeakAnyLinkage: return 1;
  271. case GlobalValue::AppendingLinkage: return 2;
  272. case GlobalValue::InternalLinkage: return 3;
  273. case GlobalValue::LinkOnceAnyLinkage: return 4;
  274. case GlobalValue::DLLImportLinkage: return 5;
  275. case GlobalValue::DLLExportLinkage: return 6;
  276. case GlobalValue::ExternalWeakLinkage: return 7;
  277. case GlobalValue::CommonLinkage: return 8;
  278. case GlobalValue::PrivateLinkage: return 9;
  279. case GlobalValue::WeakODRLinkage: return 10;
  280. case GlobalValue::LinkOnceODRLinkage: return 11;
  281. case GlobalValue::AvailableExternallyLinkage: return 12;
  282. case GlobalValue::LinkerPrivateLinkage: return 13;
  283. }
  284. }
  285. static unsigned getEncodedVisibility(const GlobalValue *GV) {
  286. switch (GV->getVisibility()) {
  287. default: llvm_unreachable("Invalid visibility!");
  288. case GlobalValue::DefaultVisibility: return 0;
  289. case GlobalValue::HiddenVisibility: return 1;
  290. case GlobalValue::ProtectedVisibility: return 2;
  291. }
  292. }
  293. // Emit top-level description of module, including target triple, inline asm,
  294. // descriptors for global variables, and function prototype info.
  295. static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
  296. BitstreamWriter &Stream) {
  297. // Emit the list of dependent libraries for the Module.
  298. for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
  299. WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
  300. // Emit various pieces of data attached to a module.
  301. if (!M->getTargetTriple().empty())
  302. WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
  303. 0/*TODO*/, Stream);
  304. if (!M->getDataLayout().empty())
  305. WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
  306. 0/*TODO*/, Stream);
  307. if (!M->getModuleInlineAsm().empty())
  308. WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
  309. 0/*TODO*/, Stream);
  310. // Emit information about sections and GC, computing how many there are. Also
  311. // compute the maximum alignment value.
  312. std::map<std::string, unsigned> SectionMap;
  313. std::map<std::string, unsigned> GCMap;
  314. unsigned MaxAlignment = 0;
  315. unsigned MaxGlobalType = 0;
  316. for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
  317. GV != E; ++GV) {
  318. MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
  319. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
  320. if (!GV->hasSection()) continue;
  321. // Give section names unique ID's.
  322. unsigned &Entry = SectionMap[GV->getSection()];
  323. if (Entry != 0) continue;
  324. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
  325. 0/*TODO*/, Stream);
  326. Entry = SectionMap.size();
  327. }
  328. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
  329. MaxAlignment = std::max(MaxAlignment, F->getAlignment());
  330. if (F->hasSection()) {
  331. // Give section names unique ID's.
  332. unsigned &Entry = SectionMap[F->getSection()];
  333. if (!Entry) {
  334. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
  335. 0/*TODO*/, Stream);
  336. Entry = SectionMap.size();
  337. }
  338. }
  339. if (F->hasGC()) {
  340. // Same for GC names.
  341. unsigned &Entry = GCMap[F->getGC()];
  342. if (!Entry) {
  343. WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
  344. 0/*TODO*/, Stream);
  345. Entry = GCMap.size();
  346. }
  347. }
  348. }
  349. // Emit abbrev for globals, now that we know # sections and max alignment.
  350. unsigned SimpleGVarAbbrev = 0;
  351. if (!M->global_empty()) {
  352. // Add an abbrev for common globals with no visibility or thread localness.
  353. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  354. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  355. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  356. Log2_32_Ceil(MaxGlobalType+1)));
  357. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
  358. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  359. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
  360. if (MaxAlignment == 0) // Alignment.
  361. Abbv->Add(BitCodeAbbrevOp(0));
  362. else {
  363. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  364. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  365. Log2_32_Ceil(MaxEncAlignment+1)));
  366. }
  367. if (SectionMap.empty()) // Section.
  368. Abbv->Add(BitCodeAbbrevOp(0));
  369. else
  370. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  371. Log2_32_Ceil(SectionMap.size()+1)));
  372. // Don't bother emitting vis + thread local.
  373. SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
  374. }
  375. // Emit the global variable information.
  376. SmallVector<unsigned, 64> Vals;
  377. for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
  378. GV != E; ++GV) {
  379. unsigned AbbrevToUse = 0;
  380. // GLOBALVAR: [type, isconst, initid,
  381. // linkage, alignment, section, visibility, threadlocal]
  382. Vals.push_back(VE.getTypeID(GV->getType()));
  383. Vals.push_back(GV->isConstant());
  384. Vals.push_back(GV->isDeclaration() ? 0 :
  385. (VE.getValueID(GV->getInitializer()) + 1));
  386. Vals.push_back(getEncodedLinkage(GV));
  387. Vals.push_back(Log2_32(GV->getAlignment())+1);
  388. Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
  389. if (GV->isThreadLocal() ||
  390. GV->getVisibility() != GlobalValue::DefaultVisibility) {
  391. Vals.push_back(getEncodedVisibility(GV));
  392. Vals.push_back(GV->isThreadLocal());
  393. } else {
  394. AbbrevToUse = SimpleGVarAbbrev;
  395. }
  396. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  397. Vals.clear();
  398. }
  399. // Emit the function proto information.
  400. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
  401. // FUNCTION: [type, callingconv, isproto, paramattr,
  402. // linkage, alignment, section, visibility, gc]
  403. Vals.push_back(VE.getTypeID(F->getType()));
  404. Vals.push_back(F->getCallingConv());
  405. Vals.push_back(F->isDeclaration());
  406. Vals.push_back(getEncodedLinkage(F));
  407. Vals.push_back(VE.getAttributeID(F->getAttributes()));
  408. Vals.push_back(Log2_32(F->getAlignment())+1);
  409. Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
  410. Vals.push_back(getEncodedVisibility(F));
  411. Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
  412. unsigned AbbrevToUse = 0;
  413. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  414. Vals.clear();
  415. }
  416. // Emit the alias information.
  417. for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
  418. AI != E; ++AI) {
  419. Vals.push_back(VE.getTypeID(AI->getType()));
  420. Vals.push_back(VE.getValueID(AI->getAliasee()));
  421. Vals.push_back(getEncodedLinkage(AI));
  422. Vals.push_back(getEncodedVisibility(AI));
  423. unsigned AbbrevToUse = 0;
  424. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  425. Vals.clear();
  426. }
  427. }
  428. static uint64_t GetOptimizationFlags(const Value *V) {
  429. uint64_t Flags = 0;
  430. if (const OverflowingBinaryOperator *OBO =
  431. dyn_cast<OverflowingBinaryOperator>(V)) {
  432. if (OBO->hasNoSignedWrap())
  433. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  434. if (OBO->hasNoUnsignedWrap())
  435. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  436. } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
  437. if (Div->isExact())
  438. Flags |= 1 << bitc::SDIV_EXACT;
  439. }
  440. return Flags;
  441. }
  442. static void WriteMDNode(const MDNode *N,
  443. const ValueEnumerator &VE,
  444. BitstreamWriter &Stream,
  445. SmallVector<uint64_t, 64> &Record) {
  446. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  447. if (N->getOperand(i)) {
  448. Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
  449. Record.push_back(VE.getValueID(N->getOperand(i)));
  450. } else {
  451. Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
  452. Record.push_back(0);
  453. }
  454. }
  455. unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
  456. bitc::METADATA_NODE;
  457. Stream.EmitRecord(MDCode, Record, 0);
  458. Record.clear();
  459. }
  460. static void WriteModuleMetadata(const ValueEnumerator &VE,
  461. BitstreamWriter &Stream) {
  462. const ValueEnumerator::ValueList &Vals = VE.getMDValues();
  463. bool StartedMetadataBlock = false;
  464. unsigned MDSAbbrev = 0;
  465. SmallVector<uint64_t, 64> Record;
  466. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  467. if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
  468. if (!N->isFunctionLocal() || !N->getFunction()) {
  469. if (!StartedMetadataBlock) {
  470. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  471. StartedMetadataBlock = true;
  472. }
  473. WriteMDNode(N, VE, Stream, Record);
  474. }
  475. } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
  476. if (!StartedMetadataBlock) {
  477. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  478. // Abbrev for METADATA_STRING.
  479. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  480. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
  481. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  482. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  483. MDSAbbrev = Stream.EmitAbbrev(Abbv);
  484. StartedMetadataBlock = true;
  485. }
  486. // Code: [strchar x N]
  487. Record.append(MDS->begin(), MDS->end());
  488. // Emit the finished record.
  489. Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
  490. Record.clear();
  491. } else if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(Vals[i].first)) {
  492. if (!StartedMetadataBlock) {
  493. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  494. StartedMetadataBlock = true;
  495. }
  496. // Write name.
  497. StringRef Str = NMD->getName();
  498. for (unsigned i = 0, e = Str.size(); i != e; ++i)
  499. Record.push_back(Str[i]);
  500. Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
  501. Record.clear();
  502. // Write named metadata operands.
  503. for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
  504. if (NMD->getOperand(i))
  505. Record.push_back(VE.getValueID(NMD->getOperand(i)));
  506. else
  507. Record.push_back(~0U);
  508. }
  509. Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
  510. Record.clear();
  511. }
  512. }
  513. if (StartedMetadataBlock)
  514. Stream.ExitBlock();
  515. }
  516. static void WriteFunctionLocalMetadata(const Function &F,
  517. const ValueEnumerator &VE,
  518. BitstreamWriter &Stream) {
  519. bool StartedMetadataBlock = false;
  520. SmallVector<uint64_t, 64> Record;
  521. const ValueEnumerator::ValueList &Vals = VE.getMDValues();
  522. for (unsigned i = 0, e = Vals.size(); i != e; ++i)
  523. if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first))
  524. if (N->isFunctionLocal() && N->getFunction() == &F) {
  525. if (!StartedMetadataBlock) {
  526. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  527. StartedMetadataBlock = true;
  528. }
  529. WriteMDNode(N, VE, Stream, Record);
  530. }
  531. if (StartedMetadataBlock)
  532. Stream.ExitBlock();
  533. }
  534. static void WriteMetadataAttachment(const Function &F,
  535. const ValueEnumerator &VE,
  536. BitstreamWriter &Stream) {
  537. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  538. SmallVector<uint64_t, 64> Record;
  539. // Write metadata attachments
  540. // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
  541. SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
  542. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  543. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  544. I != E; ++I) {
  545. MDs.clear();
  546. I->getAllMetadataOtherThanDebugLoc(MDs);
  547. // If no metadata, ignore instruction.
  548. if (MDs.empty()) continue;
  549. Record.push_back(VE.getInstructionID(I));
  550. for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
  551. Record.push_back(MDs[i].first);
  552. Record.push_back(VE.getValueID(MDs[i].second));
  553. }
  554. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  555. Record.clear();
  556. }
  557. Stream.ExitBlock();
  558. }
  559. static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
  560. SmallVector<uint64_t, 64> Record;
  561. // Write metadata kinds
  562. // METADATA_KIND - [n x [id, name]]
  563. SmallVector<StringRef, 4> Names;
  564. M->getMDKindNames(Names);
  565. assert(Names[0] == "" && "MDKind #0 is invalid");
  566. if (Names.size() == 1) return;
  567. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  568. for (unsigned MDKindID = 1, e = Names.size(); MDKindID != e; ++MDKindID) {
  569. Record.push_back(MDKindID);
  570. StringRef KName = Names[MDKindID];
  571. Record.append(KName.begin(), KName.end());
  572. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  573. Record.clear();
  574. }
  575. Stream.ExitBlock();
  576. }
  577. static void WriteConstants(unsigned FirstVal, unsigned LastVal,
  578. const ValueEnumerator &VE,
  579. BitstreamWriter &Stream, bool isGlobal) {
  580. if (FirstVal == LastVal) return;
  581. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  582. unsigned AggregateAbbrev = 0;
  583. unsigned String8Abbrev = 0;
  584. unsigned CString7Abbrev = 0;
  585. unsigned CString6Abbrev = 0;
  586. // If this is a constant pool for the module, emit module-specific abbrevs.
  587. if (isGlobal) {
  588. // Abbrev for CST_CODE_AGGREGATE.
  589. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  590. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  591. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  592. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  593. AggregateAbbrev = Stream.EmitAbbrev(Abbv);
  594. // Abbrev for CST_CODE_STRING.
  595. Abbv = new BitCodeAbbrev();
  596. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  597. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  598. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  599. String8Abbrev = Stream.EmitAbbrev(Abbv);
  600. // Abbrev for CST_CODE_CSTRING.
  601. Abbv = new BitCodeAbbrev();
  602. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  603. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  604. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  605. CString7Abbrev = Stream.EmitAbbrev(Abbv);
  606. // Abbrev for CST_CODE_CSTRING.
  607. Abbv = new BitCodeAbbrev();
  608. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  609. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  610. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  611. CString6Abbrev = Stream.EmitAbbrev(Abbv);
  612. }
  613. SmallVector<uint64_t, 64> Record;
  614. const ValueEnumerator::ValueList &Vals = VE.getValues();
  615. const Type *LastTy = 0;
  616. for (unsigned i = FirstVal; i != LastVal; ++i) {
  617. const Value *V = Vals[i].first;
  618. // If we need to switch types, do so now.
  619. if (V->getType() != LastTy) {
  620. LastTy = V->getType();
  621. Record.push_back(VE.getTypeID(LastTy));
  622. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  623. CONSTANTS_SETTYPE_ABBREV);
  624. Record.clear();
  625. }
  626. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  627. Record.push_back(unsigned(IA->hasSideEffects()) |
  628. unsigned(IA->isAlignStack()) << 1);
  629. // Add the asm string.
  630. const std::string &AsmStr = IA->getAsmString();
  631. Record.push_back(AsmStr.size());
  632. for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
  633. Record.push_back(AsmStr[i]);
  634. // Add the constraint string.
  635. const std::string &ConstraintStr = IA->getConstraintString();
  636. Record.push_back(ConstraintStr.size());
  637. for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
  638. Record.push_back(ConstraintStr[i]);
  639. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  640. Record.clear();
  641. continue;
  642. }
  643. const Constant *C = cast<Constant>(V);
  644. unsigned Code = -1U;
  645. unsigned AbbrevToUse = 0;
  646. if (C->isNullValue()) {
  647. Code = bitc::CST_CODE_NULL;
  648. } else if (isa<UndefValue>(C)) {
  649. Code = bitc::CST_CODE_UNDEF;
  650. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  651. if (IV->getBitWidth() <= 64) {
  652. int64_t V = IV->getSExtValue();
  653. if (V >= 0)
  654. Record.push_back(V << 1);
  655. else
  656. Record.push_back((-V << 1) | 1);
  657. Code = bitc::CST_CODE_INTEGER;
  658. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  659. } else { // Wide integers, > 64 bits in size.
  660. // We have an arbitrary precision integer value to write whose
  661. // bit width is > 64. However, in canonical unsigned integer
  662. // format it is likely that the high bits are going to be zero.
  663. // So, we only write the number of active words.
  664. unsigned NWords = IV->getValue().getActiveWords();
  665. const uint64_t *RawWords = IV->getValue().getRawData();
  666. for (unsigned i = 0; i != NWords; ++i) {
  667. int64_t V = RawWords[i];
  668. if (V >= 0)
  669. Record.push_back(V << 1);
  670. else
  671. Record.push_back((-V << 1) | 1);
  672. }
  673. Code = bitc::CST_CODE_WIDE_INTEGER;
  674. }
  675. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  676. Code = bitc::CST_CODE_FLOAT;
  677. const Type *Ty = CFP->getType();
  678. if (Ty->isFloatTy() || Ty->isDoubleTy()) {
  679. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  680. } else if (Ty->isX86_FP80Ty()) {
  681. // api needed to prevent premature destruction
  682. // bits are not in the same order as a normal i80 APInt, compensate.
  683. APInt api = CFP->getValueAPF().bitcastToAPInt();
  684. const uint64_t *p = api.getRawData();
  685. Record.push_back((p[1] << 48) | (p[0] >> 16));
  686. Record.push_back(p[0] & 0xffffLL);
  687. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  688. APInt api = CFP->getValueAPF().bitcastToAPInt();
  689. const uint64_t *p = api.getRawData();
  690. Record.push_back(p[0]);
  691. Record.push_back(p[1]);
  692. } else {
  693. assert (0 && "Unknown FP type!");
  694. }
  695. } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
  696. const ConstantArray *CA = cast<ConstantArray>(C);
  697. // Emit constant strings specially.
  698. unsigned NumOps = CA->getNumOperands();
  699. // If this is a null-terminated string, use the denser CSTRING encoding.
  700. if (CA->getOperand(NumOps-1)->isNullValue()) {
  701. Code = bitc::CST_CODE_CSTRING;
  702. --NumOps; // Don't encode the null, which isn't allowed by char6.
  703. } else {
  704. Code = bitc::CST_CODE_STRING;
  705. AbbrevToUse = String8Abbrev;
  706. }
  707. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  708. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  709. for (unsigned i = 0; i != NumOps; ++i) {
  710. unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue();
  711. Record.push_back(V);
  712. isCStr7 &= (V & 128) == 0;
  713. if (isCStrChar6)
  714. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  715. }
  716. if (isCStrChar6)
  717. AbbrevToUse = CString6Abbrev;
  718. else if (isCStr7)
  719. AbbrevToUse = CString7Abbrev;
  720. } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
  721. isa<ConstantVector>(V)) {
  722. Code = bitc::CST_CODE_AGGREGATE;
  723. for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
  724. Record.push_back(VE.getValueID(C->getOperand(i)));
  725. AbbrevToUse = AggregateAbbrev;
  726. } else if (isa<ConstantUnion>(C)) {
  727. Code = bitc::CST_CODE_AGGREGATE;
  728. // Unions only have one entry but we must send type along with it.
  729. const Type *EntryKind = C->getOperand(0)->getType();
  730. const UnionType *UnTy = cast<UnionType>(C->getType());
  731. int UnionIndex = UnTy->getElementTypeIndex(EntryKind);
  732. assert(UnionIndex != -1 && "Constant union contains invalid entry");
  733. Record.push_back(UnionIndex);
  734. Record.push_back(VE.getValueID(C->getOperand(0)));
  735. AbbrevToUse = AggregateAbbrev;
  736. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  737. switch (CE->getOpcode()) {
  738. default:
  739. if (Instruction::isCast(CE->getOpcode())) {
  740. Code = bitc::CST_CODE_CE_CAST;
  741. Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
  742. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  743. Record.push_back(VE.getValueID(C->getOperand(0)));
  744. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  745. } else {
  746. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  747. Code = bitc::CST_CODE_CE_BINOP;
  748. Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
  749. Record.push_back(VE.getValueID(C->getOperand(0)));
  750. Record.push_back(VE.getValueID(C->getOperand(1)));
  751. uint64_t Flags = GetOptimizationFlags(CE);
  752. if (Flags != 0)
  753. Record.push_back(Flags);
  754. }
  755. break;
  756. case Instruction::GetElementPtr:
  757. Code = bitc::CST_CODE_CE_GEP;
  758. if (cast<GEPOperator>(C)->isInBounds())
  759. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  760. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  761. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  762. Record.push_back(VE.getValueID(C->getOperand(i)));
  763. }
  764. break;
  765. case Instruction::Select:
  766. Code = bitc::CST_CODE_CE_SELECT;
  767. Record.push_back(VE.getValueID(C->getOperand(0)));
  768. Record.push_back(VE.getValueID(C->getOperand(1)));
  769. Record.push_back(VE.getValueID(C->getOperand(2)));
  770. break;
  771. case Instruction::ExtractElement:
  772. Code = bitc::CST_CODE_CE_EXTRACTELT;
  773. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  774. Record.push_back(VE.getValueID(C->getOperand(0)));
  775. Record.push_back(VE.getValueID(C->getOperand(1)));
  776. break;
  777. case Instruction::InsertElement:
  778. Code = bitc::CST_CODE_CE_INSERTELT;
  779. Record.push_back(VE.getValueID(C->getOperand(0)));
  780. Record.push_back(VE.getValueID(C->getOperand(1)));
  781. Record.push_back(VE.getValueID(C->getOperand(2)));
  782. break;
  783. case Instruction::ShuffleVector:
  784. // If the return type and argument types are the same, this is a
  785. // standard shufflevector instruction. If the types are different,
  786. // then the shuffle is widening or truncating the input vectors, and
  787. // the argument type must also be encoded.
  788. if (C->getType() == C->getOperand(0)->getType()) {
  789. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  790. } else {
  791. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  792. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  793. }
  794. Record.push_back(VE.getValueID(C->getOperand(0)));
  795. Record.push_back(VE.getValueID(C->getOperand(1)));
  796. Record.push_back(VE.getValueID(C->getOperand(2)));
  797. break;
  798. case Instruction::ICmp:
  799. case Instruction::FCmp:
  800. Code = bitc::CST_CODE_CE_CMP;
  801. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  802. Record.push_back(VE.getValueID(C->getOperand(0)));
  803. Record.push_back(VE.getValueID(C->getOperand(1)));
  804. Record.push_back(CE->getPredicate());
  805. break;
  806. }
  807. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
  808. assert(BA->getFunction() == BA->getBasicBlock()->getParent() &&
  809. "Malformed blockaddress");
  810. Code = bitc::CST_CODE_BLOCKADDRESS;
  811. Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
  812. Record.push_back(VE.getValueID(BA->getFunction()));
  813. Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
  814. } else {
  815. llvm_unreachable("Unknown constant!");
  816. }
  817. Stream.EmitRecord(Code, Record, AbbrevToUse);
  818. Record.clear();
  819. }
  820. Stream.ExitBlock();
  821. }
  822. static void WriteModuleConstants(const ValueEnumerator &VE,
  823. BitstreamWriter &Stream) {
  824. const ValueEnumerator::ValueList &Vals = VE.getValues();
  825. // Find the first constant to emit, which is the first non-globalvalue value.
  826. // We know globalvalues have been emitted by WriteModuleInfo.
  827. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  828. if (!isa<GlobalValue>(Vals[i].first)) {
  829. WriteConstants(i, Vals.size(), VE, Stream, true);
  830. return;
  831. }
  832. }
  833. }
  834. /// PushValueAndType - The file has to encode both the value and type id for
  835. /// many values, because we need to know what type to create for forward
  836. /// references. However, most operands are not forward references, so this type
  837. /// field is not needed.
  838. ///
  839. /// This function adds V's value ID to Vals. If the value ID is higher than the
  840. /// instruction ID, then it is a forward reference, and it also includes the
  841. /// type ID.
  842. static bool PushValueAndType(const Value *V, unsigned InstID,
  843. SmallVector<unsigned, 64> &Vals,
  844. ValueEnumerator &VE) {
  845. unsigned ValID = VE.getValueID(V);
  846. Vals.push_back(ValID);
  847. if (ValID >= InstID) {
  848. Vals.push_back(VE.getTypeID(V->getType()));
  849. return true;
  850. }
  851. return false;
  852. }
  853. /// WriteInstruction - Emit an instruction to the specified stream.
  854. static void WriteInstruction(const Instruction &I, unsigned InstID,
  855. ValueEnumerator &VE, BitstreamWriter &Stream,
  856. SmallVector<unsigned, 64> &Vals) {
  857. unsigned Code = 0;
  858. unsigned AbbrevToUse = 0;
  859. VE.setInstructionID(&I);
  860. switch (I.getOpcode()) {
  861. default:
  862. if (Instruction::isCast(I.getOpcode())) {
  863. Code = bitc::FUNC_CODE_INST_CAST;
  864. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  865. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  866. Vals.push_back(VE.getTypeID(I.getType()));
  867. Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
  868. } else {
  869. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  870. Code = bitc::FUNC_CODE_INST_BINOP;
  871. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  872. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  873. Vals.push_back(VE.getValueID(I.getOperand(1)));
  874. Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
  875. uint64_t Flags = GetOptimizationFlags(&I);
  876. if (Flags != 0) {
  877. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  878. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  879. Vals.push_back(Flags);
  880. }
  881. }
  882. break;
  883. case Instruction::GetElementPtr:
  884. Code = bitc::FUNC_CODE_INST_GEP;
  885. if (cast<GEPOperator>(&I)->isInBounds())
  886. Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
  887. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  888. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  889. break;
  890. case Instruction::ExtractValue: {
  891. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  892. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  893. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  894. for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
  895. Vals.push_back(*i);
  896. break;
  897. }
  898. case Instruction::InsertValue: {
  899. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  900. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  901. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  902. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  903. for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
  904. Vals.push_back(*i);
  905. break;
  906. }
  907. case Instruction::Select:
  908. Code = bitc::FUNC_CODE_INST_VSELECT;
  909. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  910. Vals.push_back(VE.getValueID(I.getOperand(2)));
  911. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  912. break;
  913. case Instruction::ExtractElement:
  914. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  915. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  916. Vals.push_back(VE.getValueID(I.getOperand(1)));
  917. break;
  918. case Instruction::InsertElement:
  919. Code = bitc::FUNC_CODE_INST_INSERTELT;
  920. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  921. Vals.push_back(VE.getValueID(I.getOperand(1)));
  922. Vals.push_back(VE.getValueID(I.getOperand(2)));
  923. break;
  924. case Instruction::ShuffleVector:
  925. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  926. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  927. Vals.push_back(VE.getValueID(I.getOperand(1)));
  928. Vals.push_back(VE.getValueID(I.getOperand(2)));
  929. break;
  930. case Instruction::ICmp:
  931. case Instruction::FCmp:
  932. // compare returning Int1Ty or vector of Int1Ty
  933. Code = bitc::FUNC_CODE_INST_CMP2;
  934. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  935. Vals.push_back(VE.getValueID(I.getOperand(1)));
  936. Vals.push_back(cast<CmpInst>(I).getPredicate());
  937. break;
  938. case Instruction::Ret:
  939. {
  940. Code = bitc::FUNC_CODE_INST_RET;
  941. unsigned NumOperands = I.getNumOperands();
  942. if (NumOperands == 0)
  943. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  944. else if (NumOperands == 1) {
  945. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  946. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  947. } else {
  948. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  949. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  950. }
  951. }
  952. break;
  953. case Instruction::Br:
  954. {
  955. Code = bitc::FUNC_CODE_INST_BR;
  956. BranchInst &II = cast<BranchInst>(I);
  957. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  958. if (II.isConditional()) {
  959. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  960. Vals.push_back(VE.getValueID(II.getCondition()));
  961. }
  962. }
  963. break;
  964. case Instruction::Switch:
  965. Code = bitc::FUNC_CODE_INST_SWITCH;
  966. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  967. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  968. Vals.push_back(VE.getValueID(I.getOperand(i)));
  969. break;
  970. case Instruction::IndirectBr:
  971. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  972. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  973. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  974. Vals.push_back(VE.getValueID(I.getOperand(i)));
  975. break;
  976. case Instruction::Invoke: {
  977. const InvokeInst *II = cast<InvokeInst>(&I);
  978. const Value *Callee(II->getCalledValue());
  979. const PointerType *PTy = cast<PointerType>(Callee->getType());
  980. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  981. Code = bitc::FUNC_CODE_INST_INVOKE;
  982. Vals.push_back(VE.getAttributeID(II->getAttributes()));
  983. Vals.push_back(II->getCallingConv());
  984. Vals.push_back(VE.getValueID(II->getNormalDest()));
  985. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  986. PushValueAndType(Callee, InstID, Vals, VE);
  987. // Emit value #'s for the fixed parameters.
  988. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  989. Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param.
  990. // Emit type/value pairs for varargs params.
  991. if (FTy->isVarArg()) {
  992. for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
  993. i != e; ++i)
  994. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
  995. }
  996. break;
  997. }
  998. case Instruction::Unwind:
  999. Code = bitc::FUNC_CODE_INST_UNWIND;
  1000. break;
  1001. case Instruction::Unreachable:
  1002. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  1003. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  1004. break;
  1005. case Instruction::PHI:
  1006. Code = bitc::FUNC_CODE_INST_PHI;
  1007. Vals.push_back(VE.getTypeID(I.getType()));
  1008. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  1009. Vals.push_back(VE.getValueID(I.getOperand(i)));
  1010. break;
  1011. case Instruction::Alloca:
  1012. Code = bitc::FUNC_CODE_INST_ALLOCA;
  1013. Vals.push_back(VE.getTypeID(I.getType()));
  1014. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  1015. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  1016. Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
  1017. break;
  1018. case Instruction::Load:
  1019. Code = bitc::FUNC_CODE_INST_LOAD;
  1020. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
  1021. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  1022. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  1023. Vals.push_back(cast<LoadInst>(I).isVolatile());
  1024. break;
  1025. case Instruction::Store:
  1026. Code = bitc::FUNC_CODE_INST_STORE2;
  1027. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
  1028. Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
  1029. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  1030. Vals.push_back(cast<StoreInst>(I).isVolatile());
  1031. break;
  1032. case Instruction::Call: {
  1033. const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
  1034. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  1035. Code = bitc::FUNC_CODE_INST_CALL;
  1036. const CallInst *CI = cast<CallInst>(&I);
  1037. Vals.push_back(VE.getAttributeID(CI->getAttributes()));
  1038. Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
  1039. PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
  1040. // Emit value #'s for the fixed parameters.
  1041. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  1042. Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
  1043. // Emit type/value pairs for varargs params.
  1044. if (FTy->isVarArg()) {
  1045. unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
  1046. for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
  1047. i != e; ++i)
  1048. PushValueAndType(I.getOperand(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. }