BitcodeReader.cpp 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "BitcodeReader.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/InlineAsm.h"
  18. #include "llvm/IntrinsicInst.h"
  19. #include "llvm/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> : public 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. // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
  295. // value for Idx.
  296. MDValuePtrs[Idx] = V;
  297. }
  298. Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  299. if (Idx >= size())
  300. resize(Idx + 1);
  301. if (Value *V = MDValuePtrs[Idx]) {
  302. assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
  303. return V;
  304. }
  305. // Create and return a placeholder, which will later be RAUW'd.
  306. Value *V = new Argument(Type::getMetadataTy(Context));
  307. MDValuePtrs[Idx] = V;
  308. return V;
  309. }
  310. const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
  311. // If the TypeID is in range, return it.
  312. if (ID < TypeList.size())
  313. return TypeList[ID].get();
  314. if (!isTypeTable) return 0;
  315. // The type table allows forward references. Push as many Opaque types as
  316. // needed to get up to ID.
  317. while (TypeList.size() <= ID)
  318. TypeList.push_back(OpaqueType::get(Context));
  319. return TypeList.back().get();
  320. }
  321. //===----------------------------------------------------------------------===//
  322. // Functions for parsing blocks from the bitcode file
  323. //===----------------------------------------------------------------------===//
  324. bool BitcodeReader::ParseAttributeBlock() {
  325. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  326. return Error("Malformed block record");
  327. if (!MAttributes.empty())
  328. return Error("Multiple PARAMATTR blocks found!");
  329. SmallVector<uint64_t, 64> Record;
  330. SmallVector<AttributeWithIndex, 8> Attrs;
  331. // Read all the records.
  332. while (1) {
  333. unsigned Code = Stream.ReadCode();
  334. if (Code == bitc::END_BLOCK) {
  335. if (Stream.ReadBlockEnd())
  336. return Error("Error at end of PARAMATTR block");
  337. return false;
  338. }
  339. if (Code == bitc::ENTER_SUBBLOCK) {
  340. // No known subblocks, always skip them.
  341. Stream.ReadSubBlockID();
  342. if (Stream.SkipBlock())
  343. return Error("Malformed block record");
  344. continue;
  345. }
  346. if (Code == bitc::DEFINE_ABBREV) {
  347. Stream.ReadAbbrevRecord();
  348. continue;
  349. }
  350. // Read a record.
  351. Record.clear();
  352. switch (Stream.ReadRecord(Code, Record)) {
  353. default: // Default behavior: ignore.
  354. break;
  355. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
  356. if (Record.size() & 1)
  357. return Error("Invalid ENTRY record");
  358. // FIXME : Remove this autoupgrade code in LLVM 3.0.
  359. // If Function attributes are using index 0 then transfer them
  360. // to index ~0. Index 0 is used for return value attributes but used to be
  361. // used for function attributes.
  362. Attributes RetAttribute = Attribute::None;
  363. Attributes FnAttribute = Attribute::None;
  364. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  365. // FIXME: remove in LLVM 3.0
  366. // The alignment is stored as a 16-bit raw value from bits 31--16.
  367. // We shift the bits above 31 down by 11 bits.
  368. unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
  369. if (Alignment && !isPowerOf2_32(Alignment))
  370. return Error("Alignment is not a power of two.");
  371. Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
  372. if (Alignment)
  373. ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
  374. ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
  375. Record[i+1] = ReconstitutedAttr;
  376. if (Record[i] == 0)
  377. RetAttribute = Record[i+1];
  378. else if (Record[i] == ~0U)
  379. FnAttribute = Record[i+1];
  380. }
  381. unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
  382. Attribute::ReadOnly|Attribute::ReadNone);
  383. if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
  384. (RetAttribute & OldRetAttrs) != 0) {
  385. if (FnAttribute == Attribute::None) { // add a slot so they get added.
  386. Record.push_back(~0U);
  387. Record.push_back(0);
  388. }
  389. FnAttribute |= RetAttribute & OldRetAttrs;
  390. RetAttribute &= ~OldRetAttrs;
  391. }
  392. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  393. if (Record[i] == 0) {
  394. if (RetAttribute != Attribute::None)
  395. Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
  396. } else if (Record[i] == ~0U) {
  397. if (FnAttribute != Attribute::None)
  398. Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
  399. } else if (Record[i+1] != Attribute::None)
  400. Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
  401. }
  402. MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
  403. Attrs.clear();
  404. break;
  405. }
  406. }
  407. }
  408. }
  409. bool BitcodeReader::ParseTypeTable() {
  410. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
  411. return Error("Malformed block record");
  412. if (!TypeList.empty())
  413. return Error("Multiple TYPE_BLOCKs found!");
  414. SmallVector<uint64_t, 64> Record;
  415. unsigned NumRecords = 0;
  416. // Read all the records for this type table.
  417. while (1) {
  418. unsigned Code = Stream.ReadCode();
  419. if (Code == bitc::END_BLOCK) {
  420. if (NumRecords != TypeList.size())
  421. return Error("Invalid type forward reference in TYPE_BLOCK");
  422. if (Stream.ReadBlockEnd())
  423. return Error("Error at end of type table block");
  424. return false;
  425. }
  426. if (Code == bitc::ENTER_SUBBLOCK) {
  427. // No known subblocks, always skip them.
  428. Stream.ReadSubBlockID();
  429. if (Stream.SkipBlock())
  430. return Error("Malformed block record");
  431. continue;
  432. }
  433. if (Code == bitc::DEFINE_ABBREV) {
  434. Stream.ReadAbbrevRecord();
  435. continue;
  436. }
  437. // Read a record.
  438. Record.clear();
  439. const Type *ResultTy = 0;
  440. switch (Stream.ReadRecord(Code, Record)) {
  441. default: // Default behavior: unknown type.
  442. ResultTy = 0;
  443. break;
  444. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  445. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  446. // type list. This allows us to reserve space.
  447. if (Record.size() < 1)
  448. return Error("Invalid TYPE_CODE_NUMENTRY record");
  449. TypeList.reserve(Record[0]);
  450. continue;
  451. case bitc::TYPE_CODE_VOID: // VOID
  452. ResultTy = Type::getVoidTy(Context);
  453. break;
  454. case bitc::TYPE_CODE_FLOAT: // FLOAT
  455. ResultTy = Type::getFloatTy(Context);
  456. break;
  457. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  458. ResultTy = Type::getDoubleTy(Context);
  459. break;
  460. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  461. ResultTy = Type::getX86_FP80Ty(Context);
  462. break;
  463. case bitc::TYPE_CODE_FP128: // FP128
  464. ResultTy = Type::getFP128Ty(Context);
  465. break;
  466. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  467. ResultTy = Type::getPPC_FP128Ty(Context);
  468. break;
  469. case bitc::TYPE_CODE_LABEL: // LABEL
  470. ResultTy = Type::getLabelTy(Context);
  471. break;
  472. case bitc::TYPE_CODE_OPAQUE: // OPAQUE
  473. ResultTy = 0;
  474. break;
  475. case bitc::TYPE_CODE_METADATA: // METADATA
  476. ResultTy = Type::getMetadataTy(Context);
  477. break;
  478. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  479. if (Record.size() < 1)
  480. return Error("Invalid Integer type record");
  481. ResultTy = IntegerType::get(Context, Record[0]);
  482. break;
  483. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  484. // [pointee type, address space]
  485. if (Record.size() < 1)
  486. return Error("Invalid POINTER type record");
  487. unsigned AddressSpace = 0;
  488. if (Record.size() == 2)
  489. AddressSpace = Record[1];
  490. ResultTy = PointerType::get(getTypeByID(Record[0], true),
  491. AddressSpace);
  492. break;
  493. }
  494. case bitc::TYPE_CODE_FUNCTION: {
  495. // FIXME: attrid is dead, remove it in LLVM 3.0
  496. // FUNCTION: [vararg, attrid, retty, paramty x N]
  497. if (Record.size() < 3)
  498. return Error("Invalid FUNCTION type record");
  499. std::vector<const Type*> ArgTys;
  500. for (unsigned i = 3, e = Record.size(); i != e; ++i)
  501. ArgTys.push_back(getTypeByID(Record[i], true));
  502. ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
  503. Record[0]);
  504. break;
  505. }
  506. case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
  507. if (Record.size() < 1)
  508. return Error("Invalid STRUCT type record");
  509. std::vector<const Type*> EltTys;
  510. for (unsigned i = 1, e = Record.size(); i != e; ++i)
  511. EltTys.push_back(getTypeByID(Record[i], true));
  512. ResultTy = StructType::get(Context, EltTys, Record[0]);
  513. break;
  514. }
  515. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  516. if (Record.size() < 2)
  517. return Error("Invalid ARRAY type record");
  518. ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
  519. break;
  520. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  521. if (Record.size() < 2)
  522. return Error("Invalid VECTOR type record");
  523. ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
  524. break;
  525. }
  526. if (NumRecords == TypeList.size()) {
  527. // If this is a new type slot, just append it.
  528. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
  529. ++NumRecords;
  530. } else if (ResultTy == 0) {
  531. // Otherwise, this was forward referenced, so an opaque type was created,
  532. // but the result type is actually just an opaque. Leave the one we
  533. // created previously.
  534. ++NumRecords;
  535. } else {
  536. // Otherwise, this was forward referenced, so an opaque type was created.
  537. // Resolve the opaque type to the real type now.
  538. assert(NumRecords < TypeList.size() && "Typelist imbalance");
  539. const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
  540. // Don't directly push the new type on the Tab. Instead we want to replace
  541. // the opaque type we previously inserted with the new concrete value. The
  542. // refinement from the abstract (opaque) type to the new type causes all
  543. // uses of the abstract type to use the concrete type (NewTy). This will
  544. // also cause the opaque type to be deleted.
  545. const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
  546. // This should have replaced the old opaque type with the new type in the
  547. // value table... or with a preexisting type that was already in the
  548. // system. Let's just make sure it did.
  549. assert(TypeList[NumRecords-1].get() != OldTy &&
  550. "refineAbstractType didn't work!");
  551. }
  552. }
  553. }
  554. bool BitcodeReader::ParseTypeSymbolTable() {
  555. if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
  556. return Error("Malformed block record");
  557. SmallVector<uint64_t, 64> Record;
  558. // Read all the records for this type table.
  559. std::string TypeName;
  560. while (1) {
  561. unsigned Code = Stream.ReadCode();
  562. if (Code == bitc::END_BLOCK) {
  563. if (Stream.ReadBlockEnd())
  564. return Error("Error at end of type symbol table block");
  565. return false;
  566. }
  567. if (Code == bitc::ENTER_SUBBLOCK) {
  568. // No known subblocks, always skip them.
  569. Stream.ReadSubBlockID();
  570. if (Stream.SkipBlock())
  571. return Error("Malformed block record");
  572. continue;
  573. }
  574. if (Code == bitc::DEFINE_ABBREV) {
  575. Stream.ReadAbbrevRecord();
  576. continue;
  577. }
  578. // Read a record.
  579. Record.clear();
  580. switch (Stream.ReadRecord(Code, Record)) {
  581. default: // Default behavior: unknown type.
  582. break;
  583. case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
  584. if (ConvertToString(Record, 1, TypeName))
  585. return Error("Invalid TST_ENTRY record");
  586. unsigned TypeID = Record[0];
  587. if (TypeID >= TypeList.size())
  588. return Error("Invalid Type ID in TST_ENTRY record");
  589. TheModule->addTypeName(TypeName, TypeList[TypeID].get());
  590. TypeName.clear();
  591. break;
  592. }
  593. }
  594. }
  595. bool BitcodeReader::ParseValueSymbolTable() {
  596. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  597. return Error("Malformed block record");
  598. SmallVector<uint64_t, 64> Record;
  599. // Read all the records for this value table.
  600. SmallString<128> ValueName;
  601. while (1) {
  602. unsigned Code = Stream.ReadCode();
  603. if (Code == bitc::END_BLOCK) {
  604. if (Stream.ReadBlockEnd())
  605. return Error("Error at end of value symbol table block");
  606. return false;
  607. }
  608. if (Code == bitc::ENTER_SUBBLOCK) {
  609. // No known subblocks, always skip them.
  610. Stream.ReadSubBlockID();
  611. if (Stream.SkipBlock())
  612. return Error("Malformed block record");
  613. continue;
  614. }
  615. if (Code == bitc::DEFINE_ABBREV) {
  616. Stream.ReadAbbrevRecord();
  617. continue;
  618. }
  619. // Read a record.
  620. Record.clear();
  621. switch (Stream.ReadRecord(Code, Record)) {
  622. default: // Default behavior: unknown type.
  623. break;
  624. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  625. if (ConvertToString(Record, 1, ValueName))
  626. return Error("Invalid VST_ENTRY record");
  627. unsigned ValueID = Record[0];
  628. if (ValueID >= ValueList.size())
  629. return Error("Invalid Value ID in VST_ENTRY record");
  630. Value *V = ValueList[ValueID];
  631. V->setName(StringRef(ValueName.data(), ValueName.size()));
  632. ValueName.clear();
  633. break;
  634. }
  635. case bitc::VST_CODE_BBENTRY: {
  636. if (ConvertToString(Record, 1, ValueName))
  637. return Error("Invalid VST_BBENTRY record");
  638. BasicBlock *BB = getBasicBlock(Record[0]);
  639. if (BB == 0)
  640. return Error("Invalid BB ID in VST_BBENTRY record");
  641. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  642. ValueName.clear();
  643. break;
  644. }
  645. }
  646. }
  647. }
  648. bool BitcodeReader::ParseMetadata() {
  649. unsigned NextValueNo = MDValueList.size();
  650. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  651. return Error("Malformed block record");
  652. SmallVector<uint64_t, 64> Record;
  653. // Read all the records.
  654. while (1) {
  655. unsigned Code = Stream.ReadCode();
  656. if (Code == bitc::END_BLOCK) {
  657. if (Stream.ReadBlockEnd())
  658. return Error("Error at end of PARAMATTR block");
  659. return false;
  660. }
  661. if (Code == bitc::ENTER_SUBBLOCK) {
  662. // No known subblocks, always skip them.
  663. Stream.ReadSubBlockID();
  664. if (Stream.SkipBlock())
  665. return Error("Malformed block record");
  666. continue;
  667. }
  668. if (Code == bitc::DEFINE_ABBREV) {
  669. Stream.ReadAbbrevRecord();
  670. continue;
  671. }
  672. // Read a record.
  673. Record.clear();
  674. switch (Stream.ReadRecord(Code, Record)) {
  675. default: // Default behavior: ignore.
  676. break;
  677. case bitc::METADATA_NAME: {
  678. // Read named of the named metadata.
  679. unsigned NameLength = Record.size();
  680. SmallString<8> Name;
  681. Name.resize(NameLength);
  682. for (unsigned i = 0; i != NameLength; ++i)
  683. Name[i] = Record[i];
  684. Record.clear();
  685. Code = Stream.ReadCode();
  686. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  687. if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
  688. assert ( 0 && "Inavlid Named Metadata record");
  689. // Read named metadata elements.
  690. unsigned Size = Record.size();
  691. SmallVector<MetadataBase*, 8> Elts;
  692. for (unsigned i = 0; i != Size; ++i) {
  693. Value *MD = MDValueList.getValueFwdRef(Record[i]);
  694. if (MetadataBase *B = dyn_cast<MetadataBase>(MD))
  695. Elts.push_back(B);
  696. }
  697. Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
  698. Elts.size(), TheModule);
  699. MDValueList.AssignValue(V, NextValueNo++);
  700. break;
  701. }
  702. case bitc::METADATA_NODE: {
  703. if (Record.empty() || Record.size() % 2 == 1)
  704. return Error("Invalid METADATA_NODE record");
  705. unsigned Size = Record.size();
  706. SmallVector<Value*, 8> Elts;
  707. for (unsigned i = 0; i != Size; i += 2) {
  708. const Type *Ty = getTypeByID(Record[i], false);
  709. if (Ty->isMetadataTy())
  710. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  711. else if (Ty != Type::getVoidTy(Context))
  712. Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
  713. else
  714. Elts.push_back(NULL);
  715. }
  716. Value *V = MDNode::get(Context, &Elts[0], Elts.size());
  717. MDValueList.AssignValue(V, NextValueNo++);
  718. break;
  719. }
  720. case bitc::METADATA_STRING: {
  721. unsigned MDStringLength = Record.size();
  722. SmallString<8> String;
  723. String.resize(MDStringLength);
  724. for (unsigned i = 0; i != MDStringLength; ++i)
  725. String[i] = Record[i];
  726. Value *V = MDString::get(Context,
  727. StringRef(String.data(), String.size()));
  728. MDValueList.AssignValue(V, NextValueNo++);
  729. break;
  730. }
  731. case bitc::METADATA_KIND: {
  732. unsigned RecordLength = Record.size();
  733. if (Record.empty() || RecordLength < 2)
  734. return Error("Invalid METADATA_KIND record");
  735. SmallString<8> Name;
  736. Name.resize(RecordLength-1);
  737. unsigned Kind = Record[0];
  738. (void) Kind;
  739. for (unsigned i = 1; i != RecordLength; ++i)
  740. Name[i-1] = Record[i];
  741. MetadataContext &TheMetadata = Context.getMetadata();
  742. unsigned ExistingKind = TheMetadata.getMDKind(Name.str());
  743. if (ExistingKind == 0) {
  744. unsigned NewKind = TheMetadata.registerMDKind(Name.str());
  745. (void) NewKind;
  746. assert (Kind == NewKind
  747. && "Unable to handle custom metadata mismatch!");
  748. } else {
  749. assert (ExistingKind == Kind
  750. && "Unable to handle custom metadata mismatch!");
  751. }
  752. break;
  753. }
  754. }
  755. }
  756. }
  757. /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
  758. /// the LSB for dense VBR encoding.
  759. static uint64_t DecodeSignRotatedValue(uint64_t V) {
  760. if ((V & 1) == 0)
  761. return V >> 1;
  762. if (V != 1)
  763. return -(V >> 1);
  764. // There is no such thing as -0 with integers. "-0" really means MININT.
  765. return 1ULL << 63;
  766. }
  767. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  768. /// values and aliases that we can.
  769. bool BitcodeReader::ResolveGlobalAndAliasInits() {
  770. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  771. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  772. GlobalInitWorklist.swap(GlobalInits);
  773. AliasInitWorklist.swap(AliasInits);
  774. while (!GlobalInitWorklist.empty()) {
  775. unsigned ValID = GlobalInitWorklist.back().second;
  776. if (ValID >= ValueList.size()) {
  777. // Not ready to resolve this yet, it requires something later in the file.
  778. GlobalInits.push_back(GlobalInitWorklist.back());
  779. } else {
  780. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  781. GlobalInitWorklist.back().first->setInitializer(C);
  782. else
  783. return Error("Global variable initializer is not a constant!");
  784. }
  785. GlobalInitWorklist.pop_back();
  786. }
  787. while (!AliasInitWorklist.empty()) {
  788. unsigned ValID = AliasInitWorklist.back().second;
  789. if (ValID >= ValueList.size()) {
  790. AliasInits.push_back(AliasInitWorklist.back());
  791. } else {
  792. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  793. AliasInitWorklist.back().first->setAliasee(C);
  794. else
  795. return Error("Alias initializer is not a constant!");
  796. }
  797. AliasInitWorklist.pop_back();
  798. }
  799. return false;
  800. }
  801. bool BitcodeReader::ParseConstants() {
  802. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  803. return Error("Malformed block record");
  804. SmallVector<uint64_t, 64> Record;
  805. // Read all the records for this value table.
  806. const Type *CurTy = Type::getInt32Ty(Context);
  807. unsigned NextCstNo = ValueList.size();
  808. while (1) {
  809. unsigned Code = Stream.ReadCode();
  810. if (Code == bitc::END_BLOCK)
  811. break;
  812. if (Code == bitc::ENTER_SUBBLOCK) {
  813. // No known subblocks, always skip them.
  814. Stream.ReadSubBlockID();
  815. if (Stream.SkipBlock())
  816. return Error("Malformed block record");
  817. continue;
  818. }
  819. if (Code == bitc::DEFINE_ABBREV) {
  820. Stream.ReadAbbrevRecord();
  821. continue;
  822. }
  823. // Read a record.
  824. Record.clear();
  825. Value *V = 0;
  826. unsigned BitCode = Stream.ReadRecord(Code, Record);
  827. switch (BitCode) {
  828. default: // Default behavior: unknown constant
  829. case bitc::CST_CODE_UNDEF: // UNDEF
  830. V = UndefValue::get(CurTy);
  831. break;
  832. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  833. if (Record.empty())
  834. return Error("Malformed CST_SETTYPE record");
  835. if (Record[0] >= TypeList.size())
  836. return Error("Invalid Type ID in CST_SETTYPE record");
  837. CurTy = TypeList[Record[0]];
  838. continue; // Skip the ValueList manipulation.
  839. case bitc::CST_CODE_NULL: // NULL
  840. V = Constant::getNullValue(CurTy);
  841. break;
  842. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  843. if (!isa<IntegerType>(CurTy) || Record.empty())
  844. return Error("Invalid CST_INTEGER record");
  845. V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
  846. break;
  847. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  848. if (!isa<IntegerType>(CurTy) || Record.empty())
  849. return Error("Invalid WIDE_INTEGER record");
  850. unsigned NumWords = Record.size();
  851. SmallVector<uint64_t, 8> Words;
  852. Words.resize(NumWords);
  853. for (unsigned i = 0; i != NumWords; ++i)
  854. Words[i] = DecodeSignRotatedValue(Record[i]);
  855. V = ConstantInt::get(Context,
  856. APInt(cast<IntegerType>(CurTy)->getBitWidth(),
  857. NumWords, &Words[0]));
  858. break;
  859. }
  860. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  861. if (Record.empty())
  862. return Error("Invalid FLOAT record");
  863. if (CurTy->isFloatTy())
  864. V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
  865. else if (CurTy->isDoubleTy())
  866. V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
  867. else if (CurTy->isX86_FP80Ty()) {
  868. // Bits are not stored the same way as a normal i80 APInt, compensate.
  869. uint64_t Rearrange[2];
  870. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  871. Rearrange[1] = Record[0] >> 48;
  872. V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
  873. } else if (CurTy->isFP128Ty())
  874. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
  875. else if (CurTy->isPPC_FP128Ty())
  876. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
  877. else
  878. V = UndefValue::get(CurTy);
  879. break;
  880. }
  881. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  882. if (Record.empty())
  883. return Error("Invalid CST_AGGREGATE record");
  884. unsigned Size = Record.size();
  885. std::vector<Constant*> Elts;
  886. if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
  887. for (unsigned i = 0; i != Size; ++i)
  888. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  889. STy->getElementType(i)));
  890. V = ConstantStruct::get(STy, Elts);
  891. } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  892. const Type *EltTy = ATy->getElementType();
  893. for (unsigned i = 0; i != Size; ++i)
  894. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  895. V = ConstantArray::get(ATy, Elts);
  896. } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  897. const Type *EltTy = VTy->getElementType();
  898. for (unsigned i = 0; i != Size; ++i)
  899. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  900. V = ConstantVector::get(Elts);
  901. } else {
  902. V = UndefValue::get(CurTy);
  903. }
  904. break;
  905. }
  906. case bitc::CST_CODE_STRING: { // STRING: [values]
  907. if (Record.empty())
  908. return Error("Invalid CST_AGGREGATE record");
  909. const ArrayType *ATy = cast<ArrayType>(CurTy);
  910. const Type *EltTy = ATy->getElementType();
  911. unsigned Size = Record.size();
  912. std::vector<Constant*> Elts;
  913. for (unsigned i = 0; i != Size; ++i)
  914. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  915. V = ConstantArray::get(ATy, Elts);
  916. break;
  917. }
  918. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  919. if (Record.empty())
  920. return Error("Invalid CST_AGGREGATE record");
  921. const ArrayType *ATy = cast<ArrayType>(CurTy);
  922. const Type *EltTy = ATy->getElementType();
  923. unsigned Size = Record.size();
  924. std::vector<Constant*> Elts;
  925. for (unsigned i = 0; i != Size; ++i)
  926. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  927. Elts.push_back(Constant::getNullValue(EltTy));
  928. V = ConstantArray::get(ATy, Elts);
  929. break;
  930. }
  931. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  932. if (Record.size() < 3) return Error("Invalid CE_BINOP record");
  933. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  934. if (Opc < 0) {
  935. V = UndefValue::get(CurTy); // Unknown binop.
  936. } else {
  937. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  938. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  939. unsigned Flags = 0;
  940. if (Record.size() >= 4) {
  941. if (Opc == Instruction::Add ||
  942. Opc == Instruction::Sub ||
  943. Opc == Instruction::Mul) {
  944. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  945. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  946. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  947. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  948. } else if (Opc == Instruction::SDiv) {
  949. if (Record[3] & (1 << bitc::SDIV_EXACT))
  950. Flags |= SDivOperator::IsExact;
  951. }
  952. }
  953. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  954. }
  955. break;
  956. }
  957. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  958. if (Record.size() < 3) return Error("Invalid CE_CAST record");
  959. int Opc = GetDecodedCastOpcode(Record[0]);
  960. if (Opc < 0) {
  961. V = UndefValue::get(CurTy); // Unknown cast.
  962. } else {
  963. const Type *OpTy = getTypeByID(Record[1]);
  964. if (!OpTy) return Error("Invalid CE_CAST record");
  965. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  966. V = ConstantExpr::getCast(Opc, Op, CurTy);
  967. }
  968. break;
  969. }
  970. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  971. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  972. if (Record.size() & 1) return Error("Invalid CE_GEP record");
  973. SmallVector<Constant*, 16> Elts;
  974. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  975. const Type *ElTy = getTypeByID(Record[i]);
  976. if (!ElTy) return Error("Invalid CE_GEP record");
  977. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  978. }
  979. if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
  980. V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
  981. Elts.size()-1);
  982. else
  983. V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
  984. Elts.size()-1);
  985. break;
  986. }
  987. case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
  988. if (Record.size() < 3) return Error("Invalid CE_SELECT record");
  989. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  990. Type::getInt1Ty(Context)),
  991. ValueList.getConstantFwdRef(Record[1],CurTy),
  992. ValueList.getConstantFwdRef(Record[2],CurTy));
  993. break;
  994. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  995. if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
  996. const VectorType *OpTy =
  997. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  998. if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
  999. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1000. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1001. V = ConstantExpr::getExtractElement(Op0, Op1);
  1002. break;
  1003. }
  1004. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  1005. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1006. if (Record.size() < 3 || OpTy == 0)
  1007. return Error("Invalid CE_INSERTELT record");
  1008. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1009. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  1010. OpTy->getElementType());
  1011. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1012. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  1013. break;
  1014. }
  1015. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  1016. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1017. if (Record.size() < 3 || OpTy == 0)
  1018. return Error("Invalid CE_SHUFFLEVEC record");
  1019. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1020. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1021. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1022. OpTy->getNumElements());
  1023. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  1024. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1025. break;
  1026. }
  1027. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  1028. const VectorType *RTy = dyn_cast<VectorType>(CurTy);
  1029. const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
  1030. if (Record.size() < 4 || RTy == 0 || OpTy == 0)
  1031. return Error("Invalid CE_SHUFVEC_EX record");
  1032. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1033. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1034. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1035. RTy->getNumElements());
  1036. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  1037. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1038. break;
  1039. }
  1040. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  1041. if (Record.size() < 4) return Error("Invalid CE_CMP record");
  1042. const Type *OpTy = getTypeByID(Record[0]);
  1043. if (OpTy == 0) return Error("Invalid CE_CMP record");
  1044. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1045. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1046. if (OpTy->isFloatingPoint())
  1047. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  1048. else
  1049. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  1050. break;
  1051. }
  1052. case bitc::CST_CODE_INLINEASM: {
  1053. if (Record.size() < 2) return Error("Invalid INLINEASM record");
  1054. std::string AsmStr, ConstrStr;
  1055. bool HasSideEffects = Record[0] & 1;
  1056. bool IsAlignStack = Record[0] >> 1;
  1057. unsigned AsmStrSize = Record[1];
  1058. if (2+AsmStrSize >= Record.size())
  1059. return Error("Invalid INLINEASM record");
  1060. unsigned ConstStrSize = Record[2+AsmStrSize];
  1061. if (3+AsmStrSize+ConstStrSize > Record.size())
  1062. return Error("Invalid INLINEASM record");
  1063. for (unsigned i = 0; i != AsmStrSize; ++i)
  1064. AsmStr += (char)Record[2+i];
  1065. for (unsigned i = 0; i != ConstStrSize; ++i)
  1066. ConstrStr += (char)Record[3+AsmStrSize+i];
  1067. const PointerType *PTy = cast<PointerType>(CurTy);
  1068. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1069. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  1070. break;
  1071. }
  1072. case bitc::CST_CODE_BLOCKADDRESS:{
  1073. if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
  1074. const Type *FnTy = getTypeByID(Record[0]);
  1075. if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1076. Function *Fn =
  1077. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  1078. if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1079. GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
  1080. Type::getInt8Ty(Context),
  1081. false, GlobalValue::InternalLinkage,
  1082. 0, "");
  1083. BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
  1084. V = FwdRef;
  1085. break;
  1086. }
  1087. }
  1088. ValueList.AssignValue(V, NextCstNo);
  1089. ++NextCstNo;
  1090. }
  1091. if (NextCstNo != ValueList.size())
  1092. return Error("Invalid constant reference!");
  1093. if (Stream.ReadBlockEnd())
  1094. return Error("Error at end of constants block");
  1095. // Once all the constants have been read, go through and resolve forward
  1096. // references.
  1097. ValueList.ResolveConstantForwardRefs();
  1098. return false;
  1099. }
  1100. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  1101. /// remember where it is and then skip it. This lets us lazily deserialize the
  1102. /// functions.
  1103. bool BitcodeReader::RememberAndSkipFunctionBody() {
  1104. // Get the function we are talking about.
  1105. if (FunctionsWithBodies.empty())
  1106. return Error("Insufficient function protos");
  1107. Function *Fn = FunctionsWithBodies.back();
  1108. FunctionsWithBodies.pop_back();
  1109. // Save the current stream state.
  1110. uint64_t CurBit = Stream.GetCurrentBitNo();
  1111. DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
  1112. // Set the functions linkage to GhostLinkage so we know it is lazily
  1113. // deserialized.
  1114. Fn->setLinkage(GlobalValue::GhostLinkage);
  1115. // Skip over the function block for now.
  1116. if (Stream.SkipBlock())
  1117. return Error("Malformed block record");
  1118. return false;
  1119. }
  1120. bool BitcodeReader::ParseModule(const std::string &ModuleID) {
  1121. // Reject multiple MODULE_BLOCK's in a single bitstream.
  1122. if (TheModule)
  1123. return Error("Multiple MODULE_BLOCKs in same stream");
  1124. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1125. return Error("Malformed block record");
  1126. // Otherwise, create the module.
  1127. TheModule = new Module(ModuleID, Context);
  1128. SmallVector<uint64_t, 64> Record;
  1129. std::vector<std::string> SectionTable;
  1130. std::vector<std::string> GCTable;
  1131. // Read all the records for this module.
  1132. while (!Stream.AtEndOfStream()) {
  1133. unsigned Code = Stream.ReadCode();
  1134. if (Code == bitc::END_BLOCK) {
  1135. if (Stream.ReadBlockEnd())
  1136. return Error("Error at end of module block");
  1137. // Patch the initializers for globals and aliases up.
  1138. ResolveGlobalAndAliasInits();
  1139. if (!GlobalInits.empty() || !AliasInits.empty())
  1140. return Error("Malformed global initializer set");
  1141. if (!FunctionsWithBodies.empty())
  1142. return Error("Too few function bodies found");
  1143. // Look for intrinsic functions which need to be upgraded at some point
  1144. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  1145. FI != FE; ++FI) {
  1146. Function* NewFn;
  1147. if (UpgradeIntrinsicFunction(FI, NewFn))
  1148. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  1149. }
  1150. // Force deallocation of memory for these vectors to favor the client that
  1151. // want lazy deserialization.
  1152. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  1153. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  1154. std::vector<Function*>().swap(FunctionsWithBodies);
  1155. return false;
  1156. }
  1157. if (Code == bitc::ENTER_SUBBLOCK) {
  1158. switch (Stream.ReadSubBlockID()) {
  1159. default: // Skip unknown content.
  1160. if (Stream.SkipBlock())
  1161. return Error("Malformed block record");
  1162. break;
  1163. case bitc::BLOCKINFO_BLOCK_ID:
  1164. if (Stream.ReadBlockInfoBlock())
  1165. return Error("Malformed BlockInfoBlock");
  1166. break;
  1167. case bitc::PARAMATTR_BLOCK_ID:
  1168. if (ParseAttributeBlock())
  1169. return true;
  1170. break;
  1171. case bitc::TYPE_BLOCK_ID:
  1172. if (ParseTypeTable())
  1173. return true;
  1174. break;
  1175. case bitc::TYPE_SYMTAB_BLOCK_ID:
  1176. if (ParseTypeSymbolTable())
  1177. return true;
  1178. break;
  1179. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1180. if (ParseValueSymbolTable())
  1181. return true;
  1182. break;
  1183. case bitc::CONSTANTS_BLOCK_ID:
  1184. if (ParseConstants() || ResolveGlobalAndAliasInits())
  1185. return true;
  1186. break;
  1187. case bitc::METADATA_BLOCK_ID:
  1188. if (ParseMetadata())
  1189. return true;
  1190. break;
  1191. case bitc::FUNCTION_BLOCK_ID:
  1192. // If this is the first function body we've seen, reverse the
  1193. // FunctionsWithBodies list.
  1194. if (!HasReversedFunctionsWithBodies) {
  1195. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  1196. HasReversedFunctionsWithBodies = true;
  1197. }
  1198. if (RememberAndSkipFunctionBody())
  1199. return true;
  1200. break;
  1201. }
  1202. continue;
  1203. }
  1204. if (Code == bitc::DEFINE_ABBREV) {
  1205. Stream.ReadAbbrevRecord();
  1206. continue;
  1207. }
  1208. // Read a record.
  1209. switch (Stream.ReadRecord(Code, Record)) {
  1210. default: break; // Default behavior, ignore unknown content.
  1211. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  1212. if (Record.size() < 1)
  1213. return Error("Malformed MODULE_CODE_VERSION");
  1214. // Only version #0 is supported so far.
  1215. if (Record[0] != 0)
  1216. return Error("Unknown bitstream version!");
  1217. break;
  1218. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1219. std::string S;
  1220. if (ConvertToString(Record, 0, S))
  1221. return Error("Invalid MODULE_CODE_TRIPLE record");
  1222. TheModule->setTargetTriple(S);
  1223. break;
  1224. }
  1225. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  1226. std::string S;
  1227. if (ConvertToString(Record, 0, S))
  1228. return Error("Invalid MODULE_CODE_DATALAYOUT record");
  1229. TheModule->setDataLayout(S);
  1230. break;
  1231. }
  1232. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  1233. std::string S;
  1234. if (ConvertToString(Record, 0, S))
  1235. return Error("Invalid MODULE_CODE_ASM record");
  1236. TheModule->setModuleInlineAsm(S);
  1237. break;
  1238. }
  1239. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  1240. std::string S;
  1241. if (ConvertToString(Record, 0, S))
  1242. return Error("Invalid MODULE_CODE_DEPLIB record");
  1243. TheModule->addLibrary(S);
  1244. break;
  1245. }
  1246. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  1247. std::string S;
  1248. if (ConvertToString(Record, 0, S))
  1249. return Error("Invalid MODULE_CODE_SECTIONNAME record");
  1250. SectionTable.push_back(S);
  1251. break;
  1252. }
  1253. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  1254. std::string S;
  1255. if (ConvertToString(Record, 0, S))
  1256. return Error("Invalid MODULE_CODE_GCNAME record");
  1257. GCTable.push_back(S);
  1258. break;
  1259. }
  1260. // GLOBALVAR: [pointer type, isconst, initid,
  1261. // linkage, alignment, section, visibility, threadlocal]
  1262. case bitc::MODULE_CODE_GLOBALVAR: {
  1263. if (Record.size() < 6)
  1264. return Error("Invalid MODULE_CODE_GLOBALVAR record");
  1265. const Type *Ty = getTypeByID(Record[0]);
  1266. if (!isa<PointerType>(Ty))
  1267. return Error("Global not a pointer type!");
  1268. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  1269. Ty = cast<PointerType>(Ty)->getElementType();
  1270. bool isConstant = Record[1];
  1271. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  1272. unsigned Alignment = (1 << Record[4]) >> 1;
  1273. std::string Section;
  1274. if (Record[5]) {
  1275. if (Record[5]-1 >= SectionTable.size())
  1276. return Error("Invalid section ID");
  1277. Section = SectionTable[Record[5]-1];
  1278. }
  1279. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  1280. if (Record.size() > 6)
  1281. Visibility = GetDecodedVisibility(Record[6]);
  1282. bool isThreadLocal = false;
  1283. if (Record.size() > 7)
  1284. isThreadLocal = Record[7];
  1285. GlobalVariable *NewGV =
  1286. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
  1287. isThreadLocal, AddressSpace);
  1288. NewGV->setAlignment(Alignment);
  1289. if (!Section.empty())
  1290. NewGV->setSection(Section);
  1291. NewGV->setVisibility(Visibility);
  1292. NewGV->setThreadLocal(isThreadLocal);
  1293. ValueList.push_back(NewGV);
  1294. // Remember which value to use for the global initializer.
  1295. if (unsigned InitID = Record[2])
  1296. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  1297. break;
  1298. }
  1299. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  1300. // alignment, section, visibility, gc]
  1301. case bitc::MODULE_CODE_FUNCTION: {
  1302. if (Record.size() < 8)
  1303. return Error("Invalid MODULE_CODE_FUNCTION record");
  1304. const Type *Ty = getTypeByID(Record[0]);
  1305. if (!isa<PointerType>(Ty))
  1306. return Error("Function not a pointer type!");
  1307. const FunctionType *FTy =
  1308. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1309. if (!FTy)
  1310. return Error("Function not a pointer to function type!");
  1311. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  1312. "", TheModule);
  1313. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  1314. bool isProto = Record[2];
  1315. Func->setLinkage(GetDecodedLinkage(Record[3]));
  1316. Func->setAttributes(getAttributes(Record[4]));
  1317. Func->setAlignment((1 << Record[5]) >> 1);
  1318. if (Record[6]) {
  1319. if (Record[6]-1 >= SectionTable.size())
  1320. return Error("Invalid section ID");
  1321. Func->setSection(SectionTable[Record[6]-1]);
  1322. }
  1323. Func->setVisibility(GetDecodedVisibility(Record[7]));
  1324. if (Record.size() > 8 && Record[8]) {
  1325. if (Record[8]-1 > GCTable.size())
  1326. return Error("Invalid GC ID");
  1327. Func->setGC(GCTable[Record[8]-1].c_str());
  1328. }
  1329. ValueList.push_back(Func);
  1330. // If this is a function with a body, remember the prototype we are
  1331. // creating now, so that we can match up the body with them later.
  1332. if (!isProto)
  1333. FunctionsWithBodies.push_back(Func);
  1334. break;
  1335. }
  1336. // ALIAS: [alias type, aliasee val#, linkage]
  1337. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  1338. case bitc::MODULE_CODE_ALIAS: {
  1339. if (Record.size() < 3)
  1340. return Error("Invalid MODULE_ALIAS record");
  1341. const Type *Ty = getTypeByID(Record[0]);
  1342. if (!isa<PointerType>(Ty))
  1343. return Error("Function not a pointer type!");
  1344. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  1345. "", 0, TheModule);
  1346. // Old bitcode files didn't have visibility field.
  1347. if (Record.size() > 3)
  1348. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  1349. ValueList.push_back(NewGA);
  1350. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  1351. break;
  1352. }
  1353. /// MODULE_CODE_PURGEVALS: [numvals]
  1354. case bitc::MODULE_CODE_PURGEVALS:
  1355. // Trim down the value list to the specified size.
  1356. if (Record.size() < 1 || Record[0] > ValueList.size())
  1357. return Error("Invalid MODULE_PURGEVALS record");
  1358. ValueList.shrinkTo(Record[0]);
  1359. break;
  1360. }
  1361. Record.clear();
  1362. }
  1363. return Error("Premature end of bitstream");
  1364. }
  1365. bool BitcodeReader::ParseBitcode() {
  1366. TheModule = 0;
  1367. if (Buffer->getBufferSize() & 3)
  1368. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  1369. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  1370. unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  1371. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  1372. // The magic number is 0x0B17C0DE stored in little endian.
  1373. if (isBitcodeWrapper(BufPtr, BufEnd))
  1374. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
  1375. return Error("Invalid bitcode wrapper header");
  1376. StreamFile.init(BufPtr, BufEnd);
  1377. Stream.init(StreamFile);
  1378. // Sniff for the signature.
  1379. if (Stream.Read(8) != 'B' ||
  1380. Stream.Read(8) != 'C' ||
  1381. Stream.Read(4) != 0x0 ||
  1382. Stream.Read(4) != 0xC ||
  1383. Stream.Read(4) != 0xE ||
  1384. Stream.Read(4) != 0xD)
  1385. return Error("Invalid bitcode signature");
  1386. // We expect a number of well-defined blocks, though we don't necessarily
  1387. // need to understand them all.
  1388. while (!Stream.AtEndOfStream()) {
  1389. unsigned Code = Stream.ReadCode();
  1390. if (Code != bitc::ENTER_SUBBLOCK)
  1391. return Error("Invalid record at top-level");
  1392. unsigned BlockID = Stream.ReadSubBlockID();
  1393. // We only know the MODULE subblock ID.
  1394. switch (BlockID) {
  1395. case bitc::BLOCKINFO_BLOCK_ID:
  1396. if (Stream.ReadBlockInfoBlock())
  1397. return Error("Malformed BlockInfoBlock");
  1398. break;
  1399. case bitc::MODULE_BLOCK_ID:
  1400. if (ParseModule(Buffer->getBufferIdentifier()))
  1401. return true;
  1402. break;
  1403. default:
  1404. if (Stream.SkipBlock())
  1405. return Error("Malformed block record");
  1406. break;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. /// ParseMetadataAttachment - Parse metadata attachments.
  1412. bool BitcodeReader::ParseMetadataAttachment() {
  1413. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1414. return Error("Malformed block record");
  1415. MetadataContext &TheMetadata = Context.getMetadata();
  1416. SmallVector<uint64_t, 64> Record;
  1417. while(1) {
  1418. unsigned Code = Stream.ReadCode();
  1419. if (Code == bitc::END_BLOCK) {
  1420. if (Stream.ReadBlockEnd())
  1421. return Error("Error at end of PARAMATTR block");
  1422. break;
  1423. }
  1424. if (Code == bitc::DEFINE_ABBREV) {
  1425. Stream.ReadAbbrevRecord();
  1426. continue;
  1427. }
  1428. // Read a metadata attachment record.
  1429. Record.clear();
  1430. switch (Stream.ReadRecord(Code, Record)) {
  1431. default: // Default behavior: ignore.
  1432. break;
  1433. case bitc::METADATA_ATTACHMENT: {
  1434. unsigned RecordLength = Record.size();
  1435. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  1436. return Error ("Invalid METADATA_ATTACHMENT reader!");
  1437. Instruction *Inst = InstructionList[Record[0]];
  1438. for (unsigned i = 1; i != RecordLength; i = i+2) {
  1439. unsigned Kind = Record[i];
  1440. Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
  1441. TheMetadata.addMD(Kind, cast<MDNode>(Node), Inst);
  1442. }
  1443. break;
  1444. }
  1445. }
  1446. }
  1447. return false;
  1448. }
  1449. /// ParseFunctionBody - Lazily parse the specified function body block.
  1450. bool BitcodeReader::ParseFunctionBody(Function *F) {
  1451. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1452. return Error("Malformed block record");
  1453. unsigned ModuleValueListSize = ValueList.size();
  1454. // Add all the function arguments to the value table.
  1455. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1456. ValueList.push_back(I);
  1457. unsigned NextValueNo = ValueList.size();
  1458. BasicBlock *CurBB = 0;
  1459. unsigned CurBBNo = 0;
  1460. // Read all the records.
  1461. SmallVector<uint64_t, 64> Record;
  1462. while (1) {
  1463. unsigned Code = Stream.ReadCode();
  1464. if (Code == bitc::END_BLOCK) {
  1465. if (Stream.ReadBlockEnd())
  1466. return Error("Error at end of function block");
  1467. break;
  1468. }
  1469. if (Code == bitc::ENTER_SUBBLOCK) {
  1470. switch (Stream.ReadSubBlockID()) {
  1471. default: // Skip unknown content.
  1472. if (Stream.SkipBlock())
  1473. return Error("Malformed block record");
  1474. break;
  1475. case bitc::CONSTANTS_BLOCK_ID:
  1476. if (ParseConstants()) return true;
  1477. NextValueNo = ValueList.size();
  1478. break;
  1479. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1480. if (ParseValueSymbolTable()) return true;
  1481. break;
  1482. case bitc::METADATA_ATTACHMENT_ID:
  1483. if (ParseMetadataAttachment()) return true;
  1484. break;
  1485. }
  1486. continue;
  1487. }
  1488. if (Code == bitc::DEFINE_ABBREV) {
  1489. Stream.ReadAbbrevRecord();
  1490. continue;
  1491. }
  1492. // Read a record.
  1493. Record.clear();
  1494. Instruction *I = 0;
  1495. unsigned BitCode = Stream.ReadRecord(Code, Record);
  1496. switch (BitCode) {
  1497. default: // Default behavior: reject
  1498. return Error("Unknown instruction");
  1499. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  1500. if (Record.size() < 1 || Record[0] == 0)
  1501. return Error("Invalid DECLAREBLOCKS record");
  1502. // Create all the basic blocks for the function.
  1503. FunctionBBs.resize(Record[0]);
  1504. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1505. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  1506. CurBB = FunctionBBs[0];
  1507. continue;
  1508. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  1509. unsigned OpNum = 0;
  1510. Value *LHS, *RHS;
  1511. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1512. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1513. OpNum+1 > Record.size())
  1514. return Error("Invalid BINOP record");
  1515. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  1516. if (Opc == -1) return Error("Invalid BINOP record");
  1517. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  1518. InstructionList.push_back(I);
  1519. if (OpNum < Record.size()) {
  1520. if (Opc == Instruction::Add ||
  1521. Opc == Instruction::Sub ||
  1522. Opc == Instruction::Mul) {
  1523. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  1524. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  1525. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  1526. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  1527. } else if (Opc == Instruction::SDiv) {
  1528. if (Record[3] & (1 << bitc::SDIV_EXACT))
  1529. cast<BinaryOperator>(I)->setIsExact(true);
  1530. }
  1531. }
  1532. break;
  1533. }
  1534. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  1535. unsigned OpNum = 0;
  1536. Value *Op;
  1537. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1538. OpNum+2 != Record.size())
  1539. return Error("Invalid CAST record");
  1540. const Type *ResTy = getTypeByID(Record[OpNum]);
  1541. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  1542. if (Opc == -1 || ResTy == 0)
  1543. return Error("Invalid CAST record");
  1544. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  1545. InstructionList.push_back(I);
  1546. break;
  1547. }
  1548. case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
  1549. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  1550. unsigned OpNum = 0;
  1551. Value *BasePtr;
  1552. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  1553. return Error("Invalid GEP record");
  1554. SmallVector<Value*, 16> GEPIdx;
  1555. while (OpNum != Record.size()) {
  1556. Value *Op;
  1557. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1558. return Error("Invalid GEP record");
  1559. GEPIdx.push_back(Op);
  1560. }
  1561. I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
  1562. InstructionList.push_back(I);
  1563. if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
  1564. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  1565. break;
  1566. }
  1567. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  1568. // EXTRACTVAL: [opty, opval, n x indices]
  1569. unsigned OpNum = 0;
  1570. Value *Agg;
  1571. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1572. return Error("Invalid EXTRACTVAL record");
  1573. SmallVector<unsigned, 4> EXTRACTVALIdx;
  1574. for (unsigned RecSize = Record.size();
  1575. OpNum != RecSize; ++OpNum) {
  1576. uint64_t Index = Record[OpNum];
  1577. if ((unsigned)Index != Index)
  1578. return Error("Invalid EXTRACTVAL index");
  1579. EXTRACTVALIdx.push_back((unsigned)Index);
  1580. }
  1581. I = ExtractValueInst::Create(Agg,
  1582. EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
  1583. InstructionList.push_back(I);
  1584. break;
  1585. }
  1586. case bitc::FUNC_CODE_INST_INSERTVAL: {
  1587. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  1588. unsigned OpNum = 0;
  1589. Value *Agg;
  1590. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1591. return Error("Invalid INSERTVAL record");
  1592. Value *Val;
  1593. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  1594. return Error("Invalid INSERTVAL record");
  1595. SmallVector<unsigned, 4> INSERTVALIdx;
  1596. for (unsigned RecSize = Record.size();
  1597. OpNum != RecSize; ++OpNum) {
  1598. uint64_t Index = Record[OpNum];
  1599. if ((unsigned)Index != Index)
  1600. return Error("Invalid INSERTVAL index");
  1601. INSERTVALIdx.push_back((unsigned)Index);
  1602. }
  1603. I = InsertValueInst::Create(Agg, Val,
  1604. INSERTVALIdx.begin(), INSERTVALIdx.end());
  1605. InstructionList.push_back(I);
  1606. break;
  1607. }
  1608. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  1609. // obsolete form of select
  1610. // handles select i1 ... in old bitcode
  1611. unsigned OpNum = 0;
  1612. Value *TrueVal, *FalseVal, *Cond;
  1613. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1614. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1615. getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
  1616. return Error("Invalid SELECT record");
  1617. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1618. InstructionList.push_back(I);
  1619. break;
  1620. }
  1621. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  1622. // new form of select
  1623. // handles select i1 or select [N x i1]
  1624. unsigned OpNum = 0;
  1625. Value *TrueVal, *FalseVal, *Cond;
  1626. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1627. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1628. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  1629. return Error("Invalid SELECT record");
  1630. // select condition can be either i1 or [N x i1]
  1631. if (const VectorType* vector_type =
  1632. dyn_cast<const VectorType>(Cond->getType())) {
  1633. // expect <n x i1>
  1634. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  1635. return Error("Invalid SELECT condition type");
  1636. } else {
  1637. // expect i1
  1638. if (Cond->getType() != Type::getInt1Ty(Context))
  1639. return Error("Invalid SELECT condition type");
  1640. }
  1641. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1642. InstructionList.push_back(I);
  1643. break;
  1644. }
  1645. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  1646. unsigned OpNum = 0;
  1647. Value *Vec, *Idx;
  1648. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1649. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1650. return Error("Invalid EXTRACTELT record");
  1651. I = ExtractElementInst::Create(Vec, Idx);
  1652. InstructionList.push_back(I);
  1653. break;
  1654. }
  1655. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  1656. unsigned OpNum = 0;
  1657. Value *Vec, *Elt, *Idx;
  1658. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1659. getValue(Record, OpNum,
  1660. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  1661. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1662. return Error("Invalid INSERTELT record");
  1663. I = InsertElementInst::Create(Vec, Elt, Idx);
  1664. InstructionList.push_back(I);
  1665. break;
  1666. }
  1667. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  1668. unsigned OpNum = 0;
  1669. Value *Vec1, *Vec2, *Mask;
  1670. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  1671. getValue(Record, OpNum, Vec1->getType(), Vec2))
  1672. return Error("Invalid SHUFFLEVEC record");
  1673. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  1674. return Error("Invalid SHUFFLEVEC record");
  1675. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  1676. InstructionList.push_back(I);
  1677. break;
  1678. }
  1679. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  1680. // Old form of ICmp/FCmp returning bool
  1681. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  1682. // both legal on vectors but had different behaviour.
  1683. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  1684. // FCmp/ICmp returning bool or vector of bool
  1685. unsigned OpNum = 0;
  1686. Value *LHS, *RHS;
  1687. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1688. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1689. OpNum+1 != Record.size())
  1690. return Error("Invalid CMP record");
  1691. if (LHS->getType()->isFPOrFPVector())
  1692. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  1693. else
  1694. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  1695. InstructionList.push_back(I);
  1696. break;
  1697. }
  1698. case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
  1699. if (Record.size() != 2)
  1700. return Error("Invalid GETRESULT record");
  1701. unsigned OpNum = 0;
  1702. Value *Op;
  1703. getValueTypePair(Record, OpNum, NextValueNo, Op);
  1704. unsigned Index = Record[1];
  1705. I = ExtractValueInst::Create(Op, Index);
  1706. InstructionList.push_back(I);
  1707. break;
  1708. }
  1709. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  1710. {
  1711. unsigned Size = Record.size();
  1712. if (Size == 0) {
  1713. I = ReturnInst::Create(Context);
  1714. InstructionList.push_back(I);
  1715. break;
  1716. }
  1717. unsigned OpNum = 0;
  1718. SmallVector<Value *,4> Vs;
  1719. do {
  1720. Value *Op = NULL;
  1721. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1722. return Error("Invalid RET record");
  1723. Vs.push_back(Op);
  1724. } while(OpNum != Record.size());
  1725. const Type *ReturnType = F->getReturnType();
  1726. if (Vs.size() > 1 ||
  1727. (isa<StructType>(ReturnType) &&
  1728. (Vs.empty() || Vs[0]->getType() != ReturnType))) {
  1729. Value *RV = UndefValue::get(ReturnType);
  1730. for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
  1731. I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
  1732. InstructionList.push_back(I);
  1733. CurBB->getInstList().push_back(I);
  1734. ValueList.AssignValue(I, NextValueNo++);
  1735. RV = I;
  1736. }
  1737. I = ReturnInst::Create(Context, RV);
  1738. InstructionList.push_back(I);
  1739. break;
  1740. }
  1741. I = ReturnInst::Create(Context, Vs[0]);
  1742. InstructionList.push_back(I);
  1743. break;
  1744. }
  1745. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  1746. if (Record.size() != 1 && Record.size() != 3)
  1747. return Error("Invalid BR record");
  1748. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  1749. if (TrueDest == 0)
  1750. return Error("Invalid BR record");
  1751. if (Record.size() == 1) {
  1752. I = BranchInst::Create(TrueDest);
  1753. InstructionList.push_back(I);
  1754. }
  1755. else {
  1756. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  1757. Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
  1758. if (FalseDest == 0 || Cond == 0)
  1759. return Error("Invalid BR record");
  1760. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  1761. InstructionList.push_back(I);
  1762. }
  1763. break;
  1764. }
  1765. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  1766. if (Record.size() < 3 || (Record.size() & 1) == 0)
  1767. return Error("Invalid SWITCH record");
  1768. const Type *OpTy = getTypeByID(Record[0]);
  1769. Value *Cond = getFnValueByID(Record[1], OpTy);
  1770. BasicBlock *Default = getBasicBlock(Record[2]);
  1771. if (OpTy == 0 || Cond == 0 || Default == 0)
  1772. return Error("Invalid SWITCH record");
  1773. unsigned NumCases = (Record.size()-3)/2;
  1774. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  1775. InstructionList.push_back(SI);
  1776. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  1777. ConstantInt *CaseVal =
  1778. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  1779. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  1780. if (CaseVal == 0 || DestBB == 0) {
  1781. delete SI;
  1782. return Error("Invalid SWITCH record!");
  1783. }
  1784. SI->addCase(CaseVal, DestBB);
  1785. }
  1786. I = SI;
  1787. break;
  1788. }
  1789. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  1790. if (Record.size() < 2)
  1791. return Error("Invalid INDIRECTBR record");
  1792. const Type *OpTy = getTypeByID(Record[0]);
  1793. Value *Address = getFnValueByID(Record[1], OpTy);
  1794. if (OpTy == 0 || Address == 0)
  1795. return Error("Invalid INDIRECTBR record");
  1796. unsigned NumDests = Record.size()-2;
  1797. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  1798. InstructionList.push_back(IBI);
  1799. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  1800. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  1801. IBI->addDestination(DestBB);
  1802. } else {
  1803. delete IBI;
  1804. return Error("Invalid INDIRECTBR record!");
  1805. }
  1806. }
  1807. I = IBI;
  1808. break;
  1809. }
  1810. case bitc::FUNC_CODE_INST_INVOKE: {
  1811. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  1812. if (Record.size() < 4) return Error("Invalid INVOKE record");
  1813. AttrListPtr PAL = getAttributes(Record[0]);
  1814. unsigned CCInfo = Record[1];
  1815. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  1816. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  1817. unsigned OpNum = 4;
  1818. Value *Callee;
  1819. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1820. return Error("Invalid INVOKE record");
  1821. const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  1822. const FunctionType *FTy = !CalleeTy ? 0 :
  1823. dyn_cast<FunctionType>(CalleeTy->getElementType());
  1824. // Check that the right number of fixed parameters are here.
  1825. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  1826. Record.size() < OpNum+FTy->getNumParams())
  1827. return Error("Invalid INVOKE record");
  1828. SmallVector<Value*, 16> Ops;
  1829. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1830. Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1831. if (Ops.back() == 0) return Error("Invalid INVOKE record");
  1832. }
  1833. if (!FTy->isVarArg()) {
  1834. if (Record.size() != OpNum)
  1835. return Error("Invalid INVOKE record");
  1836. } else {
  1837. // Read type/value pairs for varargs params.
  1838. while (OpNum != Record.size()) {
  1839. Value *Op;
  1840. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1841. return Error("Invalid INVOKE record");
  1842. Ops.push_back(Op);
  1843. }
  1844. }
  1845. I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
  1846. Ops.begin(), Ops.end());
  1847. InstructionList.push_back(I);
  1848. cast<InvokeInst>(I)->setCallingConv(
  1849. static_cast<CallingConv::ID>(CCInfo));
  1850. cast<InvokeInst>(I)->setAttributes(PAL);
  1851. break;
  1852. }
  1853. case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
  1854. I = new UnwindInst(Context);
  1855. InstructionList.push_back(I);
  1856. break;
  1857. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  1858. I = new UnreachableInst(Context);
  1859. InstructionList.push_back(I);
  1860. break;
  1861. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  1862. if (Record.size() < 1 || ((Record.size()-1)&1))
  1863. return Error("Invalid PHI record");
  1864. const Type *Ty = getTypeByID(Record[0]);
  1865. if (!Ty) return Error("Invalid PHI record");
  1866. PHINode *PN = PHINode::Create(Ty);
  1867. InstructionList.push_back(PN);
  1868. PN->reserveOperandSpace((Record.size()-1)/2);
  1869. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  1870. Value *V = getFnValueByID(Record[1+i], Ty);
  1871. BasicBlock *BB = getBasicBlock(Record[2+i]);
  1872. if (!V || !BB) return Error("Invalid PHI record");
  1873. PN->addIncoming(V, BB);
  1874. }
  1875. I = PN;
  1876. break;
  1877. }
  1878. case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
  1879. // Autoupgrade malloc instruction to malloc call.
  1880. // FIXME: Remove in LLVM 3.0.
  1881. if (Record.size() < 3)
  1882. return Error("Invalid MALLOC record");
  1883. const PointerType *Ty =
  1884. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1885. Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
  1886. if (!Ty || !Size) return Error("Invalid MALLOC record");
  1887. if (!CurBB) return Error("Invalid malloc instruction with no BB");
  1888. const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
  1889. I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
  1890. Size, NULL);
  1891. InstructionList.push_back(I);
  1892. break;
  1893. }
  1894. case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
  1895. unsigned OpNum = 0;
  1896. Value *Op;
  1897. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1898. OpNum != Record.size())
  1899. return Error("Invalid FREE record");
  1900. if (!CurBB) return Error("Invalid free instruction with no BB");
  1901. I = CallInst::CreateFree(Op, CurBB);
  1902. InstructionList.push_back(I);
  1903. break;
  1904. }
  1905. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
  1906. if (Record.size() < 3)
  1907. return Error("Invalid ALLOCA record");
  1908. const PointerType *Ty =
  1909. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1910. Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
  1911. unsigned Align = Record[2];
  1912. if (!Ty || !Size) return Error("Invalid ALLOCA record");
  1913. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1914. InstructionList.push_back(I);
  1915. break;
  1916. }
  1917. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  1918. unsigned OpNum = 0;
  1919. Value *Op;
  1920. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1921. OpNum+2 != Record.size())
  1922. return Error("Invalid LOAD record");
  1923. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1924. InstructionList.push_back(I);
  1925. break;
  1926. }
  1927. case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
  1928. unsigned OpNum = 0;
  1929. Value *Val, *Ptr;
  1930. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  1931. getValue(Record, OpNum,
  1932. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  1933. OpNum+2 != Record.size())
  1934. return Error("Invalid STORE record");
  1935. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1936. InstructionList.push_back(I);
  1937. break;
  1938. }
  1939. case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
  1940. // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
  1941. unsigned OpNum = 0;
  1942. Value *Val, *Ptr;
  1943. if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
  1944. getValue(Record, OpNum,
  1945. PointerType::getUnqual(Val->getType()), Ptr)||
  1946. OpNum+2 != Record.size())
  1947. return Error("Invalid STORE record");
  1948. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  1949. InstructionList.push_back(I);
  1950. break;
  1951. }
  1952. case bitc::FUNC_CODE_INST_CALL: {
  1953. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  1954. if (Record.size() < 3)
  1955. return Error("Invalid CALL record");
  1956. AttrListPtr PAL = getAttributes(Record[0]);
  1957. unsigned CCInfo = Record[1];
  1958. unsigned OpNum = 2;
  1959. Value *Callee;
  1960. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1961. return Error("Invalid CALL record");
  1962. const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  1963. const FunctionType *FTy = 0;
  1964. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  1965. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  1966. return Error("Invalid CALL record");
  1967. SmallVector<Value*, 16> Args;
  1968. // Read the fixed params.
  1969. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1970. if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
  1971. Args.push_back(getBasicBlock(Record[OpNum]));
  1972. else
  1973. Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1974. if (Args.back() == 0) return Error("Invalid CALL record");
  1975. }
  1976. // Read type/value pairs for varargs params.
  1977. if (!FTy->isVarArg()) {
  1978. if (OpNum != Record.size())
  1979. return Error("Invalid CALL record");
  1980. } else {
  1981. while (OpNum != Record.size()) {
  1982. Value *Op;
  1983. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1984. return Error("Invalid CALL record");
  1985. Args.push_back(Op);
  1986. }
  1987. }
  1988. I = CallInst::Create(Callee, Args.begin(), Args.end());
  1989. InstructionList.push_back(I);
  1990. cast<CallInst>(I)->setCallingConv(
  1991. static_cast<CallingConv::ID>(CCInfo>>1));
  1992. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  1993. cast<CallInst>(I)->setAttributes(PAL);
  1994. break;
  1995. }
  1996. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  1997. if (Record.size() < 3)
  1998. return Error("Invalid VAARG record");
  1999. const Type *OpTy = getTypeByID(Record[0]);
  2000. Value *Op = getFnValueByID(Record[1], OpTy);
  2001. const Type *ResTy = getTypeByID(Record[2]);
  2002. if (!OpTy || !Op || !ResTy)
  2003. return Error("Invalid VAARG record");
  2004. I = new VAArgInst(Op, ResTy);
  2005. InstructionList.push_back(I);
  2006. break;
  2007. }
  2008. }
  2009. // Add instruction to end of current BB. If there is no current BB, reject
  2010. // this file.
  2011. if (CurBB == 0) {
  2012. delete I;
  2013. return Error("Invalid instruction with no BB");
  2014. }
  2015. CurBB->getInstList().push_back(I);
  2016. // If this was a terminator instruction, move to the next block.
  2017. if (isa<TerminatorInst>(I)) {
  2018. ++CurBBNo;
  2019. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  2020. }
  2021. // Non-void values get registered in the value table for future use.
  2022. if (I && I->getType() != Type::getVoidTy(Context))
  2023. ValueList.AssignValue(I, NextValueNo++);
  2024. }
  2025. // Check the function list for unresolved values.
  2026. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  2027. if (A->getParent() == 0) {
  2028. // We found at least one unresolved value. Nuke them all to avoid leaks.
  2029. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  2030. if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
  2031. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  2032. delete A;
  2033. }
  2034. }
  2035. return Error("Never resolved value found in function!");
  2036. }
  2037. }
  2038. // See if anything took the address of blocks in this function. If so,
  2039. // resolve them now.
  2040. /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
  2041. /// are resolved lazily when functions are loaded.
  2042. DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
  2043. BlockAddrFwdRefs.find(F);
  2044. if (BAFRI != BlockAddrFwdRefs.end()) {
  2045. std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
  2046. for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
  2047. unsigned BlockIdx = RefList[i].first;
  2048. if (BlockIdx >= FunctionBBs.size())
  2049. return Error("Invalid blockaddress block #");
  2050. GlobalVariable *FwdRef = RefList[i].second;
  2051. FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
  2052. FwdRef->eraseFromParent();
  2053. }
  2054. BlockAddrFwdRefs.erase(BAFRI);
  2055. }
  2056. // Trim the value list down to the size it was before we parsed this function.
  2057. ValueList.shrinkTo(ModuleValueListSize);
  2058. std::vector<BasicBlock*>().swap(FunctionBBs);
  2059. return false;
  2060. }
  2061. //===----------------------------------------------------------------------===//
  2062. // ModuleProvider implementation
  2063. //===----------------------------------------------------------------------===//
  2064. bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
  2065. // If it already is material, ignore the request.
  2066. if (!F->hasNotBeenReadFromBitcode()) return false;
  2067. DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
  2068. DeferredFunctionInfo.find(F);
  2069. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  2070. // Move the bit stream to the saved position of the deferred function body and
  2071. // restore the real linkage type for the function.
  2072. Stream.JumpToBit(DFII->second.first);
  2073. F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
  2074. if (ParseFunctionBody(F)) {
  2075. if (ErrInfo) *ErrInfo = ErrorString;
  2076. return true;
  2077. }
  2078. // Upgrade any old intrinsic calls in the function.
  2079. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  2080. E = UpgradedIntrinsics.end(); I != E; ++I) {
  2081. if (I->first != I->second) {
  2082. for (Value::use_iterator UI = I->first->use_begin(),
  2083. UE = I->first->use_end(); UI != UE; ) {
  2084. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2085. UpgradeIntrinsicCall(CI, I->second);
  2086. }
  2087. }
  2088. }
  2089. return false;
  2090. }
  2091. void BitcodeReader::dematerializeFunction(Function *F) {
  2092. // If this function isn't materialized, or if it is a proto, this is a noop.
  2093. if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
  2094. return;
  2095. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  2096. // Just forget the function body, we can remat it later.
  2097. F->deleteBody();
  2098. F->setLinkage(GlobalValue::GhostLinkage);
  2099. }
  2100. Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
  2101. // Iterate over the module, deserializing any functions that are still on
  2102. // disk.
  2103. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  2104. F != E; ++F)
  2105. if (F->hasNotBeenReadFromBitcode() &&
  2106. materializeFunction(F, ErrInfo))
  2107. return 0;
  2108. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  2109. // delete the old functions to clean up. We can't do this unless the entire
  2110. // module is materialized because there could always be another function body
  2111. // with calls to the old function.
  2112. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  2113. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  2114. if (I->first != I->second) {
  2115. for (Value::use_iterator UI = I->first->use_begin(),
  2116. UE = I->first->use_end(); UI != UE; ) {
  2117. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2118. UpgradeIntrinsicCall(CI, I->second);
  2119. }
  2120. if (!I->first->use_empty())
  2121. I->first->replaceAllUsesWith(I->second);
  2122. I->first->eraseFromParent();
  2123. }
  2124. }
  2125. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  2126. // Check debug info intrinsics.
  2127. CheckDebugInfoIntrinsics(TheModule);
  2128. return TheModule;
  2129. }
  2130. /// This method is provided by the parent ModuleProvde class and overriden
  2131. /// here. It simply releases the module from its provided and frees up our
  2132. /// state.
  2133. /// @brief Release our hold on the generated module
  2134. Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
  2135. // Since we're losing control of this Module, we must hand it back complete
  2136. Module *M = ModuleProvider::releaseModule(ErrInfo);
  2137. FreeState();
  2138. return M;
  2139. }
  2140. //===----------------------------------------------------------------------===//
  2141. // External interface
  2142. //===----------------------------------------------------------------------===//
  2143. /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
  2144. ///
  2145. ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
  2146. LLVMContext& Context,
  2147. std::string *ErrMsg) {
  2148. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2149. if (R->ParseBitcode()) {
  2150. if (ErrMsg)
  2151. *ErrMsg = R->getErrorString();
  2152. // Don't let the BitcodeReader dtor delete 'Buffer'.
  2153. R->releaseMemoryBuffer();
  2154. delete R;
  2155. return 0;
  2156. }
  2157. return R;
  2158. }
  2159. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  2160. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  2161. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
  2162. std::string *ErrMsg){
  2163. BitcodeReader *R;
  2164. R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
  2165. ErrMsg));
  2166. if (!R) return 0;
  2167. // Read in the entire module.
  2168. Module *M = R->materializeModule(ErrMsg);
  2169. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  2170. // there was an error.
  2171. R->releaseMemoryBuffer();
  2172. // If there was no error, tell ModuleProvider not to delete it when its dtor
  2173. // is run.
  2174. if (M)
  2175. M = R->releaseModule(ErrMsg);
  2176. delete R;
  2177. return M;
  2178. }