BitcodeReader.cpp 102 KB

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