BitcodeReader.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442
  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/IntrinsicInst.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/Operator.h"
  21. #include "llvm/AutoUpgrade.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/OperandTraits.h"
  27. using namespace llvm;
  28. void BitcodeReader::FreeState() {
  29. delete Buffer;
  30. Buffer = 0;
  31. std::vector<PATypeHolder>().swap(TypeList);
  32. ValueList.clear();
  33. MDValueList.clear();
  34. std::vector<AttrListPtr>().swap(MAttributes);
  35. std::vector<BasicBlock*>().swap(FunctionBBs);
  36. std::vector<Function*>().swap(FunctionsWithBodies);
  37. DeferredFunctionInfo.clear();
  38. }
  39. //===----------------------------------------------------------------------===//
  40. // Helper functions to implement forward reference resolution, etc.
  41. //===----------------------------------------------------------------------===//
  42. /// ConvertToString - Convert a string from a record into an std::string, return
  43. /// true on failure.
  44. template<typename StrTy>
  45. static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
  46. StrTy &Result) {
  47. if (Idx > Record.size())
  48. return true;
  49. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  50. Result += (char)Record[i];
  51. return false;
  52. }
  53. static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  54. switch (Val) {
  55. default: // Map unknown/new linkages to external
  56. case 0: return GlobalValue::ExternalLinkage;
  57. case 1: return GlobalValue::WeakAnyLinkage;
  58. case 2: return GlobalValue::AppendingLinkage;
  59. case 3: return GlobalValue::InternalLinkage;
  60. case 4: return GlobalValue::LinkOnceAnyLinkage;
  61. case 5: return GlobalValue::DLLImportLinkage;
  62. case 6: return GlobalValue::DLLExportLinkage;
  63. case 7: return GlobalValue::ExternalWeakLinkage;
  64. case 8: return GlobalValue::CommonLinkage;
  65. case 9: return GlobalValue::PrivateLinkage;
  66. case 10: return GlobalValue::WeakODRLinkage;
  67. case 11: return GlobalValue::LinkOnceODRLinkage;
  68. case 12: return GlobalValue::AvailableExternallyLinkage;
  69. case 13: return GlobalValue::LinkerPrivateLinkage;
  70. }
  71. }
  72. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  73. switch (Val) {
  74. default: // Map unknown visibilities to default.
  75. case 0: return GlobalValue::DefaultVisibility;
  76. case 1: return GlobalValue::HiddenVisibility;
  77. case 2: return GlobalValue::ProtectedVisibility;
  78. }
  79. }
  80. static int GetDecodedCastOpcode(unsigned Val) {
  81. switch (Val) {
  82. default: return -1;
  83. case bitc::CAST_TRUNC : return Instruction::Trunc;
  84. case bitc::CAST_ZEXT : return Instruction::ZExt;
  85. case bitc::CAST_SEXT : return Instruction::SExt;
  86. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  87. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  88. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  89. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  90. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  91. case bitc::CAST_FPEXT : return Instruction::FPExt;
  92. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  93. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  94. case bitc::CAST_BITCAST : return Instruction::BitCast;
  95. }
  96. }
  97. static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
  98. switch (Val) {
  99. default: return -1;
  100. case bitc::BINOP_ADD:
  101. return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
  102. case bitc::BINOP_SUB:
  103. return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
  104. case bitc::BINOP_MUL:
  105. return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
  106. case bitc::BINOP_UDIV: return Instruction::UDiv;
  107. case bitc::BINOP_SDIV:
  108. return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
  109. case bitc::BINOP_UREM: return Instruction::URem;
  110. case bitc::BINOP_SREM:
  111. return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
  112. case bitc::BINOP_SHL: return Instruction::Shl;
  113. case bitc::BINOP_LSHR: return Instruction::LShr;
  114. case bitc::BINOP_ASHR: return Instruction::AShr;
  115. case bitc::BINOP_AND: return Instruction::And;
  116. case bitc::BINOP_OR: return Instruction::Or;
  117. case bitc::BINOP_XOR: return Instruction::Xor;
  118. }
  119. }
  120. namespace llvm {
  121. namespace {
  122. /// @brief A class for maintaining the slot number definition
  123. /// as a placeholder for the actual definition for forward constants defs.
  124. class ConstantPlaceHolder : public ConstantExpr {
  125. ConstantPlaceHolder(); // DO NOT IMPLEMENT
  126. void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
  127. public:
  128. // allocate space for exactly one operand
  129. void *operator new(size_t s) {
  130. return User::operator new(s, 1);
  131. }
  132. explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
  133. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  134. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  135. }
  136. /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
  137. static inline bool classof(const ConstantPlaceHolder *) { return true; }
  138. static bool classof(const Value *V) {
  139. return isa<ConstantExpr>(V) &&
  140. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  141. }
  142. /// Provide fast operand accessors
  143. //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  144. };
  145. }
  146. // FIXME: can we inherit this from ConstantExpr?
  147. template <>
  148. struct OperandTraits<ConstantPlaceHolder> : public FixedNumOperandTraits<1> {
  149. };
  150. }
  151. void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
  152. if (Idx == size()) {
  153. push_back(V);
  154. return;
  155. }
  156. if (Idx >= size())
  157. resize(Idx+1);
  158. WeakVH &OldV = ValuePtrs[Idx];
  159. if (OldV == 0) {
  160. OldV = V;
  161. return;
  162. }
  163. // Handle constants and non-constants (e.g. instrs) differently for
  164. // efficiency.
  165. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  166. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  167. OldV = V;
  168. } else {
  169. // If there was a forward reference to this value, replace it.
  170. Value *PrevVal = OldV;
  171. OldV->replaceAllUsesWith(V);
  172. delete PrevVal;
  173. }
  174. }
  175. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  176. const Type *Ty) {
  177. if (Idx >= size())
  178. resize(Idx + 1);
  179. if (Value *V = ValuePtrs[Idx]) {
  180. assert(Ty == V->getType() && "Type mismatch in constant table!");
  181. return cast<Constant>(V);
  182. }
  183. // Create and return a placeholder, which will later be RAUW'd.
  184. Constant *C = new ConstantPlaceHolder(Ty, Context);
  185. ValuePtrs[Idx] = C;
  186. return C;
  187. }
  188. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
  189. if (Idx >= size())
  190. resize(Idx + 1);
  191. if (Value *V = ValuePtrs[Idx]) {
  192. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  193. return V;
  194. }
  195. // No type specified, must be invalid reference.
  196. if (Ty == 0) return 0;
  197. // Create and return a placeholder, which will later be RAUW'd.
  198. Value *V = new Argument(Ty);
  199. ValuePtrs[Idx] = V;
  200. return V;
  201. }
  202. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  203. /// resolves any forward references. The idea behind this is that we sometimes
  204. /// get constants (such as large arrays) which reference *many* forward ref
  205. /// constants. Replacing each of these causes a lot of thrashing when
  206. /// building/reuniquing the constant. Instead of doing this, we look at all the
  207. /// uses and rewrite all the place holders at once for any constant that uses
  208. /// a placeholder.
  209. void BitcodeReaderValueList::ResolveConstantForwardRefs() {
  210. // Sort the values by-pointer so that they are efficient to look up with a
  211. // binary search.
  212. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  213. SmallVector<Constant*, 64> NewOps;
  214. while (!ResolveConstants.empty()) {
  215. Value *RealVal = operator[](ResolveConstants.back().second);
  216. Constant *Placeholder = ResolveConstants.back().first;
  217. ResolveConstants.pop_back();
  218. // Loop over all users of the placeholder, updating them to reference the
  219. // new value. If they reference more than one placeholder, update them all
  220. // at once.
  221. while (!Placeholder->use_empty()) {
  222. Value::use_iterator UI = Placeholder->use_begin();
  223. // If the using object isn't uniqued, just update the operands. This
  224. // handles instructions and initializers for global variables.
  225. if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
  226. UI.getUse().set(RealVal);
  227. continue;
  228. }
  229. // Otherwise, we have a constant that uses the placeholder. Replace that
  230. // constant with a new constant that has *all* placeholder uses updated.
  231. Constant *UserC = cast<Constant>(*UI);
  232. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  233. I != E; ++I) {
  234. Value *NewOp;
  235. if (!isa<ConstantPlaceHolder>(*I)) {
  236. // Not a placeholder reference.
  237. NewOp = *I;
  238. } else if (*I == Placeholder) {
  239. // Common case is that it just references this one placeholder.
  240. NewOp = RealVal;
  241. } else {
  242. // Otherwise, look up the placeholder in ResolveConstants.
  243. ResolveConstantsTy::iterator It =
  244. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  245. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  246. 0));
  247. assert(It != ResolveConstants.end() && It->first == *I);
  248. NewOp = operator[](It->second);
  249. }
  250. NewOps.push_back(cast<Constant>(NewOp));
  251. }
  252. // Make the new constant.
  253. Constant *NewC;
  254. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  255. NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
  256. NewOps.size());
  257. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  258. NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
  259. UserCS->getType()->isPacked());
  260. } else if (isa<ConstantVector>(UserC)) {
  261. NewC = ConstantVector::get(&NewOps[0], NewOps.size());
  262. } else {
  263. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  264. NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
  265. NewOps.size());
  266. }
  267. UserC->replaceAllUsesWith(NewC);
  268. UserC->destroyConstant();
  269. NewOps.clear();
  270. }
  271. // Update all ValueHandles, they should be the only users at this point.
  272. Placeholder->replaceAllUsesWith(RealVal);
  273. delete Placeholder;
  274. }
  275. }
  276. void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
  277. if (Idx == size()) {
  278. push_back(V);
  279. return;
  280. }
  281. if (Idx >= size())
  282. resize(Idx+1);
  283. WeakVH &OldV = MDValuePtrs[Idx];
  284. if (OldV == 0) {
  285. OldV = V;
  286. return;
  287. }
  288. // If there was a forward reference to this value, replace it.
  289. Value *PrevVal = OldV;
  290. OldV->replaceAllUsesWith(V);
  291. delete PrevVal;
  292. // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
  293. // value for Idx.
  294. MDValuePtrs[Idx] = V;
  295. }
  296. Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  297. if (Idx >= size())
  298. resize(Idx + 1);
  299. if (Value *V = MDValuePtrs[Idx]) {
  300. assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
  301. return V;
  302. }
  303. // Create and return a placeholder, which will later be RAUW'd.
  304. Value *V = new Argument(Type::getMetadataTy(Context));
  305. MDValuePtrs[Idx] = V;
  306. return V;
  307. }
  308. const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
  309. // If the TypeID is in range, return it.
  310. if (ID < TypeList.size())
  311. return TypeList[ID].get();
  312. if (!isTypeTable) return 0;
  313. // The type table allows forward references. Push as many Opaque types as
  314. // needed to get up to ID.
  315. while (TypeList.size() <= ID)
  316. TypeList.push_back(OpaqueType::get(Context));
  317. return TypeList.back().get();
  318. }
  319. //===----------------------------------------------------------------------===//
  320. // Functions for parsing blocks from the bitcode file
  321. //===----------------------------------------------------------------------===//
  322. bool BitcodeReader::ParseAttributeBlock() {
  323. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  324. return Error("Malformed block record");
  325. if (!MAttributes.empty())
  326. return Error("Multiple PARAMATTR blocks found!");
  327. SmallVector<uint64_t, 64> Record;
  328. SmallVector<AttributeWithIndex, 8> Attrs;
  329. // Read all the records.
  330. while (1) {
  331. unsigned Code = Stream.ReadCode();
  332. if (Code == bitc::END_BLOCK) {
  333. if (Stream.ReadBlockEnd())
  334. return Error("Error at end of PARAMATTR block");
  335. return false;
  336. }
  337. if (Code == bitc::ENTER_SUBBLOCK) {
  338. // No known subblocks, always skip them.
  339. Stream.ReadSubBlockID();
  340. if (Stream.SkipBlock())
  341. return Error("Malformed block record");
  342. continue;
  343. }
  344. if (Code == bitc::DEFINE_ABBREV) {
  345. Stream.ReadAbbrevRecord();
  346. continue;
  347. }
  348. // Read a record.
  349. Record.clear();
  350. switch (Stream.ReadRecord(Code, Record)) {
  351. default: // Default behavior: ignore.
  352. break;
  353. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
  354. if (Record.size() & 1)
  355. return Error("Invalid ENTRY record");
  356. // FIXME : Remove this autoupgrade code in LLVM 3.0.
  357. // If Function attributes are using index 0 then transfer them
  358. // to index ~0. Index 0 is used for return value attributes but used to be
  359. // used for function attributes.
  360. Attributes RetAttribute = Attribute::None;
  361. Attributes FnAttribute = Attribute::None;
  362. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  363. // FIXME: remove in LLVM 3.0
  364. // The alignment is stored as a 16-bit raw value from bits 31--16.
  365. // We shift the bits above 31 down by 11 bits.
  366. unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
  367. if (Alignment && !isPowerOf2_32(Alignment))
  368. return Error("Alignment is not a power of two.");
  369. Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
  370. if (Alignment)
  371. ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
  372. ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
  373. Record[i+1] = ReconstitutedAttr;
  374. if (Record[i] == 0)
  375. RetAttribute = Record[i+1];
  376. else if (Record[i] == ~0U)
  377. FnAttribute = Record[i+1];
  378. }
  379. unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
  380. Attribute::ReadOnly|Attribute::ReadNone);
  381. if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
  382. (RetAttribute & OldRetAttrs) != 0) {
  383. if (FnAttribute == Attribute::None) { // add a slot so they get added.
  384. Record.push_back(~0U);
  385. Record.push_back(0);
  386. }
  387. FnAttribute |= RetAttribute & OldRetAttrs;
  388. RetAttribute &= ~OldRetAttrs;
  389. }
  390. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  391. if (Record[i] == 0) {
  392. if (RetAttribute != Attribute::None)
  393. Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
  394. } else if (Record[i] == ~0U) {
  395. if (FnAttribute != Attribute::None)
  396. Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
  397. } else if (Record[i+1] != Attribute::None)
  398. Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
  399. }
  400. MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
  401. Attrs.clear();
  402. break;
  403. }
  404. }
  405. }
  406. }
  407. bool BitcodeReader::ParseTypeTable() {
  408. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
  409. return Error("Malformed block record");
  410. if (!TypeList.empty())
  411. return Error("Multiple TYPE_BLOCKs found!");
  412. SmallVector<uint64_t, 64> Record;
  413. unsigned NumRecords = 0;
  414. // Read all the records for this type table.
  415. while (1) {
  416. unsigned Code = Stream.ReadCode();
  417. if (Code == bitc::END_BLOCK) {
  418. if (NumRecords != TypeList.size())
  419. return Error("Invalid type forward reference in TYPE_BLOCK");
  420. if (Stream.ReadBlockEnd())
  421. return Error("Error at end of type table block");
  422. return false;
  423. }
  424. if (Code == bitc::ENTER_SUBBLOCK) {
  425. // No known subblocks, always skip them.
  426. Stream.ReadSubBlockID();
  427. if (Stream.SkipBlock())
  428. return Error("Malformed block record");
  429. continue;
  430. }
  431. if (Code == bitc::DEFINE_ABBREV) {
  432. Stream.ReadAbbrevRecord();
  433. continue;
  434. }
  435. // Read a record.
  436. Record.clear();
  437. const Type *ResultTy = 0;
  438. switch (Stream.ReadRecord(Code, Record)) {
  439. default: // Default behavior: unknown type.
  440. ResultTy = 0;
  441. break;
  442. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  443. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  444. // type list. This allows us to reserve space.
  445. if (Record.size() < 1)
  446. return Error("Invalid TYPE_CODE_NUMENTRY record");
  447. TypeList.reserve(Record[0]);
  448. continue;
  449. case bitc::TYPE_CODE_VOID: // VOID
  450. ResultTy = Type::getVoidTy(Context);
  451. break;
  452. case bitc::TYPE_CODE_FLOAT: // FLOAT
  453. ResultTy = Type::getFloatTy(Context);
  454. break;
  455. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  456. ResultTy = Type::getDoubleTy(Context);
  457. break;
  458. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  459. ResultTy = Type::getX86_FP80Ty(Context);
  460. break;
  461. case bitc::TYPE_CODE_FP128: // FP128
  462. ResultTy = Type::getFP128Ty(Context);
  463. break;
  464. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  465. ResultTy = Type::getPPC_FP128Ty(Context);
  466. break;
  467. case bitc::TYPE_CODE_LABEL: // LABEL
  468. ResultTy = Type::getLabelTy(Context);
  469. break;
  470. case bitc::TYPE_CODE_OPAQUE: // OPAQUE
  471. ResultTy = 0;
  472. break;
  473. case bitc::TYPE_CODE_METADATA: // METADATA
  474. ResultTy = Type::getMetadataTy(Context);
  475. break;
  476. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  477. if (Record.size() < 1)
  478. return Error("Invalid Integer type record");
  479. ResultTy = IntegerType::get(Context, Record[0]);
  480. break;
  481. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  482. // [pointee type, address space]
  483. if (Record.size() < 1)
  484. return Error("Invalid POINTER type record");
  485. unsigned AddressSpace = 0;
  486. if (Record.size() == 2)
  487. AddressSpace = Record[1];
  488. ResultTy = PointerType::get(getTypeByID(Record[0], true),
  489. AddressSpace);
  490. break;
  491. }
  492. case bitc::TYPE_CODE_FUNCTION: {
  493. // FIXME: attrid is dead, remove it in LLVM 3.0
  494. // FUNCTION: [vararg, attrid, retty, paramty x N]
  495. if (Record.size() < 3)
  496. return Error("Invalid FUNCTION type record");
  497. std::vector<const Type*> ArgTys;
  498. for (unsigned i = 3, e = Record.size(); i != e; ++i)
  499. ArgTys.push_back(getTypeByID(Record[i], true));
  500. ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
  501. Record[0]);
  502. break;
  503. }
  504. case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
  505. if (Record.size() < 1)
  506. return Error("Invalid STRUCT type record");
  507. std::vector<const Type*> EltTys;
  508. for (unsigned i = 1, e = Record.size(); i != e; ++i)
  509. EltTys.push_back(getTypeByID(Record[i], true));
  510. ResultTy = StructType::get(Context, EltTys, Record[0]);
  511. break;
  512. }
  513. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  514. if (Record.size() < 2)
  515. return Error("Invalid ARRAY type record");
  516. ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
  517. break;
  518. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  519. if (Record.size() < 2)
  520. return Error("Invalid VECTOR type record");
  521. ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
  522. break;
  523. }
  524. if (NumRecords == TypeList.size()) {
  525. // If this is a new type slot, just append it.
  526. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
  527. ++NumRecords;
  528. } else if (ResultTy == 0) {
  529. // Otherwise, this was forward referenced, so an opaque type was created,
  530. // but the result type is actually just an opaque. Leave the one we
  531. // created previously.
  532. ++NumRecords;
  533. } else {
  534. // Otherwise, this was forward referenced, so an opaque type was created.
  535. // Resolve the opaque type to the real type now.
  536. assert(NumRecords < TypeList.size() && "Typelist imbalance");
  537. const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
  538. // Don't directly push the new type on the Tab. Instead we want to replace
  539. // the opaque type we previously inserted with the new concrete value. The
  540. // refinement from the abstract (opaque) type to the new type causes all
  541. // uses of the abstract type to use the concrete type (NewTy). This will
  542. // also cause the opaque type to be deleted.
  543. const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
  544. // This should have replaced the old opaque type with the new type in the
  545. // value table... or with a preexisting type that was already in the
  546. // system. Let's just make sure it did.
  547. assert(TypeList[NumRecords-1].get() != OldTy &&
  548. "refineAbstractType didn't work!");
  549. }
  550. }
  551. }
  552. bool BitcodeReader::ParseTypeSymbolTable() {
  553. if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
  554. return Error("Malformed block record");
  555. SmallVector<uint64_t, 64> Record;
  556. // Read all the records for this type table.
  557. std::string TypeName;
  558. while (1) {
  559. unsigned Code = Stream.ReadCode();
  560. if (Code == bitc::END_BLOCK) {
  561. if (Stream.ReadBlockEnd())
  562. return Error("Error at end of type symbol table block");
  563. return false;
  564. }
  565. if (Code == bitc::ENTER_SUBBLOCK) {
  566. // No known subblocks, always skip them.
  567. Stream.ReadSubBlockID();
  568. if (Stream.SkipBlock())
  569. return Error("Malformed block record");
  570. continue;
  571. }
  572. if (Code == bitc::DEFINE_ABBREV) {
  573. Stream.ReadAbbrevRecord();
  574. continue;
  575. }
  576. // Read a record.
  577. Record.clear();
  578. switch (Stream.ReadRecord(Code, Record)) {
  579. default: // Default behavior: unknown type.
  580. break;
  581. case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
  582. if (ConvertToString(Record, 1, TypeName))
  583. return Error("Invalid TST_ENTRY record");
  584. unsigned TypeID = Record[0];
  585. if (TypeID >= TypeList.size())
  586. return Error("Invalid Type ID in TST_ENTRY record");
  587. TheModule->addTypeName(TypeName, TypeList[TypeID].get());
  588. TypeName.clear();
  589. break;
  590. }
  591. }
  592. }
  593. bool BitcodeReader::ParseValueSymbolTable() {
  594. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  595. return Error("Malformed block record");
  596. SmallVector<uint64_t, 64> Record;
  597. // Read all the records for this value table.
  598. SmallString<128> ValueName;
  599. while (1) {
  600. unsigned Code = Stream.ReadCode();
  601. if (Code == bitc::END_BLOCK) {
  602. if (Stream.ReadBlockEnd())
  603. return Error("Error at end of value symbol table block");
  604. return false;
  605. }
  606. if (Code == bitc::ENTER_SUBBLOCK) {
  607. // No known subblocks, always skip them.
  608. Stream.ReadSubBlockID();
  609. if (Stream.SkipBlock())
  610. return Error("Malformed block record");
  611. continue;
  612. }
  613. if (Code == bitc::DEFINE_ABBREV) {
  614. Stream.ReadAbbrevRecord();
  615. continue;
  616. }
  617. // Read a record.
  618. Record.clear();
  619. switch (Stream.ReadRecord(Code, Record)) {
  620. default: // Default behavior: unknown type.
  621. break;
  622. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  623. if (ConvertToString(Record, 1, ValueName))
  624. return Error("Invalid VST_ENTRY record");
  625. unsigned ValueID = Record[0];
  626. if (ValueID >= ValueList.size())
  627. return Error("Invalid Value ID in VST_ENTRY record");
  628. Value *V = ValueList[ValueID];
  629. V->setName(StringRef(ValueName.data(), ValueName.size()));
  630. ValueName.clear();
  631. break;
  632. }
  633. case bitc::VST_CODE_BBENTRY: {
  634. if (ConvertToString(Record, 1, ValueName))
  635. return Error("Invalid VST_BBENTRY record");
  636. BasicBlock *BB = getBasicBlock(Record[0]);
  637. if (BB == 0)
  638. return Error("Invalid BB ID in VST_BBENTRY record");
  639. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  640. ValueName.clear();
  641. break;
  642. }
  643. }
  644. }
  645. }
  646. bool BitcodeReader::ParseMetadata() {
  647. unsigned NextValueNo = MDValueList.size();
  648. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  649. return Error("Malformed block record");
  650. SmallVector<uint64_t, 64> Record;
  651. // Read all the records.
  652. while (1) {
  653. unsigned Code = Stream.ReadCode();
  654. if (Code == bitc::END_BLOCK) {
  655. if (Stream.ReadBlockEnd())
  656. return Error("Error at end of PARAMATTR block");
  657. return false;
  658. }
  659. if (Code == bitc::ENTER_SUBBLOCK) {
  660. // No known subblocks, always skip them.
  661. Stream.ReadSubBlockID();
  662. if (Stream.SkipBlock())
  663. return Error("Malformed block record");
  664. continue;
  665. }
  666. if (Code == bitc::DEFINE_ABBREV) {
  667. Stream.ReadAbbrevRecord();
  668. continue;
  669. }
  670. bool IsFunctionLocal = false;
  671. // Read a record.
  672. Record.clear();
  673. switch (Stream.ReadRecord(Code, Record)) {
  674. default: // Default behavior: ignore.
  675. break;
  676. case bitc::METADATA_NAME: {
  677. // Read named of the named metadata.
  678. unsigned NameLength = Record.size();
  679. SmallString<8> Name;
  680. Name.resize(NameLength);
  681. for (unsigned i = 0; i != NameLength; ++i)
  682. Name[i] = Record[i];
  683. Record.clear();
  684. Code = Stream.ReadCode();
  685. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  686. if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
  687. assert ( 0 && "Inavlid Named Metadata record");
  688. // Read named metadata elements.
  689. unsigned Size = Record.size();
  690. SmallVector<MDNode *, 8> Elts;
  691. for (unsigned i = 0; i != Size; ++i) {
  692. if (Record[i] == ~0U) {
  693. Elts.push_back(NULL);
  694. continue;
  695. }
  696. MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  697. if (MD == 0)
  698. return Error("Malformed metadata record");
  699. Elts.push_back(MD);
  700. }
  701. Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
  702. Elts.size(), TheModule);
  703. // FIXME: This shouldn't poke NextValueNo?
  704. MDValueList.AssignValue(V, NextValueNo++);
  705. break;
  706. }
  707. case bitc::METADATA_FN_NODE:
  708. IsFunctionLocal = true;
  709. // fall-through
  710. case bitc::METADATA_NODE: {
  711. if (Record.empty() || Record.size() % 2 == 1)
  712. return Error("Invalid METADATA_NODE record");
  713. unsigned Size = Record.size();
  714. SmallVector<Value*, 8> Elts;
  715. for (unsigned i = 0; i != Size; i += 2) {
  716. const Type *Ty = getTypeByID(Record[i], false);
  717. if (Ty->isMetadataTy())
  718. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  719. else if (!Ty->isVoidTy())
  720. Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
  721. else
  722. Elts.push_back(NULL);
  723. }
  724. Value *V = MDNode::getWhenValsUnresolved(Context, &Elts[0], Elts.size(),
  725. IsFunctionLocal);
  726. IsFunctionLocal = false;
  727. MDValueList.AssignValue(V, NextValueNo++);
  728. break;
  729. }
  730. case bitc::METADATA_STRING: {
  731. unsigned MDStringLength = Record.size();
  732. SmallString<8> String;
  733. String.resize(MDStringLength);
  734. for (unsigned i = 0; i != MDStringLength; ++i)
  735. String[i] = Record[i];
  736. Value *V = MDString::get(Context,
  737. StringRef(String.data(), String.size()));
  738. MDValueList.AssignValue(V, NextValueNo++);
  739. break;
  740. }
  741. case bitc::METADATA_KIND: {
  742. unsigned RecordLength = Record.size();
  743. if (Record.empty() || RecordLength < 2)
  744. return Error("Invalid METADATA_KIND record");
  745. SmallString<8> Name;
  746. Name.resize(RecordLength-1);
  747. unsigned Kind = Record[0];
  748. (void) Kind;
  749. for (unsigned i = 1; i != RecordLength; ++i)
  750. Name[i-1] = Record[i];
  751. unsigned NewKind = TheModule->getMDKindID(Name.str());
  752. assert(Kind == NewKind &&
  753. "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind;
  754. break;
  755. }
  756. }
  757. }
  758. }
  759. /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
  760. /// the LSB for dense VBR encoding.
  761. static uint64_t DecodeSignRotatedValue(uint64_t V) {
  762. if ((V & 1) == 0)
  763. return V >> 1;
  764. if (V != 1)
  765. return -(V >> 1);
  766. // There is no such thing as -0 with integers. "-0" really means MININT.
  767. return 1ULL << 63;
  768. }
  769. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  770. /// values and aliases that we can.
  771. bool BitcodeReader::ResolveGlobalAndAliasInits() {
  772. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  773. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  774. GlobalInitWorklist.swap(GlobalInits);
  775. AliasInitWorklist.swap(AliasInits);
  776. while (!GlobalInitWorklist.empty()) {
  777. unsigned ValID = GlobalInitWorklist.back().second;
  778. if (ValID >= ValueList.size()) {
  779. // Not ready to resolve this yet, it requires something later in the file.
  780. GlobalInits.push_back(GlobalInitWorklist.back());
  781. } else {
  782. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  783. GlobalInitWorklist.back().first->setInitializer(C);
  784. else
  785. return Error("Global variable initializer is not a constant!");
  786. }
  787. GlobalInitWorklist.pop_back();
  788. }
  789. while (!AliasInitWorklist.empty()) {
  790. unsigned ValID = AliasInitWorklist.back().second;
  791. if (ValID >= ValueList.size()) {
  792. AliasInits.push_back(AliasInitWorklist.back());
  793. } else {
  794. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  795. AliasInitWorklist.back().first->setAliasee(C);
  796. else
  797. return Error("Alias initializer is not a constant!");
  798. }
  799. AliasInitWorklist.pop_back();
  800. }
  801. return false;
  802. }
  803. bool BitcodeReader::ParseConstants() {
  804. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  805. return Error("Malformed block record");
  806. SmallVector<uint64_t, 64> Record;
  807. // Read all the records for this value table.
  808. const Type *CurTy = Type::getInt32Ty(Context);
  809. unsigned NextCstNo = ValueList.size();
  810. while (1) {
  811. unsigned Code = Stream.ReadCode();
  812. if (Code == bitc::END_BLOCK)
  813. break;
  814. if (Code == bitc::ENTER_SUBBLOCK) {
  815. // No known subblocks, always skip them.
  816. Stream.ReadSubBlockID();
  817. if (Stream.SkipBlock())
  818. return Error("Malformed block record");
  819. continue;
  820. }
  821. if (Code == bitc::DEFINE_ABBREV) {
  822. Stream.ReadAbbrevRecord();
  823. continue;
  824. }
  825. // Read a record.
  826. Record.clear();
  827. Value *V = 0;
  828. unsigned BitCode = Stream.ReadRecord(Code, Record);
  829. switch (BitCode) {
  830. default: // Default behavior: unknown constant
  831. case bitc::CST_CODE_UNDEF: // UNDEF
  832. V = UndefValue::get(CurTy);
  833. break;
  834. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  835. if (Record.empty())
  836. return Error("Malformed CST_SETTYPE record");
  837. if (Record[0] >= TypeList.size())
  838. return Error("Invalid Type ID in CST_SETTYPE record");
  839. CurTy = TypeList[Record[0]];
  840. continue; // Skip the ValueList manipulation.
  841. case bitc::CST_CODE_NULL: // NULL
  842. V = Constant::getNullValue(CurTy);
  843. break;
  844. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  845. if (!isa<IntegerType>(CurTy) || Record.empty())
  846. return Error("Invalid CST_INTEGER record");
  847. V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
  848. break;
  849. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  850. if (!isa<IntegerType>(CurTy) || Record.empty())
  851. return Error("Invalid WIDE_INTEGER record");
  852. unsigned NumWords = Record.size();
  853. SmallVector<uint64_t, 8> Words;
  854. Words.resize(NumWords);
  855. for (unsigned i = 0; i != NumWords; ++i)
  856. Words[i] = DecodeSignRotatedValue(Record[i]);
  857. V = ConstantInt::get(Context,
  858. APInt(cast<IntegerType>(CurTy)->getBitWidth(),
  859. NumWords, &Words[0]));
  860. break;
  861. }
  862. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  863. if (Record.empty())
  864. return Error("Invalid FLOAT record");
  865. if (CurTy->isFloatTy())
  866. V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
  867. else if (CurTy->isDoubleTy())
  868. V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
  869. else if (CurTy->isX86_FP80Ty()) {
  870. // Bits are not stored the same way as a normal i80 APInt, compensate.
  871. uint64_t Rearrange[2];
  872. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  873. Rearrange[1] = Record[0] >> 48;
  874. V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
  875. } else if (CurTy->isFP128Ty())
  876. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
  877. else if (CurTy->isPPC_FP128Ty())
  878. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
  879. else
  880. V = UndefValue::get(CurTy);
  881. break;
  882. }
  883. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  884. if (Record.empty())
  885. return Error("Invalid CST_AGGREGATE record");
  886. unsigned Size = Record.size();
  887. std::vector<Constant*> Elts;
  888. if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
  889. for (unsigned i = 0; i != Size; ++i)
  890. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  891. STy->getElementType(i)));
  892. V = ConstantStruct::get(STy, Elts);
  893. } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  894. const Type *EltTy = ATy->getElementType();
  895. for (unsigned i = 0; i != Size; ++i)
  896. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  897. V = ConstantArray::get(ATy, Elts);
  898. } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  899. const Type *EltTy = VTy->getElementType();
  900. for (unsigned i = 0; i != Size; ++i)
  901. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  902. V = ConstantVector::get(Elts);
  903. } else {
  904. V = UndefValue::get(CurTy);
  905. }
  906. break;
  907. }
  908. case bitc::CST_CODE_STRING: { // STRING: [values]
  909. if (Record.empty())
  910. return Error("Invalid CST_AGGREGATE record");
  911. const ArrayType *ATy = cast<ArrayType>(CurTy);
  912. const Type *EltTy = ATy->getElementType();
  913. unsigned Size = Record.size();
  914. std::vector<Constant*> Elts;
  915. for (unsigned i = 0; i != Size; ++i)
  916. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  917. V = ConstantArray::get(ATy, Elts);
  918. break;
  919. }
  920. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  921. if (Record.empty())
  922. return Error("Invalid CST_AGGREGATE record");
  923. const ArrayType *ATy = cast<ArrayType>(CurTy);
  924. const Type *EltTy = ATy->getElementType();
  925. unsigned Size = Record.size();
  926. std::vector<Constant*> Elts;
  927. for (unsigned i = 0; i != Size; ++i)
  928. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  929. Elts.push_back(Constant::getNullValue(EltTy));
  930. V = ConstantArray::get(ATy, Elts);
  931. break;
  932. }
  933. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  934. if (Record.size() < 3) return Error("Invalid CE_BINOP record");
  935. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  936. if (Opc < 0) {
  937. V = UndefValue::get(CurTy); // Unknown binop.
  938. } else {
  939. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  940. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  941. unsigned Flags = 0;
  942. if (Record.size() >= 4) {
  943. if (Opc == Instruction::Add ||
  944. Opc == Instruction::Sub ||
  945. Opc == Instruction::Mul) {
  946. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  947. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  948. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  949. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  950. } else if (Opc == Instruction::SDiv) {
  951. if (Record[3] & (1 << bitc::SDIV_EXACT))
  952. Flags |= SDivOperator::IsExact;
  953. }
  954. }
  955. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  956. }
  957. break;
  958. }
  959. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  960. if (Record.size() < 3) return Error("Invalid CE_CAST record");
  961. int Opc = GetDecodedCastOpcode(Record[0]);
  962. if (Opc < 0) {
  963. V = UndefValue::get(CurTy); // Unknown cast.
  964. } else {
  965. const Type *OpTy = getTypeByID(Record[1]);
  966. if (!OpTy) return Error("Invalid CE_CAST record");
  967. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  968. V = ConstantExpr::getCast(Opc, Op, CurTy);
  969. }
  970. break;
  971. }
  972. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  973. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  974. if (Record.size() & 1) return Error("Invalid CE_GEP record");
  975. SmallVector<Constant*, 16> Elts;
  976. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  977. const Type *ElTy = getTypeByID(Record[i]);
  978. if (!ElTy) return Error("Invalid CE_GEP record");
  979. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  980. }
  981. if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
  982. V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
  983. Elts.size()-1);
  984. else
  985. V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
  986. Elts.size()-1);
  987. break;
  988. }
  989. case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
  990. if (Record.size() < 3) return Error("Invalid CE_SELECT record");
  991. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  992. Type::getInt1Ty(Context)),
  993. ValueList.getConstantFwdRef(Record[1],CurTy),
  994. ValueList.getConstantFwdRef(Record[2],CurTy));
  995. break;
  996. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  997. if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
  998. const VectorType *OpTy =
  999. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1000. if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
  1001. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1002. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1003. V = ConstantExpr::getExtractElement(Op0, Op1);
  1004. break;
  1005. }
  1006. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  1007. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1008. if (Record.size() < 3 || OpTy == 0)
  1009. return Error("Invalid CE_INSERTELT record");
  1010. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1011. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  1012. OpTy->getElementType());
  1013. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1014. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  1015. break;
  1016. }
  1017. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  1018. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1019. if (Record.size() < 3 || OpTy == 0)
  1020. return Error("Invalid CE_SHUFFLEVEC record");
  1021. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1022. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1023. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1024. OpTy->getNumElements());
  1025. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  1026. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1027. break;
  1028. }
  1029. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  1030. const VectorType *RTy = dyn_cast<VectorType>(CurTy);
  1031. const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
  1032. if (Record.size() < 4 || RTy == 0 || OpTy == 0)
  1033. return Error("Invalid CE_SHUFVEC_EX record");
  1034. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1035. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1036. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1037. RTy->getNumElements());
  1038. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  1039. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1040. break;
  1041. }
  1042. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  1043. if (Record.size() < 4) return Error("Invalid CE_CMP record");
  1044. const Type *OpTy = getTypeByID(Record[0]);
  1045. if (OpTy == 0) return Error("Invalid CE_CMP record");
  1046. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1047. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1048. if (OpTy->isFloatingPoint())
  1049. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  1050. else
  1051. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  1052. break;
  1053. }
  1054. case bitc::CST_CODE_INLINEASM: {
  1055. if (Record.size() < 2) return Error("Invalid INLINEASM record");
  1056. std::string AsmStr, ConstrStr;
  1057. bool HasSideEffects = Record[0] & 1;
  1058. bool IsAlignStack = Record[0] >> 1;
  1059. unsigned AsmStrSize = Record[1];
  1060. if (2+AsmStrSize >= Record.size())
  1061. return Error("Invalid INLINEASM record");
  1062. unsigned ConstStrSize = Record[2+AsmStrSize];
  1063. if (3+AsmStrSize+ConstStrSize > Record.size())
  1064. return Error("Invalid INLINEASM record");
  1065. for (unsigned i = 0; i != AsmStrSize; ++i)
  1066. AsmStr += (char)Record[2+i];
  1067. for (unsigned i = 0; i != ConstStrSize; ++i)
  1068. ConstrStr += (char)Record[3+AsmStrSize+i];
  1069. const PointerType *PTy = cast<PointerType>(CurTy);
  1070. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1071. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  1072. break;
  1073. }
  1074. case bitc::CST_CODE_BLOCKADDRESS:{
  1075. if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
  1076. const Type *FnTy = getTypeByID(Record[0]);
  1077. if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1078. Function *Fn =
  1079. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  1080. if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1081. GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
  1082. Type::getInt8Ty(Context),
  1083. false, GlobalValue::InternalLinkage,
  1084. 0, "");
  1085. BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
  1086. V = FwdRef;
  1087. break;
  1088. }
  1089. }
  1090. ValueList.AssignValue(V, NextCstNo);
  1091. ++NextCstNo;
  1092. }
  1093. if (NextCstNo != ValueList.size())
  1094. return Error("Invalid constant reference!");
  1095. if (Stream.ReadBlockEnd())
  1096. return Error("Error at end of constants block");
  1097. // Once all the constants have been read, go through and resolve forward
  1098. // references.
  1099. ValueList.ResolveConstantForwardRefs();
  1100. return false;
  1101. }
  1102. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  1103. /// remember where it is and then skip it. This lets us lazily deserialize the
  1104. /// functions.
  1105. bool BitcodeReader::RememberAndSkipFunctionBody() {
  1106. // Get the function we are talking about.
  1107. if (FunctionsWithBodies.empty())
  1108. return Error("Insufficient function protos");
  1109. Function *Fn = FunctionsWithBodies.back();
  1110. FunctionsWithBodies.pop_back();
  1111. // Save the current stream state.
  1112. uint64_t CurBit = Stream.GetCurrentBitNo();
  1113. DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
  1114. // Set the functions linkage to GhostLinkage so we know it is lazily
  1115. // deserialized.
  1116. Fn->setLinkage(GlobalValue::GhostLinkage);
  1117. // Skip over the function block for now.
  1118. if (Stream.SkipBlock())
  1119. return Error("Malformed block record");
  1120. return false;
  1121. }
  1122. bool BitcodeReader::ParseModule(const std::string &ModuleID) {
  1123. // Reject multiple MODULE_BLOCK's in a single bitstream.
  1124. if (TheModule)
  1125. return Error("Multiple MODULE_BLOCKs in same stream");
  1126. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1127. return Error("Malformed block record");
  1128. // Otherwise, create the module.
  1129. TheModule = new Module(ModuleID, Context);
  1130. SmallVector<uint64_t, 64> Record;
  1131. std::vector<std::string> SectionTable;
  1132. std::vector<std::string> GCTable;
  1133. // Read all the records for this module.
  1134. while (!Stream.AtEndOfStream()) {
  1135. unsigned Code = Stream.ReadCode();
  1136. if (Code == bitc::END_BLOCK) {
  1137. if (Stream.ReadBlockEnd())
  1138. return Error("Error at end of module block");
  1139. // Patch the initializers for globals and aliases up.
  1140. ResolveGlobalAndAliasInits();
  1141. if (!GlobalInits.empty() || !AliasInits.empty())
  1142. return Error("Malformed global initializer set");
  1143. if (!FunctionsWithBodies.empty())
  1144. return Error("Too few function bodies found");
  1145. // Look for intrinsic functions which need to be upgraded at some point
  1146. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  1147. FI != FE; ++FI) {
  1148. Function* NewFn;
  1149. if (UpgradeIntrinsicFunction(FI, NewFn))
  1150. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  1151. }
  1152. // Force deallocation of memory for these vectors to favor the client that
  1153. // want lazy deserialization.
  1154. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  1155. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  1156. std::vector<Function*>().swap(FunctionsWithBodies);
  1157. return false;
  1158. }
  1159. if (Code == bitc::ENTER_SUBBLOCK) {
  1160. switch (Stream.ReadSubBlockID()) {
  1161. default: // Skip unknown content.
  1162. if (Stream.SkipBlock())
  1163. return Error("Malformed block record");
  1164. break;
  1165. case bitc::BLOCKINFO_BLOCK_ID:
  1166. if (Stream.ReadBlockInfoBlock())
  1167. return Error("Malformed BlockInfoBlock");
  1168. break;
  1169. case bitc::PARAMATTR_BLOCK_ID:
  1170. if (ParseAttributeBlock())
  1171. return true;
  1172. break;
  1173. case bitc::TYPE_BLOCK_ID:
  1174. if (ParseTypeTable())
  1175. return true;
  1176. break;
  1177. case bitc::TYPE_SYMTAB_BLOCK_ID:
  1178. if (ParseTypeSymbolTable())
  1179. return true;
  1180. break;
  1181. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1182. if (ParseValueSymbolTable())
  1183. return true;
  1184. break;
  1185. case bitc::CONSTANTS_BLOCK_ID:
  1186. if (ParseConstants() || ResolveGlobalAndAliasInits())
  1187. return true;
  1188. break;
  1189. case bitc::METADATA_BLOCK_ID:
  1190. if (ParseMetadata())
  1191. return true;
  1192. break;
  1193. case bitc::FUNCTION_BLOCK_ID:
  1194. // If this is the first function body we've seen, reverse the
  1195. // FunctionsWithBodies list.
  1196. if (!HasReversedFunctionsWithBodies) {
  1197. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  1198. HasReversedFunctionsWithBodies = true;
  1199. }
  1200. if (RememberAndSkipFunctionBody())
  1201. return true;
  1202. break;
  1203. }
  1204. continue;
  1205. }
  1206. if (Code == bitc::DEFINE_ABBREV) {
  1207. Stream.ReadAbbrevRecord();
  1208. continue;
  1209. }
  1210. // Read a record.
  1211. switch (Stream.ReadRecord(Code, Record)) {
  1212. default: break; // Default behavior, ignore unknown content.
  1213. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  1214. if (Record.size() < 1)
  1215. return Error("Malformed MODULE_CODE_VERSION");
  1216. // Only version #0 is supported so far.
  1217. if (Record[0] != 0)
  1218. return Error("Unknown bitstream version!");
  1219. break;
  1220. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1221. std::string S;
  1222. if (ConvertToString(Record, 0, S))
  1223. return Error("Invalid MODULE_CODE_TRIPLE record");
  1224. TheModule->setTargetTriple(S);
  1225. break;
  1226. }
  1227. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  1228. std::string S;
  1229. if (ConvertToString(Record, 0, S))
  1230. return Error("Invalid MODULE_CODE_DATALAYOUT record");
  1231. TheModule->setDataLayout(S);
  1232. break;
  1233. }
  1234. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  1235. std::string S;
  1236. if (ConvertToString(Record, 0, S))
  1237. return Error("Invalid MODULE_CODE_ASM record");
  1238. TheModule->setModuleInlineAsm(S);
  1239. break;
  1240. }
  1241. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  1242. std::string S;
  1243. if (ConvertToString(Record, 0, S))
  1244. return Error("Invalid MODULE_CODE_DEPLIB record");
  1245. TheModule->addLibrary(S);
  1246. break;
  1247. }
  1248. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  1249. std::string S;
  1250. if (ConvertToString(Record, 0, S))
  1251. return Error("Invalid MODULE_CODE_SECTIONNAME record");
  1252. SectionTable.push_back(S);
  1253. break;
  1254. }
  1255. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  1256. std::string S;
  1257. if (ConvertToString(Record, 0, S))
  1258. return Error("Invalid MODULE_CODE_GCNAME record");
  1259. GCTable.push_back(S);
  1260. break;
  1261. }
  1262. // GLOBALVAR: [pointer type, isconst, initid,
  1263. // linkage, alignment, section, visibility, threadlocal]
  1264. case bitc::MODULE_CODE_GLOBALVAR: {
  1265. if (Record.size() < 6)
  1266. return Error("Invalid MODULE_CODE_GLOBALVAR record");
  1267. const Type *Ty = getTypeByID(Record[0]);
  1268. if (!isa<PointerType>(Ty))
  1269. return Error("Global not a pointer type!");
  1270. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  1271. Ty = cast<PointerType>(Ty)->getElementType();
  1272. bool isConstant = Record[1];
  1273. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  1274. unsigned Alignment = (1 << Record[4]) >> 1;
  1275. std::string Section;
  1276. if (Record[5]) {
  1277. if (Record[5]-1 >= SectionTable.size())
  1278. return Error("Invalid section ID");
  1279. Section = SectionTable[Record[5]-1];
  1280. }
  1281. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  1282. if (Record.size() > 6)
  1283. Visibility = GetDecodedVisibility(Record[6]);
  1284. bool isThreadLocal = false;
  1285. if (Record.size() > 7)
  1286. isThreadLocal = Record[7];
  1287. GlobalVariable *NewGV =
  1288. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
  1289. isThreadLocal, AddressSpace);
  1290. NewGV->setAlignment(Alignment);
  1291. if (!Section.empty())
  1292. NewGV->setSection(Section);
  1293. NewGV->setVisibility(Visibility);
  1294. NewGV->setThreadLocal(isThreadLocal);
  1295. ValueList.push_back(NewGV);
  1296. // Remember which value to use for the global initializer.
  1297. if (unsigned InitID = Record[2])
  1298. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  1299. break;
  1300. }
  1301. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  1302. // alignment, section, visibility, gc]
  1303. case bitc::MODULE_CODE_FUNCTION: {
  1304. if (Record.size() < 8)
  1305. return Error("Invalid MODULE_CODE_FUNCTION record");
  1306. const Type *Ty = getTypeByID(Record[0]);
  1307. if (!isa<PointerType>(Ty))
  1308. return Error("Function not a pointer type!");
  1309. const FunctionType *FTy =
  1310. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1311. if (!FTy)
  1312. return Error("Function not a pointer to function type!");
  1313. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  1314. "", TheModule);
  1315. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  1316. bool isProto = Record[2];
  1317. Func->setLinkage(GetDecodedLinkage(Record[3]));
  1318. Func->setAttributes(getAttributes(Record[4]));
  1319. Func->setAlignment((1 << Record[5]) >> 1);
  1320. if (Record[6]) {
  1321. if (Record[6]-1 >= SectionTable.size())
  1322. return Error("Invalid section ID");
  1323. Func->setSection(SectionTable[Record[6]-1]);
  1324. }
  1325. Func->setVisibility(GetDecodedVisibility(Record[7]));
  1326. if (Record.size() > 8 && Record[8]) {
  1327. if (Record[8]-1 > GCTable.size())
  1328. return Error("Invalid GC ID");
  1329. Func->setGC(GCTable[Record[8]-1].c_str());
  1330. }
  1331. ValueList.push_back(Func);
  1332. // If this is a function with a body, remember the prototype we are
  1333. // creating now, so that we can match up the body with them later.
  1334. if (!isProto)
  1335. FunctionsWithBodies.push_back(Func);
  1336. break;
  1337. }
  1338. // ALIAS: [alias type, aliasee val#, linkage]
  1339. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  1340. case bitc::MODULE_CODE_ALIAS: {
  1341. if (Record.size() < 3)
  1342. return Error("Invalid MODULE_ALIAS record");
  1343. const Type *Ty = getTypeByID(Record[0]);
  1344. if (!isa<PointerType>(Ty))
  1345. return Error("Function not a pointer type!");
  1346. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  1347. "", 0, TheModule);
  1348. // Old bitcode files didn't have visibility field.
  1349. if (Record.size() > 3)
  1350. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  1351. ValueList.push_back(NewGA);
  1352. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  1353. break;
  1354. }
  1355. /// MODULE_CODE_PURGEVALS: [numvals]
  1356. case bitc::MODULE_CODE_PURGEVALS:
  1357. // Trim down the value list to the specified size.
  1358. if (Record.size() < 1 || Record[0] > ValueList.size())
  1359. return Error("Invalid MODULE_PURGEVALS record");
  1360. ValueList.shrinkTo(Record[0]);
  1361. break;
  1362. }
  1363. Record.clear();
  1364. }
  1365. return Error("Premature end of bitstream");
  1366. }
  1367. bool BitcodeReader::ParseBitcode() {
  1368. TheModule = 0;
  1369. if (Buffer->getBufferSize() & 3)
  1370. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  1371. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  1372. unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  1373. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  1374. // The magic number is 0x0B17C0DE stored in little endian.
  1375. if (isBitcodeWrapper(BufPtr, BufEnd))
  1376. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
  1377. return Error("Invalid bitcode wrapper header");
  1378. StreamFile.init(BufPtr, BufEnd);
  1379. Stream.init(StreamFile);
  1380. // Sniff for the signature.
  1381. if (Stream.Read(8) != 'B' ||
  1382. Stream.Read(8) != 'C' ||
  1383. Stream.Read(4) != 0x0 ||
  1384. Stream.Read(4) != 0xC ||
  1385. Stream.Read(4) != 0xE ||
  1386. Stream.Read(4) != 0xD)
  1387. return Error("Invalid bitcode signature");
  1388. // We expect a number of well-defined blocks, though we don't necessarily
  1389. // need to understand them all.
  1390. while (!Stream.AtEndOfStream()) {
  1391. unsigned Code = Stream.ReadCode();
  1392. if (Code != bitc::ENTER_SUBBLOCK)
  1393. return Error("Invalid record at top-level");
  1394. unsigned BlockID = Stream.ReadSubBlockID();
  1395. // We only know the MODULE subblock ID.
  1396. switch (BlockID) {
  1397. case bitc::BLOCKINFO_BLOCK_ID:
  1398. if (Stream.ReadBlockInfoBlock())
  1399. return Error("Malformed BlockInfoBlock");
  1400. break;
  1401. case bitc::MODULE_BLOCK_ID:
  1402. if (ParseModule(Buffer->getBufferIdentifier()))
  1403. return true;
  1404. break;
  1405. default:
  1406. if (Stream.SkipBlock())
  1407. return Error("Malformed block record");
  1408. break;
  1409. }
  1410. }
  1411. return false;
  1412. }
  1413. /// ParseMetadataAttachment - Parse metadata attachments.
  1414. bool BitcodeReader::ParseMetadataAttachment() {
  1415. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1416. return Error("Malformed block record");
  1417. SmallVector<uint64_t, 64> Record;
  1418. while(1) {
  1419. unsigned Code = Stream.ReadCode();
  1420. if (Code == bitc::END_BLOCK) {
  1421. if (Stream.ReadBlockEnd())
  1422. return Error("Error at end of PARAMATTR block");
  1423. break;
  1424. }
  1425. if (Code == bitc::DEFINE_ABBREV) {
  1426. Stream.ReadAbbrevRecord();
  1427. continue;
  1428. }
  1429. // Read a metadata attachment record.
  1430. Record.clear();
  1431. switch (Stream.ReadRecord(Code, Record)) {
  1432. default: // Default behavior: ignore.
  1433. break;
  1434. case bitc::METADATA_ATTACHMENT: {
  1435. unsigned RecordLength = Record.size();
  1436. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  1437. return Error ("Invalid METADATA_ATTACHMENT reader!");
  1438. Instruction *Inst = InstructionList[Record[0]];
  1439. for (unsigned i = 1; i != RecordLength; i = i+2) {
  1440. unsigned Kind = Record[i];
  1441. Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
  1442. Inst->setMetadata(Kind, cast<MDNode>(Node));
  1443. }
  1444. break;
  1445. }
  1446. }
  1447. }
  1448. return false;
  1449. }
  1450. /// ParseFunctionBody - Lazily parse the specified function body block.
  1451. bool BitcodeReader::ParseFunctionBody(Function *F) {
  1452. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1453. return Error("Malformed block record");
  1454. unsigned ModuleValueListSize = ValueList.size();
  1455. // Add all the function arguments to the value table.
  1456. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1457. ValueList.push_back(I);
  1458. unsigned NextValueNo = ValueList.size();
  1459. BasicBlock *CurBB = 0;
  1460. unsigned CurBBNo = 0;
  1461. // Read all the records.
  1462. SmallVector<uint64_t, 64> Record;
  1463. while (1) {
  1464. unsigned Code = Stream.ReadCode();
  1465. if (Code == bitc::END_BLOCK) {
  1466. if (Stream.ReadBlockEnd())
  1467. return Error("Error at end of function block");
  1468. break;
  1469. }
  1470. if (Code == bitc::ENTER_SUBBLOCK) {
  1471. switch (Stream.ReadSubBlockID()) {
  1472. default: // Skip unknown content.
  1473. if (Stream.SkipBlock())
  1474. return Error("Malformed block record");
  1475. break;
  1476. case bitc::CONSTANTS_BLOCK_ID:
  1477. if (ParseConstants()) return true;
  1478. NextValueNo = ValueList.size();
  1479. break;
  1480. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1481. if (ParseValueSymbolTable()) return true;
  1482. break;
  1483. case bitc::METADATA_ATTACHMENT_ID:
  1484. if (ParseMetadataAttachment()) return true;
  1485. break;
  1486. }
  1487. continue;
  1488. }
  1489. if (Code == bitc::DEFINE_ABBREV) {
  1490. Stream.ReadAbbrevRecord();
  1491. continue;
  1492. }
  1493. // Read a record.
  1494. Record.clear();
  1495. Instruction *I = 0;
  1496. unsigned BitCode = Stream.ReadRecord(Code, Record);
  1497. switch (BitCode) {
  1498. default: // Default behavior: reject
  1499. return Error("Unknown instruction");
  1500. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  1501. if (Record.size() < 1 || Record[0] == 0)
  1502. return Error("Invalid DECLAREBLOCKS record");
  1503. // Create all the basic blocks for the function.
  1504. FunctionBBs.resize(Record[0]);
  1505. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1506. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  1507. CurBB = FunctionBBs[0];
  1508. continue;
  1509. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  1510. unsigned OpNum = 0;
  1511. Value *LHS, *RHS;
  1512. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1513. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1514. OpNum+1 > Record.size())
  1515. return Error("Invalid BINOP record");
  1516. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  1517. if (Opc == -1) return Error("Invalid BINOP record");
  1518. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  1519. InstructionList.push_back(I);
  1520. if (OpNum < Record.size()) {
  1521. if (Opc == Instruction::Add ||
  1522. Opc == Instruction::Sub ||
  1523. Opc == Instruction::Mul) {
  1524. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  1525. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  1526. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  1527. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  1528. } else if (Opc == Instruction::SDiv) {
  1529. if (Record[3] & (1 << bitc::SDIV_EXACT))
  1530. cast<BinaryOperator>(I)->setIsExact(true);
  1531. }
  1532. }
  1533. break;
  1534. }
  1535. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  1536. unsigned OpNum = 0;
  1537. Value *Op;
  1538. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1539. OpNum+2 != Record.size())
  1540. return Error("Invalid CAST record");
  1541. const Type *ResTy = getTypeByID(Record[OpNum]);
  1542. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  1543. if (Opc == -1 || ResTy == 0)
  1544. return Error("Invalid CAST record");
  1545. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  1546. InstructionList.push_back(I);
  1547. break;
  1548. }
  1549. case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
  1550. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  1551. unsigned OpNum = 0;
  1552. Value *BasePtr;
  1553. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  1554. return Error("Invalid GEP record");
  1555. SmallVector<Value*, 16> GEPIdx;
  1556. while (OpNum != Record.size()) {
  1557. Value *Op;
  1558. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1559. return Error("Invalid GEP record");
  1560. GEPIdx.push_back(Op);
  1561. }
  1562. I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
  1563. InstructionList.push_back(I);
  1564. if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
  1565. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  1566. break;
  1567. }
  1568. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  1569. // EXTRACTVAL: [opty, opval, n x indices]
  1570. unsigned OpNum = 0;
  1571. Value *Agg;
  1572. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1573. return Error("Invalid EXTRACTVAL record");
  1574. SmallVector<unsigned, 4> EXTRACTVALIdx;
  1575. for (unsigned RecSize = Record.size();
  1576. OpNum != RecSize; ++OpNum) {
  1577. uint64_t Index = Record[OpNum];
  1578. if ((unsigned)Index != Index)
  1579. return Error("Invalid EXTRACTVAL index");
  1580. EXTRACTVALIdx.push_back((unsigned)Index);
  1581. }
  1582. I = ExtractValueInst::Create(Agg,
  1583. EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
  1584. InstructionList.push_back(I);
  1585. break;
  1586. }
  1587. case bitc::FUNC_CODE_INST_INSERTVAL: {
  1588. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  1589. unsigned OpNum = 0;
  1590. Value *Agg;
  1591. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1592. return Error("Invalid INSERTVAL record");
  1593. Value *Val;
  1594. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  1595. return Error("Invalid INSERTVAL record");
  1596. SmallVector<unsigned, 4> INSERTVALIdx;
  1597. for (unsigned RecSize = Record.size();
  1598. OpNum != RecSize; ++OpNum) {
  1599. uint64_t Index = Record[OpNum];
  1600. if ((unsigned)Index != Index)
  1601. return Error("Invalid INSERTVAL index");
  1602. INSERTVALIdx.push_back((unsigned)Index);
  1603. }
  1604. I = InsertValueInst::Create(Agg, Val,
  1605. INSERTVALIdx.begin(), INSERTVALIdx.end());
  1606. InstructionList.push_back(I);
  1607. break;
  1608. }
  1609. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  1610. // obsolete form of select
  1611. // handles select i1 ... in old bitcode
  1612. unsigned OpNum = 0;
  1613. Value *TrueVal, *FalseVal, *Cond;
  1614. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1615. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1616. getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
  1617. return Error("Invalid SELECT record");
  1618. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1619. InstructionList.push_back(I);
  1620. break;
  1621. }
  1622. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  1623. // new form of select
  1624. // handles select i1 or select [N x i1]
  1625. unsigned OpNum = 0;
  1626. Value *TrueVal, *FalseVal, *Cond;
  1627. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1628. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1629. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  1630. return Error("Invalid SELECT record");
  1631. // select condition can be either i1 or [N x i1]
  1632. if (const VectorType* vector_type =
  1633. dyn_cast<const VectorType>(Cond->getType())) {
  1634. // expect <n x i1>
  1635. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  1636. return Error("Invalid SELECT condition type");
  1637. } else {
  1638. // expect i1
  1639. if (Cond->getType() != Type::getInt1Ty(Context))
  1640. return Error("Invalid SELECT condition type");
  1641. }
  1642. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1643. InstructionList.push_back(I);
  1644. break;
  1645. }
  1646. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  1647. unsigned OpNum = 0;
  1648. Value *Vec, *Idx;
  1649. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1650. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1651. return Error("Invalid EXTRACTELT record");
  1652. I = ExtractElementInst::Create(Vec, Idx);
  1653. InstructionList.push_back(I);
  1654. break;
  1655. }
  1656. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  1657. unsigned OpNum = 0;
  1658. Value *Vec, *Elt, *Idx;
  1659. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1660. getValue(Record, OpNum,
  1661. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  1662. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1663. return Error("Invalid INSERTELT record");
  1664. I = InsertElementInst::Create(Vec, Elt, Idx);
  1665. InstructionList.push_back(I);
  1666. break;
  1667. }
  1668. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  1669. unsigned OpNum = 0;
  1670. Value *Vec1, *Vec2, *Mask;
  1671. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  1672. getValue(Record, OpNum, Vec1->getType(), Vec2))
  1673. return Error("Invalid SHUFFLEVEC record");
  1674. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  1675. return Error("Invalid SHUFFLEVEC record");
  1676. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  1677. InstructionList.push_back(I);
  1678. break;
  1679. }
  1680. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  1681. // Old form of ICmp/FCmp returning bool
  1682. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  1683. // both legal on vectors but had different behaviour.
  1684. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  1685. // FCmp/ICmp returning bool or vector of bool
  1686. unsigned OpNum = 0;
  1687. Value *LHS, *RHS;
  1688. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1689. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1690. OpNum+1 != Record.size())
  1691. return Error("Invalid CMP record");
  1692. if (LHS->getType()->isFPOrFPVector())
  1693. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  1694. else
  1695. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  1696. InstructionList.push_back(I);
  1697. break;
  1698. }
  1699. case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
  1700. if (Record.size() != 2)
  1701. return Error("Invalid GETRESULT record");
  1702. unsigned OpNum = 0;
  1703. Value *Op;
  1704. getValueTypePair(Record, OpNum, NextValueNo, Op);
  1705. unsigned Index = Record[1];
  1706. I = ExtractValueInst::Create(Op, Index);
  1707. InstructionList.push_back(I);
  1708. break;
  1709. }
  1710. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  1711. {
  1712. unsigned Size = Record.size();
  1713. if (Size == 0) {
  1714. I = ReturnInst::Create(Context);
  1715. InstructionList.push_back(I);
  1716. break;
  1717. }
  1718. unsigned OpNum = 0;
  1719. SmallVector<Value *,4> Vs;
  1720. do {
  1721. Value *Op = NULL;
  1722. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1723. return Error("Invalid RET record");
  1724. Vs.push_back(Op);
  1725. } while(OpNum != Record.size());
  1726. const Type *ReturnType = F->getReturnType();
  1727. if (Vs.size() > 1 ||
  1728. (isa<StructType>(ReturnType) &&
  1729. (Vs.empty() || Vs[0]->getType() != ReturnType))) {
  1730. Value *RV = UndefValue::get(ReturnType);
  1731. for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
  1732. I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
  1733. InstructionList.push_back(I);
  1734. CurBB->getInstList().push_back(I);
  1735. ValueList.AssignValue(I, NextValueNo++);
  1736. RV = I;
  1737. }
  1738. I = ReturnInst::Create(Context, RV);
  1739. InstructionList.push_back(I);
  1740. break;
  1741. }
  1742. I = ReturnInst::Create(Context, Vs[0]);
  1743. InstructionList.push_back(I);
  1744. break;
  1745. }
  1746. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  1747. if (Record.size() != 1 && Record.size() != 3)
  1748. return Error("Invalid BR record");
  1749. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  1750. if (TrueDest == 0)
  1751. return Error("Invalid BR record");
  1752. if (Record.size() == 1) {
  1753. I = BranchInst::Create(TrueDest);
  1754. InstructionList.push_back(I);
  1755. }
  1756. else {
  1757. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  1758. Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
  1759. if (FalseDest == 0 || Cond == 0)
  1760. return Error("Invalid BR record");
  1761. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  1762. InstructionList.push_back(I);
  1763. }
  1764. break;
  1765. }
  1766. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  1767. if (Record.size() < 3 || (Record.size() & 1) == 0)
  1768. return Error("Invalid SWITCH record");
  1769. const Type *OpTy = getTypeByID(Record[0]);
  1770. Value *Cond = getFnValueByID(Record[1], OpTy);
  1771. BasicBlock *Default = getBasicBlock(Record[2]);
  1772. if (OpTy == 0 || Cond == 0 || Default == 0)
  1773. return Error("Invalid SWITCH record");
  1774. unsigned NumCases = (Record.size()-3)/2;
  1775. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  1776. InstructionList.push_back(SI);
  1777. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  1778. ConstantInt *CaseVal =
  1779. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  1780. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  1781. if (CaseVal == 0 || DestBB == 0) {
  1782. delete SI;
  1783. return Error("Invalid SWITCH record!");
  1784. }
  1785. SI->addCase(CaseVal, DestBB);
  1786. }
  1787. I = SI;
  1788. break;
  1789. }
  1790. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  1791. if (Record.size() < 2)
  1792. return Error("Invalid INDIRECTBR record");
  1793. const Type *OpTy = getTypeByID(Record[0]);
  1794. Value *Address = getFnValueByID(Record[1], OpTy);
  1795. if (OpTy == 0 || Address == 0)
  1796. return Error("Invalid INDIRECTBR record");
  1797. unsigned NumDests = Record.size()-2;
  1798. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  1799. InstructionList.push_back(IBI);
  1800. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  1801. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  1802. IBI->addDestination(DestBB);
  1803. } else {
  1804. delete IBI;
  1805. return Error("Invalid INDIRECTBR record!");
  1806. }
  1807. }
  1808. I = IBI;
  1809. break;
  1810. }
  1811. case bitc::FUNC_CODE_INST_INVOKE: {
  1812. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  1813. if (Record.size() < 4) return Error("Invalid INVOKE record");
  1814. AttrListPtr PAL = getAttributes(Record[0]);
  1815. unsigned CCInfo = Record[1];
  1816. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  1817. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  1818. unsigned OpNum = 4;
  1819. Value *Callee;
  1820. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1821. return Error("Invalid INVOKE record");
  1822. const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  1823. const FunctionType *FTy = !CalleeTy ? 0 :
  1824. dyn_cast<FunctionType>(CalleeTy->getElementType());
  1825. // Check that the right number of fixed parameters are here.
  1826. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  1827. Record.size() < OpNum+FTy->getNumParams())
  1828. return Error("Invalid INVOKE record");
  1829. SmallVector<Value*, 16> Ops;
  1830. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1831. Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1832. if (Ops.back() == 0) return Error("Invalid INVOKE record");
  1833. }
  1834. if (!FTy->isVarArg()) {
  1835. if (Record.size() != OpNum)
  1836. return Error("Invalid INVOKE record");
  1837. } else {
  1838. // Read type/value pairs for varargs params.
  1839. while (OpNum != Record.size()) {
  1840. Value *Op;
  1841. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1842. return Error("Invalid INVOKE record");
  1843. Ops.push_back(Op);
  1844. }
  1845. }
  1846. I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
  1847. Ops.begin(), Ops.end());
  1848. InstructionList.push_back(I);
  1849. cast<InvokeInst>(I)->setCallingConv(
  1850. static_cast<CallingConv::ID>(CCInfo));
  1851. cast<InvokeInst>(I)->setAttributes(PAL);
  1852. break;
  1853. }
  1854. case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
  1855. I = new UnwindInst(Context);
  1856. InstructionList.push_back(I);
  1857. break;
  1858. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  1859. I = new UnreachableInst(Context);
  1860. InstructionList.push_back(I);
  1861. break;
  1862. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  1863. if (Record.size() < 1 || ((Record.size()-1)&1))
  1864. return Error("Invalid PHI record");
  1865. const Type *Ty = getTypeByID(Record[0]);
  1866. if (!Ty) return Error("Invalid PHI record");
  1867. PHINode *PN = PHINode::Create(Ty);
  1868. InstructionList.push_back(PN);
  1869. PN->reserveOperandSpace((Record.size()-1)/2);
  1870. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  1871. Value *V = getFnValueByID(Record[1+i], Ty);
  1872. BasicBlock *BB = getBasicBlock(Record[2+i]);
  1873. if (!V || !BB) return Error("Invalid PHI record");
  1874. PN->addIncoming(V, BB);
  1875. }
  1876. I = PN;
  1877. break;
  1878. }
  1879. case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
  1880. // Autoupgrade malloc instruction to malloc call.
  1881. // FIXME: Remove in LLVM 3.0.
  1882. if (Record.size() < 3)
  1883. return Error("Invalid MALLOC record");
  1884. const PointerType *Ty =
  1885. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1886. Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
  1887. if (!Ty || !Size) return Error("Invalid MALLOC record");
  1888. if (!CurBB) return Error("Invalid malloc instruction with no BB");
  1889. const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
  1890. Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
  1891. AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
  1892. I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
  1893. AllocSize, Size, NULL);
  1894. InstructionList.push_back(I);
  1895. break;
  1896. }
  1897. case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
  1898. unsigned OpNum = 0;
  1899. Value *Op;
  1900. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1901. OpNum != Record.size())
  1902. return Error("Invalid FREE record");
  1903. if (!CurBB) return Error("Invalid free instruction with no BB");
  1904. I = CallInst::CreateFree(Op, CurBB);
  1905. InstructionList.push_back(I);
  1906. break;
  1907. }
  1908. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
  1909. if (Record.size() < 3)
  1910. return Error("Invalid ALLOCA record");
  1911. const PointerType *Ty =
  1912. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1913. Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
  1914. unsigned Align = Record[2];
  1915. if (!Ty || !Size) return Error("Invalid ALLOCA record");
  1916. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1917. InstructionList.push_back(I);
  1918. break;
  1919. }
  1920. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  1921. unsigned OpNum = 0;
  1922. Value *Op;
  1923. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1924. OpNum+2 != Record.size())
  1925. return Error("Invalid LOAD record");
  1926. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1927. InstructionList.push_back(I);
  1928. break;
  1929. }
  1930. case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
  1931. unsigned OpNum = 0;
  1932. Value *Val, *Ptr;
  1933. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  1934. getValue(Record, OpNum,
  1935. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  1936. OpNum+2 != Record.size())
  1937. return Error("Invalid STORE record");
  1938. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1939. InstructionList.push_back(I);
  1940. break;
  1941. }
  1942. case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
  1943. // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
  1944. unsigned OpNum = 0;
  1945. Value *Val, *Ptr;
  1946. if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
  1947. getValue(Record, OpNum,
  1948. PointerType::getUnqual(Val->getType()), Ptr)||
  1949. OpNum+2 != Record.size())
  1950. return Error("Invalid STORE record");
  1951. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1952. InstructionList.push_back(I);
  1953. break;
  1954. }
  1955. case bitc::FUNC_CODE_INST_CALL: {
  1956. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  1957. if (Record.size() < 3)
  1958. return Error("Invalid CALL record");
  1959. AttrListPtr PAL = getAttributes(Record[0]);
  1960. unsigned CCInfo = Record[1];
  1961. unsigned OpNum = 2;
  1962. Value *Callee;
  1963. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1964. return Error("Invalid CALL record");
  1965. const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  1966. const FunctionType *FTy = 0;
  1967. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  1968. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  1969. return Error("Invalid CALL record");
  1970. SmallVector<Value*, 16> Args;
  1971. // Read the fixed params.
  1972. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1973. if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
  1974. Args.push_back(getBasicBlock(Record[OpNum]));
  1975. else
  1976. Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1977. if (Args.back() == 0) return Error("Invalid CALL record");
  1978. }
  1979. // Read type/value pairs for varargs params.
  1980. if (!FTy->isVarArg()) {
  1981. if (OpNum != Record.size())
  1982. return Error("Invalid CALL record");
  1983. } else {
  1984. while (OpNum != Record.size()) {
  1985. Value *Op;
  1986. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1987. return Error("Invalid CALL record");
  1988. Args.push_back(Op);
  1989. }
  1990. }
  1991. I = CallInst::Create(Callee, Args.begin(), Args.end());
  1992. InstructionList.push_back(I);
  1993. cast<CallInst>(I)->setCallingConv(
  1994. static_cast<CallingConv::ID>(CCInfo>>1));
  1995. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  1996. cast<CallInst>(I)->setAttributes(PAL);
  1997. break;
  1998. }
  1999. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  2000. if (Record.size() < 3)
  2001. return Error("Invalid VAARG record");
  2002. const Type *OpTy = getTypeByID(Record[0]);
  2003. Value *Op = getFnValueByID(Record[1], OpTy);
  2004. const Type *ResTy = getTypeByID(Record[2]);
  2005. if (!OpTy || !Op || !ResTy)
  2006. return Error("Invalid VAARG record");
  2007. I = new VAArgInst(Op, ResTy);
  2008. InstructionList.push_back(I);
  2009. break;
  2010. }
  2011. }
  2012. // Add instruction to end of current BB. If there is no current BB, reject
  2013. // this file.
  2014. if (CurBB == 0) {
  2015. delete I;
  2016. return Error("Invalid instruction with no BB");
  2017. }
  2018. CurBB->getInstList().push_back(I);
  2019. // If this was a terminator instruction, move to the next block.
  2020. if (isa<TerminatorInst>(I)) {
  2021. ++CurBBNo;
  2022. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  2023. }
  2024. // Non-void values get registered in the value table for future use.
  2025. if (I && !I->getType()->isVoidTy())
  2026. ValueList.AssignValue(I, NextValueNo++);
  2027. }
  2028. // Check the function list for unresolved values.
  2029. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  2030. if (A->getParent() == 0) {
  2031. // We found at least one unresolved value. Nuke them all to avoid leaks.
  2032. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  2033. if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
  2034. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  2035. delete A;
  2036. }
  2037. }
  2038. return Error("Never resolved value found in function!");
  2039. }
  2040. }
  2041. // See if anything took the address of blocks in this function. If so,
  2042. // resolve them now.
  2043. /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
  2044. /// are resolved lazily when functions are loaded.
  2045. DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
  2046. BlockAddrFwdRefs.find(F);
  2047. if (BAFRI != BlockAddrFwdRefs.end()) {
  2048. std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
  2049. for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
  2050. unsigned BlockIdx = RefList[i].first;
  2051. if (BlockIdx >= FunctionBBs.size())
  2052. return Error("Invalid blockaddress block #");
  2053. GlobalVariable *FwdRef = RefList[i].second;
  2054. FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
  2055. FwdRef->eraseFromParent();
  2056. }
  2057. BlockAddrFwdRefs.erase(BAFRI);
  2058. }
  2059. // Trim the value list down to the size it was before we parsed this function.
  2060. ValueList.shrinkTo(ModuleValueListSize);
  2061. std::vector<BasicBlock*>().swap(FunctionBBs);
  2062. return false;
  2063. }
  2064. //===----------------------------------------------------------------------===//
  2065. // ModuleProvider implementation
  2066. //===----------------------------------------------------------------------===//
  2067. bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
  2068. // If it already is material, ignore the request.
  2069. if (!F->hasNotBeenReadFromBitcode()) return false;
  2070. DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
  2071. DeferredFunctionInfo.find(F);
  2072. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  2073. // Move the bit stream to the saved position of the deferred function body and
  2074. // restore the real linkage type for the function.
  2075. Stream.JumpToBit(DFII->second.first);
  2076. F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
  2077. if (ParseFunctionBody(F)) {
  2078. if (ErrInfo) *ErrInfo = ErrorString;
  2079. return true;
  2080. }
  2081. // Upgrade any old intrinsic calls in the function.
  2082. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  2083. E = UpgradedIntrinsics.end(); I != E; ++I) {
  2084. if (I->first != I->second) {
  2085. for (Value::use_iterator UI = I->first->use_begin(),
  2086. UE = I->first->use_end(); UI != UE; ) {
  2087. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2088. UpgradeIntrinsicCall(CI, I->second);
  2089. }
  2090. }
  2091. }
  2092. return false;
  2093. }
  2094. void BitcodeReader::dematerializeFunction(Function *F) {
  2095. // If this function isn't materialized, or if it is a proto, this is a noop.
  2096. if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
  2097. return;
  2098. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  2099. // Just forget the function body, we can remat it later.
  2100. F->deleteBody();
  2101. F->setLinkage(GlobalValue::GhostLinkage);
  2102. }
  2103. Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
  2104. // Iterate over the module, deserializing any functions that are still on
  2105. // disk.
  2106. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  2107. F != E; ++F)
  2108. if (F->hasNotBeenReadFromBitcode() &&
  2109. materializeFunction(F, ErrInfo))
  2110. return 0;
  2111. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  2112. // delete the old functions to clean up. We can't do this unless the entire
  2113. // module is materialized because there could always be another function body
  2114. // with calls to the old function.
  2115. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  2116. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  2117. if (I->first != I->second) {
  2118. for (Value::use_iterator UI = I->first->use_begin(),
  2119. UE = I->first->use_end(); UI != UE; ) {
  2120. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2121. UpgradeIntrinsicCall(CI, I->second);
  2122. }
  2123. if (!I->first->use_empty())
  2124. I->first->replaceAllUsesWith(I->second);
  2125. I->first->eraseFromParent();
  2126. }
  2127. }
  2128. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  2129. // Check debug info intrinsics.
  2130. CheckDebugInfoIntrinsics(TheModule);
  2131. return TheModule;
  2132. }
  2133. /// This method is provided by the parent ModuleProvde class and overriden
  2134. /// here. It simply releases the module from its provided and frees up our
  2135. /// state.
  2136. /// @brief Release our hold on the generated module
  2137. Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
  2138. // Since we're losing control of this Module, we must hand it back complete
  2139. Module *M = ModuleProvider::releaseModule(ErrInfo);
  2140. FreeState();
  2141. return M;
  2142. }
  2143. //===----------------------------------------------------------------------===//
  2144. // External interface
  2145. //===----------------------------------------------------------------------===//
  2146. /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
  2147. ///
  2148. ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
  2149. LLVMContext& Context,
  2150. std::string *ErrMsg) {
  2151. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2152. if (R->ParseBitcode()) {
  2153. if (ErrMsg)
  2154. *ErrMsg = R->getErrorString();
  2155. // Don't let the BitcodeReader dtor delete 'Buffer'.
  2156. R->releaseMemoryBuffer();
  2157. delete R;
  2158. return 0;
  2159. }
  2160. return R;
  2161. }
  2162. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  2163. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  2164. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
  2165. std::string *ErrMsg){
  2166. BitcodeReader *R;
  2167. R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
  2168. ErrMsg));
  2169. if (!R) return 0;
  2170. // Read in the entire module.
  2171. Module *M = R->materializeModule(ErrMsg);
  2172. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  2173. // there was an error.
  2174. R->releaseMemoryBuffer();
  2175. // If there was no error, tell ModuleProvider not to delete it when its dtor
  2176. // is run.
  2177. if (M)
  2178. M = R->releaseModule(ErrMsg);
  2179. delete R;
  2180. return M;
  2181. }