BitcodeReader.cpp 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "BitcodeReader.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/InlineAsm.h"
  18. #include "llvm/IntrinsicInst.h"
  19. #include "llvm/Module.h"
  20. #include "llvm/Operator.h"
  21. #include "llvm/AutoUpgrade.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/Support/MathExtras.h"
  25. #include "llvm/Support/MemoryBuffer.h"
  26. #include "llvm/OperandTraits.h"
  27. using namespace llvm;
  28. void BitcodeReader::FreeState() {
  29. if (BufferOwned)
  30. delete Buffer;
  31. Buffer = 0;
  32. std::vector<PATypeHolder>().swap(TypeList);
  33. ValueList.clear();
  34. MDValueList.clear();
  35. std::vector<AttrListPtr>().swap(MAttributes);
  36. std::vector<BasicBlock*>().swap(FunctionBBs);
  37. std::vector<Function*>().swap(FunctionsWithBodies);
  38. DeferredFunctionInfo.clear();
  39. MDKindMap.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. case 14: return GlobalValue::LinkerPrivateWeakLinkage;
  73. case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
  74. }
  75. }
  76. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  77. switch (Val) {
  78. default: // Map unknown visibilities to default.
  79. case 0: return GlobalValue::DefaultVisibility;
  80. case 1: return GlobalValue::HiddenVisibility;
  81. case 2: return GlobalValue::ProtectedVisibility;
  82. }
  83. }
  84. static int GetDecodedCastOpcode(unsigned Val) {
  85. switch (Val) {
  86. default: return -1;
  87. case bitc::CAST_TRUNC : return Instruction::Trunc;
  88. case bitc::CAST_ZEXT : return Instruction::ZExt;
  89. case bitc::CAST_SEXT : return Instruction::SExt;
  90. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  91. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  92. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  93. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  94. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  95. case bitc::CAST_FPEXT : return Instruction::FPExt;
  96. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  97. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  98. case bitc::CAST_BITCAST : return Instruction::BitCast;
  99. }
  100. }
  101. static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
  102. switch (Val) {
  103. default: return -1;
  104. case bitc::BINOP_ADD:
  105. return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
  106. case bitc::BINOP_SUB:
  107. return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
  108. case bitc::BINOP_MUL:
  109. return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
  110. case bitc::BINOP_UDIV: return Instruction::UDiv;
  111. case bitc::BINOP_SDIV:
  112. return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
  113. case bitc::BINOP_UREM: return Instruction::URem;
  114. case bitc::BINOP_SREM:
  115. return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
  116. case bitc::BINOP_SHL: return Instruction::Shl;
  117. case bitc::BINOP_LSHR: return Instruction::LShr;
  118. case bitc::BINOP_ASHR: return Instruction::AShr;
  119. case bitc::BINOP_AND: return Instruction::And;
  120. case bitc::BINOP_OR: return Instruction::Or;
  121. case bitc::BINOP_XOR: return Instruction::Xor;
  122. }
  123. }
  124. namespace llvm {
  125. namespace {
  126. /// @brief A class for maintaining the slot number definition
  127. /// as a placeholder for the actual definition for forward constants defs.
  128. class ConstantPlaceHolder : public ConstantExpr {
  129. void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
  130. public:
  131. // allocate space for exactly one operand
  132. void *operator new(size_t s) {
  133. return User::operator new(s, 1);
  134. }
  135. explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
  136. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  137. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  138. }
  139. /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
  140. //static inline bool classof(const ConstantPlaceHolder *) { return true; }
  141. static bool classof(const Value *V) {
  142. return isa<ConstantExpr>(V) &&
  143. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  144. }
  145. /// Provide fast operand accessors
  146. //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  147. };
  148. }
  149. // FIXME: can we inherit this from ConstantExpr?
  150. template <>
  151. struct OperandTraits<ConstantPlaceHolder> :
  152. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  153. };
  154. }
  155. void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
  156. if (Idx == size()) {
  157. push_back(V);
  158. return;
  159. }
  160. if (Idx >= size())
  161. resize(Idx+1);
  162. WeakVH &OldV = ValuePtrs[Idx];
  163. if (OldV == 0) {
  164. OldV = V;
  165. return;
  166. }
  167. // Handle constants and non-constants (e.g. instrs) differently for
  168. // efficiency.
  169. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  170. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  171. OldV = V;
  172. } else {
  173. // If there was a forward reference to this value, replace it.
  174. Value *PrevVal = OldV;
  175. OldV->replaceAllUsesWith(V);
  176. delete PrevVal;
  177. }
  178. }
  179. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  180. const Type *Ty) {
  181. if (Idx >= size())
  182. resize(Idx + 1);
  183. if (Value *V = ValuePtrs[Idx]) {
  184. assert(Ty == V->getType() && "Type mismatch in constant table!");
  185. return cast<Constant>(V);
  186. }
  187. // Create and return a placeholder, which will later be RAUW'd.
  188. Constant *C = new ConstantPlaceHolder(Ty, Context);
  189. ValuePtrs[Idx] = C;
  190. return C;
  191. }
  192. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
  193. if (Idx >= size())
  194. resize(Idx + 1);
  195. if (Value *V = ValuePtrs[Idx]) {
  196. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  197. return V;
  198. }
  199. // No type specified, must be invalid reference.
  200. if (Ty == 0) return 0;
  201. // Create and return a placeholder, which will later be RAUW'd.
  202. Value *V = new Argument(Ty);
  203. ValuePtrs[Idx] = V;
  204. return V;
  205. }
  206. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  207. /// resolves any forward references. The idea behind this is that we sometimes
  208. /// get constants (such as large arrays) which reference *many* forward ref
  209. /// constants. Replacing each of these causes a lot of thrashing when
  210. /// building/reuniquing the constant. Instead of doing this, we look at all the
  211. /// uses and rewrite all the place holders at once for any constant that uses
  212. /// a placeholder.
  213. void BitcodeReaderValueList::ResolveConstantForwardRefs() {
  214. // Sort the values by-pointer so that they are efficient to look up with a
  215. // binary search.
  216. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  217. SmallVector<Constant*, 64> NewOps;
  218. while (!ResolveConstants.empty()) {
  219. Value *RealVal = operator[](ResolveConstants.back().second);
  220. Constant *Placeholder = ResolveConstants.back().first;
  221. ResolveConstants.pop_back();
  222. // Loop over all users of the placeholder, updating them to reference the
  223. // new value. If they reference more than one placeholder, update them all
  224. // at once.
  225. while (!Placeholder->use_empty()) {
  226. Value::use_iterator UI = Placeholder->use_begin();
  227. User *U = *UI;
  228. // If the using object isn't uniqued, just update the operands. This
  229. // handles instructions and initializers for global variables.
  230. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  231. UI.getUse().set(RealVal);
  232. continue;
  233. }
  234. // Otherwise, we have a constant that uses the placeholder. Replace that
  235. // constant with a new constant that has *all* placeholder uses updated.
  236. Constant *UserC = cast<Constant>(U);
  237. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  238. I != E; ++I) {
  239. Value *NewOp;
  240. if (!isa<ConstantPlaceHolder>(*I)) {
  241. // Not a placeholder reference.
  242. NewOp = *I;
  243. } else if (*I == Placeholder) {
  244. // Common case is that it just references this one placeholder.
  245. NewOp = RealVal;
  246. } else {
  247. // Otherwise, look up the placeholder in ResolveConstants.
  248. ResolveConstantsTy::iterator It =
  249. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  250. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  251. 0));
  252. assert(It != ResolveConstants.end() && It->first == *I);
  253. NewOp = operator[](It->second);
  254. }
  255. NewOps.push_back(cast<Constant>(NewOp));
  256. }
  257. // Make the new constant.
  258. Constant *NewC;
  259. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  260. NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
  261. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  262. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  263. } else if (isa<ConstantVector>(UserC)) {
  264. NewC = ConstantVector::get(NewOps);
  265. } else {
  266. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  267. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  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. MDNode *PrevVal = cast<MDNode>(OldV);
  292. OldV->replaceAllUsesWith(V);
  293. MDNode::deleteTemporary(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 = MDNode::getTemporary(Context, ArrayRef<Value*>());
  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_X86_MMX: // X86_MMX
  479. ResultTy = Type::getX86_MMXTy(Context);
  480. break;
  481. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  482. if (Record.size() < 1)
  483. return Error("Invalid Integer type record");
  484. ResultTy = IntegerType::get(Context, Record[0]);
  485. break;
  486. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  487. // [pointee type, address space]
  488. if (Record.size() < 1)
  489. return Error("Invalid POINTER type record");
  490. unsigned AddressSpace = 0;
  491. if (Record.size() == 2)
  492. AddressSpace = Record[1];
  493. ResultTy = PointerType::get(getTypeByID(Record[0], true),
  494. AddressSpace);
  495. break;
  496. }
  497. case bitc::TYPE_CODE_FUNCTION: {
  498. // FIXME: attrid is dead, remove it in LLVM 3.0
  499. // FUNCTION: [vararg, attrid, retty, paramty x N]
  500. if (Record.size() < 3)
  501. return Error("Invalid FUNCTION type record");
  502. std::vector<const Type*> ArgTys;
  503. for (unsigned i = 3, e = Record.size(); i != e; ++i)
  504. ArgTys.push_back(getTypeByID(Record[i], true));
  505. ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
  506. Record[0]);
  507. break;
  508. }
  509. case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
  510. if (Record.size() < 1)
  511. return Error("Invalid STRUCT type record");
  512. std::vector<const Type*> EltTys;
  513. for (unsigned i = 1, e = Record.size(); i != e; ++i)
  514. EltTys.push_back(getTypeByID(Record[i], true));
  515. ResultTy = StructType::get(Context, EltTys, Record[0]);
  516. break;
  517. }
  518. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  519. if (Record.size() < 2)
  520. return Error("Invalid ARRAY type record");
  521. ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
  522. break;
  523. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  524. if (Record.size() < 2)
  525. return Error("Invalid VECTOR type record");
  526. ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
  527. break;
  528. }
  529. if (NumRecords == TypeList.size()) {
  530. // If this is a new type slot, just append it.
  531. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
  532. ++NumRecords;
  533. } else if (ResultTy == 0) {
  534. // Otherwise, this was forward referenced, so an opaque type was created,
  535. // but the result type is actually just an opaque. Leave the one we
  536. // created previously.
  537. ++NumRecords;
  538. } else {
  539. // Otherwise, this was forward referenced, so an opaque type was created.
  540. // Resolve the opaque type to the real type now.
  541. assert(NumRecords < TypeList.size() && "Typelist imbalance");
  542. const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
  543. // Don't directly push the new type on the Tab. Instead we want to replace
  544. // the opaque type we previously inserted with the new concrete value. The
  545. // refinement from the abstract (opaque) type to the new type causes all
  546. // uses of the abstract type to use the concrete type (NewTy). This will
  547. // also cause the opaque type to be deleted.
  548. const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
  549. // This should have replaced the old opaque type with the new type in the
  550. // value table... or with a preexisting type that was already in the
  551. // system. Let's just make sure it did.
  552. assert(TypeList[NumRecords-1].get() != OldTy &&
  553. "refineAbstractType didn't work!");
  554. }
  555. }
  556. }
  557. bool BitcodeReader::ParseTypeSymbolTable() {
  558. if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
  559. return Error("Malformed block record");
  560. SmallVector<uint64_t, 64> Record;
  561. // Read all the records for this type table.
  562. std::string TypeName;
  563. while (1) {
  564. unsigned Code = Stream.ReadCode();
  565. if (Code == bitc::END_BLOCK) {
  566. if (Stream.ReadBlockEnd())
  567. return Error("Error at end of type symbol table block");
  568. return false;
  569. }
  570. if (Code == bitc::ENTER_SUBBLOCK) {
  571. // No known subblocks, always skip them.
  572. Stream.ReadSubBlockID();
  573. if (Stream.SkipBlock())
  574. return Error("Malformed block record");
  575. continue;
  576. }
  577. if (Code == bitc::DEFINE_ABBREV) {
  578. Stream.ReadAbbrevRecord();
  579. continue;
  580. }
  581. // Read a record.
  582. Record.clear();
  583. switch (Stream.ReadRecord(Code, Record)) {
  584. default: // Default behavior: unknown type.
  585. break;
  586. case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
  587. if (ConvertToString(Record, 1, TypeName))
  588. return Error("Invalid TST_ENTRY record");
  589. unsigned TypeID = Record[0];
  590. if (TypeID >= TypeList.size())
  591. return Error("Invalid Type ID in TST_ENTRY record");
  592. TheModule->addTypeName(TypeName, TypeList[TypeID].get());
  593. TypeName.clear();
  594. break;
  595. }
  596. }
  597. }
  598. bool BitcodeReader::ParseValueSymbolTable() {
  599. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  600. return Error("Malformed block record");
  601. SmallVector<uint64_t, 64> Record;
  602. // Read all the records for this value table.
  603. SmallString<128> ValueName;
  604. while (1) {
  605. unsigned Code = Stream.ReadCode();
  606. if (Code == bitc::END_BLOCK) {
  607. if (Stream.ReadBlockEnd())
  608. return Error("Error at end of value symbol table block");
  609. return false;
  610. }
  611. if (Code == bitc::ENTER_SUBBLOCK) {
  612. // No known subblocks, always skip them.
  613. Stream.ReadSubBlockID();
  614. if (Stream.SkipBlock())
  615. return Error("Malformed block record");
  616. continue;
  617. }
  618. if (Code == bitc::DEFINE_ABBREV) {
  619. Stream.ReadAbbrevRecord();
  620. continue;
  621. }
  622. // Read a record.
  623. Record.clear();
  624. switch (Stream.ReadRecord(Code, Record)) {
  625. default: // Default behavior: unknown type.
  626. break;
  627. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  628. if (ConvertToString(Record, 1, ValueName))
  629. return Error("Invalid VST_ENTRY record");
  630. unsigned ValueID = Record[0];
  631. if (ValueID >= ValueList.size())
  632. return Error("Invalid Value ID in VST_ENTRY record");
  633. Value *V = ValueList[ValueID];
  634. V->setName(StringRef(ValueName.data(), ValueName.size()));
  635. ValueName.clear();
  636. break;
  637. }
  638. case bitc::VST_CODE_BBENTRY: {
  639. if (ConvertToString(Record, 1, ValueName))
  640. return Error("Invalid VST_BBENTRY record");
  641. BasicBlock *BB = getBasicBlock(Record[0]);
  642. if (BB == 0)
  643. return Error("Invalid BB ID in VST_BBENTRY record");
  644. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  645. ValueName.clear();
  646. break;
  647. }
  648. }
  649. }
  650. }
  651. bool BitcodeReader::ParseMetadata() {
  652. unsigned NextMDValueNo = MDValueList.size();
  653. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  654. return Error("Malformed block record");
  655. SmallVector<uint64_t, 64> Record;
  656. // Read all the records.
  657. while (1) {
  658. unsigned Code = Stream.ReadCode();
  659. if (Code == bitc::END_BLOCK) {
  660. if (Stream.ReadBlockEnd())
  661. return Error("Error at end of PARAMATTR block");
  662. return false;
  663. }
  664. if (Code == bitc::ENTER_SUBBLOCK) {
  665. // No known subblocks, always skip them.
  666. Stream.ReadSubBlockID();
  667. if (Stream.SkipBlock())
  668. return Error("Malformed block record");
  669. continue;
  670. }
  671. if (Code == bitc::DEFINE_ABBREV) {
  672. Stream.ReadAbbrevRecord();
  673. continue;
  674. }
  675. bool IsFunctionLocal = false;
  676. // Read a record.
  677. Record.clear();
  678. Code = Stream.ReadRecord(Code, Record);
  679. switch (Code) {
  680. default: // Default behavior: ignore.
  681. break;
  682. case bitc::METADATA_NAME: {
  683. // Read named of the named metadata.
  684. unsigned NameLength = Record.size();
  685. SmallString<8> Name;
  686. Name.resize(NameLength);
  687. for (unsigned i = 0; i != NameLength; ++i)
  688. Name[i] = Record[i];
  689. Record.clear();
  690. Code = Stream.ReadCode();
  691. // METADATA_NAME is always followed by METADATA_NAMED_NODE.
  692. unsigned NextBitCode = Stream.ReadRecord(Code, Record);
  693. assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
  694. // Read named metadata elements.
  695. unsigned Size = Record.size();
  696. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  697. for (unsigned i = 0; i != Size; ++i) {
  698. MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  699. if (MD == 0)
  700. return Error("Malformed metadata record");
  701. NMD->addOperand(MD);
  702. }
  703. break;
  704. }
  705. case bitc::METADATA_FN_NODE:
  706. IsFunctionLocal = true;
  707. // fall-through
  708. case bitc::METADATA_NODE: {
  709. if (Record.size() % 2 == 1)
  710. return Error("Invalid METADATA_NODE record");
  711. unsigned Size = Record.size();
  712. SmallVector<Value*, 8> Elts;
  713. for (unsigned i = 0; i != Size; i += 2) {
  714. const Type *Ty = getTypeByID(Record[i]);
  715. if (!Ty) return Error("Invalid METADATA_NODE record");
  716. if (Ty->isMetadataTy())
  717. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  718. else if (!Ty->isVoidTy())
  719. Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
  720. else
  721. Elts.push_back(NULL);
  722. }
  723. Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
  724. IsFunctionLocal = false;
  725. MDValueList.AssignValue(V, NextMDValueNo++);
  726. break;
  727. }
  728. case bitc::METADATA_STRING: {
  729. unsigned MDStringLength = Record.size();
  730. SmallString<8> String;
  731. String.resize(MDStringLength);
  732. for (unsigned i = 0; i != MDStringLength; ++i)
  733. String[i] = Record[i];
  734. Value *V = MDString::get(Context,
  735. StringRef(String.data(), String.size()));
  736. MDValueList.AssignValue(V, NextMDValueNo++);
  737. break;
  738. }
  739. case bitc::METADATA_KIND: {
  740. unsigned RecordLength = Record.size();
  741. if (Record.empty() || RecordLength < 2)
  742. return Error("Invalid METADATA_KIND record");
  743. SmallString<8> Name;
  744. Name.resize(RecordLength-1);
  745. unsigned Kind = Record[0];
  746. for (unsigned i = 1; i != RecordLength; ++i)
  747. Name[i-1] = Record[i];
  748. unsigned NewKind = TheModule->getMDKindID(Name.str());
  749. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  750. return Error("Conflicting METADATA_KIND records");
  751. break;
  752. }
  753. }
  754. }
  755. }
  756. /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
  757. /// the LSB for dense VBR encoding.
  758. static uint64_t DecodeSignRotatedValue(uint64_t V) {
  759. if ((V & 1) == 0)
  760. return V >> 1;
  761. if (V != 1)
  762. return -(V >> 1);
  763. // There is no such thing as -0 with integers. "-0" really means MININT.
  764. return 1ULL << 63;
  765. }
  766. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  767. /// values and aliases that we can.
  768. bool BitcodeReader::ResolveGlobalAndAliasInits() {
  769. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  770. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  771. GlobalInitWorklist.swap(GlobalInits);
  772. AliasInitWorklist.swap(AliasInits);
  773. while (!GlobalInitWorklist.empty()) {
  774. unsigned ValID = GlobalInitWorklist.back().second;
  775. if (ValID >= ValueList.size()) {
  776. // Not ready to resolve this yet, it requires something later in the file.
  777. GlobalInits.push_back(GlobalInitWorklist.back());
  778. } else {
  779. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  780. GlobalInitWorklist.back().first->setInitializer(C);
  781. else
  782. return Error("Global variable initializer is not a constant!");
  783. }
  784. GlobalInitWorklist.pop_back();
  785. }
  786. while (!AliasInitWorklist.empty()) {
  787. unsigned ValID = AliasInitWorklist.back().second;
  788. if (ValID >= ValueList.size()) {
  789. AliasInits.push_back(AliasInitWorklist.back());
  790. } else {
  791. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  792. AliasInitWorklist.back().first->setAliasee(C);
  793. else
  794. return Error("Alias initializer is not a constant!");
  795. }
  796. AliasInitWorklist.pop_back();
  797. }
  798. return false;
  799. }
  800. bool BitcodeReader::ParseConstants() {
  801. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  802. return Error("Malformed block record");
  803. SmallVector<uint64_t, 64> Record;
  804. // Read all the records for this value table.
  805. const Type *CurTy = Type::getInt32Ty(Context);
  806. unsigned NextCstNo = ValueList.size();
  807. while (1) {
  808. unsigned Code = Stream.ReadCode();
  809. if (Code == bitc::END_BLOCK)
  810. break;
  811. if (Code == bitc::ENTER_SUBBLOCK) {
  812. // No known subblocks, always skip them.
  813. Stream.ReadSubBlockID();
  814. if (Stream.SkipBlock())
  815. return Error("Malformed block record");
  816. continue;
  817. }
  818. if (Code == bitc::DEFINE_ABBREV) {
  819. Stream.ReadAbbrevRecord();
  820. continue;
  821. }
  822. // Read a record.
  823. Record.clear();
  824. Value *V = 0;
  825. unsigned BitCode = Stream.ReadRecord(Code, Record);
  826. switch (BitCode) {
  827. default: // Default behavior: unknown constant
  828. case bitc::CST_CODE_UNDEF: // UNDEF
  829. V = UndefValue::get(CurTy);
  830. break;
  831. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  832. if (Record.empty())
  833. return Error("Malformed CST_SETTYPE record");
  834. if (Record[0] >= TypeList.size())
  835. return Error("Invalid Type ID in CST_SETTYPE record");
  836. CurTy = TypeList[Record[0]];
  837. continue; // Skip the ValueList manipulation.
  838. case bitc::CST_CODE_NULL: // NULL
  839. V = Constant::getNullValue(CurTy);
  840. break;
  841. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  842. if (!CurTy->isIntegerTy() || Record.empty())
  843. return Error("Invalid CST_INTEGER record");
  844. V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
  845. break;
  846. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  847. if (!CurTy->isIntegerTy() || Record.empty())
  848. return Error("Invalid WIDE_INTEGER record");
  849. unsigned NumWords = Record.size();
  850. SmallVector<uint64_t, 8> Words;
  851. Words.resize(NumWords);
  852. for (unsigned i = 0; i != NumWords; ++i)
  853. Words[i] = DecodeSignRotatedValue(Record[i]);
  854. V = ConstantInt::get(Context,
  855. APInt(cast<IntegerType>(CurTy)->getBitWidth(),
  856. NumWords, &Words[0]));
  857. break;
  858. }
  859. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  860. if (Record.empty())
  861. return Error("Invalid FLOAT record");
  862. if (CurTy->isFloatTy())
  863. V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
  864. else if (CurTy->isDoubleTy())
  865. V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
  866. else if (CurTy->isX86_FP80Ty()) {
  867. // Bits are not stored the same way as a normal i80 APInt, compensate.
  868. uint64_t Rearrange[2];
  869. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  870. Rearrange[1] = Record[0] >> 48;
  871. V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
  872. } else if (CurTy->isFP128Ty())
  873. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
  874. else if (CurTy->isPPC_FP128Ty())
  875. V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
  876. else
  877. V = UndefValue::get(CurTy);
  878. break;
  879. }
  880. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  881. if (Record.empty())
  882. return Error("Invalid CST_AGGREGATE record");
  883. unsigned Size = Record.size();
  884. std::vector<Constant*> Elts;
  885. if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
  886. for (unsigned i = 0; i != Size; ++i)
  887. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  888. STy->getElementType(i)));
  889. V = ConstantStruct::get(STy, Elts);
  890. } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  891. const Type *EltTy = ATy->getElementType();
  892. for (unsigned i = 0; i != Size; ++i)
  893. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  894. V = ConstantArray::get(ATy, Elts);
  895. } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  896. const Type *EltTy = VTy->getElementType();
  897. for (unsigned i = 0; i != Size; ++i)
  898. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  899. V = ConstantVector::get(Elts);
  900. } else {
  901. V = UndefValue::get(CurTy);
  902. }
  903. break;
  904. }
  905. case bitc::CST_CODE_STRING: { // STRING: [values]
  906. if (Record.empty())
  907. return Error("Invalid CST_AGGREGATE record");
  908. const ArrayType *ATy = cast<ArrayType>(CurTy);
  909. const Type *EltTy = ATy->getElementType();
  910. unsigned Size = Record.size();
  911. std::vector<Constant*> Elts;
  912. for (unsigned i = 0; i != Size; ++i)
  913. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  914. V = ConstantArray::get(ATy, Elts);
  915. break;
  916. }
  917. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  918. if (Record.empty())
  919. return Error("Invalid CST_AGGREGATE record");
  920. const ArrayType *ATy = cast<ArrayType>(CurTy);
  921. const Type *EltTy = ATy->getElementType();
  922. unsigned Size = Record.size();
  923. std::vector<Constant*> Elts;
  924. for (unsigned i = 0; i != Size; ++i)
  925. Elts.push_back(ConstantInt::get(EltTy, Record[i]));
  926. Elts.push_back(Constant::getNullValue(EltTy));
  927. V = ConstantArray::get(ATy, Elts);
  928. break;
  929. }
  930. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  931. if (Record.size() < 3) return Error("Invalid CE_BINOP record");
  932. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  933. if (Opc < 0) {
  934. V = UndefValue::get(CurTy); // Unknown binop.
  935. } else {
  936. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  937. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  938. unsigned Flags = 0;
  939. if (Record.size() >= 4) {
  940. if (Opc == Instruction::Add ||
  941. Opc == Instruction::Sub ||
  942. Opc == Instruction::Mul ||
  943. Opc == Instruction::Shl) {
  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. Opc == Instruction::UDiv ||
  950. Opc == Instruction::LShr ||
  951. Opc == Instruction::AShr) {
  952. if (Record[3] & (1 << bitc::PEO_EXACT))
  953. Flags |= SDivOperator::IsExact;
  954. }
  955. }
  956. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  957. }
  958. break;
  959. }
  960. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  961. if (Record.size() < 3) return Error("Invalid CE_CAST record");
  962. int Opc = GetDecodedCastOpcode(Record[0]);
  963. if (Opc < 0) {
  964. V = UndefValue::get(CurTy); // Unknown cast.
  965. } else {
  966. const Type *OpTy = getTypeByID(Record[1]);
  967. if (!OpTy) return Error("Invalid CE_CAST record");
  968. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  969. V = ConstantExpr::getCast(Opc, Op, CurTy);
  970. }
  971. break;
  972. }
  973. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  974. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  975. if (Record.size() & 1) return Error("Invalid CE_GEP record");
  976. SmallVector<Constant*, 16> Elts;
  977. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  978. const Type *ElTy = getTypeByID(Record[i]);
  979. if (!ElTy) return Error("Invalid CE_GEP record");
  980. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  981. }
  982. if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
  983. V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
  984. Elts.size()-1);
  985. else
  986. V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
  987. Elts.size()-1);
  988. break;
  989. }
  990. case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
  991. if (Record.size() < 3) return Error("Invalid CE_SELECT record");
  992. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  993. Type::getInt1Ty(Context)),
  994. ValueList.getConstantFwdRef(Record[1],CurTy),
  995. ValueList.getConstantFwdRef(Record[2],CurTy));
  996. break;
  997. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  998. if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
  999. const VectorType *OpTy =
  1000. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1001. if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
  1002. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1003. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1004. V = ConstantExpr::getExtractElement(Op0, Op1);
  1005. break;
  1006. }
  1007. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  1008. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1009. if (Record.size() < 3 || OpTy == 0)
  1010. return Error("Invalid CE_INSERTELT record");
  1011. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1012. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  1013. OpTy->getElementType());
  1014. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  1015. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  1016. break;
  1017. }
  1018. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  1019. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  1020. if (Record.size() < 3 || OpTy == 0)
  1021. return Error("Invalid CE_SHUFFLEVEC record");
  1022. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  1023. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1024. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1025. OpTy->getNumElements());
  1026. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  1027. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1028. break;
  1029. }
  1030. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  1031. const VectorType *RTy = dyn_cast<VectorType>(CurTy);
  1032. const VectorType *OpTy =
  1033. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1034. if (Record.size() < 4 || RTy == 0 || OpTy == 0)
  1035. return Error("Invalid CE_SHUFVEC_EX record");
  1036. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1037. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1038. const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  1039. RTy->getNumElements());
  1040. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  1041. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  1042. break;
  1043. }
  1044. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  1045. if (Record.size() < 4) return Error("Invalid CE_CMP record");
  1046. const Type *OpTy = getTypeByID(Record[0]);
  1047. if (OpTy == 0) return Error("Invalid CE_CMP record");
  1048. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  1049. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  1050. if (OpTy->isFPOrFPVectorTy())
  1051. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  1052. else
  1053. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  1054. break;
  1055. }
  1056. case bitc::CST_CODE_INLINEASM: {
  1057. if (Record.size() < 2) return Error("Invalid INLINEASM record");
  1058. std::string AsmStr, ConstrStr;
  1059. bool HasSideEffects = Record[0] & 1;
  1060. bool IsAlignStack = Record[0] >> 1;
  1061. unsigned AsmStrSize = Record[1];
  1062. if (2+AsmStrSize >= Record.size())
  1063. return Error("Invalid INLINEASM record");
  1064. unsigned ConstStrSize = Record[2+AsmStrSize];
  1065. if (3+AsmStrSize+ConstStrSize > Record.size())
  1066. return Error("Invalid INLINEASM record");
  1067. for (unsigned i = 0; i != AsmStrSize; ++i)
  1068. AsmStr += (char)Record[2+i];
  1069. for (unsigned i = 0; i != ConstStrSize; ++i)
  1070. ConstrStr += (char)Record[3+AsmStrSize+i];
  1071. const PointerType *PTy = cast<PointerType>(CurTy);
  1072. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  1073. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  1074. break;
  1075. }
  1076. case bitc::CST_CODE_BLOCKADDRESS:{
  1077. if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
  1078. const Type *FnTy = getTypeByID(Record[0]);
  1079. if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1080. Function *Fn =
  1081. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  1082. if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
  1083. GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
  1084. Type::getInt8Ty(Context),
  1085. false, GlobalValue::InternalLinkage,
  1086. 0, "");
  1087. BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
  1088. V = FwdRef;
  1089. break;
  1090. }
  1091. }
  1092. ValueList.AssignValue(V, NextCstNo);
  1093. ++NextCstNo;
  1094. }
  1095. if (NextCstNo != ValueList.size())
  1096. return Error("Invalid constant reference!");
  1097. if (Stream.ReadBlockEnd())
  1098. return Error("Error at end of constants block");
  1099. // Once all the constants have been read, go through and resolve forward
  1100. // references.
  1101. ValueList.ResolveConstantForwardRefs();
  1102. return false;
  1103. }
  1104. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  1105. /// remember where it is and then skip it. This lets us lazily deserialize the
  1106. /// functions.
  1107. bool BitcodeReader::RememberAndSkipFunctionBody() {
  1108. // Get the function we are talking about.
  1109. if (FunctionsWithBodies.empty())
  1110. return Error("Insufficient function protos");
  1111. Function *Fn = FunctionsWithBodies.back();
  1112. FunctionsWithBodies.pop_back();
  1113. // Save the current stream state.
  1114. uint64_t CurBit = Stream.GetCurrentBitNo();
  1115. DeferredFunctionInfo[Fn] = CurBit;
  1116. // Skip over the function block for now.
  1117. if (Stream.SkipBlock())
  1118. return Error("Malformed block record");
  1119. return false;
  1120. }
  1121. bool BitcodeReader::ParseModule() {
  1122. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1123. return Error("Malformed block record");
  1124. SmallVector<uint64_t, 64> Record;
  1125. std::vector<std::string> SectionTable;
  1126. std::vector<std::string> GCTable;
  1127. // Read all the records for this module.
  1128. while (!Stream.AtEndOfStream()) {
  1129. unsigned Code = Stream.ReadCode();
  1130. if (Code == bitc::END_BLOCK) {
  1131. if (Stream.ReadBlockEnd())
  1132. return Error("Error at end of module block");
  1133. // Patch the initializers for globals and aliases up.
  1134. ResolveGlobalAndAliasInits();
  1135. if (!GlobalInits.empty() || !AliasInits.empty())
  1136. return Error("Malformed global initializer set");
  1137. if (!FunctionsWithBodies.empty())
  1138. return Error("Too few function bodies found");
  1139. // Look for intrinsic functions which need to be upgraded at some point
  1140. for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
  1141. FI != FE; ++FI) {
  1142. Function* NewFn;
  1143. if (UpgradeIntrinsicFunction(FI, NewFn))
  1144. UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
  1145. }
  1146. // Look for global variables which need to be renamed.
  1147. for (Module::global_iterator
  1148. GI = TheModule->global_begin(), GE = TheModule->global_end();
  1149. GI != GE; ++GI)
  1150. UpgradeGlobalVariable(GI);
  1151. // Force deallocation of memory for these vectors to favor the client that
  1152. // want lazy deserialization.
  1153. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  1154. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  1155. std::vector<Function*>().swap(FunctionsWithBodies);
  1156. return false;
  1157. }
  1158. if (Code == bitc::ENTER_SUBBLOCK) {
  1159. switch (Stream.ReadSubBlockID()) {
  1160. default: // Skip unknown content.
  1161. if (Stream.SkipBlock())
  1162. return Error("Malformed block record");
  1163. break;
  1164. case bitc::BLOCKINFO_BLOCK_ID:
  1165. if (Stream.ReadBlockInfoBlock())
  1166. return Error("Malformed BlockInfoBlock");
  1167. break;
  1168. case bitc::PARAMATTR_BLOCK_ID:
  1169. if (ParseAttributeBlock())
  1170. return true;
  1171. break;
  1172. case bitc::TYPE_BLOCK_ID:
  1173. if (ParseTypeTable())
  1174. return true;
  1175. break;
  1176. case bitc::TYPE_SYMTAB_BLOCK_ID:
  1177. if (ParseTypeSymbolTable())
  1178. return true;
  1179. break;
  1180. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1181. if (ParseValueSymbolTable())
  1182. return true;
  1183. break;
  1184. case bitc::CONSTANTS_BLOCK_ID:
  1185. if (ParseConstants() || ResolveGlobalAndAliasInits())
  1186. return true;
  1187. break;
  1188. case bitc::METADATA_BLOCK_ID:
  1189. if (ParseMetadata())
  1190. return true;
  1191. break;
  1192. case bitc::FUNCTION_BLOCK_ID:
  1193. // If this is the first function body we've seen, reverse the
  1194. // FunctionsWithBodies list.
  1195. if (!HasReversedFunctionsWithBodies) {
  1196. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  1197. HasReversedFunctionsWithBodies = true;
  1198. }
  1199. if (RememberAndSkipFunctionBody())
  1200. return true;
  1201. break;
  1202. }
  1203. continue;
  1204. }
  1205. if (Code == bitc::DEFINE_ABBREV) {
  1206. Stream.ReadAbbrevRecord();
  1207. continue;
  1208. }
  1209. // Read a record.
  1210. switch (Stream.ReadRecord(Code, Record)) {
  1211. default: break; // Default behavior, ignore unknown content.
  1212. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  1213. if (Record.size() < 1)
  1214. return Error("Malformed MODULE_CODE_VERSION");
  1215. // Only version #0 is supported so far.
  1216. if (Record[0] != 0)
  1217. return Error("Unknown bitstream version!");
  1218. break;
  1219. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1220. std::string S;
  1221. if (ConvertToString(Record, 0, S))
  1222. return Error("Invalid MODULE_CODE_TRIPLE record");
  1223. TheModule->setTargetTriple(S);
  1224. break;
  1225. }
  1226. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  1227. std::string S;
  1228. if (ConvertToString(Record, 0, S))
  1229. return Error("Invalid MODULE_CODE_DATALAYOUT record");
  1230. TheModule->setDataLayout(S);
  1231. break;
  1232. }
  1233. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  1234. std::string S;
  1235. if (ConvertToString(Record, 0, S))
  1236. return Error("Invalid MODULE_CODE_ASM record");
  1237. TheModule->setModuleInlineAsm(S);
  1238. break;
  1239. }
  1240. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  1241. std::string S;
  1242. if (ConvertToString(Record, 0, S))
  1243. return Error("Invalid MODULE_CODE_DEPLIB record");
  1244. TheModule->addLibrary(S);
  1245. break;
  1246. }
  1247. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  1248. std::string S;
  1249. if (ConvertToString(Record, 0, S))
  1250. return Error("Invalid MODULE_CODE_SECTIONNAME record");
  1251. SectionTable.push_back(S);
  1252. break;
  1253. }
  1254. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  1255. std::string S;
  1256. if (ConvertToString(Record, 0, S))
  1257. return Error("Invalid MODULE_CODE_GCNAME record");
  1258. GCTable.push_back(S);
  1259. break;
  1260. }
  1261. // GLOBALVAR: [pointer type, isconst, initid,
  1262. // linkage, alignment, section, visibility, threadlocal,
  1263. // unnamed_addr]
  1264. case bitc::MODULE_CODE_GLOBALVAR: {
  1265. if (Record.size() < 6)
  1266. return Error("Invalid MODULE_CODE_GLOBALVAR record");
  1267. const Type *Ty = getTypeByID(Record[0]);
  1268. if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
  1269. if (!Ty->isPointerTy())
  1270. return Error("Global not a pointer type!");
  1271. unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  1272. Ty = cast<PointerType>(Ty)->getElementType();
  1273. bool isConstant = Record[1];
  1274. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  1275. unsigned Alignment = (1 << Record[4]) >> 1;
  1276. std::string Section;
  1277. if (Record[5]) {
  1278. if (Record[5]-1 >= SectionTable.size())
  1279. return Error("Invalid section ID");
  1280. Section = SectionTable[Record[5]-1];
  1281. }
  1282. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  1283. if (Record.size() > 6)
  1284. Visibility = GetDecodedVisibility(Record[6]);
  1285. bool isThreadLocal = false;
  1286. if (Record.size() > 7)
  1287. isThreadLocal = Record[7];
  1288. bool UnnamedAddr = false;
  1289. if (Record.size() > 8)
  1290. UnnamedAddr = Record[8];
  1291. GlobalVariable *NewGV =
  1292. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
  1293. isThreadLocal, AddressSpace);
  1294. NewGV->setAlignment(Alignment);
  1295. if (!Section.empty())
  1296. NewGV->setSection(Section);
  1297. NewGV->setVisibility(Visibility);
  1298. NewGV->setThreadLocal(isThreadLocal);
  1299. NewGV->setUnnamedAddr(UnnamedAddr);
  1300. ValueList.push_back(NewGV);
  1301. // Remember which value to use for the global initializer.
  1302. if (unsigned InitID = Record[2])
  1303. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  1304. break;
  1305. }
  1306. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  1307. // alignment, section, visibility, gc, unnamed_addr]
  1308. case bitc::MODULE_CODE_FUNCTION: {
  1309. if (Record.size() < 8)
  1310. return Error("Invalid MODULE_CODE_FUNCTION record");
  1311. const Type *Ty = getTypeByID(Record[0]);
  1312. if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
  1313. if (!Ty->isPointerTy())
  1314. return Error("Function not a pointer type!");
  1315. const FunctionType *FTy =
  1316. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1317. if (!FTy)
  1318. return Error("Function not a pointer to function type!");
  1319. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  1320. "", TheModule);
  1321. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  1322. bool isProto = Record[2];
  1323. Func->setLinkage(GetDecodedLinkage(Record[3]));
  1324. Func->setAttributes(getAttributes(Record[4]));
  1325. Func->setAlignment((1 << Record[5]) >> 1);
  1326. if (Record[6]) {
  1327. if (Record[6]-1 >= SectionTable.size())
  1328. return Error("Invalid section ID");
  1329. Func->setSection(SectionTable[Record[6]-1]);
  1330. }
  1331. Func->setVisibility(GetDecodedVisibility(Record[7]));
  1332. if (Record.size() > 8 && Record[8]) {
  1333. if (Record[8]-1 > GCTable.size())
  1334. return Error("Invalid GC ID");
  1335. Func->setGC(GCTable[Record[8]-1].c_str());
  1336. }
  1337. bool UnnamedAddr = false;
  1338. if (Record.size() > 9)
  1339. UnnamedAddr = Record[9];
  1340. Func->setUnnamedAddr(UnnamedAddr);
  1341. ValueList.push_back(Func);
  1342. // If this is a function with a body, remember the prototype we are
  1343. // creating now, so that we can match up the body with them later.
  1344. if (!isProto)
  1345. FunctionsWithBodies.push_back(Func);
  1346. break;
  1347. }
  1348. // ALIAS: [alias type, aliasee val#, linkage]
  1349. // ALIAS: [alias type, aliasee val#, linkage, visibility]
  1350. case bitc::MODULE_CODE_ALIAS: {
  1351. if (Record.size() < 3)
  1352. return Error("Invalid MODULE_ALIAS record");
  1353. const Type *Ty = getTypeByID(Record[0]);
  1354. if (!Ty) return Error("Invalid MODULE_ALIAS record");
  1355. if (!Ty->isPointerTy())
  1356. return Error("Function not a pointer type!");
  1357. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  1358. "", 0, TheModule);
  1359. // Old bitcode files didn't have visibility field.
  1360. if (Record.size() > 3)
  1361. NewGA->setVisibility(GetDecodedVisibility(Record[3]));
  1362. ValueList.push_back(NewGA);
  1363. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  1364. break;
  1365. }
  1366. /// MODULE_CODE_PURGEVALS: [numvals]
  1367. case bitc::MODULE_CODE_PURGEVALS:
  1368. // Trim down the value list to the specified size.
  1369. if (Record.size() < 1 || Record[0] > ValueList.size())
  1370. return Error("Invalid MODULE_PURGEVALS record");
  1371. ValueList.shrinkTo(Record[0]);
  1372. break;
  1373. }
  1374. Record.clear();
  1375. }
  1376. return Error("Premature end of bitstream");
  1377. }
  1378. bool BitcodeReader::ParseBitcodeInto(Module *M) {
  1379. TheModule = 0;
  1380. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  1381. unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  1382. if (Buffer->getBufferSize() & 3) {
  1383. if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
  1384. return Error("Invalid bitcode signature");
  1385. else
  1386. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  1387. }
  1388. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  1389. // The magic number is 0x0B17C0DE stored in little endian.
  1390. if (isBitcodeWrapper(BufPtr, BufEnd))
  1391. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
  1392. return Error("Invalid bitcode wrapper header");
  1393. StreamFile.init(BufPtr, BufEnd);
  1394. Stream.init(StreamFile);
  1395. // Sniff for the signature.
  1396. if (Stream.Read(8) != 'B' ||
  1397. Stream.Read(8) != 'C' ||
  1398. Stream.Read(4) != 0x0 ||
  1399. Stream.Read(4) != 0xC ||
  1400. Stream.Read(4) != 0xE ||
  1401. Stream.Read(4) != 0xD)
  1402. return Error("Invalid bitcode signature");
  1403. // We expect a number of well-defined blocks, though we don't necessarily
  1404. // need to understand them all.
  1405. while (!Stream.AtEndOfStream()) {
  1406. unsigned Code = Stream.ReadCode();
  1407. if (Code != bitc::ENTER_SUBBLOCK) {
  1408. // The ranlib in xcode 4 will align archive members by appending newlines to the
  1409. // end of them. If this file size is a multiple of 4 but not 8, we have to read and
  1410. // ignore these final 4 bytes :-(
  1411. if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
  1412. Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
  1413. Stream.AtEndOfStream())
  1414. return false;
  1415. return Error("Invalid record at top-level");
  1416. }
  1417. unsigned BlockID = Stream.ReadSubBlockID();
  1418. // We only know the MODULE subblock ID.
  1419. switch (BlockID) {
  1420. case bitc::BLOCKINFO_BLOCK_ID:
  1421. if (Stream.ReadBlockInfoBlock())
  1422. return Error("Malformed BlockInfoBlock");
  1423. break;
  1424. case bitc::MODULE_BLOCK_ID:
  1425. // Reject multiple MODULE_BLOCK's in a single bitstream.
  1426. if (TheModule)
  1427. return Error("Multiple MODULE_BLOCKs in same stream");
  1428. TheModule = M;
  1429. if (ParseModule())
  1430. return true;
  1431. break;
  1432. default:
  1433. if (Stream.SkipBlock())
  1434. return Error("Malformed block record");
  1435. break;
  1436. }
  1437. }
  1438. return false;
  1439. }
  1440. bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
  1441. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  1442. return Error("Malformed block record");
  1443. SmallVector<uint64_t, 64> Record;
  1444. // Read all the records for this module.
  1445. while (!Stream.AtEndOfStream()) {
  1446. unsigned Code = Stream.ReadCode();
  1447. if (Code == bitc::END_BLOCK) {
  1448. if (Stream.ReadBlockEnd())
  1449. return Error("Error at end of module block");
  1450. return false;
  1451. }
  1452. if (Code == bitc::ENTER_SUBBLOCK) {
  1453. switch (Stream.ReadSubBlockID()) {
  1454. default: // Skip unknown content.
  1455. if (Stream.SkipBlock())
  1456. return Error("Malformed block record");
  1457. break;
  1458. }
  1459. continue;
  1460. }
  1461. if (Code == bitc::DEFINE_ABBREV) {
  1462. Stream.ReadAbbrevRecord();
  1463. continue;
  1464. }
  1465. // Read a record.
  1466. switch (Stream.ReadRecord(Code, Record)) {
  1467. default: break; // Default behavior, ignore unknown content.
  1468. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  1469. if (Record.size() < 1)
  1470. return Error("Malformed MODULE_CODE_VERSION");
  1471. // Only version #0 is supported so far.
  1472. if (Record[0] != 0)
  1473. return Error("Unknown bitstream version!");
  1474. break;
  1475. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  1476. std::string S;
  1477. if (ConvertToString(Record, 0, S))
  1478. return Error("Invalid MODULE_CODE_TRIPLE record");
  1479. Triple = S;
  1480. break;
  1481. }
  1482. }
  1483. Record.clear();
  1484. }
  1485. return Error("Premature end of bitstream");
  1486. }
  1487. bool BitcodeReader::ParseTriple(std::string &Triple) {
  1488. if (Buffer->getBufferSize() & 3)
  1489. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  1490. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  1491. unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  1492. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  1493. // The magic number is 0x0B17C0DE stored in little endian.
  1494. if (isBitcodeWrapper(BufPtr, BufEnd))
  1495. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
  1496. return Error("Invalid bitcode wrapper header");
  1497. StreamFile.init(BufPtr, BufEnd);
  1498. Stream.init(StreamFile);
  1499. // Sniff for the signature.
  1500. if (Stream.Read(8) != 'B' ||
  1501. Stream.Read(8) != 'C' ||
  1502. Stream.Read(4) != 0x0 ||
  1503. Stream.Read(4) != 0xC ||
  1504. Stream.Read(4) != 0xE ||
  1505. Stream.Read(4) != 0xD)
  1506. return Error("Invalid bitcode signature");
  1507. // We expect a number of well-defined blocks, though we don't necessarily
  1508. // need to understand them all.
  1509. while (!Stream.AtEndOfStream()) {
  1510. unsigned Code = Stream.ReadCode();
  1511. if (Code != bitc::ENTER_SUBBLOCK)
  1512. return Error("Invalid record at top-level");
  1513. unsigned BlockID = Stream.ReadSubBlockID();
  1514. // We only know the MODULE subblock ID.
  1515. switch (BlockID) {
  1516. case bitc::MODULE_BLOCK_ID:
  1517. if (ParseModuleTriple(Triple))
  1518. return true;
  1519. break;
  1520. default:
  1521. if (Stream.SkipBlock())
  1522. return Error("Malformed block record");
  1523. break;
  1524. }
  1525. }
  1526. return false;
  1527. }
  1528. /// ParseMetadataAttachment - Parse metadata attachments.
  1529. bool BitcodeReader::ParseMetadataAttachment() {
  1530. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1531. return Error("Malformed block record");
  1532. SmallVector<uint64_t, 64> Record;
  1533. while(1) {
  1534. unsigned Code = Stream.ReadCode();
  1535. if (Code == bitc::END_BLOCK) {
  1536. if (Stream.ReadBlockEnd())
  1537. return Error("Error at end of PARAMATTR block");
  1538. break;
  1539. }
  1540. if (Code == bitc::DEFINE_ABBREV) {
  1541. Stream.ReadAbbrevRecord();
  1542. continue;
  1543. }
  1544. // Read a metadata attachment record.
  1545. Record.clear();
  1546. switch (Stream.ReadRecord(Code, Record)) {
  1547. default: // Default behavior: ignore.
  1548. break;
  1549. case bitc::METADATA_ATTACHMENT: {
  1550. unsigned RecordLength = Record.size();
  1551. if (Record.empty() || (RecordLength - 1) % 2 == 1)
  1552. return Error ("Invalid METADATA_ATTACHMENT reader!");
  1553. Instruction *Inst = InstructionList[Record[0]];
  1554. for (unsigned i = 1; i != RecordLength; i = i+2) {
  1555. unsigned Kind = Record[i];
  1556. DenseMap<unsigned, unsigned>::iterator I =
  1557. MDKindMap.find(Kind);
  1558. if (I == MDKindMap.end())
  1559. return Error("Invalid metadata kind ID");
  1560. Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
  1561. Inst->setMetadata(I->second, cast<MDNode>(Node));
  1562. }
  1563. break;
  1564. }
  1565. }
  1566. }
  1567. return false;
  1568. }
  1569. /// ParseFunctionBody - Lazily parse the specified function body block.
  1570. bool BitcodeReader::ParseFunctionBody(Function *F) {
  1571. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  1572. return Error("Malformed block record");
  1573. InstructionList.clear();
  1574. unsigned ModuleValueListSize = ValueList.size();
  1575. unsigned ModuleMDValueListSize = MDValueList.size();
  1576. // Add all the function arguments to the value table.
  1577. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  1578. ValueList.push_back(I);
  1579. unsigned NextValueNo = ValueList.size();
  1580. BasicBlock *CurBB = 0;
  1581. unsigned CurBBNo = 0;
  1582. DebugLoc LastLoc;
  1583. // Read all the records.
  1584. SmallVector<uint64_t, 64> Record;
  1585. while (1) {
  1586. unsigned Code = Stream.ReadCode();
  1587. if (Code == bitc::END_BLOCK) {
  1588. if (Stream.ReadBlockEnd())
  1589. return Error("Error at end of function block");
  1590. break;
  1591. }
  1592. if (Code == bitc::ENTER_SUBBLOCK) {
  1593. switch (Stream.ReadSubBlockID()) {
  1594. default: // Skip unknown content.
  1595. if (Stream.SkipBlock())
  1596. return Error("Malformed block record");
  1597. break;
  1598. case bitc::CONSTANTS_BLOCK_ID:
  1599. if (ParseConstants()) return true;
  1600. NextValueNo = ValueList.size();
  1601. break;
  1602. case bitc::VALUE_SYMTAB_BLOCK_ID:
  1603. if (ParseValueSymbolTable()) return true;
  1604. break;
  1605. case bitc::METADATA_ATTACHMENT_ID:
  1606. if (ParseMetadataAttachment()) return true;
  1607. break;
  1608. case bitc::METADATA_BLOCK_ID:
  1609. if (ParseMetadata()) return true;
  1610. break;
  1611. }
  1612. continue;
  1613. }
  1614. if (Code == bitc::DEFINE_ABBREV) {
  1615. Stream.ReadAbbrevRecord();
  1616. continue;
  1617. }
  1618. // Read a record.
  1619. Record.clear();
  1620. Instruction *I = 0;
  1621. unsigned BitCode = Stream.ReadRecord(Code, Record);
  1622. switch (BitCode) {
  1623. default: // Default behavior: reject
  1624. return Error("Unknown instruction");
  1625. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  1626. if (Record.size() < 1 || Record[0] == 0)
  1627. return Error("Invalid DECLAREBLOCKS record");
  1628. // Create all the basic blocks for the function.
  1629. FunctionBBs.resize(Record[0]);
  1630. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1631. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  1632. CurBB = FunctionBBs[0];
  1633. continue;
  1634. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  1635. // This record indicates that the last instruction is at the same
  1636. // location as the previous instruction with a location.
  1637. I = 0;
  1638. // Get the last instruction emitted.
  1639. if (CurBB && !CurBB->empty())
  1640. I = &CurBB->back();
  1641. else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
  1642. !FunctionBBs[CurBBNo-1]->empty())
  1643. I = &FunctionBBs[CurBBNo-1]->back();
  1644. if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
  1645. I->setDebugLoc(LastLoc);
  1646. I = 0;
  1647. continue;
  1648. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  1649. I = 0; // Get the last instruction emitted.
  1650. if (CurBB && !CurBB->empty())
  1651. I = &CurBB->back();
  1652. else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
  1653. !FunctionBBs[CurBBNo-1]->empty())
  1654. I = &FunctionBBs[CurBBNo-1]->back();
  1655. if (I == 0 || Record.size() < 4)
  1656. return Error("Invalid FUNC_CODE_DEBUG_LOC record");
  1657. unsigned Line = Record[0], Col = Record[1];
  1658. unsigned ScopeID = Record[2], IAID = Record[3];
  1659. MDNode *Scope = 0, *IA = 0;
  1660. if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
  1661. if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
  1662. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  1663. I->setDebugLoc(LastLoc);
  1664. I = 0;
  1665. continue;
  1666. }
  1667. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  1668. unsigned OpNum = 0;
  1669. Value *LHS, *RHS;
  1670. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1671. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1672. OpNum+1 > Record.size())
  1673. return Error("Invalid BINOP record");
  1674. int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  1675. if (Opc == -1) return Error("Invalid BINOP record");
  1676. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  1677. InstructionList.push_back(I);
  1678. if (OpNum < Record.size()) {
  1679. if (Opc == Instruction::Add ||
  1680. Opc == Instruction::Sub ||
  1681. Opc == Instruction::Mul ||
  1682. Opc == Instruction::Shl) {
  1683. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  1684. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  1685. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  1686. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  1687. } else if (Opc == Instruction::SDiv ||
  1688. Opc == Instruction::UDiv ||
  1689. Opc == Instruction::LShr ||
  1690. Opc == Instruction::AShr) {
  1691. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  1692. cast<BinaryOperator>(I)->setIsExact(true);
  1693. }
  1694. }
  1695. break;
  1696. }
  1697. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  1698. unsigned OpNum = 0;
  1699. Value *Op;
  1700. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  1701. OpNum+2 != Record.size())
  1702. return Error("Invalid CAST record");
  1703. const Type *ResTy = getTypeByID(Record[OpNum]);
  1704. int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
  1705. if (Opc == -1 || ResTy == 0)
  1706. return Error("Invalid CAST record");
  1707. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  1708. InstructionList.push_back(I);
  1709. break;
  1710. }
  1711. case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
  1712. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
  1713. unsigned OpNum = 0;
  1714. Value *BasePtr;
  1715. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  1716. return Error("Invalid GEP record");
  1717. SmallVector<Value*, 16> GEPIdx;
  1718. while (OpNum != Record.size()) {
  1719. Value *Op;
  1720. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1721. return Error("Invalid GEP record");
  1722. GEPIdx.push_back(Op);
  1723. }
  1724. I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
  1725. InstructionList.push_back(I);
  1726. if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
  1727. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  1728. break;
  1729. }
  1730. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  1731. // EXTRACTVAL: [opty, opval, n x indices]
  1732. unsigned OpNum = 0;
  1733. Value *Agg;
  1734. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1735. return Error("Invalid EXTRACTVAL record");
  1736. SmallVector<unsigned, 4> EXTRACTVALIdx;
  1737. for (unsigned RecSize = Record.size();
  1738. OpNum != RecSize; ++OpNum) {
  1739. uint64_t Index = Record[OpNum];
  1740. if ((unsigned)Index != Index)
  1741. return Error("Invalid EXTRACTVAL index");
  1742. EXTRACTVALIdx.push_back((unsigned)Index);
  1743. }
  1744. I = ExtractValueInst::Create(Agg,
  1745. EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
  1746. InstructionList.push_back(I);
  1747. break;
  1748. }
  1749. case bitc::FUNC_CODE_INST_INSERTVAL: {
  1750. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  1751. unsigned OpNum = 0;
  1752. Value *Agg;
  1753. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  1754. return Error("Invalid INSERTVAL record");
  1755. Value *Val;
  1756. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  1757. return Error("Invalid INSERTVAL record");
  1758. SmallVector<unsigned, 4> INSERTVALIdx;
  1759. for (unsigned RecSize = Record.size();
  1760. OpNum != RecSize; ++OpNum) {
  1761. uint64_t Index = Record[OpNum];
  1762. if ((unsigned)Index != Index)
  1763. return Error("Invalid INSERTVAL index");
  1764. INSERTVALIdx.push_back((unsigned)Index);
  1765. }
  1766. I = InsertValueInst::Create(Agg, Val,
  1767. INSERTVALIdx.begin(), INSERTVALIdx.end());
  1768. InstructionList.push_back(I);
  1769. break;
  1770. }
  1771. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  1772. // obsolete form of select
  1773. // handles select i1 ... in old bitcode
  1774. unsigned OpNum = 0;
  1775. Value *TrueVal, *FalseVal, *Cond;
  1776. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1777. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1778. getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
  1779. return Error("Invalid SELECT record");
  1780. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1781. InstructionList.push_back(I);
  1782. break;
  1783. }
  1784. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  1785. // new form of select
  1786. // handles select i1 or select [N x i1]
  1787. unsigned OpNum = 0;
  1788. Value *TrueVal, *FalseVal, *Cond;
  1789. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  1790. getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
  1791. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  1792. return Error("Invalid SELECT record");
  1793. // select condition can be either i1 or [N x i1]
  1794. if (const VectorType* vector_type =
  1795. dyn_cast<const VectorType>(Cond->getType())) {
  1796. // expect <n x i1>
  1797. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  1798. return Error("Invalid SELECT condition type");
  1799. } else {
  1800. // expect i1
  1801. if (Cond->getType() != Type::getInt1Ty(Context))
  1802. return Error("Invalid SELECT condition type");
  1803. }
  1804. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  1805. InstructionList.push_back(I);
  1806. break;
  1807. }
  1808. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  1809. unsigned OpNum = 0;
  1810. Value *Vec, *Idx;
  1811. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1812. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1813. return Error("Invalid EXTRACTELT record");
  1814. I = ExtractElementInst::Create(Vec, Idx);
  1815. InstructionList.push_back(I);
  1816. break;
  1817. }
  1818. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  1819. unsigned OpNum = 0;
  1820. Value *Vec, *Elt, *Idx;
  1821. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  1822. getValue(Record, OpNum,
  1823. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  1824. getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
  1825. return Error("Invalid INSERTELT record");
  1826. I = InsertElementInst::Create(Vec, Elt, Idx);
  1827. InstructionList.push_back(I);
  1828. break;
  1829. }
  1830. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  1831. unsigned OpNum = 0;
  1832. Value *Vec1, *Vec2, *Mask;
  1833. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  1834. getValue(Record, OpNum, Vec1->getType(), Vec2))
  1835. return Error("Invalid SHUFFLEVEC record");
  1836. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  1837. return Error("Invalid SHUFFLEVEC record");
  1838. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  1839. InstructionList.push_back(I);
  1840. break;
  1841. }
  1842. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  1843. // Old form of ICmp/FCmp returning bool
  1844. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  1845. // both legal on vectors but had different behaviour.
  1846. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  1847. // FCmp/ICmp returning bool or vector of bool
  1848. unsigned OpNum = 0;
  1849. Value *LHS, *RHS;
  1850. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  1851. getValue(Record, OpNum, LHS->getType(), RHS) ||
  1852. OpNum+1 != Record.size())
  1853. return Error("Invalid CMP record");
  1854. if (LHS->getType()->isFPOrFPVectorTy())
  1855. I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
  1856. else
  1857. I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
  1858. InstructionList.push_back(I);
  1859. break;
  1860. }
  1861. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  1862. {
  1863. unsigned Size = Record.size();
  1864. if (Size == 0) {
  1865. I = ReturnInst::Create(Context);
  1866. InstructionList.push_back(I);
  1867. break;
  1868. }
  1869. unsigned OpNum = 0;
  1870. Value *Op = NULL;
  1871. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1872. return Error("Invalid RET record");
  1873. if (OpNum != Record.size())
  1874. return Error("Invalid RET record");
  1875. I = ReturnInst::Create(Context, Op);
  1876. InstructionList.push_back(I);
  1877. break;
  1878. }
  1879. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  1880. if (Record.size() != 1 && Record.size() != 3)
  1881. return Error("Invalid BR record");
  1882. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  1883. if (TrueDest == 0)
  1884. return Error("Invalid BR record");
  1885. if (Record.size() == 1) {
  1886. I = BranchInst::Create(TrueDest);
  1887. InstructionList.push_back(I);
  1888. }
  1889. else {
  1890. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  1891. Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
  1892. if (FalseDest == 0 || Cond == 0)
  1893. return Error("Invalid BR record");
  1894. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  1895. InstructionList.push_back(I);
  1896. }
  1897. break;
  1898. }
  1899. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  1900. if (Record.size() < 3 || (Record.size() & 1) == 0)
  1901. return Error("Invalid SWITCH record");
  1902. const Type *OpTy = getTypeByID(Record[0]);
  1903. Value *Cond = getFnValueByID(Record[1], OpTy);
  1904. BasicBlock *Default = getBasicBlock(Record[2]);
  1905. if (OpTy == 0 || Cond == 0 || Default == 0)
  1906. return Error("Invalid SWITCH record");
  1907. unsigned NumCases = (Record.size()-3)/2;
  1908. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  1909. InstructionList.push_back(SI);
  1910. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  1911. ConstantInt *CaseVal =
  1912. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  1913. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  1914. if (CaseVal == 0 || DestBB == 0) {
  1915. delete SI;
  1916. return Error("Invalid SWITCH record!");
  1917. }
  1918. SI->addCase(CaseVal, DestBB);
  1919. }
  1920. I = SI;
  1921. break;
  1922. }
  1923. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  1924. if (Record.size() < 2)
  1925. return Error("Invalid INDIRECTBR record");
  1926. const Type *OpTy = getTypeByID(Record[0]);
  1927. Value *Address = getFnValueByID(Record[1], OpTy);
  1928. if (OpTy == 0 || Address == 0)
  1929. return Error("Invalid INDIRECTBR record");
  1930. unsigned NumDests = Record.size()-2;
  1931. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  1932. InstructionList.push_back(IBI);
  1933. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  1934. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  1935. IBI->addDestination(DestBB);
  1936. } else {
  1937. delete IBI;
  1938. return Error("Invalid INDIRECTBR record!");
  1939. }
  1940. }
  1941. I = IBI;
  1942. break;
  1943. }
  1944. case bitc::FUNC_CODE_INST_INVOKE: {
  1945. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  1946. if (Record.size() < 4) return Error("Invalid INVOKE record");
  1947. AttrListPtr PAL = getAttributes(Record[0]);
  1948. unsigned CCInfo = Record[1];
  1949. BasicBlock *NormalBB = getBasicBlock(Record[2]);
  1950. BasicBlock *UnwindBB = getBasicBlock(Record[3]);
  1951. unsigned OpNum = 4;
  1952. Value *Callee;
  1953. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  1954. return Error("Invalid INVOKE record");
  1955. const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  1956. const FunctionType *FTy = !CalleeTy ? 0 :
  1957. dyn_cast<FunctionType>(CalleeTy->getElementType());
  1958. // Check that the right number of fixed parameters are here.
  1959. if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
  1960. Record.size() < OpNum+FTy->getNumParams())
  1961. return Error("Invalid INVOKE record");
  1962. SmallVector<Value*, 16> Ops;
  1963. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  1964. Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  1965. if (Ops.back() == 0) return Error("Invalid INVOKE record");
  1966. }
  1967. if (!FTy->isVarArg()) {
  1968. if (Record.size() != OpNum)
  1969. return Error("Invalid INVOKE record");
  1970. } else {
  1971. // Read type/value pairs for varargs params.
  1972. while (OpNum != Record.size()) {
  1973. Value *Op;
  1974. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  1975. return Error("Invalid INVOKE record");
  1976. Ops.push_back(Op);
  1977. }
  1978. }
  1979. I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
  1980. Ops.begin(), Ops.end());
  1981. InstructionList.push_back(I);
  1982. cast<InvokeInst>(I)->setCallingConv(
  1983. static_cast<CallingConv::ID>(CCInfo));
  1984. cast<InvokeInst>(I)->setAttributes(PAL);
  1985. break;
  1986. }
  1987. case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
  1988. I = new UnwindInst(Context);
  1989. InstructionList.push_back(I);
  1990. break;
  1991. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  1992. I = new UnreachableInst(Context);
  1993. InstructionList.push_back(I);
  1994. break;
  1995. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  1996. if (Record.size() < 1 || ((Record.size()-1)&1))
  1997. return Error("Invalid PHI record");
  1998. const Type *Ty = getTypeByID(Record[0]);
  1999. if (!Ty) return Error("Invalid PHI record");
  2000. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  2001. InstructionList.push_back(PN);
  2002. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  2003. Value *V = getFnValueByID(Record[1+i], Ty);
  2004. BasicBlock *BB = getBasicBlock(Record[2+i]);
  2005. if (!V || !BB) return Error("Invalid PHI record");
  2006. PN->addIncoming(V, BB);
  2007. }
  2008. I = PN;
  2009. break;
  2010. }
  2011. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  2012. if (Record.size() != 4)
  2013. return Error("Invalid ALLOCA record");
  2014. const PointerType *Ty =
  2015. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  2016. const Type *OpTy = getTypeByID(Record[1]);
  2017. Value *Size = getFnValueByID(Record[2], OpTy);
  2018. unsigned Align = Record[3];
  2019. if (!Ty || !Size) return Error("Invalid ALLOCA record");
  2020. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  2021. InstructionList.push_back(I);
  2022. break;
  2023. }
  2024. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  2025. unsigned OpNum = 0;
  2026. Value *Op;
  2027. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  2028. OpNum+2 != Record.size())
  2029. return Error("Invalid LOAD record");
  2030. I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  2031. InstructionList.push_back(I);
  2032. break;
  2033. }
  2034. case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
  2035. unsigned OpNum = 0;
  2036. Value *Val, *Ptr;
  2037. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  2038. getValue(Record, OpNum,
  2039. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  2040. OpNum+2 != Record.size())
  2041. return Error("Invalid STORE record");
  2042. I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
  2043. InstructionList.push_back(I);
  2044. break;
  2045. }
  2046. case bitc::FUNC_CODE_INST_CALL: {
  2047. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  2048. if (Record.size() < 3)
  2049. return Error("Invalid CALL record");
  2050. AttrListPtr PAL = getAttributes(Record[0]);
  2051. unsigned CCInfo = Record[1];
  2052. unsigned OpNum = 2;
  2053. Value *Callee;
  2054. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  2055. return Error("Invalid CALL record");
  2056. const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  2057. const FunctionType *FTy = 0;
  2058. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  2059. if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
  2060. return Error("Invalid CALL record");
  2061. SmallVector<Value*, 16> Args;
  2062. // Read the fixed params.
  2063. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  2064. if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
  2065. Args.push_back(getBasicBlock(Record[OpNum]));
  2066. else
  2067. Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
  2068. if (Args.back() == 0) return Error("Invalid CALL record");
  2069. }
  2070. // Read type/value pairs for varargs params.
  2071. if (!FTy->isVarArg()) {
  2072. if (OpNum != Record.size())
  2073. return Error("Invalid CALL record");
  2074. } else {
  2075. while (OpNum != Record.size()) {
  2076. Value *Op;
  2077. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  2078. return Error("Invalid CALL record");
  2079. Args.push_back(Op);
  2080. }
  2081. }
  2082. I = CallInst::Create(Callee, Args.begin(), Args.end());
  2083. InstructionList.push_back(I);
  2084. cast<CallInst>(I)->setCallingConv(
  2085. static_cast<CallingConv::ID>(CCInfo>>1));
  2086. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  2087. cast<CallInst>(I)->setAttributes(PAL);
  2088. break;
  2089. }
  2090. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  2091. if (Record.size() < 3)
  2092. return Error("Invalid VAARG record");
  2093. const Type *OpTy = getTypeByID(Record[0]);
  2094. Value *Op = getFnValueByID(Record[1], OpTy);
  2095. const Type *ResTy = getTypeByID(Record[2]);
  2096. if (!OpTy || !Op || !ResTy)
  2097. return Error("Invalid VAARG record");
  2098. I = new VAArgInst(Op, ResTy);
  2099. InstructionList.push_back(I);
  2100. break;
  2101. }
  2102. }
  2103. // Add instruction to end of current BB. If there is no current BB, reject
  2104. // this file.
  2105. if (CurBB == 0) {
  2106. delete I;
  2107. return Error("Invalid instruction with no BB");
  2108. }
  2109. CurBB->getInstList().push_back(I);
  2110. // If this was a terminator instruction, move to the next block.
  2111. if (isa<TerminatorInst>(I)) {
  2112. ++CurBBNo;
  2113. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  2114. }
  2115. // Non-void values get registered in the value table for future use.
  2116. if (I && !I->getType()->isVoidTy())
  2117. ValueList.AssignValue(I, NextValueNo++);
  2118. }
  2119. // Check the function list for unresolved values.
  2120. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  2121. if (A->getParent() == 0) {
  2122. // We found at least one unresolved value. Nuke them all to avoid leaks.
  2123. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  2124. if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
  2125. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  2126. delete A;
  2127. }
  2128. }
  2129. return Error("Never resolved value found in function!");
  2130. }
  2131. }
  2132. // FIXME: Check for unresolved forward-declared metadata references
  2133. // and clean up leaks.
  2134. // See if anything took the address of blocks in this function. If so,
  2135. // resolve them now.
  2136. DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
  2137. BlockAddrFwdRefs.find(F);
  2138. if (BAFRI != BlockAddrFwdRefs.end()) {
  2139. std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
  2140. for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
  2141. unsigned BlockIdx = RefList[i].first;
  2142. if (BlockIdx >= FunctionBBs.size())
  2143. return Error("Invalid blockaddress block #");
  2144. GlobalVariable *FwdRef = RefList[i].second;
  2145. FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
  2146. FwdRef->eraseFromParent();
  2147. }
  2148. BlockAddrFwdRefs.erase(BAFRI);
  2149. }
  2150. // Trim the value list down to the size it was before we parsed this function.
  2151. ValueList.shrinkTo(ModuleValueListSize);
  2152. MDValueList.shrinkTo(ModuleMDValueListSize);
  2153. std::vector<BasicBlock*>().swap(FunctionBBs);
  2154. return false;
  2155. }
  2156. //===----------------------------------------------------------------------===//
  2157. // GVMaterializer implementation
  2158. //===----------------------------------------------------------------------===//
  2159. bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
  2160. if (const Function *F = dyn_cast<Function>(GV)) {
  2161. return F->isDeclaration() &&
  2162. DeferredFunctionInfo.count(const_cast<Function*>(F));
  2163. }
  2164. return false;
  2165. }
  2166. bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
  2167. Function *F = dyn_cast<Function>(GV);
  2168. // If it's not a function or is already material, ignore the request.
  2169. if (!F || !F->isMaterializable()) return false;
  2170. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  2171. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  2172. // Move the bit stream to the saved position of the deferred function body.
  2173. Stream.JumpToBit(DFII->second);
  2174. if (ParseFunctionBody(F)) {
  2175. if (ErrInfo) *ErrInfo = ErrorString;
  2176. return true;
  2177. }
  2178. // Upgrade any old intrinsic calls in the function.
  2179. for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
  2180. E = UpgradedIntrinsics.end(); I != E; ++I) {
  2181. if (I->first != I->second) {
  2182. for (Value::use_iterator UI = I->first->use_begin(),
  2183. UE = I->first->use_end(); UI != UE; ) {
  2184. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2185. UpgradeIntrinsicCall(CI, I->second);
  2186. }
  2187. }
  2188. }
  2189. return false;
  2190. }
  2191. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  2192. const Function *F = dyn_cast<Function>(GV);
  2193. if (!F || F->isDeclaration())
  2194. return false;
  2195. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  2196. }
  2197. void BitcodeReader::Dematerialize(GlobalValue *GV) {
  2198. Function *F = dyn_cast<Function>(GV);
  2199. // If this function isn't dematerializable, this is a noop.
  2200. if (!F || !isDematerializable(F))
  2201. return;
  2202. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  2203. // Just forget the function body, we can remat it later.
  2204. F->deleteBody();
  2205. }
  2206. bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
  2207. assert(M == TheModule &&
  2208. "Can only Materialize the Module this BitcodeReader is attached to.");
  2209. // Iterate over the module, deserializing any functions that are still on
  2210. // disk.
  2211. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  2212. F != E; ++F)
  2213. if (F->isMaterializable() &&
  2214. Materialize(F, ErrInfo))
  2215. return true;
  2216. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  2217. // delete the old functions to clean up. We can't do this unless the entire
  2218. // module is materialized because there could always be another function body
  2219. // with calls to the old function.
  2220. for (std::vector<std::pair<Function*, Function*> >::iterator I =
  2221. UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
  2222. if (I->first != I->second) {
  2223. for (Value::use_iterator UI = I->first->use_begin(),
  2224. UE = I->first->use_end(); UI != UE; ) {
  2225. if (CallInst* CI = dyn_cast<CallInst>(*UI++))
  2226. UpgradeIntrinsicCall(CI, I->second);
  2227. }
  2228. if (!I->first->use_empty())
  2229. I->first->replaceAllUsesWith(I->second);
  2230. I->first->eraseFromParent();
  2231. }
  2232. }
  2233. std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
  2234. // Check debug info intrinsics.
  2235. CheckDebugInfoIntrinsics(TheModule);
  2236. return false;
  2237. }
  2238. //===----------------------------------------------------------------------===//
  2239. // External interface
  2240. //===----------------------------------------------------------------------===//
  2241. /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
  2242. ///
  2243. Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
  2244. LLVMContext& Context,
  2245. std::string *ErrMsg) {
  2246. Module *M = new Module(Buffer->getBufferIdentifier(), Context);
  2247. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2248. M->setMaterializer(R);
  2249. if (R->ParseBitcodeInto(M)) {
  2250. if (ErrMsg)
  2251. *ErrMsg = R->getErrorString();
  2252. delete M; // Also deletes R.
  2253. return 0;
  2254. }
  2255. // Have the BitcodeReader dtor delete 'Buffer'.
  2256. R->setBufferOwned(true);
  2257. return M;
  2258. }
  2259. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  2260. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  2261. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
  2262. std::string *ErrMsg){
  2263. Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
  2264. if (!M) return 0;
  2265. // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
  2266. // there was an error.
  2267. static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
  2268. // Read in the entire module, and destroy the BitcodeReader.
  2269. if (M->MaterializeAllPermanently(ErrMsg)) {
  2270. delete M;
  2271. return 0;
  2272. }
  2273. return M;
  2274. }
  2275. std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
  2276. LLVMContext& Context,
  2277. std::string *ErrMsg) {
  2278. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  2279. // Don't let the BitcodeReader dtor delete 'Buffer'.
  2280. R->setBufferOwned(false);
  2281. std::string Triple("");
  2282. if (R->ParseTriple(Triple))
  2283. if (ErrMsg)
  2284. *ErrMsg = R->getErrorString();
  2285. delete R;
  2286. return Triple;
  2287. }