BitcodeReader.cpp 160 KB

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