BitcodeWriter.cpp 74 KB

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