BitcodeReader.cpp 99 KB

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