BitcodeReader.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  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. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "BitcodeReader.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/InlineAsm.h"
  18. #include "llvm/Instructions.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/ParamAttrsList.h"
  21. #include "llvm/AutoUpgrade.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. using namespace llvm;
  27. void BitcodeReader::FreeState() {
  28. delete Buffer;
  29. Buffer = 0;
  30. std::vector<PATypeHolder>().swap(TypeList);
  31. ValueList.clear();
  32. std::vector<const ParamAttrsList*>().swap(ParamAttrs);
  33. std::vector<BasicBlock*>().swap(FunctionBBs);
  34. std::vector<Function*>().swap(FunctionsWithBodies);
  35. DeferredFunctionInfo.clear();
  36. }
  37. //===----------------------------------------------------------------------===//
  38. // Helper functions to implement forward reference resolution, etc.
  39. //===----------------------------------------------------------------------===//
  40. /// ConvertToString - Convert a string from a record into an std::string, return
  41. /// true on failure.
  42. template<typename StrTy>
  43. static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
  44. StrTy &Result) {
  45. if (Idx > Record.size())
  46. return true;
  47. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  48. Result += (char)Record[i];
  49. return false;
  50. }
  51. static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  52. switch (Val) {
  53. default: // Map unknown/new linkages to external
  54. case 0: return GlobalValue::ExternalLinkage;
  55. case 1: return GlobalValue::WeakLinkage;
  56. case 2: return GlobalValue::AppendingLinkage;
  57. case 3: return GlobalValue::InternalLinkage;
  58. case 4: return GlobalValue::LinkOnceLinkage;
  59. case 5: return GlobalValue::DLLImportLinkage;
  60. case 6: return GlobalValue::DLLExportLinkage;
  61. case 7: return GlobalValue::ExternalWeakLinkage;
  62. }
  63. }
  64. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  65. switch (Val) {
  66. default: // Map unknown visibilities to default.
  67. case 0: return GlobalValue::DefaultVisibility;
  68. case 1: return GlobalValue::HiddenVisibility;
  69. case 2: return GlobalValue::ProtectedVisibility;
  70. }
  71. }
  72. static int GetDecodedCastOpcode(unsigned Val) {
  73. switch (Val) {
  74. default: return -1;
  75. case bitc::CAST_TRUNC : return Instruction::Trunc;
  76. case bitc::CAST_ZEXT : return Instruction::ZExt;
  77. case bitc::CAST_SEXT : return Instruction::SExt;
  78. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  79. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  80. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  81. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  82. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  83. case bitc::CAST_FPEXT : return Instruction::FPExt;
  84. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  85. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  86. case bitc::CAST_BITCAST : return Instruction::BitCast;
  87. }
  88. }
  89. static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
  90. switch (Val) {
  91. default: return -1;
  92. case bitc::BINOP_ADD: return Instruction::Add;
  93. case bitc::BINOP_SUB: return Instruction::Sub;
  94. case bitc::BINOP_MUL: return Instruction::Mul;
  95. case bitc::BINOP_UDIV: return Instruction::UDiv;
  96. case bitc::BINOP_SDIV:
  97. return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
  98. case bitc::BINOP_UREM: return Instruction::URem;
  99. case bitc::BINOP_SREM:
  100. return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
  101. case bitc::BINOP_SHL: return Instruction::Shl;
  102. case bitc::BINOP_LSHR: return Instruction::LShr;
  103. case bitc::BINOP_ASHR: return Instruction::AShr;
  104. case bitc::BINOP_AND: return Instruction::And;
  105. case bitc::BINOP_OR: return Instruction::Or;
  106. case bitc::BINOP_XOR: return Instruction::Xor;
  107. }
  108. }
  109. namespace {
  110. /// @brief A class for maintaining the slot number definition
  111. /// as a placeholder for the actual definition for forward constants defs.
  112. class ConstantPlaceHolder : public ConstantExpr {
  113. ConstantPlaceHolder(); // DO NOT IMPLEMENT
  114. void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
  115. public:
  116. Use Op;
  117. explicit ConstantPlaceHolder(const Type *Ty)
  118. : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
  119. Op(UndefValue::get(Type::Int32Ty), this) {
  120. }
  121. };
  122. }
  123. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  124. const Type *Ty) {
  125. if (Idx >= size()) {
  126. // Insert a bunch of null values.
  127. Uses.resize(Idx+1);
  128. OperandList = &Uses[0];
  129. NumOperands = Idx+1;
  130. }
  131. if (Value *V = Uses[Idx]) {
  132. assert(Ty == V->getType() && "Type mismatch in constant table!");
  133. return cast<Constant>(V);
  134. }
  135. // Create and return a placeholder, which will later be RAUW'd.
  136. Constant *C = new ConstantPlaceHolder(Ty);
  137. Uses[Idx].init(C, this);
  138. return C;
  139. }
  140. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
  141. if (Idx >= size()) {
  142. // Insert a bunch of null values.
  143. Uses.resize(Idx+1);
  144. OperandList = &Uses[0];
  145. NumOperands = Idx+1;
  146. }
  147. if (Value *V = Uses[Idx]) {
  148. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  149. return V;
  150. }
  151. // No type specified, must be invalid reference.
  152. if (Ty == 0) return 0;
  153. // Create and return a placeholder, which will later be RAUW'd.
  154. Value *V = new Argument(Ty);
  155. Uses[Idx].init(V, this);
  156. return V;
  157. }
  158. const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
  159. // If the TypeID is in range, return it.
  160. if (ID < TypeList.size())
  161. return TypeList[ID].get();
  162. if (!isTypeTable) return 0;
  163. // The type table allows forward references. Push as many Opaque types as
  164. // needed to get up to ID.
  165. while (TypeList.size() <= ID)
  166. TypeList.push_back(OpaqueType::get());
  167. return TypeList.back().get();
  168. }
  169. //===----------------------------------------------------------------------===//
  170. // Functions for parsing blocks from the bitcode file
  171. //===----------------------------------------------------------------------===//
  172. bool BitcodeReader::ParseParamAttrBlock() {
  173. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  174. return Error("Malformed block record");
  175. if (!ParamAttrs.empty())
  176. return Error("Multiple PARAMATTR blocks found!");
  177. SmallVector<uint64_t, 64> Record;
  178. ParamAttrsVector Attrs;
  179. // Read all the records.
  180. while (1) {
  181. unsigned Code = Stream.ReadCode();
  182. if (Code == bitc::END_BLOCK) {
  183. if (Stream.ReadBlockEnd())
  184. return Error("Error at end of PARAMATTR block");
  185. return false;
  186. }
  187. if (Code == bitc::ENTER_SUBBLOCK) {
  188. // No known subblocks, always skip them.
  189. Stream.ReadSubBlockID();
  190. if (Stream.SkipBlock())
  191. return Error("Malformed block record");
  192. continue;
  193. }
  194. if (Code == bitc::DEFINE_ABBREV) {
  195. Stream.ReadAbbrevRecord();
  196. continue;
  197. }
  198. // Read a record.
  199. Record.clear();
  200. switch (Stream.ReadRecord(Code, Record)) {
  201. default: // Default behavior: ignore.
  202. break;
  203. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
  204. if (Record.size() & 1)
  205. return Error("Invalid ENTRY record");
  206. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  207. if (Record[i+1] != ParamAttr::None)
  208. Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
  209. }
  210. ParamAttrs.push_back(Attrs.empty() ? NULL : ParamAttrsList::get(Attrs));
  211. Attrs.clear();
  212. break;
  213. }
  214. }
  215. }
  216. }
  217. bool BitcodeReader::ParseTypeTable() {
  218. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
  219. return Error("Malformed block record");
  220. if (!TypeList.empty())
  221. return Error("Multiple TYPE_BLOCKs found!");
  222. SmallVector<uint64_t, 64> Record;
  223. unsigned NumRecords = 0;
  224. // Read all the records for this type table.
  225. while (1) {
  226. unsigned Code = Stream.ReadCode();
  227. if (Code == bitc::END_BLOCK) {
  228. if (NumRecords != TypeList.size())
  229. return Error("Invalid type forward reference in TYPE_BLOCK");
  230. if (Stream.ReadBlockEnd())
  231. return Error("Error at end of type table block");
  232. return false;
  233. }
  234. if (Code == bitc::ENTER_SUBBLOCK) {
  235. // No known subblocks, always skip them.
  236. Stream.ReadSubBlockID();
  237. if (Stream.SkipBlock())
  238. return Error("Malformed block record");
  239. continue;
  240. }
  241. if (Code == bitc::DEFINE_ABBREV) {
  242. Stream.ReadAbbrevRecord();
  243. continue;
  244. }
  245. // Read a record.
  246. Record.clear();
  247. const Type *ResultTy = 0;
  248. switch (Stream.ReadRecord(Code, Record)) {
  249. default: // Default behavior: unknown type.
  250. ResultTy = 0;
  251. break;
  252. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  253. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  254. // type list. This allows us to reserve space.
  255. if (Record.size() < 1)
  256. return Error("Invalid TYPE_CODE_NUMENTRY record");
  257. TypeList.reserve(Record[0]);
  258. continue;
  259. case bitc::TYPE_CODE_VOID: // VOID
  260. ResultTy = Type::VoidTy;
  261. break;
  262. case bitc::TYPE_CODE_FLOAT: // FLOAT
  263. ResultTy = Type::FloatTy;
  264. break;
  265. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  266. ResultTy = Type::DoubleTy;
  267. break;
  268. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  269. ResultTy = Type::X86_FP80Ty;
  270. break;
  271. case bitc::TYPE_CODE_FP128: // FP128
  272. ResultTy = Type::FP128Ty;
  273. break;
  274. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  275. ResultTy = Type::PPC_FP128Ty;
  276. break;
  277. case bitc::TYPE_CODE_LABEL: // LABEL
  278. ResultTy = Type::LabelTy;
  279. break;
  280. case bitc::TYPE_CODE_OPAQUE: // OPAQUE
  281. ResultTy = 0;
  282. break;
  283. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  284. if (Record.size() < 1)
  285. return Error("Invalid Integer type record");
  286. ResultTy = IntegerType::get(Record[0]);
  287. break;
  288. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  289. // [pointee type, address space]
  290. if (Record.size() < 1)
  291. return Error("Invalid POINTER type record");
  292. unsigned AddressSpace = 0;
  293. if (Record.size() == 2)
  294. AddressSpace = Record[1];
  295. ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
  296. break;
  297. }
  298. case bitc::TYPE_CODE_FUNCTION: {
  299. // FIXME: attrid is dead, remove it in LLVM 3.0
  300. // FUNCTION: [vararg, attrid, retty, paramty x N]
  301. if (Record.size() < 3)
  302. return Error("Invalid FUNCTION type record");
  303. std::vector<const Type*> ArgTys;
  304. for (unsigned i = 3, e = Record.size(); i != e; ++i)
  305. ArgTys.push_back(getTypeByID(Record[i], true));
  306. ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
  307. Record[0]);
  308. break;
  309. }
  310. case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
  311. if (Record.size() < 1)
  312. return Error("Invalid STRUCT type record");
  313. std::vector<const Type*> EltTys;
  314. for (unsigned i = 1, e = Record.size(); i != e; ++i)
  315. EltTys.push_back(getTypeByID(Record[i], true));
  316. ResultTy = StructType::get(EltTys, Record[0]);
  317. break;
  318. }
  319. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  320. if (Record.size() < 2)
  321. return Error("Invalid ARRAY type record");
  322. ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
  323. break;
  324. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  325. if (Record.size() < 2)
  326. return Error("Invalid VECTOR type record");
  327. ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
  328. break;
  329. }
  330. if (NumRecords == TypeList.size()) {
  331. // If this is a new type slot, just append it.
  332. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
  333. ++NumRecords;
  334. } else if (ResultTy == 0) {
  335. // Otherwise, this was forward referenced, so an opaque type was created,
  336. // but the result type is actually just an opaque. Leave the one we
  337. // created previously.
  338. ++NumRecords;
  339. } else {
  340. // Otherwise, this was forward referenced, so an opaque type was created.
  341. // Resolve the opaque type to the real type now.
  342. assert(NumRecords < TypeList.size() && "Typelist imbalance");
  343. const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
  344. // Don't directly push the new type on the Tab. Instead we want to replace
  345. // the opaque type we previously inserted with the new concrete value. The
  346. // refinement from the abstract (opaque) type to the new type causes all
  347. // uses of the abstract type to use the concrete type (NewTy). This will
  348. // also cause the opaque type to be deleted.
  349. const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
  350. // This should have replaced the old opaque type with the new type in the
  351. // value table... or with a preexisting type that was already in the
  352. // system. Let's just make sure it did.
  353. assert(TypeList[NumRecords-1].get() != OldTy &&
  354. "refineAbstractType didn't work!");
  355. }
  356. }
  357. }
  358. bool BitcodeReader::ParseTypeSymbolTable() {
  359. if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
  360. return Error("Malformed block record");
  361. SmallVector<uint64_t, 64> Record;
  362. // Read all the records for this type table.
  363. std::string TypeName;
  364. while (1) {
  365. unsigned Code = Stream.ReadCode();
  366. if (Code == bitc::END_BLOCK) {
  367. if (Stream.ReadBlockEnd())
  368. return Error("Error at end of type symbol table block");
  369. return false;
  370. }
  371. if (Code == bitc::ENTER_SUBBLOCK) {
  372. // No known subblocks, always skip them.
  373. Stream.ReadSubBlockID();
  374. if (Stream.SkipBlock())
  375. return Error("Malformed block record");
  376. continue;
  377. }
  378. if (Code == bitc::DEFINE_ABBREV) {
  379. Stream.ReadAbbrevRecord();
  380. continue;
  381. }
  382. // Read a record.
  383. Record.clear();
  384. switch (Stream.ReadRecord(Code, Record)) {
  385. default: // Default behavior: unknown type.
  386. break;
  387. case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
  388. if (ConvertToString(Record, 1, TypeName))
  389. return Error("Invalid TST_ENTRY record");
  390. unsigned TypeID = Record[0];
  391. if (TypeID >= TypeList.size())
  392. return Error("Invalid Type ID in TST_ENTRY record");
  393. TheModule->addTypeName(TypeName, TypeList[TypeID].get());
  394. TypeName.clear();
  395. break;
  396. }
  397. }
  398. }
  399. bool BitcodeReader::ParseValueSymbolTable() {
  400. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  401. return Error("Malformed block record");
  402. SmallVector<uint64_t, 64> Record;
  403. // Read all the records for this value table.
  404. SmallString<128> ValueName;
  405. while (1) {
  406. unsigned Code = Stream.ReadCode();
  407. if (Code == bitc::END_BLOCK) {
  408. if (Stream.ReadBlockEnd())
  409. return Error("Error at end of value symbol table block");
  410. return false;
  411. }
  412. if (Code == bitc::ENTER_SUBBLOCK) {
  413. // No known subblocks, always skip them.
  414. Stream.ReadSubBlockID();
  415. if (Stream.SkipBlock())
  416. return Error("Malformed block record");
  417. continue;
  418. }
  419. if (Code == bitc::DEFINE_ABBREV) {
  420. Stream.ReadAbbrevRecord();
  421. continue;
  422. }
  423. // Read a record.
  424. Record.clear();
  425. switch (Stream.ReadRecord(Code, Record)) {
  426. default: // Default behavior: unknown type.
  427. break;
  428. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  429. if (ConvertToString(Record, 1, ValueName))
  430. return Error("Invalid TST_ENTRY record");
  431. unsigned ValueID = Record[0];
  432. if (ValueID >= ValueList.size())
  433. return Error("Invalid Value ID in VST_ENTRY record");
  434. Value *V = ValueList[ValueID];
  435. V->setName(&ValueName[0], ValueName.size());
  436. ValueName.clear();
  437. break;
  438. }
  439. case bitc::VST_CODE_BBENTRY: {
  440. if (ConvertToString(Record, 1, ValueName))
  441. return Error("Invalid VST_BBENTRY record");
  442. BasicBlock *BB = getBasicBlock(Record[0]);
  443. if (BB == 0)
  444. return Error("Invalid BB ID in VST_BBENTRY record");
  445. BB->setName(&ValueName[0], ValueName.size());
  446. ValueName.clear();
  447. break;
  448. }
  449. }
  450. }
  451. }
  452. /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
  453. /// the LSB for dense VBR encoding.
  454. static uint64_t DecodeSignRotatedValue(uint64_t V) {
  455. if ((V & 1) == 0)
  456. return V >> 1;
  457. if (V != 1)
  458. return -(V >> 1);
  459. // There is no such thing as -0 with integers. "-0" really means MININT.
  460. return 1ULL << 63;
  461. }
  462. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  463. /// values and aliases that we can.
  464. bool BitcodeReader::ResolveGlobalAndAliasInits() {
  465. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  466. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  467. GlobalInitWorklist.swap(GlobalInits);
  468. AliasInitWorklist.swap(AliasInits);
  469. while (!GlobalInitWorklist.empty()) {
  470. unsigned ValID = GlobalInitWorklist.back().second;
  471. if (ValID >= ValueList.size()) {
  472. // Not ready to resolve this yet, it requires something later in the file.
  473. GlobalInits.push_back(GlobalInitWorklist.back());
  474. } else {
  475. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  476. GlobalInitWorklist.back().first->setInitializer(C);
  477. else
  478. return Error("Global variable initializer is not a constant!");
  479. }
  480. GlobalInitWorklist.pop_back();
  481. }
  482. while (!AliasInitWorklist.empty()) {
  483. unsigned ValID = AliasInitWorklist.back().second;
  484. if (ValID >= ValueList.size()) {
  485. AliasInits.push_back(AliasInitWorklist.back());
  486. } else {
  487. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  488. AliasInitWorklist.back().first->setAliasee(C);
  489. else
  490. return Error("Alias initializer is not a constant!");
  491. }
  492. AliasInitWorklist.pop_back();
  493. }
  494. return false;
  495. }
  496. bool BitcodeReader::ParseConstants() {
  497. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  498. return Error("Malformed block record");
  499. SmallVector<uint64_t, 64> Record;
  500. // Read all the records for this value table.
  501. const Type *CurTy = Type::Int32Ty;
  502. unsigned NextCstNo = ValueList.size();
  503. while (1) {
  504. unsigned Code = Stream.ReadCode();
  505. if (Code == bitc::END_BLOCK) {
  506. if (NextCstNo != ValueList.size())
  507. return Error("Invalid constant reference!");
  508. if (Stream.ReadBlockEnd())
  509. return Error("Error at end of constants block");
  510. return false;
  511. }
  512. if (Code == bitc::ENTER_SUBBLOCK) {
  513. // No known subblocks, always skip them.
  514. Stream.ReadSubBlockID();
  515. if (Stream.SkipBlock())
  516. return Error("Malformed block record");
  517. continue;
  518. }
  519. if (Code == bitc::DEFINE_ABBREV) {
  520. Stream.ReadAbbrevRecord();
  521. continue;
  522. }
  523. // Read a record.
  524. Record.clear();
  525. Value *V = 0;
  526. switch (Stream.ReadRecord(Code, Record)) {
  527. default: // Default behavior: unknown constant
  528. case bitc::CST_CODE_UNDEF: // UNDEF
  529. V = UndefValue::get(CurTy);
  530. break;
  531. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  532. if (Record.empty())
  533. return Error("Malformed CST_SETTYPE record");
  534. if (Record[0] >= TypeList.size())
  535. return Error("Invalid Type ID in CST_SETTYPE record");
  536. CurTy = TypeList[Record[0]];
  537. continue; // Skip the ValueList manipulation.
  538. case bitc::CST_CODE_NULL: // NULL
  539. V = Constant::getNullValue(CurTy);
  540. break;
  541. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  542. if (!isa<IntegerType>(CurTy) || Record.empty())
  543. return Error("Invalid CST_INTEGER record");
  544. V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
  545. break;
  546. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  547. if (!isa<IntegerType>(CurTy) || Record.empty())
  548. return Error("Invalid WIDE_INTEGER record");
  549. unsigned NumWords = Record.size();
  550. SmallVector<uint64_t, 8> Words;
  551. Words.resize(NumWords);
  552. for (unsigned i = 0; i != NumWords; ++i)
  553. Words[i] = DecodeSignRotatedValue(Record[i]);
  554. V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
  555. NumWords, &Words[0]));
  556. break;
  557. }
  558. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  559. if (Record.empty())
  560. return Error("Invalid FLOAT record");
  561. if (CurTy == Type::FloatTy)
  562. V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
  563. else if (CurTy == Type::DoubleTy)
  564. V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
  565. else if (CurTy == Type::X86_FP80Ty)
  566. V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
  567. else if (CurTy == Type::FP128Ty)
  568. V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
  569. else if (CurTy == Type::PPC_FP128Ty)
  570. V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
  571. else
  572. V = UndefValue::get(CurTy);
  573. break;
  574. }
  575. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  576. if (Record.empty())
  577. return Error("Invalid CST_AGGREGATE record");
  578. unsigned Size = Record.size();
  579. std::vector<Constant*> Elts;
  580. if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
  581. for (unsigned i = 0; i != Size; ++i)
  582. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  583. STy->getElementType(i)));
  584. V = ConstantStruct::get(STy, Elts);
  585. } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  586. const Type *EltTy = ATy->getElementType();
  587. for (unsigned i = 0; i != Size; ++i)
  588. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  589. V = ConstantArray::get(ATy, Elts);
  590. } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  591. const Type *EltTy = VTy->getElementType();
  592. for (unsigned i = 0; i != Size; ++i)
  593. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  594. V = ConstantVector::get(Elts);
  595. } else {
  596. V = UndefValue::get(CurTy);
  597. }
  598. break;
  599. }
  600. case bitc::CST_CODE_STRING: { // STRING: [values]
  601. if (Record.empty())
  602. return Error("Invalid CST_AGGREGATE record");
  603. const ArrayType *ATy = cast<ArrayType>(CurTy);
  604. const Type *EltTy = ATy->getElementType();
  605. unsigned Size = Record.size();
  606. std::vector<Constant*> Elts;
  607. for (unsigned i = 0; i != Size; ++i)
  608. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  609. V = ConstantArray::get(ATy, Elts);
  610. break;
  611. }
  612. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  613. if (Record.empty())
  614. return Error("Invalid CST_AGGREGATE record");
  615. const ArrayType *ATy = cast<ArrayType>(CurTy);
  616. const Type *EltTy = ATy->getElementType();
  617. unsigned Size = Record.size();
  618. std::vector<Constant*> Elts;
  619. for (unsigned i = 0; i != Size; ++i)
  620. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  621. Elts.push_back(Constant::getNullValue(EltTy));
  622. V = ConstantArray::get(ATy, Elts);
  623. break;
  624. }
  625. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  626. if (Record.size() < 3) return Error("Invalid CE_BINOP record");
  627. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  628. if (Opc < 0) {
  629. V = UndefValue::get(CurTy); // Unknown binop.
  630. } else {
  631. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  632. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  633. V = ConstantExpr::get(Opc, LHS, RHS);
  634. }
  635. break;
  636. }
  637. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  638. if (Record.size() < 3) return Error("Invalid CE_CAST record");
  639. int Opc = GetDecodedCastOpcode(Record[0]);
  640. if (Opc < 0) {
  641. V = UndefValue::get(CurTy); // Unknown cast.
  642. } else {
  643. const Type *OpTy = getTypeByID(Record[1]);
  644. if (!OpTy) return Error("Invalid CE_CAST record");
  645. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  646. V = ConstantExpr::getCast(Opc, Op, CurTy);
  647. }
  648. break;
  649. }
  650. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  651. if (Record.size() & 1) return Error("Invalid CE_GEP record");
  652. SmallVector<Constant*, 16> Elts;
  653. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  654. const Type *ElTy = getTypeByID(Record[i]);
  655. if (!ElTy) return Error("Invalid CE_GEP record");
  656. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  657. }
  658. V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
  659. break;
  660. }
  661. case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
  662. if (Record.size() < 3) return Error("Invalid CE_SELECT record");
  663. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  664. Type::Int1Ty),
  665. ValueList.getConstantFwdRef(Record[1],CurTy),
  666. ValueList.getConstantFwdRef(Record[2],CurTy));
  667. break;
  668. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  669. if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
  670. const VectorType *OpTy =
  671. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  672. if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
  673. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  674. Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
  675. OpTy->getElementType());
  676. V = ConstantExpr::getExtractElement(Op0, Op1);
  677. break;
  678. }
  679. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  680. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  681. if (Record.size() < 3 || OpTy == 0)
  682. return Error("Invalid CE_INSERTELT record");
  683. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  684. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  685. OpTy->getElementType());
  686. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
  687. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  688. break;
  689. }
  690. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  691. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  692. if (Record.size() < 3 || OpTy == 0)
  693. return Error("Invalid CE_INSERTELT record");
  694. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  695. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  696. const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
  697. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  698. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  699. break;
  700. }
  701. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  702. if (Record.size() < 4) return Error("Invalid CE_CMP record");
  703. const Type *OpTy = getTypeByID(Record[0]);
  704. if (OpTy == 0) return Error("Invalid CE_CMP record");
  705. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  706. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  707. if (OpTy->isFloatingPoint())
  708. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  709. else
  710. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  711. break;
  712. }
  713. case bitc::CST_CODE_INLINEASM: {
  714. if (Record.size() < 2) return Error("Invalid INLINEASM record");
  715. std::string AsmStr, ConstrStr;
  716. bool HasSideEffects = Record[0];
  717. unsigned AsmStrSize = Record[1];
  718. if (2+AsmStrSize >= Record.size())
  719. return Error("Invalid INLINEASM record");
  720. unsigned ConstStrSize = Record[2+AsmStrSize];
  721. if (3+AsmStrSize+ConstStrSize > Record.size())
  722. return Error("Invalid INLINEASM record");
  723. for (unsigned i = 0; i != AsmStrSize; ++i)
  724. AsmStr += (char)Record[2+i];
  725. for (unsigned i = 0; i != ConstStrSize; ++i)
  726. ConstrStr += (char)Record[3+AsmStrSize+i];
  727. const PointerType *PTy = cast<PointerType>(CurTy);
  728. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  729. AsmStr, ConstrStr, HasSideEffects);
  730. break;
  731. }
  732. }
  733. ValueList.AssignValue(V, NextCstNo);
  734. ++NextCstNo;
  735. }
  736. }
  737. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  738. /// remember where it is and then skip it. This lets us lazily deserialize the
  739. /// functions.
  740. bool BitcodeReader::RememberAndSkipFunctionBody() {
  741. // Get the function we are talking about.
  742. if (FunctionsWithBodies.empty())
  743. return Error("Insufficient function protos");
  744. Function *Fn = FunctionsWithBodies.back();
  745. FunctionsWithBodies.pop_back();
  746. // Save the current stream state.
  747. uint64_t CurBit = Stream.GetCurrentBitNo();
  748. DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
  749. // Set the functions linkage to GhostLinkage so we know it is lazily
  750. // deserialized.
  751. Fn->setLinkage(GlobalValue::GhostLinkage);
  752. // Skip over the function block for now.
  753. if (Stream.SkipBlock())
  754. return Error("Malformed block record");
  755. return false;
  756. }
  757. bool BitcodeReader::ParseModule(const std::string &ModuleID) {
  758. // Reject multiple MODULE_BLOCK's in a single bitstream.
  759. if (TheModule)
  760. return Error("Multiple MODULE_BLOCKs in same stream");
  761. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  762. return Error("Malformed block record");
  763. // Otherwise, create the module.
  764. TheModule = new Module(ModuleID);
  765. SmallVector<uint64_t, 64> Record;
  766. std::vector<std::string> SectionTable;
  767. std::vector<std::string> CollectorTable;
  768. // Read all the records for this module.
  769. while (!Stream.AtEndOfStream()) {
  770. unsigned Code = Stream.ReadCode();
  771. if (Code == bitc::END_BLOCK) {
  772. if (Stream.ReadBlockEnd())
  773. return Error("Error at end of module block");
  774. // Patch the initializers for globals and aliases up.
  775. ResolveGlobalAndAliasInits();
  776. if (!GlobalInits.empty() || !AliasInits.empty())
  777. return Error("Malformed global initializer set");
  778. if (!FunctionsWithBodies.empty())
  779. return Error("Too few function bodies found");
  780. // Look for intrinsic functions which need to be upgraded at some point
  781. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  782. FI != FE; ++FI) {
  783. Function* NewFn;
  784. if (UpgradeIntrinsicFunction(FI, NewFn))
  785. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  786. }
  787. // Force deallocation of memory for these vectors to favor the client that
  788. // want lazy deserialization.
  789. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  790. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  791. std::vector<Function*>().swap(FunctionsWithBodies);
  792. return false;
  793. }
  794. if (Code == bitc::ENTER_SUBBLOCK) {
  795. switch (Stream.ReadSubBlockID()) {
  796. default: // Skip unknown content.
  797. if (Stream.SkipBlock())
  798. return Error("Malformed block record");
  799. break;
  800. case bitc::BLOCKINFO_BLOCK_ID:
  801. if (Stream.ReadBlockInfoBlock())
  802. return Error("Malformed BlockInfoBlock");
  803. break;
  804. case bitc::PARAMATTR_BLOCK_ID:
  805. if (ParseParamAttrBlock())
  806. return true;
  807. break;
  808. case bitc::TYPE_BLOCK_ID:
  809. if (ParseTypeTable())
  810. return true;
  811. break;
  812. case bitc::TYPE_SYMTAB_BLOCK_ID:
  813. if (ParseTypeSymbolTable())
  814. return true;
  815. break;
  816. case bitc::VALUE_SYMTAB_BLOCK_ID:
  817. if (ParseValueSymbolTable())
  818. return true;
  819. break;
  820. case bitc::CONSTANTS_BLOCK_ID:
  821. if (ParseConstants() || ResolveGlobalAndAliasInits())
  822. return true;
  823. break;
  824. case bitc::FUNCTION_BLOCK_ID:
  825. // If this is the first function body we've seen, reverse the
  826. // FunctionsWithBodies list.
  827. if (!HasReversedFunctionsWithBodies) {
  828. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  829. HasReversedFunctionsWithBodies = true;
  830. }
  831. if (RememberAndSkipFunctionBody())
  832. return true;
  833. break;
  834. }
  835. continue;
  836. }
  837. if (Code == bitc::DEFINE_ABBREV) {
  838. Stream.ReadAbbrevRecord();
  839. continue;
  840. }
  841. // Read a record.
  842. switch (Stream.ReadRecord(Code, Record)) {
  843. default: break; // Default behavior, ignore unknown content.
  844. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  845. if (Record.size() < 1)
  846. return Error("Malformed MODULE_CODE_VERSION");
  847. // Only version #0 is supported so far.
  848. if (Record[0] != 0)
  849. return Error("Unknown bitstream version!");
  850. break;
  851. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  852. std::string S;
  853. if (ConvertToString(Record, 0, S))
  854. return Error("Invalid MODULE_CODE_TRIPLE record");
  855. TheModule->setTargetTriple(S);
  856. break;
  857. }
  858. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  859. std::string S;
  860. if (ConvertToString(Record, 0, S))
  861. return Error("Invalid MODULE_CODE_DATALAYOUT record");
  862. TheModule->setDataLayout(S);
  863. break;
  864. }
  865. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  866. std::string S;
  867. if (ConvertToString(Record, 0, S))
  868. return Error("Invalid MODULE_CODE_ASM record");
  869. TheModule->setModuleInlineAsm(S);
  870. break;
  871. }
  872. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  873. std::string S;
  874. if (ConvertToString(Record, 0, S))
  875. return Error("Invalid MODULE_CODE_DEPLIB record");
  876. TheModule->addLibrary(S);
  877. break;
  878. }
  879. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  880. std::string S;
  881. if (ConvertToString(Record, 0, S))
  882. return Error("Invalid MODULE_CODE_SECTIONNAME record");
  883. SectionTable.push_back(S);
  884. break;
  885. }
  886. case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
  887. std::string S;
  888. if (ConvertToString(Record, 0, S))
  889. return Error("Invalid MODULE_CODE_COLLECTORNAME record");
  890. CollectorTable.push_back(S);
  891. break;
  892. }
  893. // GLOBALVAR: [pointer type, isconst, initid,
  894. // linkage, alignment, section, visibility, threadlocal]
  895. case bitc::MODULE_CODE_GLOBALVAR: {
  896. if (Record.size() < 6)
  897. return Error("Invalid MODULE_CODE_GLOBALVAR record");
  898. const Type *Ty = getTypeByID(Record[0]);
  899. if (!isa<PointerType>(Ty))
  900. return Error("Global not a pointer type!");
  901. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  902. Ty = cast<PointerType>(Ty)->getElementType();
  903. bool isConstant = Record[1];
  904. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  905. unsigned Alignment = (1 << Record[4]) >> 1;
  906. std::string Section;
  907. if (Record[5]) {
  908. if (Record[5]-1 >= SectionTable.size())
  909. return Error("Invalid section ID");
  910. Section = SectionTable[Record[5]-1];
  911. }
  912. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  913. if (Record.size() > 6)
  914. Visibility = GetDecodedVisibility(Record[6]);
  915. bool isThreadLocal = false;
  916. if (Record.size() > 7)
  917. isThreadLocal = Record[7];
  918. GlobalVariable *NewGV =
  919. new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
  920. isThreadLocal, AddressSpace);
  921. NewGV->setAlignment(Alignment);
  922. if (!Section.empty())
  923. NewGV->setSection(Section);
  924. NewGV->setVisibility(Visibility);
  925. NewGV->setThreadLocal(isThreadLocal);
  926. ValueList.push_back(NewGV);
  927. // Remember which value to use for the global initializer.
  928. if (unsigned InitID = Record[2])
  929. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  930. break;
  931. }
  932. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  933. // alignment, section, visibility, collector]
  934. case bitc::MODULE_CODE_FUNCTION: {
  935. if (Record.size() < 8)
  936. return Error("Invalid MODULE_CODE_FUNCTION record");
  937. const Type *Ty = getTypeByID(Record[0]);
  938. if (!isa<PointerType>(Ty))
  939. return Error("Function not a pointer type!");
  940. const FunctionType *FTy =
  941. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  942. if (!FTy)
  943. return Error("Function not a pointer to function type!");
  944. Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
  945. "", TheModule);
  946. Func->setCallingConv(Record[1]);
  947. bool isProto = Record[2];
  948. Func->setLinkage(GetDecodedLinkage(Record[3]));
  949. const ParamAttrsList *PAL = getParamAttrs(Record[4]);
  950. Func->setParamAttrs(PAL);
  951. Func->setAlignment((1 << Record[5]) >> 1);
  952. if (Record[6]) {
  953. if (Record[6]-1 >= SectionTable.size())
  954. return Error("Invalid section ID");
  955. Func->setSection(SectionTable[Record[6]-1]);
  956. }
  957. Func->setVisibility(GetDecodedVisibility(Record[7]));
  958. if (Record.size() > 8 && Record[8]) {
  959. if (Record[8]-1 > CollectorTable.size())
  960. return Error("Invalid collector ID");
  961. Func->setCollector(CollectorTable[Record[8]-1].c_str());
  962. }
  963. ValueList.push_back(Func);
  964. // If this is a function with a body, remember the prototype we are
  965. // creating now, so that we can match up the body with them later.
  966. if (!isProto)
  967. FunctionsWithBodies.push_back(Func);
  968. break;
  969. }
  970. // ALIAS: [alias type, aliasee val#, linkage]
  971. case bitc::MODULE_CODE_ALIAS: {
  972. if (Record.size() < 3)
  973. return Error("Invalid MODULE_ALIAS record");
  974. const Type *Ty = getTypeByID(Record[0]);
  975. if (!isa<PointerType>(Ty))
  976. return Error("Function not a pointer type!");
  977. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  978. "", 0, TheModule);
  979. ValueList.push_back(NewGA);
  980. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  981. break;
  982. }
  983. /// MODULE_CODE_PURGEVALS: [numvals]
  984. case bitc::MODULE_CODE_PURGEVALS:
  985. // Trim down the value list to the specified size.
  986. if (Record.size() < 1 || Record[0] > ValueList.size())
  987. return Error("Invalid MODULE_PURGEVALS record");
  988. ValueList.shrinkTo(Record[0]);
  989. break;
  990. }
  991. Record.clear();
  992. }
  993. return Error("Premature end of bitstream");
  994. }
  995. bool BitcodeReader::ParseBitcode() {
  996. TheModule = 0;
  997. if (Buffer->getBufferSize() & 3)
  998. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  999. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  1000. Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
  1001. // Sniff for the signature.
  1002. if (Stream.Read(8) != 'B' ||
  1003. Stream.Read(8) != 'C' ||
  1004. Stream.Read(4) != 0x0 ||
  1005. Stream.Read(4) != 0xC ||
  1006. Stream.Read(4) != 0xE ||
  1007. Stream.Read(4) != 0xD)
  1008. return Error("Invalid bitcode signature");
  1009. // We expect a number of well-defined blocks, though we don't necessarily
  1010. // need to understand them all.
  1011. while (!Stream.AtEndOfStream()) {
  1012. unsigned Code = Stream.ReadCode();
  1013. if (Code != bitc::ENTER_SUBBLOCK)
  1014. return Error("Invalid record at top-level");
  1015. unsigned BlockID = Stream.ReadSubBlockID();
  1016. // We only know the MODULE subblock ID.
  1017. switch (BlockID) {
  1018. case bitc::BLOCKINFO_BLOCK_ID:
  1019. if (Stream.ReadBlockInfoBlock())
  1020. return Error("Malformed BlockInfoBlock");
  1021. break;
  1022. case bitc::MODULE_BLOCK_ID:
  1023. if (ParseModule(Buffer->getBufferIdentifier()))
  1024. return true;
  1025. break;
  1026. default:
  1027. if (Stream.SkipBlock())
  1028. return Error("Malformed block record");
  1029. break;
  1030. }
  1031. }
  1032. return false;
  1033. }
  1034. /// ParseFunctionBody - Lazily parse the specified function body block.
  1035. bool BitcodeReader::ParseFunctionBody(Function *F) {
  1036. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1037. return Error("Malformed block record");
  1038. unsigned ModuleValueListSize = ValueList.size();
  1039. // Add all the function arguments to the value table.
  1040. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1041. ValueList.push_back(I);
  1042. unsigned NextValueNo = ValueList.size();
  1043. BasicBlock *CurBB = 0;
  1044. unsigned CurBBNo = 0;
  1045. // Read all the records.
  1046. SmallVector<uint64_t, 64> Record;
  1047. while (1) {
  1048. unsigned Code = Stream.ReadCode();
  1049. if (Code == bitc::END_BLOCK) {
  1050. if (Stream.ReadBlockEnd())
  1051. return Error("Error at end of function block");
  1052. break;
  1053. }
  1054. if (Code == bitc::ENTER_SUBBLOCK) {
  1055. switch (Stream.ReadSubBlockID()) {
  1056. default: // Skip unknown content.
  1057. if (Stream.SkipBlock())
  1058. return Error("Malformed block record");
  1059. break;
  1060. case bitc::CONSTANTS_BLOCK_ID:
  1061. if (ParseConstants()) return true;
  1062. NextValueNo = ValueList.size();
  1063. break;
  1064. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1065. if (ParseValueSymbolTable()) return true;
  1066. break;
  1067. }
  1068. continue;
  1069. }
  1070. if (Code == bitc::DEFINE_ABBREV) {
  1071. Stream.ReadAbbrevRecord();
  1072. continue;
  1073. }
  1074. // Read a record.
  1075. Record.clear();
  1076. Instruction *I = 0;
  1077. switch (Stream.ReadRecord(Code, Record)) {
  1078. default: // Default behavior: reject
  1079. return Error("Unknown instruction");
  1080. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  1081. if (Record.size() < 1 || Record[0] == 0)
  1082. return Error("Invalid DECLAREBLOCKS record");
  1083. // Create all the basic blocks for the function.
  1084. FunctionBBs.resize(Record[0]);
  1085. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1086. FunctionBBs[i] = new BasicBlock("", F);
  1087. CurBB = FunctionBBs[0];
  1088. continue;
  1089. case bitc::FUNC_CODE_INST_BB_UNWINDDEST: // BB_UNWINDDEST: [bb#]
  1090. if (CurBB->getUnwindDest())
  1091. return Error("Only permit one BB_UNWINDDEST per BB");
  1092. if (Record.size() != 1)
  1093. return Error("Invalid BB_UNWINDDEST record");
  1094. CurBB->setUnwindDest(getBasicBlock(Record[0]));
  1095. continue;
  1096. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  1097. unsigned OpNum = 0;
  1098. Value *LHS, *RHS;
  1099. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1100. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1101. OpNum+1 != Record.size())
  1102. return Error("Invalid BINOP record");
  1103. int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
  1104. if (Opc == -1) return Error("Invalid BINOP record");
  1105. I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
  1106. break;
  1107. }
  1108. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  1109. unsigned OpNum = 0;
  1110. Value *Op;
  1111. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1112. OpNum+2 != Record.size())
  1113. return Error("Invalid CAST record");
  1114. const Type *ResTy = getTypeByID(Record[OpNum]);
  1115. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  1116. if (Opc == -1 || ResTy == 0)
  1117. return Error("Invalid CAST record");
  1118. I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
  1119. break;
  1120. }
  1121. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  1122. unsigned OpNum = 0;
  1123. Value *BasePtr;
  1124. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  1125. return Error("Invalid GEP record");
  1126. SmallVector<Value*, 16> GEPIdx;
  1127. while (OpNum != Record.size()) {
  1128. Value *Op;
  1129. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1130. return Error("Invalid GEP record");
  1131. GEPIdx.push_back(Op);
  1132. }
  1133. I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
  1134. break;
  1135. }
  1136. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  1137. unsigned OpNum = 0;
  1138. Value *TrueVal, *FalseVal, *Cond;
  1139. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1140. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1141. getValue(Record, OpNum, Type::Int1Ty, Cond))
  1142. return Error("Invalid SELECT record");
  1143. I = new SelectInst(Cond, TrueVal, FalseVal);
  1144. break;
  1145. }
  1146. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  1147. unsigned OpNum = 0;
  1148. Value *Vec, *Idx;
  1149. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1150. getValue(Record, OpNum, Type::Int32Ty, Idx))
  1151. return Error("Invalid EXTRACTELT record");
  1152. I = new ExtractElementInst(Vec, Idx);
  1153. break;
  1154. }
  1155. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  1156. unsigned OpNum = 0;
  1157. Value *Vec, *Elt, *Idx;
  1158. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1159. getValue(Record, OpNum,
  1160. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  1161. getValue(Record, OpNum, Type::Int32Ty, Idx))
  1162. return Error("Invalid INSERTELT record");
  1163. I = new InsertElementInst(Vec, Elt, Idx);
  1164. break;
  1165. }
  1166. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  1167. unsigned OpNum = 0;
  1168. Value *Vec1, *Vec2, *Mask;
  1169. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  1170. getValue(Record, OpNum, Vec1->getType(), Vec2))
  1171. return Error("Invalid SHUFFLEVEC record");
  1172. const Type *MaskTy =
  1173. VectorType::get(Type::Int32Ty,
  1174. cast<VectorType>(Vec1->getType())->getNumElements());
  1175. if (getValue(Record, OpNum, MaskTy, Mask))
  1176. return Error("Invalid SHUFFLEVEC record");
  1177. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  1178. break;
  1179. }
  1180. case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
  1181. unsigned OpNum = 0;
  1182. Value *LHS, *RHS;
  1183. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1184. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1185. OpNum+1 != Record.size())
  1186. return Error("Invalid CMP record");
  1187. if (LHS->getType()->isFPOrFPVector())
  1188. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  1189. else
  1190. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  1191. break;
  1192. }
  1193. case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
  1194. if (Record.size() != 2)
  1195. return Error("Invalid GETRESULT record");
  1196. unsigned OpNum = 0;
  1197. Value *Op;
  1198. getValueTypePair(Record, OpNum, NextValueNo, Op);
  1199. unsigned Index = Record[1];
  1200. I = new GetResultInst(Op, Index);
  1201. break;
  1202. }
  1203. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  1204. {
  1205. unsigned Size = Record.size();
  1206. if (Size == 0) {
  1207. I = new ReturnInst();
  1208. break;
  1209. } else {
  1210. unsigned OpNum = 0;
  1211. SmallVector<Value *,4> Vs;
  1212. do {
  1213. Value *Op = NULL;
  1214. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1215. return Error("Invalid RET record");
  1216. Vs.push_back(Op);
  1217. } while(OpNum != Record.size());
  1218. // SmallVector Vs has at least one element.
  1219. I = new ReturnInst(&Vs[0], Vs.size());
  1220. break;
  1221. }
  1222. }
  1223. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  1224. if (Record.size() != 1 && Record.size() != 3)
  1225. return Error("Invalid BR record");
  1226. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  1227. if (TrueDest == 0)
  1228. return Error("Invalid BR record");
  1229. if (Record.size() == 1)
  1230. I = new BranchInst(TrueDest);
  1231. else {
  1232. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  1233. Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
  1234. if (FalseDest == 0 || Cond == 0)
  1235. return Error("Invalid BR record");
  1236. I = new BranchInst(TrueDest, FalseDest, Cond);
  1237. }
  1238. break;
  1239. }
  1240. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
  1241. if (Record.size() < 3 || (Record.size() & 1) == 0)
  1242. return Error("Invalid SWITCH record");
  1243. const Type *OpTy = getTypeByID(Record[0]);
  1244. Value *Cond = getFnValueByID(Record[1], OpTy);
  1245. BasicBlock *Default = getBasicBlock(Record[2]);
  1246. if (OpTy == 0 || Cond == 0 || Default == 0)
  1247. return Error("Invalid SWITCH record");
  1248. unsigned NumCases = (Record.size()-3)/2;
  1249. SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
  1250. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  1251. ConstantInt *CaseVal =
  1252. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  1253. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  1254. if (CaseVal == 0 || DestBB == 0) {
  1255. delete SI;
  1256. return Error("Invalid SWITCH record!");
  1257. }
  1258. SI->addCase(CaseVal, DestBB);
  1259. }
  1260. I = SI;
  1261. break;
  1262. }
  1263. case bitc::FUNC_CODE_INST_INVOKE: {
  1264. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  1265. if (Record.size() < 4) return Error("Invalid INVOKE record");
  1266. const ParamAttrsList *PAL = getParamAttrs(Record[0]);
  1267. unsigned CCInfo = Record[1];
  1268. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  1269. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  1270. unsigned OpNum = 4;
  1271. Value *Callee;
  1272. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1273. return Error("Invalid INVOKE record");
  1274. const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  1275. const FunctionType *FTy = !CalleeTy ? 0 :
  1276. dyn_cast<FunctionType>(CalleeTy->getElementType());
  1277. // Check that the right number of fixed parameters are here.
  1278. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  1279. Record.size() < OpNum+FTy->getNumParams())
  1280. return Error("Invalid INVOKE record");
  1281. SmallVector<Value*, 16> Ops;
  1282. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1283. Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1284. if (Ops.back() == 0) return Error("Invalid INVOKE record");
  1285. }
  1286. if (!FTy->isVarArg()) {
  1287. if (Record.size() != OpNum)
  1288. return Error("Invalid INVOKE record");
  1289. } else {
  1290. // Read type/value pairs for varargs params.
  1291. while (OpNum != Record.size()) {
  1292. Value *Op;
  1293. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1294. return Error("Invalid INVOKE record");
  1295. Ops.push_back(Op);
  1296. }
  1297. }
  1298. I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
  1299. cast<InvokeInst>(I)->setCallingConv(CCInfo);
  1300. cast<InvokeInst>(I)->setParamAttrs(PAL);
  1301. break;
  1302. }
  1303. case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
  1304. I = new UnwindInst();
  1305. break;
  1306. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  1307. I = new UnreachableInst();
  1308. break;
  1309. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  1310. if (Record.size() < 1 || ((Record.size()-1)&1))
  1311. return Error("Invalid PHI record");
  1312. const Type *Ty = getTypeByID(Record[0]);
  1313. if (!Ty) return Error("Invalid PHI record");
  1314. PHINode *PN = new PHINode(Ty);
  1315. PN->reserveOperandSpace(Record.size()-1);
  1316. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  1317. Value *V = getFnValueByID(Record[1+i], Ty);
  1318. BasicBlock *BB = getBasicBlock(Record[2+i]);
  1319. if (!V || !BB) return Error("Invalid PHI record");
  1320. PN->addIncoming(V, BB);
  1321. }
  1322. I = PN;
  1323. break;
  1324. }
  1325. case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
  1326. if (Record.size() < 3)
  1327. return Error("Invalid MALLOC record");
  1328. const PointerType *Ty =
  1329. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1330. Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
  1331. unsigned Align = Record[2];
  1332. if (!Ty || !Size) return Error("Invalid MALLOC record");
  1333. I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1334. break;
  1335. }
  1336. case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
  1337. unsigned OpNum = 0;
  1338. Value *Op;
  1339. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1340. OpNum != Record.size())
  1341. return Error("Invalid FREE record");
  1342. I = new FreeInst(Op);
  1343. break;
  1344. }
  1345. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
  1346. if (Record.size() < 3)
  1347. return Error("Invalid ALLOCA record");
  1348. const PointerType *Ty =
  1349. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1350. Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
  1351. unsigned Align = Record[2];
  1352. if (!Ty || !Size) return Error("Invalid ALLOCA record");
  1353. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1354. break;
  1355. }
  1356. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  1357. unsigned OpNum = 0;
  1358. Value *Op;
  1359. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1360. OpNum+2 != Record.size())
  1361. return Error("Invalid LOAD record");
  1362. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1363. break;
  1364. }
  1365. case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
  1366. unsigned OpNum = 0;
  1367. Value *Val, *Ptr;
  1368. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  1369. getValue(Record, OpNum,
  1370. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  1371. OpNum+2 != Record.size())
  1372. return Error("Invalid STORE record");
  1373. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1374. break;
  1375. }
  1376. case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
  1377. // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
  1378. unsigned OpNum = 0;
  1379. Value *Val, *Ptr;
  1380. if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
  1381. getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
  1382. OpNum+2 != Record.size())
  1383. return Error("Invalid STORE record");
  1384. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1385. break;
  1386. }
  1387. case bitc::FUNC_CODE_INST_CALL: {
  1388. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  1389. if (Record.size() < 3)
  1390. return Error("Invalid CALL record");
  1391. const ParamAttrsList *PAL = getParamAttrs(Record[0]);
  1392. unsigned CCInfo = Record[1];
  1393. unsigned OpNum = 2;
  1394. Value *Callee;
  1395. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1396. return Error("Invalid CALL record");
  1397. const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  1398. const FunctionType *FTy = 0;
  1399. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  1400. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  1401. return Error("Invalid CALL record");
  1402. SmallVector<Value*, 16> Args;
  1403. // Read the fixed params.
  1404. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1405. if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
  1406. Args.push_back(getBasicBlock(Record[OpNum]));
  1407. else
  1408. Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1409. if (Args.back() == 0) return Error("Invalid CALL record");
  1410. }
  1411. // Read type/value pairs for varargs params.
  1412. if (!FTy->isVarArg()) {
  1413. if (OpNum != Record.size())
  1414. return Error("Invalid CALL record");
  1415. } else {
  1416. while (OpNum != Record.size()) {
  1417. Value *Op;
  1418. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1419. return Error("Invalid CALL record");
  1420. Args.push_back(Op);
  1421. }
  1422. }
  1423. I = new CallInst(Callee, Args.begin(), Args.end());
  1424. cast<CallInst>(I)->setCallingConv(CCInfo>>1);
  1425. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  1426. cast<CallInst>(I)->setParamAttrs(PAL);
  1427. break;
  1428. }
  1429. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  1430. if (Record.size() < 3)
  1431. return Error("Invalid VAARG record");
  1432. const Type *OpTy = getTypeByID(Record[0]);
  1433. Value *Op = getFnValueByID(Record[1], OpTy);
  1434. const Type *ResTy = getTypeByID(Record[2]);
  1435. if (!OpTy || !Op || !ResTy)
  1436. return Error("Invalid VAARG record");
  1437. I = new VAArgInst(Op, ResTy);
  1438. break;
  1439. }
  1440. }
  1441. // Add instruction to end of current BB. If there is no current BB, reject
  1442. // this file.
  1443. if (CurBB == 0) {
  1444. delete I;
  1445. return Error("Invalid instruction with no BB");
  1446. }
  1447. CurBB->getInstList().push_back(I);
  1448. // If this was a terminator instruction, move to the next block.
  1449. if (isa<TerminatorInst>(I)) {
  1450. ++CurBBNo;
  1451. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  1452. }
  1453. // Non-void values get registered in the value table for future use.
  1454. if (I && I->getType() != Type::VoidTy)
  1455. ValueList.AssignValue(I, NextValueNo++);
  1456. }
  1457. // Check the function list for unresolved values.
  1458. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  1459. if (A->getParent() == 0) {
  1460. // We found at least one unresolved value. Nuke them all to avoid leaks.
  1461. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  1462. if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
  1463. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  1464. delete A;
  1465. }
  1466. }
  1467. return Error("Never resolved value found in function!");
  1468. }
  1469. }
  1470. // Trim the value list down to the size it was before we parsed this function.
  1471. ValueList.shrinkTo(ModuleValueListSize);
  1472. std::vector<BasicBlock*>().swap(FunctionBBs);
  1473. return false;
  1474. }
  1475. //===----------------------------------------------------------------------===//
  1476. // ModuleProvider implementation
  1477. //===----------------------------------------------------------------------===//
  1478. bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
  1479. // If it already is material, ignore the request.
  1480. if (!F->hasNotBeenReadFromBitcode()) return false;
  1481. DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
  1482. DeferredFunctionInfo.find(F);
  1483. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  1484. // Move the bit stream to the saved position of the deferred function body and
  1485. // restore the real linkage type for the function.
  1486. Stream.JumpToBit(DFII->second.first);
  1487. F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
  1488. if (ParseFunctionBody(F)) {
  1489. if (ErrInfo) *ErrInfo = ErrorString;
  1490. return true;
  1491. }
  1492. // Upgrade any old intrinsic calls in the function.
  1493. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  1494. E = UpgradedIntrinsics.end(); I != E; ++I) {
  1495. if (I->first != I->second) {
  1496. for (Value::use_iterator UI = I->first->use_begin(),
  1497. UE = I->first->use_end(); UI != UE; ) {
  1498. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  1499. UpgradeIntrinsicCall(CI, I->second);
  1500. }
  1501. }
  1502. }
  1503. return false;
  1504. }
  1505. void BitcodeReader::dematerializeFunction(Function *F) {
  1506. // If this function isn't materialized, or if it is a proto, this is a noop.
  1507. if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
  1508. return;
  1509. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  1510. // Just forget the function body, we can remat it later.
  1511. F->deleteBody();
  1512. F->setLinkage(GlobalValue::GhostLinkage);
  1513. }
  1514. Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
  1515. for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
  1516. DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
  1517. ++I) {
  1518. Function *F = I->first;
  1519. if (F->hasNotBeenReadFromBitcode() &&
  1520. materializeFunction(F, ErrInfo))
  1521. return 0;
  1522. }
  1523. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  1524. // delete the old functions to clean up. We can't do this unless the entire
  1525. // module is materialized because there could always be another function body
  1526. // with calls to the old function.
  1527. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  1528. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  1529. if (I->first != I->second) {
  1530. for (Value::use_iterator UI = I->first->use_begin(),
  1531. UE = I->first->use_end(); UI != UE; ) {
  1532. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  1533. UpgradeIntrinsicCall(CI, I->second);
  1534. }
  1535. ValueList.replaceUsesOfWith(I->first, I->second);
  1536. I->first->eraseFromParent();
  1537. }
  1538. }
  1539. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  1540. return TheModule;
  1541. }
  1542. /// This method is provided by the parent ModuleProvde class and overriden
  1543. /// here. It simply releases the module from its provided and frees up our
  1544. /// state.
  1545. /// @brief Release our hold on the generated module
  1546. Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
  1547. // Since we're losing control of this Module, we must hand it back complete
  1548. Module *M = ModuleProvider::releaseModule(ErrInfo);
  1549. FreeState();
  1550. return M;
  1551. }
  1552. //===----------------------------------------------------------------------===//
  1553. // External interface
  1554. //===----------------------------------------------------------------------===//
  1555. /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
  1556. ///
  1557. ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
  1558. std::string *ErrMsg) {
  1559. BitcodeReader *R = new BitcodeReader(Buffer);
  1560. if (R->ParseBitcode()) {
  1561. if (ErrMsg)
  1562. *ErrMsg = R->getErrorString();
  1563. // Don't let the BitcodeReader dtor delete 'Buffer'.
  1564. R->releaseMemoryBuffer();
  1565. delete R;
  1566. return 0;
  1567. }
  1568. return R;
  1569. }
  1570. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  1571. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  1572. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
  1573. BitcodeReader *R;
  1574. R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
  1575. if (!R) return 0;
  1576. // Read in the entire module.
  1577. Module *M = R->materializeModule(ErrMsg);
  1578. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  1579. // there was an error.
  1580. R->releaseMemoryBuffer();
  1581. // If there was no error, tell ModuleProvider not to delete it when its dtor
  1582. // is run.
  1583. if (M)
  1584. M = R->releaseModule(ErrMsg);
  1585. delete R;
  1586. return M;
  1587. }