BitcodeReader.cpp 127 KB

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