BitcodeWriter.cpp 69 KB

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