BitcodeReader.cpp 66 KB

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