BitcodeReader.cpp 104 KB

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