BitcodeReader.cpp 115 KB

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