BitcodeReader.cpp 72 KB

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