BitcodeWriter.cpp 75 KB

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