BitcodeReader.cpp 89 KB

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