BitcodeWriter.cpp 74 KB

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