BitcodeReader.cpp 181 KB

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