BitcodeReader.cpp 72 KB

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