BitcodeReader.cpp 90 KB

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