BitcodeReader.cpp 106 KB

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