BitcodeReader.cpp 195 KB

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