BitcodeReader.cpp 80 KB

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