BitcodeReader.cpp 89 KB

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