BitcodeReader.cpp 103 KB

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